hytopia 0.12.0-prerelease-2 → 0.12.0-prerelease-3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/scripts.js +1 -1
- package/package.json +2 -1
- package/server.mjs +1 -1
package/bin/scripts.js
CHANGED
|
@@ -461,7 +461,7 @@ async function packageProject() {
|
|
|
461
461
|
async function build(devMode = false) {
|
|
462
462
|
let envFlags = devMode ? '' : '--minify --sourcemap=inline';
|
|
463
463
|
|
|
464
|
-
execSync(`npx --yes bun build --target=node --env=disable --format=esm ${envFlags} --outfile=index.mjs index.ts`, { stdio: 'inherit' });
|
|
464
|
+
execSync(`npx --yes bun build --target=node --env=disable --format=esm ${envFlags} --external=@fails-components/webtransport-transport-http3-quiche --outfile=index.mjs index.ts`, { stdio: 'inherit' });
|
|
465
465
|
}
|
|
466
466
|
|
|
467
467
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hytopia",
|
|
3
|
-
"version": "0.12.0-prerelease-
|
|
3
|
+
"version": "0.12.0-prerelease-3",
|
|
4
4
|
"description": "The HYTOPIA SDK makes it easy for developers to create massively multiplayer games using JavaScript or TypeScript.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./server.mjs",
|
|
@@ -56,6 +56,7 @@
|
|
|
56
56
|
},
|
|
57
57
|
"homepage": "https://github.com/hytopiagg/sdk#readme",
|
|
58
58
|
"dependencies": {
|
|
59
|
+
"@fails-components/webtransport-transport-http3-quiche": "1.4.4",
|
|
59
60
|
"@gltf-transform/cli": "4.2.1",
|
|
60
61
|
"archiver": "7.0.1",
|
|
61
62
|
"bun": "1.3.0",
|
package/server.mjs
CHANGED
|
@@ -548,7 +548,7 @@ cijsj5N9QPsSkv8BK77xNaQ0V0i9PPwtYE1jGO03NFNp41hXBDz/mGfYmICknf+j
|
|
|
548
548
|
1dCIyP0CgYBFauaJifm3nuAftrVkoVn8spz+C7cd5NTxW1YVpPksX0l0BgTWwcM8
|
|
549
549
|
qbRA4h4f3jIb3+2KHm2RhqzMzRcnEK2erXLkpm3+MbSIo7Kmce0v0g10CxZptWAf
|
|
550
550
|
q+PdVnQ8LyvkFwDkAtWMCfRFAaysLbFYHeaKUUdV3yzTssGARBZTCw==
|
|
551
|
-
-----END RSA PRIVATE KEY-----`;var JT=process.env.PORT??8080,On="0.12.0-prerelease-2",Dn;((Q)=>{Q.READY="WEBSERVER.READY";Q.STOPPED="WEBSERVER.STOPPED";Q.ERROR="WEBSERVER.ERROR";Q.UPGRADE="WEBSERVER.UPGRADE"})(Dn||={});class Bz extends $1{static instance=new Bz;_webserver=eC.default();_internalHttpServer;constructor(){super();this._webserver.use(($,X,Y)=>{X.header("Access-Control-Allow-Origin","*"),Y()}),this._webserver.get("/",($,X)=>{X.json({status:"OK",version:On,runtime:"node"})}),this._webserver.use(eC.default.static("assets",{dotfiles:"allow"}));let J=eW.instance.assetsLibraryPath;if(process.env.NODE_ENV!=="production"&&J)this._webserver.use(($,X,Y)=>{let Q=kT6.join(J,$.path);eW.instance.syncAsset(Q),Y()}),this._webserver.use(eC.default.static(J,{dotfiles:"allow"}))}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?CT6.createServer(this._webserver):TT6.createServer({key:tC,cert:rC},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else s.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(JT,this._onStarted),console.info(`WebServer.start(): Server running on port ${JT}.`)}stop(){if(this._internalHttpServer)return new Promise((J,$)=>{this._internalHttpServer.close((X)=>{if(X)$(X);else J(!0)})});else return s.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=(J,$,X)=>{this.emitWithGlobal("WEBSERVER.UPGRADE",{req:J,socket:$,head:X})};_onError=(J)=>{s.error(`WebServer._onError(): ${J.message}`),this.emitWithGlobal("WEBSERVER.ERROR",{error:J})};_onStopped=()=>{this.emitWithGlobal("WEBSERVER.STOPPED",{})}}var x3;((U)=>{U.BUILD_PACKETS="build_packets";U.ENTITIES_EMIT_UPDATES="entities_emit_updates";U.ENTITIES_TICK="entities_tick";U.NETWORK_SYNCHRONIZE="network_synchronize";U.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";U.PHYSICS_CLEANUP="physics_cleanup";U.PHYSICS_STEP="physics_step";U.SEND_ALL_PACKETS="send_all_packets";U.SEND_PACKETS="send_packets";U.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";U.SERIALIZE_PACKETS="serialize_packets";U.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";U.SIMULATION_STEP="simulation_step";U.TICKER_TICK="ticker_tick";U.WORLD_TICK="world_tick"})(x3||={});class I6{static getProcessStats(J=!1){let $=process.memoryUsage(),X={jsHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:$.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:$.heapUsed/$.heapTotal,unit:"percent"},processHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:$.rss/1024/1024,unit:"megabyte"}};if(J)return X;return Object.fromEntries(Object.entries(X).map(([Y,Q])=>[Y,Q.value]))}static initializeSentry(J,$=50){YC({dsn:J,release:On,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=I6.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let Q=X?.start_timestamp,K=X?.timestamp;if(!Q||!K)return null;if((K-Q)*1000>$)return X.measurements=I6.getProcessStats(!0),X}return null}})}static startSpan(J,$){if(VU())return l7({attributes:J.attributes,name:J.operation,op:J.operation},$);else return $()}static sentry(){return zd}}if(!HO)console.warn("Connection: msgpackr native acceleration is not enabled, using fallback implementation.");var yR1=new XG({useFloat32:b2.ALWAYS}),ST6=5000;class R$ extends $1{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_ws;_wsBinding=!1;_wt;_wtBinding=!1;_wtReliableReader;_wtReliableWriter;_wtUnreliableReader;_wtUnreliableWriter;id;constructor(J,$,X){super();this.id=Fz0(),this.onPacket(c0.PacketId.HEARTBEAT,this._onHeartbeatPacket);let Y=()=>{$1.globalInstance.emit("CONNECTION.OPENED",{connection:this,session:X})};if(J)this.bindWs(J),Y();else if($)this.bindWt($).then(Y).catch((Q)=>{this._onClose(),s.error(`Connection.constructor(): Failed to bind WebTransport. Error: ${Q}`)})}static clearCachedPacketsSerializedBuffers(){if(R$._cachedPacketsSerializedBuffer.size>0)R$._cachedPacketsSerializedBuffer.clear()}static serializePackets(J){for(let X of J)if(!c0.isValidPacket(X))return s.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let $=R$._cachedPacketsSerializedBuffer.get(J);if($)return $;return I6.startSpan({operation:"serialize_packets",attributes:{packets:J.length,packetIds:J.map((X)=>X[0]).join(",")}},(X)=>{let Y=yR1.pack(J);if(Y.byteLength>65536)Y=ET6(Y,{level:1});return X?.setAttribute("serializedBytes",Y.byteLength),R$._cachedPacketsSerializedBuffer.set(J,Y),Y})}bindWs(J){this._wsBinding=!0;let $=this._handleReconnect();if(this._cleanupConnections(),this._ws=J,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onClose,this._ws.onerror=this._onError,this._wsBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}async bindWt(J){this._wtBinding=!0;let $=this._handleReconnect();this._cleanupConnections(),J.userData.onclose=this._onClose,J.closed.catch(()=>{}).finally(()=>J.userData.onclose?.()),this._wt=J,await this._wt.ready;let X=this._wt.incomingBidirectionalStreams.getReader();try{let{value:Y}=await X.read();if(Y)this._wtReliableReader=Y.readable,this._wtReliableWriter=Y.writable.getWriter()}finally{X.releaseLock()}if(this._wtUnreliableReader=this._wt.datagrams.readable,this._wtUnreliableWriter=this._wt.datagrams.createWritable().getWriter(),(async()=>{if(!this._wtReliableReader)return;let Y=this._wt,Q=c0.createPacketBufferUnframer();for await(let K of this._wtReliableReader){if(Y!==this._wt)return;for(let W of Q(K))this._onMessage(W)}})().catch(()=>this._wt?.close()),(async()=>{if(!this._wtUnreliableReader)return;let Y=this._wt;for await(let Q of this._wtUnreliableReader){if(Y!==this._wt)return;this._onMessage(Q)}})().catch(()=>this._wt?.close()),this._wtBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}disconnect(){try{this._ws?.close(),this._wt?.close()}catch(J){s.error(`Connection.disconnect(): Connection disconnect failed. Error: ${J}`)}}onPacket(J,$){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===J)$(X)})}send(J,$=!0){if(this._closeTimeout||this._wsBinding||this._wtBinding)return;if(!this._ws&&!this._wt)return;let X=this._ws&&this._ws.readyState===bq.default.OPEN,Y=this._wt&&(this._wt.state==="connected"||this._wt.state==="draining");if(!X&&!Y)return;I6.startSpan({operation:"send_packets"},()=>{try{let Q=R$.serializePackets(J);if(!Q)return;if(Y)if($)this._wtReliableWriter?.write(c0.framePacketBuffer(Q)).catch(()=>{s.error("Connection.send(): WebTransport reliable write failed, connection closing?")});else this._wtUnreliableWriter?.write(Q).catch(()=>{s.error("Connection.send(): WebTransport unreliable write failed, connection closing?")});else this._ws.send(Q);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:J})}catch(Q){s.error(`Connection.send(): Packet send failed. Error: ${Q}`)}})}_onHeartbeatPacket=()=>{this.send([c0.createPacket(c0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0)};_onMessage=(J)=>{try{let $=this._deserialize(J);if(!$)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:$})}catch($){s.error(`Connection._ws.onmessage(): Error: ${$}`)}};_onClose=()=>{this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},ST6)};_onError=(J)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:J})};_cleanupConnections(){if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{};if(this._wt)this._wt.userData.onclose=()=>{};this._signalKill(),this._ws=void 0,this._wt=void 0,this._wtReliableReader=void 0,this._wtReliableWriter=void 0,this._wtUnreliableReader=void 0,this._wtUnreliableWriter=void 0}_deserialize(J){let $=yR1.unpack(J);if(!$||typeof $!=="object"||typeof $[0]!=="number")return s.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify($)}`);if(!c0.isValidPacket($))return s.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify($)}`);return $}_handleReconnect(){let J=!!this._ws||!!this._wt;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;return J}_signalConnectionId(){this.send([c0.createPacket(c0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})])}_signalKill(){this.send([c0.createPacket(c0.bidirectionalPackets.connectionPacketDefinition,{k:!0})])}}class jB{_lights=new Map;_nextLightId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedLights(J){this.getAllEntityAttachedLights(J).forEach(($)=>{$.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(J){return this.getAllLights().filter(($)=>$.attachedToEntity===J)}registerLight(J){if(J.id!==void 0)return J.id;let $=this._nextLightId;return this._lights.set($,J),this._nextLightId++,$}unregisterLight(J){if(J.id===void 0)return;this._lights.delete(J.id)}}class O5{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(J){return this._map.get(J)}set(J,$){let X=this._map.has(J);if(this._map.set(J,$),!X)this._values.push($);else this._isDirty=!0;return this}has(J){return this._map.has(J)}delete(J){let $=this._map.delete(J);if($)this._isDirty=!0;return $}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(J,$){this._map.forEach((X,Y)=>{J.call($,X,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let J of this._map.values())this._values.push(J);this._isDirty=!1}}var bR1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(bR1||={});var xn;((H)=>{H.DESPAWN="LIGHT.DESPAWN";H.SET_ANGLE="LIGHT.SET_ANGLE";H.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";H.SET_COLOR="LIGHT.SET_COLOR";H.SET_DISTANCE="LIGHT.SET_DISTANCE";H.SET_INTENSITY="LIGHT.SET_INTENSITY";H.SET_OFFSET="LIGHT.SET_OFFSET";H.SET_PENUMBRA="LIGHT.SET_PENUMBRA";H.SET_POSITION="LIGHT.SET_POSITION";H.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";H.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";H.SPAWN="LIGHT.SPAWN"})(xn||={});class Pn extends $1{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)s.fatalError("Either attachedToEntity or position must be set, but not both.");super();s.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=J.angle,this._attachedToEntity=J.attachedToEntity,this._color=J.color??{r:255,g:255,b:255},this._distance=J.distance,this._intensity=J.intensity??1,this._offset=J.offset,this._penumbra=J.penumbra,this._position=J.position,this._trackedEntity=J.trackedEntity,this._trackedPosition=J.trackedPosition,this._type=J.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(J){if(this._angle===J)return;if(this._angle=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:J})}setAttachedToEntity(J){if(!J.isSpawned)return s.error(`Light.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:J})}setColor(J){if(this._color.r===J.r&&this._color.g===J.g&&this._color.b===J.b)return;if(this._color=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:J})}setDistance(J){if(this._distance===J)return;if(this._distance=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:J})}setIntensity(J){if(this._intensity===J)return;if(this._intensity=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:J})}setPenumbra(J){if(this._penumbra===J)return;if(this._penumbra=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:J})}setTrackedEntity(J){if(!J.isSpawned)return s.error(`Light.setTrackedEntity(): Entity ${J.id} is not spawned!`);if(this._trackedEntity===J)return;if(this._trackedEntity=J,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:J})}setTrackedPosition(J){if(this._trackedPosition===J)return;if(this._trackedPosition=J,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:J})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return s.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=J.lightManager.registerLight(this),this._world=J,this.emitWithWorld(J,"LIGHT.SPAWN",{light:this})}serialize(){return H1.serializeLight(this)}}var Cn;((A)=>{A.BURST="PARTICLE_EMITTER.BURST";A.DESPAWN="PARTICLE_EMITTER.DESPAWN";A.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";A.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";A.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";A.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";A.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";A.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";A.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";A.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";A.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";A.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";A.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";A.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";A.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";A.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";A.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";A.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";A.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";A.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";A.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";A.SET_RATE="PARTICLE_EMITTER.SET_RATE";A.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";A.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";A.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";A.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";A.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";A.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";A.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";A.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";A.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";A.SPAWN="PARTICLE_EMITTER.SPAWN"})(Cn||={});class Tn extends $1{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)s.fatalError("Either attachedToEntity or position must be set, but not both.");if(!J.textureUri)s.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=J.alphaTest??0.05,this._attachedToEntity=J.attachedToEntity,this._attachedToEntityNodeName=J.attachedToEntityNodeName,this._colorEnd=J.colorEnd,this._colorEndVariance=J.colorEndVariance,this._colorStart=J.colorStart,this._colorStartVariance=J.colorStartVariance,this._gravity=J.gravity,this._lifetime=J.lifetime,this._lifetimeVariance=J.lifetimeVariance,this._maxParticles=J.maxParticles,this._offset=J.offset,this._opacityEnd=J.opacityEnd,this._opacityEndVariance=J.opacityEndVariance,this._opacityStart=J.opacityStart,this._opacityStartVariance=J.opacityStartVariance,this._paused=!1,this._position=J.position,this._positionVariance=J.positionVariance,this._rate=J.rate,this._rateVariance=J.rateVariance,this._sizeEnd=J.sizeEnd,this._sizeEndVariance=J.sizeEndVariance,this._sizeStart=J.sizeStart,this._sizeStartVariance=J.sizeStartVariance,this._textureUri=J.textureUri,this._transparent=J.transparent,this._velocity=J.velocity,this._velocityVariance=J.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(J){if(this._alphaTest===J)return;if(this._alphaTest=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:J})}setAttachedToEntity(J){if(!J.isSpawned)return s.error(`ParticleEmitter.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:J})}setAttachedToEntityNodeName(J){if(this._attachedToEntityNodeName===J)return;if(this._attachedToEntityNodeName=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:J})}setColorEnd(J){if(this._colorEnd&&this._colorEnd.r===J.r&&this._colorEnd.g===J.g&&this._colorEnd.b===J.b)return;if(this._colorEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:J})}setColorEndVariance(J){if(this._colorEndVariance&&this._colorEndVariance.r===J.r&&this._colorEndVariance.g===J.g&&this._colorEndVariance.b===J.b)return;if(this._colorEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:J})}setColorStart(J){if(this._colorStart&&this._colorStart.r===J.r&&this._colorStart.g===J.g&&this._colorStart.b===J.b)return;if(this._colorStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:J})}setColorStartVariance(J){if(this._colorStartVariance&&this._colorStartVariance.r===J.r&&this._colorStartVariance.g===J.g&&this._colorStartVariance.b===J.b)return;if(this._colorStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:J})}setGravity(J){if(this._gravity&&this._gravity.x===J.x&&this._gravity.y===J.y&&this._gravity.z===J.z)return;if(this._gravity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:J})}setLifetime(J){if(this._lifetime===J)return;if(this._lifetime=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:J})}setLifetimeVariance(J){if(this._lifetimeVariance===J)return;if(this._lifetimeVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:J})}setMaxParticles(J){if(this._maxParticles===J)return;if(this._maxParticles=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:J})}setOpacityEnd(J){if(this._opacityEnd===J)return;if(this._opacityEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:J})}setOpacityEndVariance(J){if(this._opacityEndVariance===J)return;if(this._opacityEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:J})}setOpacityStart(J){if(this._opacityStart===J)return;if(this._opacityStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:J})}setOpacityStartVariance(J){if(this._opacityStartVariance===J)return;if(this._opacityStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:J})}setPositionVariance(J){if(this._positionVariance&&this._positionVariance.x===J.x&&this._positionVariance.y===J.y&&this._positionVariance.z===J.z)return;if(this._positionVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:J})}setRate(J){if(this._rate===J)return;if(this._rate=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:J})}setRateVariance(J){if(this._rateVariance===J)return;if(this._rateVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:J})}setSizeEnd(J){if(this._sizeEnd===J)return;if(this._sizeEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:J})}setSizeEndVariance(J){if(this._sizeEndVariance===J)return;if(this._sizeEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:J})}setSizeStart(J){if(this._sizeStart===J)return;if(this._sizeStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:J})}setSizeStartVariance(J){if(this._sizeStartVariance===J)return;if(this._sizeStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:J})}setTextureUri(J){if(this._textureUri===J)return;if(this._textureUri=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:J})}setTransparent(J){if(this._transparent===J)return;if(this._transparent=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:J})}setVelocity(J){if(this._velocity&&this._velocity.x===J.x&&this._velocity.y===J.y&&this._velocity.z===J.z)return;if(this._velocity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:J})}setVelocityVariance(J){if(this._velocityVariance&&this._velocityVariance.x===J.x&&this._velocityVariance.y===J.y&&this._velocityVariance.z===J.z)return;if(this._velocityVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:J})}burst(J){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:J})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return s.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=J.particleEmitterManager.registerParticleEmitter(this),this._world=J,this.emitWithWorld(J,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return H1.serializeParticleEmitter(this)}}var IT6={x:0,y:-32,z:0},kn=60,En;((Q)=>{Q.STEP_START="SIMULATION.STEP_START";Q.STEP_END="SIMULATION.STEP_END";Q.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";Q.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(En||={});class BB extends $1{_colliderMap=new I2;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(J,$=kn,X=IT6){super();this._rapierEventQueue=new W8.EventQueue(!0),this._rapierSimulation=new W8.World(X),this._rapierSimulation.timestep=Math.fround(1/$),this._world=J}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(J,$){return this._rapierSimulation.createCollider(J,$)}createRawRigidBody(J){return this._rapierSimulation.createRigidBody(J)}enableDebugRaycasting(J){this._debugRaycastingEnabled=J}enableDebugRendering(J,$=W8.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=J,this._debugRenderingFilterFlags=$}getContactManifolds(J,$){let X=[];return this._rapierSimulation.narrowPhase.contactPair(J,$,(Y,Q)=>{if(Y.numContacts()===0)return;let K=Y.normal(),W=[];for(let Z=0;Z<Y.numSolverContacts();Z++)W.push(Y.solverContactPoint(Z));X.push({contactPoints:W,localNormalA:!Q?Y.localNormal1():Y.localNormal2(),localNormalB:!Q?Y.localNormal2():Y.localNormal1(),normal:!Q?K:{x:-K.x,y:-K.y,z:-K.z}})}),X}intersectionsWithRawShape(J,$,X,Y={}){let Q=new Set,K=[];return this._rapierSimulation.intersectionsWithShape($,X,J,(W)=>{let Z=this._colliderMap.getColliderHandleBlockType(W.handle);if(Z&&!Q.has(Z))return Q.add(Z),K.push({intersectedBlockType:Z}),!0;let G=this._colliderMap.getColliderHandleEntity(W.handle);if(G&&!Q.has(G))return Q.add(G),K.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),K}raycast(J,$,X,Y={}){let Q=new W8.Ray(J,$),K=this._rapierSimulation.castRay(Q,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:J,direction:$,length:X,hit:!!K});if(!K)return null;let W=Q.pointAt(K.timeOfImpact),Z=K.timeOfImpact,G=K.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:c3.fromGlobalCoordinate({x:Math.floor(W.x-(Q.dir.x<0?0.0001:-0.0001)),y:Math.floor(W.y-(Q.dir.y<0?0.0001:-0.0001)),z:Math.floor(W.z-(Q.dir.z<0?0.0001:-0.0001))},V),hitPoint:W,hitDistance:Z};let q=this._colliderMap.getColliderHandleEntity(G.handle);if(q)return{hitEntity:q,hitPoint:W,hitDistance:Z};return null}removeRawCollider(J){this._colliderMap.queueColliderHandleForCleanup(J.handle),this._rapierSimulation.removeCollider(J,!1)}removeRawRigidBody(J){this._rapierSimulation.removeRigidBody(J)}setGravity(J){this._rapierSimulation.gravity=J}step=(J)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:J});let $=performance.now();if(I6.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),I6.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-$}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(J,$,X)=>{let[Y,Q]=this._getCollisionObjects(J,$);if(!Y||!Q)return;let K=(W,Z)=>{if(W instanceof g9&&Z instanceof g6&&W.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))W.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:W,entity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(W instanceof g6&&Z instanceof g9&&W.hasListeners("ENTITY.BLOCK_COLLISION"))W.emit("ENTITY.BLOCK_COLLISION",{entity:W,blockType:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(W instanceof g6&&Z instanceof g6&&W.hasListeners("ENTITY.ENTITY_COLLISION"))W.emit("ENTITY.ENTITY_COLLISION",{entity:W,otherEntity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(typeof W==="function"&&(Z instanceof g6||Z instanceof g9))W(Z,X,J,$)};K(Y,Q),K(Q,Y)};_onContactForceEvent=(J)=>{let[$,X]=this._getCollisionObjects(J.collider1(),J.collider2());if(!$||typeof $==="function"||!X||typeof X==="function")return;let Y={totalForce:J.totalForce(),totalForceMagnitude:J.totalForceMagnitude(),maxForceDirection:J.maxForceDirection(),maxForceMagnitude:J.maxForceMagnitude()},Q=(K,W)=>{if(K instanceof g9&&W instanceof g6&&K.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))K.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:K,entity:W,contactForceData:Y});else if(K instanceof g6&&W instanceof g9&&K.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))K.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:K,blockType:W,contactForceData:Y});else if(K instanceof g6&&W instanceof g6&&K.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))K.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:K,otherEntity:W,contactForceData:Y})};Q($,X),Q(X,$)};_getCollisionObjects(J,$){let X=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J),Y=this._colliderMap.getColliderHandleBlockType($)??this._colliderMap.getColliderHandleCollisionCallback($)??this._colliderMap.getColliderHandleEntity($);return[X,Y]}}class $T{_synchronizedPlayerReliablePackets=new O5;_queuedBroadcasts=[];_queuedAudioSynchronizations=new O5;_queuedBlockSynchronizations=new O5;_queuedBlockTypeSynchronizations=new O5;_queuedChunkSynchronizations=new O5;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new O5;_queuedLightSynchronizations=new O5;_queuedParticleEmitterSynchronizations=new O5;_queuedPerPlayerSynchronizations=new O5;_queuedPerPlayerCameraSynchronizations=new O5;_queuedPerPlayerUISynchronizations=new O5;_queuedPerPlayerUIDatasSynchronizations=new O5;_queuedPlayerSynchronizations=new O5;_queuedSceneUISynchronizations=new O5;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(J){this._world=J,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let J=[],$=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(...Q);if(this._queuedEntitySynchronizations.size>0){let Y=[],Q=[];for(let K of this._queuedEntitySynchronizations.valuesArray){let W=!1;for(let Z in K)if(Z!=="i"&&Z!=="p"&&Z!=="r"){W=!0;break}if(W)Y.push(K);else Q.push(K)}if(Q.length>0){let K=c0.createPacket(c0.outboundPackets.entitiesPacketDefinition,Q,X);$.push(K)}if(Y.length>0){let K=c0.createPacket(c0.outboundPackets.entitiesPacketDefinition,Y,X);J.push(K);for(let W of this._synchronizedPlayerReliablePackets.valuesArray)W.push(K)}}if(this._queuedAudioSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUISynchronizations){let K=c0.createPacket(c0.outboundPackets.uiPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(K)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUIDatasSynchronizations){let K=c0.createPacket(c0.outboundPackets.uiDatasPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(K)}if(this._queuedSceneUISynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedWorldSynchronization){let Y=c0.createPacket(c0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerCameraSynchronizations){let K=c0.createPacket(c0.outboundPackets.cameraPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(K)}if(this._queuedPlayerSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=c0.createPacket(c0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}I6.startSpan({operation:"send_all_packets"},()=>{for(let Y of O$.instance.getConnectedPlayersByWorld(this._world)){let Q=this._synchronizedPlayerReliablePackets.get(Y)??J;if(Q.length>0)Y.connection.send(Q);if($.length>0)Y.connection.send($,!1)}}),I6.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();R$.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_NOTIFICATION_PERMISSION",this._onPlayerRequestNotificationPermission),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity),this._world.final("WORLD.SET_SKYBOX_URI",this._onWorldSetSkyboxUri)}_onAudioPause=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pa=!0,delete $.pl,delete $.r};_onAudioPlay=(J)=>{let $=J.audio.serialize();$.pl=!0,delete $.pa,delete $.r,this._queuedAudioSynchronizations.set($.i,$)};_onAudioPlayRestart=(J)=>{let $=J.audio.serialize();$.r=!0,delete $.pa,delete $.pl,this._queuedAudioSynchronizations.set($.i,$)};_onAudioSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onAudioSetCutoffDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.cd=J.cutoffDistance};_onAudioSetDetune=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.de=J.detune};_onAudioSetDistortion=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.di=J.distortion};_onAudioSetPosition=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.position?void 0:$.e,$.p=J.position?H1.serializeVector(J.position):void 0};_onAudioSetPlaybackRate=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pr=J.playbackRate};_onAudioSetReferenceDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.rd=J.referenceDistance};_onAudioSetVolume=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.v=J.volume};_onBlockTypeRegistryRegisterBlockType=(J)=>{let $=J.blockType.serialize();this._queuedBlockTypeSynchronizations.set(J.blockType.id,$)};_onChatSendBroadcastMessage=(J)=>{let{player:$,message:X,color:Y}=J;this._queuedBroadcasts.push(c0.createPacket(c0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:$?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(J)=>{let{player:$,message:X,color:Y}=J,Q=this._queuedPerPlayerSynchronizations.get($)??[];Q.push(c0.createPacket(c0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,Q)};_onChunkLatticeAddChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk);$.b=Array.from(J.chunk.blocks),$.rm=void 0,this._spawnedChunks.add($.c.join(","))};_onChunkLatticeRemoveChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk),X=$.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else $.rm=!0};_onChunkLatticeSetBlock=(J)=>{let $=this._createOrGetQueuedBlockSync(J.globalCoordinate);$.i=J.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.ap=J.playbackRate};_onEntitySpawn=(J)=>{let $=J.entity.serialize();this._queuedEntitySynchronizations.set($.i,$),this._spawnedEntities.add($.i)};_onEntityDespawn=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if(this._spawnedEntities.has($.i))this._queuedEntitySynchronizations.delete($.i),this._spawnedEntities.delete($.i);else $.rm=!0};_onEntitySetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.h=Array.from(J.modelHiddenNodes)};_onEntitySetModelScale=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.s=J.modelScale};_onEntitySetModelShownNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.sn=Array.from(J.modelShownNodes)};_onEntitySetModelTextureUri=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.mt=J.modelTextureUri};_onEntitySetOpacity=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.o=J.opacity};_onEntitySetParent=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.pe=J.parent?J.parent.id:void 0,$.pn=J.parentNodeName};_onEntitySetTintColor=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.t=J.tintColor?H1.serializeRgbColor(J.tintColor):void 0};_onEntityStartModelLoopedAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al=Array.from(new Set([...$.al??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.ao=Array.from(new Set([...$.ao??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al)$.al=$.al.filter((X)=>!J.animations.has(X)).filter(Boolean);if($.ao)$.ao=$.ao.filter((X)=>!J.animations.has(X)).filter(Boolean);$.as=Array.from(new Set([...$.as??[],...J.animations]))};_onEntityUpdateRotation=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.r=[J.rotation.x,J.rotation.y,J.rotation.z,J.rotation.w]};_onEntityUpdatePosition=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.p=[J.position.x,J.position.y,J.position.z]};_onLightDespawn=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.rm=!0};_onLightSetAngle=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.a=J.angle};_onLightSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onLightSetColor=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.c=H1.serializeRgbColor(J.color)};_onLightSetDistance=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.d=J.distance};_onLightSetIntensity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.n=J.intensity};_onLightSetOffset=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.o=J.offset?H1.serializeVector(J.offset):void 0};_onLightSetPenumbra=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.pe=J.penumbra};_onLightSetPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.p=J.position?H1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onLightSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.te=J.entity?J.entity.id:void 0,$.tp=J.entity?void 0:$.tp};_onLightSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.tp=J.position?H1.serializeVector(J.position):void 0,$.te=J.position?void 0:$.te};_onLightSpawn=(J)=>{let $=J.light.serialize();this._queuedLightSynchronizations.set($.i,$)};_onParticleEmitterBurst=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.b=J.count};_onParticleEmitterDespawn=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rm=!0};_onParticleEmitterSetAlphaTest=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.at=J.alphaTest};_onParticleEmitterSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onParticleEmitterSetAttachedToEntityNodeName=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.en=J.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ce=J.colorEnd?H1.serializeRgbColor(J.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cev=J.colorEndVariance?H1.serializeRgbColor(J.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cs=J.colorStart?H1.serializeRgbColor(J.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.csv=J.colorStartVariance?H1.serializeRgbColor(J.colorStartVariance):void 0};_onParticleEmitterSetGravity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.g=J.gravity?H1.serializeVector(J.gravity):void 0};_onParticleEmitterSetLifetime=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.l=J.lifetime};_onParticleEmitterSetLifetimeVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.lv=J.lifetimeVariance};_onParticleEmitterSetMaxParticles=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.mp=J.maxParticles};_onParticleEmitterSetOffset=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.o=J.offset?H1.serializeVector(J.offset):void 0};_onParticleEmitterSetOpacityEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oe=J.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oev=J.opacityEndVariance};_onParticleEmitterSetOpacityStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.os=J.opacityStart};_onParticleEmitterSetOpacityStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.osv=J.opacityStartVariance};_onParticleEmitterSetPaused=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pa=J.paused};_onParticleEmitterSetPosition=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.p=J.position?H1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e,$.en=J.position?void 0:$.en};_onParticleEmitterSetPositionVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pv=J.positionVariance?H1.serializeVector(J.positionVariance):void 0};_onParticleEmitterSetRate=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.r=J.rate};_onParticleEmitterSetRateVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rv=J.rateVariance};_onParticleEmitterSetSizeEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.se=J.sizeEnd};_onParticleEmitterSetSizeEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.sev=J.sizeEndVariance};_onParticleEmitterSetSizeStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ss=J.sizeStart};_onParticleEmitterSetSizeStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ssv=J.sizeStartVariance};_onParticleEmitterSetTextureUri=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.tu=J.textureUri};_onParticleEmitterSetTransparent=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.t=J.transparent};_onParticleEmitterSetVelocity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.v=J.velocity?H1.serializeVector(J.velocity):void 0};_onParticleEmitterSetVelocityVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.vv=J.velocityVariance?H1.serializeVector(J.velocityVariance):void 0};_onParticleEmitterSpawn=(J)=>{let $=J.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set($.i,$)};_onPlayerCameraLookAtEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=H1.serializeVector(J.entity.position),delete $.et,delete $.pt};_onPlayerCameraLookAtPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=J.position?H1.serializeVector(J.position):void 0,delete $.et,delete $.pt};_onPlayerCameraSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.e=J.entity.id,delete $.p};_onPlayerCameraSetAttachedToPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.p=J.position?H1.serializeVector(J.position):void 0,delete $.e};_onPlayerCameraSetFilmOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fo=J.filmOffset};_onPlayerCameraSetForwardOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.ffo=J.forwardOffset};_onPlayerCameraSetFov=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fv=J.fov};_onPlayerCameraSetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.h=Array.from(J.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.s=Array.from(J.modelShownNodes)};_onPlayerCameraSetMode=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.m=J.mode};_onPlayerCameraSetOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.o=J.offset?H1.serializeVector(J.offset):void 0};_onPlayerCameraSetShoulderAngle=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.sa=J.shoulderAngle};_onPlayerCameraSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.et=J.entity?J.entity.id:void 0,delete $.pl,delete $.pt};_onPlayerCameraSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pt=J.position?H1.serializeVector(J.position):void 0,delete $.et,delete $.pl};_onPlayerCameraSetZoom=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.z=J.zoom};_onPlayerJoinedWorld=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(c0.createPacket(c0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((Q)=>{if($.camera.attachedToEntity===void 0&&Q instanceof KX&&Q.player===$)$.camera.setAttachedToEntity(Q);return Q.serialize()}),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.playersPacketDefinition,O$.instance.getConnectedPlayers().map((Q)=>Q.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync($.camera);this._queuedPerPlayerCameraSynchronizations.set($,{...$.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set($,X),this._queuedPlayerSynchronizations.set($.id,$.serialize())};_onPlayerLeftWorld=(J)=>{let $=this._createOrGetQueuedPlayerSync(J.player);$.rm=!0};_onPlayerReconnectedWorld=(J)=>{this._onPlayerJoinedWorld(J)};_onPlayerRequestNotificationPermission=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(c0.createPacket(c0.outboundPackets.notificationPermissionRequestPacketDefinition,null,this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,X)};_onPlayerRequestSync=(J)=>{J.player.connection.send([c0.createPacket(c0.outboundPackets.syncResponsePacketDefinition,{r:J.receivedAt,s:Date.now(),p:performance.now()-J.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.u=J.htmlUri};_onPlayerUILockPointer=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.p=J.lock};_onPlayerUISendData=(J)=>{this._createOrGetQueuedPlayerUIDatasSync(J.playerUI).push(J.data)};_onSceneUILoad=(J)=>{let $=J.sceneUI.serialize();this._queuedSceneUISynchronizations.set($.i,$),this._loadedSceneUIs.add($.i)};_onSceneUISetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onSceneUISetOffset=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.o=J.offset?H1.serializeVector(J.offset):void 0};_onSceneUISetPosition=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.p=J.position?H1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onSceneUISetState=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.s=J.state};_onSceneUISetViewDistance=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.v=J.viewDistance};_onSceneUIUnload=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);if(this._loadedSceneUIs.has($.i))this._queuedSceneUISynchronizations.delete($.i),this._loadedSceneUIs.delete($.i);else $.rm=!0};_onSimulationDebugRaycast=(J)=>{this._queuedDebugRaycastSynchronizations.push(H1.serializePhysicsDebugRaycast(J))};_onSimulationDebugRender=(J)=>{this._queuedBroadcasts.push(c0.createPacket(c0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(J.vertices),c:Array.from(J.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ac=H1.serializeRgbColor(J.color)};_onWorldSetAmbientLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ai=J.intensity};_onWorldSetDirectionalLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dc=H1.serializeRgbColor(J.color)};_onWorldSetDirectionalLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.di=J.intensity};_onWorldSetDirectionalLightPosition=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dp=H1.serializeVector(J.position)};_onWorldSetFogColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fc=H1.serializeRgbColor(J.color)};_onWorldSetFogFar=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ff=J.far};_onWorldSetFogNear=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fn=J.near};_onWorldSetSkyboxIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.si=J.intensity};_onWorldSetSkyboxUri=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.s=J.uri};_createOrGetQueuedAudioSync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let $=this._queuedAudioSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedAudioSynchronizations.set(J.id,$);return $}_createOrGetQueuedBlockSync(J){let{x:$,y:X,z:Y}=J,Q=`${$},${X},${Y}`,K=this._queuedBlockSynchronizations.get(Q);if(!K)K={i:0,c:[$,X,Y]},this._queuedBlockSynchronizations.set(Q,K);return K}_createOrGetQueuedChunkSync(J){if(!J.originCoordinate)s.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:$,y:X,z:Y}=J.originCoordinate,Q=`${$},${X},${Y}`,K=this._queuedChunkSynchronizations.get(Q);if(!K)K={c:[$,X,Y]},this._queuedChunkSynchronizations.set(Q,K);return K}_createOrGetQueuedEntitySync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let $=this._queuedEntitySynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedEntitySynchronizations.set(J.id,$);return $}_createOrGetQueuedLightSync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let $=this._queuedLightSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedLightSynchronizations.set(J.id,$);return $}_createOrGetQueuedParticleEmitterSync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let $=this._queuedParticleEmitterSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedParticleEmitterSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerSync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let $=this._queuedPlayerSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedPlayerSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerCameraSync(J){let $=this._queuedPerPlayerCameraSynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerCameraSynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUISync(J){let $=this._queuedPerPlayerUISynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerUISynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUIDatasSync(J){let $=this._queuedPerPlayerUIDatasSynchronizations.get(J.player);if(!$)$=[],this._queuedPerPlayerUIDatasSynchronizations.set(J.player,$);return $}_createOrGetQueuedSceneUISync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let $=this._queuedSceneUISynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedSceneUISynchronizations.set(J.id,$);return $}_createOrGetQueuedWorldSync(J){if(J.id!==this._world.id)s.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:J.id}}_createOrGetSynchronizedPlayerReliablePackets(J,$){let X=this._synchronizedPlayerReliablePackets.get(J);if(!X)X=[...$],this._synchronizedPlayerReliablePackets.set(J,X);return X}}class LB{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedParticleEmitters(J){this.getAllEntityAttachedParticleEmitters(J).forEach(($)=>{$.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(J){return this.getAllParticleEmitters().filter(($)=>$.attachedToEntity===J)}registerParticleEmitter(J){if(J.id!==void 0)return J.id;let $=this._nextParticleEmitterId;return this._particleEmitters.set($,J),this._nextParticleEmitterId++,$}unregisterParticleEmitter(J){if(J.id===void 0)return;this._particleEmitters.delete(J.id)}}class wB{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(J){this._world=J}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(J){return this.getAllSceneUIs().filter(($)=>$.attachedToEntity===J)}getSceneUIById(J){return this._sceneUIs.get(J)}registerSceneUI(J){if(J.id!==void 0)return J.id;let $=this._nextSceneUIId;return this._sceneUIs.set($,J),this._nextSceneUIId++,$}unloadEntityAttachedSceneUIs(J){this.getAllEntityAttachedSceneUIs(J).forEach(($)=>{$.unload()})}unregisterSceneUI(J){if(J.id===void 0)return;this._sceneUIs.delete(J.id)}}var AT6=2,_T6=3;class MB{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(J,$,X){this._targetTicksPerSecond=J,this._fixedTimestepS=Math.fround(1/J),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*_T6,this._tickFunction=$,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let J=()=>{let $=performance.now(),X=$-this._lastLoopTimeMs;if(this._lastLoopTimeMs=$,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)I6.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<AT6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(J,this._nextTickMs)};J()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(J){try{this._tickFunction(J)}catch($){if($ instanceof Error&&this._tickErrorCallback)this._tickErrorCallback($);else s.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${$}`)}}}var mR1;((K)=>{K.START="WORLD_LOOP.START";K.STOP="WORLD_LOOP.STOP";K.TICK_START="WORLD_LOOP.TICK_START";K.TICK_END="WORLD_LOOP.TICK_END";K.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(mR1||={});class NB extends $1{_currentTick=0;_ticker;_world;constructor(J,$=kn){super();this._ticker=new MB($,this._tick,this._onTickError),this._world=J}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(J)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:J});let $=performance.now();I6.startSpan({operation:"world_tick",attributes:{serverPlayerCount:O$.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{I6.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(J)),I6.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(J)),I6.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),I6.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-$})};_onTickError=(J)=>{s.error(`WorldLoop._onTickError(): Error: ${J}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:J})}}var Sn;((H)=>{H.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";H.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";H.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";H.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";H.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";H.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";H.SET_FOG_FAR="WORLD.SET_FOG_FAR";H.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";H.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";H.SET_SKYBOX_URI="WORLD.SET_SKYBOX_URI";H.START="WORLD.START";H.STOP="WORLD.STOP"})(Sn||={});class RB extends $1{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;constructor(J){super();if(this._id=J.id,this._ambientLightColor=J.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=J.ambientLightIntensity??1,this._directionalLightColor=J.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=J.directionalLightIntensity??3,this._directionalLightPosition=J.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=J.fogColor,this._fogFar=J.fogFar??550,this._fogNear=J.fogNear??500,this._name=J.name,this._skyboxIntensity=J.skyboxIntensity??1,this._skyboxUri=J.skyboxUri,this._tag=J.tag,this._audioManager=new kz(this),this._blockTypeRegistry=new iF(this),this._chatManager=new E2(this),this._chunkLattice=new S2(this),this._entityManager=new c2(this),this._lightManager=new jB(this),this._loop=new NB(this,J.tickRate),this._networkSynchronizer=new $T(this),this._particleEmitterManager=new LB(this),this._sceneUIManager=new wB(this),this._simulation=new BB(this,J.tickRate,J.gravity),J.map)this.loadMap(J.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}loadMap(J){if(this.chunkLattice.clear(),J.blockTypes)for(let $ of J.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:$.id,isLiquid:$.isLiquid,lightLevel:$.lightLevel,name:$.name,textureUri:$.textureUri});if(J.blocks){let $={};for(let X in J.blocks){let Y=J.blocks[X],Q=X.indexOf(","),K=X.indexOf(",",Q+1),W=Number(X.slice(0,Q)),Z=Number(X.slice(Q+1,K)),G=Number(X.slice(K+1));if(!$[Y])$[Y]=[];$[Y].push({x:W,y:Z,z:G})}this.chunkLattice.initializeBlocks($)}if(J.entities)for(let $ in J.entities){let X=J.entities[$],Y=$.indexOf(","),Q=$.indexOf(",",Y+1),K=Number($.slice(0,Y)),W=Number($.slice(Y+1,Q)),Z=Number($.slice(Q+1));new g6({isEnvironmental:!0,...X}).spawn(this,{x:K,y:W,z:Z})}}setAmbientLightColor(J){this._ambientLightColor=J,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:J})}setAmbientLightIntensity(J){this._ambientLightIntensity=J,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightColor(J){this._directionalLightColor=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:J})}setDirectionalLightIntensity(J){this._directionalLightIntensity=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightPosition(J){this._directionalLightPosition=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:J})}setFogColor(J){this._fogColor=J,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:J})}setFogFar(J){this._fogFar=J,this.emit("WORLD.SET_FOG_FAR",{world:this,far:J})}setFogNear(J){this._fogNear=J,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:J})}setSkyboxIntensity(J){this._skyboxIntensity=J,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:J})}setSkyboxUri(J){this._skyboxUri=J,this.emit("WORLD.SET_SKYBOX_URI",{world:this,uri:J})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return H1.serializeWorld(this)}}var uR1;(($)=>$.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(uR1||={});class iW{static instance=new iW;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(J){let $=new RB({...J,id:this._nextWorldId++});return $.start(),this._worlds.set($.id,$),$1.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:$}),$}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(J){let $=[];return this._worlds.forEach((X)=>{if(X.tag===J)$.push(X)}),$}getWorld(J){return this._worlds.get(J)}setDefaultWorld(J){this._defaultWorld=J}}var gR1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(gR1||={});class O${static instance=new O$;worldSelectionHandler;_connectionPlayers=new Map;constructor(){$1.globalInstance.on("CONNECTION.OPENED",({connection:J,session:$})=>{this._onConnectionOpened(J,$)}),$1.globalInstance.on("CONNECTION.DISCONNECTED",({connection:J})=>{this._onConnectionDisconnected(J)}),$1.globalInstance.on("CONNECTION.RECONNECTED",({connection:J})=>{this._onConnectionReconnected(J)}),$1.globalInstance.on("CONNECTION.CLOSED",({connection:J})=>{this._onConnectionClosed(J)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(J){return this.getConnectedPlayers().filter(($)=>$.world===J)}getConnectedPlayerByUsername(J){return Array.from(this._connectionPlayers.values()).find(($)=>{return $.username.toLowerCase()===J.toLowerCase()})}async _onConnectionOpened(J,$){let X=new gq(J,$);await X.loadInitialPersistedData(),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??iW.instance.getDefaultWorld()),this._connectionPlayers.set(J,X)}_onConnectionDisconnected(J){let $=this._connectionPlayers.get(J);if($)$.resetInputs(),$.camera.reset()}_onConnectionReconnected(J){let $=this._connectionPlayers.get(J);if($)$.reconnected(),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:$});else s.warning(`PlayerManager._onConnectionReconnected(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(J){let $=this._connectionPlayers.get(J);if($)$.disconnect(),this._connectionPlayers.delete(J),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:$});else s.warning(`PlayerManager._onConnectionClosed(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}}import{randomBytes as qk6}from"crypto";import{ReadableStream as Jk6}from"node:stream/web";import{ReadableStream as hT6,WritableStream as fT6}from"node:stream/web";var Lz=hT6,XT=fT6;var YT=L0(L9(),1);function In(){let J=()=>{},$=()=>{};return{promise:new Promise((Y,Q)=>{J=Y,$=Q}),resolve:J,reject:$}}function G6(J){let $=!!(typeof process>"u"||process.env.DEBUG_TRACE);return Object.assign(YT.default(J),{error:YT.default(`${J}:error`),trace:$?YT.default(`${J}:trace`):()=>{}})}class O9 extends Error{constructor(J){super(J);this.name=this[Symbol.toStringTag]="WebTransportError"}}var pR1=!0;try{let J=new ReadableStream({start:($)=>{},type:"bytes"})}catch(J){pR1=!1}var QT=pR1;var yT6=typeof process<"u"?process.pid:0,BJ=G6(`webtransport:http3wtstream(${yT6})`);class An{constructor(J){if(this.objint=J.object,this.objint.jsobj=this,this.parentobj=J.parentobj,this.transport=J.transport,this.bidirectional=J.bidirectional,this.incoming=J.incoming,this.closed=!1,this._sendGroup=J.sendGroup,this._sendOrder=J.sendOrder,this.objint.sendInitialParameters)this.objint.sendInitialParameters();if(this.pendingoperation=null,this.pendingres=null,this.readable,this.writable,this.pendingoperationRead=null,this.pendingresRead=null,this.bidirectional||this.incoming){let $={start:(X)=>{this.readableController=X,this.objint.startReading()},pull:async(X)=>{if(this.readableclosed)return Promise.resolve();this.pendingoperationRead=new Promise((Y,Q)=>{this.pendingresRead=Y}),this.objint.startReading(),await this.pendingoperationRead},cancel:(X)=>{let Y=new Promise((K,W)=>{this.cancelres=K}),Q=0;if(X&&X.code)if(X.code<0)Q=0;else if(X.code>255)Q=255;else Q=X.code;return this.readableclosed=!0,this.objint.stopSending(Q),Y},type:"bytes",autoAllocateChunkSize:4096};if(!QT)delete $.type;this.readable=new Lz($),this.readable.getStats=()=>{return Promise.resolve({timestamp:0,bytesReceived:0n,bytesRead:0n})},this.parentobj.addReceiveStream(this.readable,this.readableController)}if(this.bidirectional||!this.incoming)this.writable=new XT({start:($)=>{this.writableController=$},write:($,X)=>{if(this.writableclosed)return Promise.resolve();let Y=$;if(Y instanceof ArrayBuffer)Y=new Uint8Array(Y);if(Y instanceof Uint8Array){if(Y.byteLength===0)return;return this.pendingoperation=new Promise((Q,K)=>{this.pendingres=Q}),this.objint.writeChunk(Y),this.pendingoperation}else throw BJ.trace("chunk info:",$),Error("chunk is not of instanceof Uint8Array or Arraybuffer")},close:()=>{if(this.writableclosed)return Promise.resolve();return this.objint.streamFinal(),this.pendingoperation=new Promise(($,X)=>{this.pendingres=$}),this.pendingoperation},abort:($)=>{if(this.writableclosed)return new Promise((Q,K)=>{Q()});let X=0;if($&&$.code)if($.code<0)X=0;else if($.code>255)X=255;else X=$.code;let Y=new Promise((Q,K)=>{this.abortres=Q});return this.objint.resetStream(X),Y}},{highWaterMark:4}),this.writable.getStats=()=>{return Promise.resolve({timestamp:0,bytesWritten:0n,bytesSent:0n,bytesAcknowledged:0n})},Object.defineProperties(this.writable,{sendOrder:{get:()=>{return this._sendOrder},set:($)=>{if($!==this._sendOrder)this._sendOrder=J.sendOrder,this.updateSendOrderAndGroup()}},sendGroup:{get:()=>{return this._sendGroup},set:($)=>{if($!==this._sendGroup)this._sendGroup=$,this.updateSendOrderAndGroup()}}}),this.parentobj.addSendStream(this.writable,this.writableController);this.cancelres=null,this.pendingres=null,this.abortres=null,this.finaldrain_=!1}getReadBuffer({byteSize:J}){let $=this.readableController.byobRequest;if($){let X=$?.view;if(!(X instanceof Uint8Array))throw Error("byob view is not a Uint8Array");return{buffer:X,byob:$,readBytes:0,fin:!1}}else return{buffer:new Uint8Array(J),byob:void 0,readBytes:0,fin:!1}}commitReadBuffer({buffer:J,byob:$,drained:X,readBytes:Y,fin:Q}){if(!this.readableclosed){if($&&Y!==void 0)$.respond(Y);else if(J)this.readableController.enqueue(J)}let K={};if(Y!==void 0&&Y>0&&!this.readableclosed){if(BJ.trace("commitReadbuffer",Y),this.pendingoperationRead&&X){if(this.readableController.desiredSize!=null&&!this.finaldrain_){if(this.readableController.desiredSize<0)K.stopReading=!0}let W=this.pendingresRead;if(this.pendingoperationRead=null,this.pendingresRead=null,W)W()}}if(Q){if(this.cancelres){let Z=this.cancelres;this.cancelres=null,Z()}let W=this.parentobj.state;if(W==="closed"||W==="failed")BJ("no parent cleanup for fin as parent was closed or failed");else this.parentobj.removeReceiveStream(this.readable,this.readableController);if(!this.readableclosed)this.readableController.close(),this.readableclosed=!0}return K}updateSendOrderAndGroup(){this.objint.updateSendOrderAndGroup({sendOrder:this._sendOrder,sendGroupId:this._sendGroup._sendGroupId})}onStreamRecvSignal(J){BJ("callback",J?.nettask),BJ.trace("onStreamRecvSignal",J);let $=!0,X=this.parentobj.state;if(X==="closed"||X==="failed")BJ("no parent cleanup as parent was closed or failed"),$=!1;switch(J.nettask){case"resetStream":if(this.readable){if(this.finalDrain(),$)this.parentobj.removeReceiveStream(this.readable,this.readableController);if(!this.readableclosed)this.readableclosed=!0,this.readableController.error(new O9("Resetstream with code:"+(J.code||0)))}else BJ.error("resetStream without readable");break;case"stopSending":if(this.writable){if($)this.parentobj.removeSendStream(this.writable,this.writableController);if(!this.writableclosed)this.writableclosed=!0,this.writableController.error(new O9("StopSending with code:"+(J.code||0)))}else BJ.error("stopSending without writable");break;default:BJ.error("unhandled onStreamRecvSignal")}if(this.pendingoperation){let Y=this.pendingres;if(this.pendingoperation=null,this.pendingres=null,Y!=null)Y()}if(this.pendingoperationRead){let Y=this.pendingresRead;if(this.pendingoperationRead=null,this.pendingresRead=null,Y!=null)Y()}}finalDrain(){this.finaldrain_=!0,this.objint.drainReads()}onStreamWrite(J){if(this.pendingoperation){let $=this.pendingres;if(this.pendingoperation=null,this.pendingres=null,$!=null)$()}}onStreamNetworkFinish(J){switch(BJ("callback",J?.nettask),BJ.trace("networkfinish args",J),J.nettask){case"stopSending":if(this.cancelres){let $=this.cancelres;this.cancelres=null,$()}this.stopSendingRecv=!0;break;case"resetStream":if(this.abortres){let $=this.abortres;if(this.abortres=null,$(),this.readable)this.parentobj.removeReceiveStream(this.readable,this.readableController);if(this.writable)this.parentobj.removeSendStream(this.writable,this.writableController);this.readableclosed=!0,this.parentobj.removeStreamObj(this)}break;case"streamFinal":if(this.pendingoperation){let $=this.pendingres;if(this.pendingoperation=null,this.pendingres=null,$!=null)$()}break;default:BJ.error("onStreamNetworkFinish unknown task",J.nettask)}}}var lR1=typeof process<"u"?process.pid:0,OB=G6(`webtransport:httpwtsession(${lR1})`);class KT{constructor(J){if(J.object){if(this.objint=J.object,this.objint.jsobj=this,this.objint.sendInitialParameters)this.objint.sendInitialParameters()}this.parentobj=J.parentobj,this.state="connecting",this.readyResolve=null,this.closeHook=null,this.header=J.header,this.userData=J.userData,this.peerAddress_=J.peerAddress,this.datagramsReadableMode_=J.datagramsReadableMode,this.ready=new Promise((X,Y)=>{this.readyResolve=X,this.readyReject=Y}),this.reliability="pending",this.congestionControl="default",this.closed=new Promise((X,Y)=>{this.closedResolve=X,this.closedReject=Y}),this.draining=new Promise((X,Y)=>{this.drainingResolve=X,this.drainingReject=Y}),this.incomingBidirectionalStreams=new Lz({start:(X)=>{this.incomBiDiController=X}}),this.incomingUnidirectionalStreams=new Lz({start:(X)=>{this.incomUniDiController=X}}),this.incomDatagramControllerBytes_=void 0,this.incomDatagramController_=void 0;let $={start:(X)=>{if(this.datagramsReadableMode_==="bytes")this.incomDatagramControllerBytes_=X;else this.incomDatagramController_=X},type:void 0};if(this.datagramsReadableMode_==="bytes")$.type="bytes";if(!QT)delete $.type;this._lastGetMaxDatagramSize=0,this.datagrams={readable:new Lz($),createWritable:(X)=>{let Y=X?.sendOrder??0n,Q=X?.sendGroup,K=new XT({start:(W)=>{this.outgoDatagramController=W},write:(W,Z)=>{if(this.state==="closed")throw Error("Session is closed");if(W instanceof Uint8Array){if(this.objint==null)throw Error("this.objint is not set");let{code:G,message:V}=this.objint.writeDatagram(W);if(G!=="success"&&G!=="blocked"&&G!=="tooBig")throw new O9(G+":"+V)}else throw Error("chunk is not of type Uint8Array")},close:()=>{}});return Object.defineProperties(K,{sendOrder:{get:()=>{return Y},set:(W)=>{Y=W}},sendGroup:{get:()=>{return Q},set:(W)=>{if(W!==Q)Q=W}}}),K},get writable(){if(!this.datagramwritablepolyfilled_)console.warn("datagrams.writable is deprecated");return this.datagramwritablepolyfilled_||=this.createWritable()},get maxDatagramSize(){return this._getMaxDatagramSize()},_getMaxDatagramSize:()=>{if(this.objint)this._lastGetMaxDatagramSize=this.objint.getMaxDatagramSize();return this._lastGetMaxDatagramSize}},this.resolveBiDi=[],this.resolveUniDi=[],this.rejectBiDi=[],this.rejectUniDi=[],this.resolveSessionStats=[],this.rejectSessionStats=[],this.resolveDatagramStats=[],this.rejectDatagramStats=[],this.sendStreams=new Set,this.receiveStreams=new Set,this.streamObjs=new Set,this.sendStreamsController=new Set,this.receiveStreamsController=new Set,this._sendGroupNum=1n,this._sendGroupIndex=new Map,this._selectedProtocol=void 0}setSessionObj(J,$){if(J){if(this.objint=J,this.objint.jsobj=this,this.reliable=!!$,this.objint.sendInitialParameters)this.objint.sendInitialParameters()}}get protocol(){return this._selectedProtocol}getStats(){if(this.objint==null)throw Error("this.objint not set");let J=new Promise(($,X)=>{this.resolveSessionStats.push($),this.rejectSessionStats.push(X)});return this.objint.orderSessionStats(),J}onSessionStats({timestamp:J,expiredOutgoing:$=BigInt(0),lostOutgoing:X=BigInt(0),minRtt:Y=0,smoothedRtt:Q=0,rttVariation:K=0,estimatedSendRateBps:W}){let Z=this.resolveSessionStats.pop();if(this.rejectSessionStats.pop(),Z)Z({timestamp:J,bytesSent:BigInt(0),packetsSent:BigInt(0),packetsLost:BigInt(0),numOutgoingStreamsCreated:0,numIncomingStreamsCreated:0,bytesReceived:BigInt(0),packetsReceived:BigInt(0),smoothedRtt:Q,rttVariation:K,minRtt:Y,estimatedSendRate:W,datagrams:{timestamp:J,expiredOutgoing:$,droppedIncoming:BigInt(0),lostOutgoing:X}})}onDatagramStats({timestamp:J,expiredOutgoing:$=BigInt(0),lostOutgoing:X=BigInt(0)}){let Y=this.resolveDatagramStats.pop();if(this.rejectDatagramStats.pop(),Y)Y({timestamp:J,expiredOutgoing:$,droppedIncoming:BigInt(0),lostOutgoing:X})}notifySessionDraining(){if(this.objint==null)throw Error("this.objint not set");this.objint.notifySessionDraining()}addStreamObj(J){this.streamObjs.add(J)}removeStreamObj(J){this.streamObjs.delete(J)}addSendStream(J,$){this.sendStreams.add(J),this.sendStreamsController.add($)}removeSendStream(J,$){this.sendStreams.delete(J),this.sendStreamsController.delete($)}addReceiveStream(J,$){this.receiveStreams.add(J),this.receiveStreamsController.add($)}removeReceiveStream(J,$){this.receiveStreams.delete(J),this.receiveStreamsController.delete($)}createBidirectionalStream(J){if(this.objint==null)throw Error("this.objint not set");let $=new Promise((Y,Q)=>{this.resolveBiDi.push(Y),this.rejectBiDi.push(Q)});if(!this.objint.orderBidiStream({sendGroup:J?.sendGroup||null,sendOrder:BigInt(J?.sendOrder||0n),waitUntilAvailable:J?.waitUntilAvailable||!1})){let Y=this.rejectBiDi.pop();if(this.resolveBiDi.pop(),Y)Y(new DOMException("No streams available","QuotaExceededError"))}return $}createUnidirectionalStream(J){if(this.objint==null)throw Error("this.objint not set");let $=new Promise((Y,Q)=>{this.resolveUniDi.push(Y),this.rejectUniDi.push(Q)});if(!this.objint.orderUnidiStream({sendGroup:J?.sendGroup||null,sendOrder:J?.sendOrder||0n,waitUntilAvailable:J?.waitUntilAvailable||!1})){let Y=this.rejectUniDi.pop();if(this.resolveUniDi.pop(),Y)Y(new DOMException("No streams available","QuotaExceededError"))}return $}close(J){if(OB("closeinfo",J),this.state==="closed"||this.state==="failed")return;if(this.objint)this.objint.close({code:J?.closeCode??0,reason:J?.reason.substring(0,1023)??""})}createSendGroup(){if(this.state==="closed"||this.state==="failed")throw Error("InvalidState");let J=this._sendGroupNum++,$={_sendGroupId:J,getStats:async()=>{return{bytesWritten:0n,bytesSent:0n,bytesAcknowledged:0n}}};return this._sendGroupIndex.set(J,$),$}onReady({protocol:J}){if(J)this._selectedProtocol=J;if(this.state="connected",!this.reliable)this.reliability="supports-unreliable";else this.reliability="reliable-only";if(this.readyResolve)this.readyResolve();delete this.readyResolve}onClose(J){if(delete this.objint,this.state!=="connected"){if(OB.error('session was closed before state was "connected" - it was "%s"',this.state),this.state="failed",this.closeHook)this.closeHook(),delete this.closeHook;let Y=new O9("Opening handshake failed.");this.readyReject(Y),this.closedReject(Y);return}OB("onClose"),this.streamObjs.forEach((Y)=>Y.finalDrain());let $=new O9("Session closed");for(let Y of this.rejectBiDi)Y($);for(let Y of this.rejectUniDi)Y($);for(let Y of this.rejectSessionStats)Y($);for(let Y of this.rejectDatagramStats)Y($);this.resolveBiDi=[],this.resolveUniDi=[],this.rejectBiDi=[],this.rejectUniDi=[],this.resolveSessionStats=[],this.rejectSessionStats=[],this.resolveDatagramStats=[],this.rejectDatagramStats=[],this.incomBiDiController.close(),this.incomUniDiController.close(),(this.incomDatagramController_||this.incomDatagramControllerBytes_).close(),this.state="closed";let X=new O9(`Session closed (on process ${lR1}) with code `+J.errorcode+" and reason "+J.error);if(this.sendStreamsController.forEach((Y)=>Y.error(X)),this.receiveStreamsController.forEach((Y)=>Y.error(X)),this.streamObjs.forEach((Y)=>Y.readableclosed=!0),this.sendStreams.clear(),this.receiveStreams.clear(),this.sendStreamsController.clear(),this.receiveStreamsController.clear(),this.streamObjs.clear(),this.closedResolve)this.closedResolve({closeCode:J.errorcode,reason:J.error?J.error:""});if(this.closeHook)this.closeHook(),delete this.closeHook}onStream(J){let $=new An({object:J.stream,parentobj:this,transport:this.parentobj,bidirectional:J.bidirectional,incoming:J.incoming,sendGroup:this._sendGroupIndex.get(J.sendGroupId||0n),sendOrder:J.sendOrder});if(this.addStreamObj($),J.incoming)if(J.bidirectional)this.incomBiDiController.enqueue($);else this.incomUniDiController.enqueue($.readable);else if(J.bidirectional){if(this.resolveBiDi.length===0)throw Error("Got bidirectional stream without asking for it");this.rejectBiDi.shift();let X=this.resolveBiDi.shift();if(X!=null&&$.readable!=null&&$.writable!=null)X({readable:$.readable,writable:$.writable})}else{if(this.resolveUniDi.length===0)throw Error("Got unidirectional stream without asking for it");this.rejectUniDi.shift();let X=this.resolveUniDi.shift();if(X!=null&&$.writable!=null)X($.writable)}}onDatagramReceived(J){if(OB("datagram received",J.datagram),J.datagram.byteLength===0&&this.datagramsReadableMode_==="bytes"){OB("zerolength datagram dropped for a byte stream");return}if(this.incomDatagramControllerBytes_?.byobRequest){let $=this.incomDatagramControllerBytes_.byobRequest,X=$?.view;if(!(X instanceof Uint8Array))throw Error("byob view is not a Uint8Array");if(X.byteLength<J.datagram.byteLength)throw Error("supplied view is not large enough.");new Uint8Array(X.buffer,0+X.byteOffset,J.datagram.byteLength).set(J.datagram),$.respond(J.datagram.byteLength)}else(this.incomDatagramController_||this.incomDatagramControllerBytes_).enqueue(new Uint8Array(J.datagram))}onGoAwayReceived(J){if(this.drainingResolve)this.drainingResolve(void 0);this.state="draining"}get peerAddress(){return this.peerAddress_}}var bT6=typeof process<"u"?process.pid:0,z4=G6(`webtransport:flowcontroller(${bT6})`);class wz{static kSessionFlowControlMultiplier=1.5;constructor({tocontrol:J,sendWindowOffset:$,receiveWindowOffset:X,receiveWindowSizeLimit:Y,shouldAutoTuneReceiveWindow:Q,sessionFlowController:K}){this.tocontrol=J,this.bytesSent=0n,this.sendWindowOffset=BigInt($),this.bytesConsumed=0n,this.highestReceivedByteOffset=0n,this.receiveWindowOffset=BigInt(X),this.receiveWindowSize=BigInt(X),this.receiveWindowSizeLimit=BigInt(Y),this.autoTuneReceiveWindow=Q,this.sessionFlowController=K,this.lastBlockedSendWindowOffset=0n,this.prevWindowUpdateTime=void 0,z4("Created flow controller , setting initial receive window offset to: "+this.receiveWindowOffset+", max receive window to: "+this.receiveWindowSize+", max receive window limit to: "+this.receiveWindowSizeLimit+", setting send window offset to: "+this.sendWindowOffset)}addBytesConsumed(J){this.bytesConsumed+=BigInt(J),z4(" consumed "+J+" bytes."),this.maybeSendWindowUpdate()}updateHighestReceivedOffset(J){return z4(" highest byte offset increased from "+this.highestReceivedByteOffset," to ",this.highestReceivedByteOffset+BigInt(J)),this.highestReceivedByteOffset+=BigInt(J),!0}addBytesSent(J){let $=BigInt(J);if(this.bytesSent+$>this.sendWindowOffset){z4(" Trying to send an extra "+$+" bytes, when bytes_sent = "+this.bytesSent+", and send_window_offset_ = "+this.sendWindowOffset),this.bytesSent=this.sendWindowOffset,this.tocontrol.closeConnection({code:63,reason:this.sendWindowOffset-(this.bytesSent+$)+"bytes over send window offset"});return}this.bytesSent+=$,z4(" sent "+$+" bytes.")}flowControlViolation(){if(this.highestReceivedByteOffset>this.receiveWindowOffset)return z4("Flow control violation on , receive window offset: "+this.receiveWindowOffset+", highest received byte offset: "+this.highestReceivedByteOffset),!0;return!1}maybeIncreaseMaxWindowSize(){let J=Date.now(),$=this.prevWindowUpdateTime;if(this.prevWindowUpdateTime=J,!$){z4("first window update for ");return}if(!this.autoTuneReceiveWindow)return;let X=this.tocontrol.smoothedRtt();if(X===0){z4("rtt zero for ");return}let Y=J-$,Q=2*X;if(Y>=Q)return;let K=this.receiveWindowSize;if(this.increaseWindowSize(),this.receiveWindowSize>K){if(z4("New max window increase for NaN"+Y+" us, and RTT is "+X+"us. max wndw: "+this.receiveWindowSize),this.sessionFlowController!==void 0)this.sessionFlowController.ensureWindowAtLeast(BigInt(wz.kSessionFlowControlMultiplier*Number(this.receiveWindowSize)))}else z4("Max window at limit for after "+Y+" us, and RTT is "+X+"us. Limit size: "+this.receiveWindowSize)}increaseWindowSize(){this.receiveWindowSize*=2n,this.receiveWindowSize=this.receiveWindowSize>this.receiveWindowSizeLimit?this.receiveWindowSizeLimit:this.receiveWindowSize}windowUpdateThreshold(){return this.receiveWindowSize/2n}maybeSendWindowUpdate(){if(!this.tocontrol.connected())return;let J=this.receiveWindowOffset-this.bytesConsumed,$=this.windowUpdateThreshold();if(!this.prevWindowUpdateTime)this.prevWindowUpdateTime=Date.now();if(J>=$){z4("Not sending WindowUpdate for , available window: "+J+" >= threshold: "+$);return}this.maybeIncreaseMaxWindowSize(),this.updateReceiveWindowOffsetAndSendWindowUpdate(J)}updateReceiveWindowOffsetAndSendWindowUpdate(J){this.receiveWindowOffset+=this.receiveWindowSize-J,z4("Sending WindowUpdate frame for , consumed bytes: "+this.bytesConsumed+", available window: "+J+", and threshold: "+this.windowUpdateThreshold()+", and receive window size: "+this.receiveWindowSize+". New receive window offset is: "+this.receiveWindowOffset),this.sendWindowUpdate()}maybeSendBlocked(){if(this.sendWindowSize()!==0n||this.lastBlockedSendWindowOffset>=this.sendWindowOffset)return;z4(" is flow control blocked. Send window: "+this.sendWindowSize()+", bytes sent: "+this.bytesSent+", send limit: "+this.sendWindowOffset),this.lastBlockedSendWindowOffset=this.sendWindowOffset,this.tocontrol.sendBlocked(this.lastBlockedSendWindowOffset)}updateSendWindowOffset(J){if(J<=this.sendWindowOffset)return!1;z4("UpdateSendWindowOffset for with new offset "+J+" current offset: "+this.sendWindowOffset+" bytes_sent: "+this.bytesSent);let $=this.isBlocked();return this.sendWindowOffset=J,$}ensureWindowAtLeast(J){if(this.receiveWindowSizeLimit>=J)return;let $=this.receiveWindowOffset-this.bytesConsumed;this.increaseWindowSize(),this.updateReceiveWindowOffsetAndSendWindowUpdate($)}isBlocked(){return this.sendWindowSize()===0n}sendWindowSize(){if(this.bytesSent>this.sendWindowOffset)return 0n;return this.sendWindowOffset-this.bytesSent}updateReceiveWindowSize(J){if(z4("UpdateReceiveWindowSize for : "+J),this.receiveWindowSize!==this.receiveWindowOffset){z4("receive_window_size_:"+this.receiveWindowSize+" != receive_window_offset:"+this.receiveWindowOffset);return}this.receiveWindowSize=J,this.receiveWindowOffset=J}sendWindowUpdate(){this.tocontrol.sendWindowUpdate(this.receiveWindowOffset)}}var mT6=typeof process<"u"?process.pid:0,dR1=G6(`webtransport:http2webtransportstream(${mT6})`),WT=(J)=>setTimeout(J,0);if(typeof process<"u")WT=process.nextTick;class _n{constructor({streamid:J,unidirectional:$,incoming:X,capsuleParser:Y,sendWindowOffset:Q,receiveWindowOffset:K,shouldAutoTuneReceiveWindow:W,receiveWindowSizeLimit:Z,sessionFlowController:G,streamIdManager:V}){if(this.jsobj=void 0,this.streamid=J,this.incomdata=[],this.capsuleParser=Y,this.outgochunks=[],this.flowController=new wz({tocontrol:this,sendWindowOffset:Q,receiveWindowOffset:K,shouldAutoTuneReceiveWindow:W,receiveWindowSizeLimit:Z,sessionFlowController:G}),this.sessionFlowController=G,this.streamIdManager=V,this.final=!1,this.finalmessagesend=!1,this.stopReading_=!0,this.drainReads_=!0,this.recvBytes=0,this.outgoingClosed_=!1,this.incomingClosed_=!1,$)if(X)this.outgoingClosed_=!0;else this.incomingClosed_=!0}sendInitialParameters(){this.flowController.sendWindowUpdate()}recvData({data:J,fin:$}){if(this.incomdata.push({data:J,fin:$}),J&&J?.byteLength>0){let X=this.flowController.updateHighestReceivedOffset(J?.byteLength);if(this.sessionFlowController.updateHighestReceivedOffset(J?.byteLength)&&X){if(this.flowController.flowControlViolation()||this.sessionFlowController.flowControlViolation()){this.closeConnection({code:63,reason:"Flow control violation after increasing offset"});return}}}if(this.processRead(),this.incomdata.length>0){if(!this.stopReading_)this.processRead()}}processRead(){if(!this.jsobj)return;let J,$=0;while(this.incomdata.length>0&&(!this.stopReading_||this.drainReads_)){if(!J){if(this.incomdata.reduce((Q,K)=>Q+(K&&K.data?.byteLength||0),0)>0)J=this.jsobj.getReadBuffer({byteSize:this.incomdata.reduce((Q,K)=>Q+(K&&K.data?.byteLength||0),0)}),J.readBytes=0,$=0}let X=this.incomdata.shift();if(X?.data&&X.data.byteLength>0&&J&&J.buffer){let Y=Math.min(J.buffer.byteLength-$,X.data.byteLength),Q=new Uint8Array(X.data.buffer,X.data.byteOffset,Y);if(new Uint8Array(J.buffer.buffer,$,Y).set(Q),$+=Y,J.readBytes+=Y,J.drained=!0,X.data.byteLength!==Y)J.drained=!1,this.incomdata.unshift({data:new Uint8Array(X.data.buffer,X.data.byteOffset+Y,X.data.byteLength-Y),fin:X.fin}),J.fin=!1;else J.fin||=X.fin;if(this.incomdata.length>0)J.drained=!1;if($===J.buffer.byteLength||this.incomdata.length===0){this.flowController.addBytesConsumed(J.readBytes||0),this.sessionFlowController.addBytesConsumed(J.readBytes||0);let{stopReading:W}=this.jsobj.commitReadBuffer(J);if(W)this.stopReading_=!0;J=void 0,$=0}this.recvBytes+=Y}else if(X?.fin)this.jsobj.commitReadBuffer({fin:!0})}}startReading(){this.stopReading_=!1,this.processRead()}drainReads(){this.drainReads_=!0,this.stopReading_=!1,this.processRead()}stopReading(){this.stopReading_=!0}onStreamSignal(J){switch(J){case"resetStream":this.closeIncoming();break;case"stopSending":this.closeOutgoing();break}}closeIncoming(){if(this.incomingClosed_=!0,this.outgoingClosed_)this.onClose()}closeOutgoing(){if(this.outgoingClosed_=!0,this.incomingClosed_)this.onClose()}onClose(){this.streamIdManager.onStreamClosed(this.streamid)}stopSending(J){this.closeIncoming(),this.capsuleParser.writeCapsule({type:x1.WT_STOP_SENDING,headerVints:[this.streamid,J],payload:void 0}),WT(()=>this.jsobj.onStreamNetworkFinish({nettask:"stopSending"}))}onFin(){this.closeIncoming()}resetStream(J){this.closeOutgoing(),this.capsuleParser.writeCapsule({type:x1.WT_RESET_STREAM,headerVints:[this.streamid,J],payload:void 0}),WT(()=>this.jsobj.onStreamNetworkFinish({nettask:"resetStream"}))}writeChunk(J){this.outgochunks.push({buf:J,fin:!1}),this.capsuleParser.scheduler.Schedule(this.streamid),this.capsuleParser.scheduleDrainWrites()}hasPendingData(){return this.outgochunks.length>0}drainWrites(){let J=!1;while(this.outgochunks.length>0&&(!this.capsuleParser.blocked||this.final||!this.capsuleParser.shouldYieldStream(this.streamid))&&this.flowController.sendWindowSize()>0n&&this.sessionFlowController.sendWindowSize()>0n){let $=this.outgochunks.shift(),X=!0;if($){let Y=$.buf;if(Y){if(Y.byteLength===0&&!$.fin)throw new O9("Trying to send zero length capsule without a fin");let Q=this.sessionFlowController.sendWindowSize(),K=this.flowController.sendWindowSize();if(Y?.byteLength>K||Y?.byteLength>Q){let W=Q>K?Number(K):Number(Q);{let Z=new Uint8Array(Y.buffer,Y.byteOffset+W,Y.byteLength-W),G=new Uint8Array(Y.byteLength-W);G.set(Z),this.outgochunks.unshift({fin:$.fin,buf:G}),X=!1}$.fin=!1,Y=$.buf=new Uint8Array(Y.buffer,Y.byteOffset,W)}}if(this.capsuleParser.writeCapsule({type:$?.fin?x1.WT_STREAM_WFIN:x1.WT_STREAM_WOFIN,headerVints:[this.streamid],payload:Y}),J||=!!$?.fin,Y)this.flowController.addBytesSent(Y?.byteLength),this.sessionFlowController.addBytesSent(Y?.byteLength)}if(X)this.jsobj.onStreamWrite({success:!0})}if(J){this.capsuleParser.removeStream(this.streamid);return}if(!(!this.capsuleParser.blocked||this.final||!this.capsuleParser.shouldYieldStream(this.streamid))&&this.outgochunks.length>0)this.capsuleParser.scheduleDrainWriteStream(this.streamid);if(this.final&&this.outgochunks.length===0&&!this.finalmessagesend)WT(()=>{this.jsobj.onStreamNetworkFinish({nettask:"streamFinal"})}),this.finalmessagesend=!0}streamFinal(){this.final=!0,this.outgochunks.push({fin:!0}),this.capsuleParser.scheduleDrainWriteStream(this.streamid),this.capsuleParser.scheduleDrainWrites()}updateSendOrderAndGroup({sendOrder:J,sendGroupId:$}){this.capsuleParser.streamUpdateSendOrderAndGroup(this.streamid,{sendOrder:J,sendGroupId:$})}sendWindowUpdate(J){dR1("sendwindow offset stream:",J),this.capsuleParser.writeCapsule({type:x1.WT_MAX_STREAM_DATA,headerVints:[this.streamid,J],payload:void 0})}sendBlocked(J){this.capsuleParser.writeCapsule({type:x1.WT_STREAM_DATA_BLOCKED,headerVints:[this.streamid,J],payload:void 0})}reportBlocked(J){dR1("Stream id: ",this.streamid," was blocked at:",J)}connected(){return this.jsobj.parentobj.state==="connected"}closeConnection({code:J,reason:$}){if(this.jsobj.parentobj?.objint)this.jsobj.parentobj.objint.closeConnection({code:J,reason:$})}smoothedRtt(){if(this.jsobj.parentobj?.objint)return this.jsobj.parentobj.objint.smoothedRtt()}}function DB(J){return J.toString()}function D5(J){return J.toString()}class nR1{constructor(J){this.priority=J,this.currentSequenceNumber=void 0}scheduled(){return typeof this.currentSequenceNumber<"u"}}function uT6(J,$){if(J.priority>$.priority)return-1;else if(J.priority===$.priority)if(J.sequenceNumber>$.sequenceNumber)return-1;else if(J.sequenceNumber===$.sequenceNumber)return 0;else return 1;else return 1}function iR1(J,$){return uT6(J.scheduleKey,$.scheduleKey)}class xB{constructor(){this.streams_={},this.schedule_=[],this.currentWriteSequenceNumber_=0}HasRegistered(){return Object.keys(this.streams_).length!==0}HasScheduled(){return Object.keys(this.schedule_).length!==0}NumScheduled(){return Object.keys(this.schedule_).length}NumRegistered(){return Object.keys(this.streams_).length}NumScheduledInPriorityRange(J,$){let X=typeof $<"u"?this.schedule_.findIndex((Q)=>Q.scheduleKey.priority<=$):0;return(typeof J<"u"?this.schedule_.findIndex((Q)=>Q.scheduleKey.priority>=J):this.schedule_.length)-X}ShouldYield(J){let $=this.streams_[D5(J)];if(!$)throw Error("ID not registered");if(this.schedule_.length===0)return!1;let X=this.schedule_[0];if(xB.StreamId(X)==J)return!1;return X.scheduleKey.priority>=$.priority}GetPriorityFor(J){let $=this.streams_[D5(J)];if(!$)return;return $.priority}PopFront(){if(this.schedule_.length===0)return;let J=this.schedule_[0];J.fullStreamEntry.streamEntry.currentSequenceNumber=void 0;let $=xB.StreamId(J);return this.schedule_.shift(),$}Register(J,$){if(this.streams_[D5(J)])throw Error("ID already registered");this.streams_[D5(J)]=new nR1($.sendOrder)}Unregister(J){let $=this.streams_[D5(J)];if(!$)throw Error("Stream not registered");if($.scheduled())this.DescheduleStream($);delete this.streams_[D5(J)]}UpdatePriority(J,$){let X=this.streams_[D5(J)];if(!X)return Error("ID not registered");let Y;if(X.scheduled())Y=this.DescheduleStream(X).scheduleKey.sequenceNumber;if(X.priority=$,Y)this.schedule_.push({scheduleKey:{priority:X.priority,sequenceNumber:Y},fullStreamEntry:{iD:J,streamEntry:X}}),this.schedule_.sort(iR1)}Schedule(J){let $=this.streams_[D5(J)];if(!$)return Error("ID not registered");if($.scheduled())return;let X={scheduleKey:{priority:$.priority,sequenceNumber:--this.currentWriteSequenceNumber_},fullStreamEntry:{iD:J,streamEntry:$}};this.schedule_.push(X),this.schedule_.sort(iR1),$.currentSequenceNumber=X.scheduleKey.sequenceNumber}Deschedule(J){let $=this.streams_[D5(J)];if(!$)throw Error("Stream not registered");if(!$.scheduled())throw Error("Stream not scheduled");this.DescheduleStream($),$.currentSequenceNumber=void 0}IsScheduled(J){let $=this.streams_[D5(J)];if(!$)return!1;return $.scheduled()}static StreamId(J){return J.fullStreamEntry.iD}DescheduleStream(J){let $=this.schedule_.findIndex((Y)=>J.priority===Y.scheduleKey.priority&&J.currentSequenceNumber===Y.fullStreamEntry.streamEntry.currentSequenceNumber);if($===-1)throw Error("Calling DescheduleStream() on an entry that is not in the schedule at the expected key.");let X=this.schedule_[$];return this.schedule_.splice($,1),X}}class cn{constructor(){this.activeGroups_=new xB,this.perGroupSchedulers_={},this.streamToGroupMap_={}}HasRegistered(){return this.activeGroups_.HasRegistered()}HasScheduled(){return this.activeGroups_.HasScheduled()}NumScheduled(){let J=0;for(let[,$]of Object.entries(this.perGroupSchedulers_))J+=$.NumScheduled();return J}Register(J,$){if(this.streamToGroupMap_[D5(J)])throw Error("Provided stream ID already registered");if(!this.perGroupSchedulers_[DB($.sendGroupId)])this.perGroupSchedulers_[DB($.sendGroupId)]=new xB,this.activeGroups_.Register($.sendGroupId,$);let X=this.perGroupSchedulers_[DB($.sendGroupId)];this.streamToGroupMap_[D5(J)]={sendGroupId:$.sendGroupId,perGroupScheduler:X},X.Register(J,$)}Unregister(J){let $=this.streamToGroupMap_[D5(J)];if(!$)throw Error("Stream ID not registered");let{sendGroupId:X,perGroupScheduler:Y}=$;if(delete this.streamToGroupMap_[D5(J)],Y.Unregister(J),!Y.HasRegistered())delete this.perGroupSchedulers_[DB(X)],this.activeGroups_.Unregister(X)}UpdateSendOrder(J,$){let X=this.SchedulerForStream(J);if(!X)throw Error("Stream ID not registered");return X.UpdatePriority(J,$)}UpdateSendGroup(J,$){let X=this.SchedulerForStream(J);if(!X)throw Error("Stream ID not registered");let Y=X.IsScheduled(J),Q=X.GetPriorityFor(J);if(!Q)throw Error("Stream registered at the top level scheduler, but not at the per-group one");if(this.Unregister(J),this.Register(J,{sendGroupId:$,sendOrder:Q}),Y)this.Schedule(J)}ShouldYield(J){let $=this.streamToGroupMap_[D5(J)];if(!$)throw Error("Stream ID not registered");let{sendGroupId:X,perGroupScheduler:Y}=$;if(this.activeGroups_.ShouldYield(X))return!0;return Y.ShouldYield(J)}GetPriorityFor(J){let $=this.streamToGroupMap_[D5(J)];if(!$)return null;let{sendGroupId:X,perGroupScheduler:Y}=$,Q=Y.GetPriorityFor(J);if(!Q)return null;return{sendGroupId:X,sendOrder:Q}}PopFront(){let J=this.activeGroups_.PopFront();if(typeof J>"u")return;let $=this.perGroupSchedulers_[DB(J)];if(!$)throw Error("Scheduled a group with no per-group scheduler attached");let X=$.PopFront();if(typeof X>"u")return;if($.HasScheduled())this.activeGroups_.Schedule(J);return X}Schedule(J){let $=this.streamToGroupMap_[D5(J)];if(!$)return Error("Stream ID not registered");let{sendGroupId:X,perGroupScheduler:Y}=$;return this.activeGroups_.Schedule(X),Y.Schedule(J)}IsScheduled(J){let $=this.SchedulerForStream(J);if(!$)return!1;return $.IsScheduled(J)}SchedulerForStream(J){let $=this.streamToGroupMap_[D5(J)];if(!$)return;return $.perGroupScheduler}}var gT6=typeof process<"u"?process.pid:0,hn=G6(`webtransport:parserbase(${gT6})`);function P3(J){if(BigInt(J)<64n)return 1;if(BigInt(J)<16384n)return 2;if(BigInt(J)<1073741824n)return 4;return 8}class x1{static PADDING=420171064;static WT_RESET_STREAM=420171065;static WT_STOP_SENDING=420171066;static WT_STREAM_WOFIN=420171067;static WT_STREAM_WFIN=420171068;static WT_MAX_DATA=420171069;static WT_MAX_STREAM_DATA=420171070;static WT_MAX_STREAMS_BIDI=420171071;static WT_MAX_STREAMS_UNIDI=420171072;static WT_DATA_BLOCKED=420171073;static WT_STREAM_DATA_BLOCKED=420171074;static WT_STREAMS_BLOCKED_UNIDI=420171075;static WT_STREAMS_BLOCKED_BIDI=420171076;static WT_CLOSE_SESSION=10307;static WT_DRAIN_SESSION=30894;static DATAGRAM=0;constructor({nativesession:J,isclient:$,initialStreamSendWindowOffsetBidi:X,initialStreamSendWindowOffsetUnidi:Y,initialStreamReceiveWindowOffset:Q,streamShouldAutoTuneReceiveWindow:K,streamReceiveWindowSizeLimit:W}){this.session=J,this.isclient=$,this.blocked=!1,this.initialStreamSendWindowOffsetUnidi=Y,this.initialStreamSendWindowOffsetBidi=X,this.initialStreamReceiveWindowOffset=Q,this.streamShouldAutoTuneReceiveWindow=K,this.streamReceiveWindowSizeLimit=W,this.wtstreams=new Map,this.scheduler=new cn}parseData(J){throw Error("Implement parseData in derived Class")}writeCapsule({type:J,headerVints:$,payload:X,end:Y}){throw Error("Implement writeCapsule in derived Class")}initialParametersMandatory(){throw Error("Implement initialParametersMandatory in derived Class")}sendClose({code:J,reason:$}){let Y=new TextEncoder().encode("AAAA"+$);Y[0]=J>>24&255,Y[1]=J>>16&255,Y[2]=J>>8&255,Y[3]=J&255,this.writeCapsule({type:x1.WT_CLOSE_SESSION,headerVints:[],payload:Y,end:()=>{this.closeHttp2Stream(J)}})}newStream(J,$){let X=this.isclient?!(J&0x1n):!!(J&0x1n),Y=J&0x2n?this.session.streamIdMngrUni:this.session.streamIdMngrBi;if(X){let W=Y.maybeIncreaseLargestPeerStreamId(J);if(W.error){this.session.closeConnection({code:20,reason:W.error});return}}let Q=!!(J&0x2n),K=new _n({streamid:J,unidirectional:Q,incoming:X,capsuleParser:this,sendWindowOffset:Q?this.initialStreamSendWindowOffsetUnidi:this.initialStreamSendWindowOffsetBidi,receiveWindowOffset:this.initialStreamReceiveWindowOffset,shouldAutoTuneReceiveWindow:this.streamShouldAutoTuneReceiveWindow,receiveWindowSizeLimit:this.streamReceiveWindowSizeLimit,sessionFlowController:this.session.flowController,streamIdManager:Y});return this.wtstreams.set(J,K),this.scheduler.Register(J,$),this.session.jsobj.onStream({bidirectional:!(J&0x2n),incoming:X,stream:K,sendGroupId:$.sendGroupId,sendOrder:$.sendOrder}),K}scheduleDrainWrites(){if(this._scheduledDrainWriteCall)return;let J=Promise.resolve();this._scheduledDrainWriteCall=J,J.then(()=>{delete this._scheduledDrainWriteCall,this.drainWrites()}).catch(($)=>hn("Error in drainWrites",$))}drainWrites(){if(!this.blocked)this.session.drainWrites();while(!this.blocked){let J=this.scheduler.PopFront();if(typeof J>"u")break;let $=this.wtstreams.get(J);if(!$)break;$.drainWrites()}}onMaxData(J){if(J&&this.session.flowController.updateSendWindowOffset(J)){let $=!1;if(this.wtstreams.forEach((X,Y)=>{if(X.hasPendingData())$=!0,this.scheduleDrainWriteStream(Y)}),$)this.drainWrites()}}onMaxStreamData(J,$){let X=this.wtstreams.get(J);if(X&&$){if(X.flowController.updateSendWindowOffset($))this.scheduleDrainWriteStream(J),this.drainWrites()}}onMaxStreamUniDi(J){if(typeof J>"u")return;this.session.streamIdMngrUni.maybeAllowNewOutgoingStreams(J),this.session.trySendingUnidirectionalStreams()}onMaxStreamBiDi(J){if(typeof J>"u")return;this.session.streamIdMngrBi.maybeAllowNewOutgoingStreams(J),this.session.trySendingBidirectionalStreams()}onDataBlocked(J){hn("Session received blocked frame "+J)}onStreamDataBlocked(J,$){hn("Stream "+J+" received blocked frame "+$)}onStreamsBlockedBidi(J){if(typeof J>"u")return;let $=this.session.streamIdMngrBi.onStreamsBlockedFrame(J);if($.error)this.session.closeConnection({code:105,reason:$.error})}onStreamsBlockedUnidi(J){if(typeof J>"u")return;let $=this.session.streamIdMngrUni.onStreamsBlockedFrame(J);if($.error)this.session.closeConnection({code:105,reason:$.error})}onCloseWebTransportSession({code:J,reason:$}){this.session.jsobj.onClose({errorcode:J,error:$}),this.closeHttp2Stream(J)}onDrain(){this.session.jsobj.onGoAwayReceived()}shouldYieldStream(J){return this.scheduler.ShouldYield(J)}scheduleDrainWriteStream(J){this.scheduler.Schedule(J)}removeStream(J){this.scheduler.Unregister(J)}streamUpdateSendOrderAndGroup(J,{sendOrder:$,sendGroupId:X}){this.scheduler.UpdateSendGroup(J,X),this.scheduler.UpdateSendOrder(J,$)}closeHttp2Stream(J){throw Error("Implement closeHttp2Stream in derived Class")}}function aR1(){return(0xffffffffn>>2n)+1n}var pT6=typeof process<"u"?process.pid:0,sR1=G6(`webtransport:streamidmanager(${pT6})`);class ZT{constructor({delegate:J,unidirectional:$,isclient:X,maxAllowedOutgoingStreams:Y,maxAllowedIncomingStreams:Q}){this.delegate=J,this.unidirectional=$,this.isclient=X,this.outgoingMaxStreams=BigInt(Y),this.nextOutgoingStreamId=this.getFirstOutgoingStreamId(),this.outgoingStreamCount=0n,this.incomingActualMaxStreams=BigInt(Q),this.incomingAdvertisedMaxStreams=BigInt(Q),this.incomingInitialMaxOpenStreams=BigInt(Q),this.incomingStreamCount=0n,this.availableStreams=new Set,this.largestPeerCreatedStreamId=BigInt(Number.MAX_SAFE_INTEGER),this.stopIncreasingIncomingMaxStreams=!1}onStreamsBlockedFrame(J){if(J>this.incomingAdvertisedMaxStreams)return{error:"StreamsBlockedFrame's stream count "+J+" exceeds incoming max stream "+this.incomingAdvertisedMaxStreams};if(this.incomingAdvertisedMaxStreams===this.incomingActualMaxStreams)return{success:!0};if(J<this.incomingActualMaxStreams&&this.delegate.canSendMaxStreams())this.sendMaxStreamsFrame();return{success:!0}}maybeAllowNewOutgoingStreams(J){if(J<=this.outgoingMaxStreams)return!1;let $=aR1();if(J<$)this.outgoingMaxStreams=J;else this.outgoingMaxStreams=$;return!0}setMaxOpenIncomingStreams(J){if(this.incomingStreamCount>0)throw Error("non-zero incoming stream count "+this.incomingStreamCount+NaN+J);if(this.incomingInitialMaxOpenStreams!==J)sR1(this.unidirectional?"unidirectional ":"bidirectional: ","incoming stream limit changed from ",this.incomingInitialMaxOpenStreams," to ",J);this.incomingActualMaxStreams=J,this.incomingAdvertisedMaxStreams=J,this.incomingInitialMaxOpenStreams=J}maybeSendMaxStreamsFrame(){let J=2n;if(J>0n){if(this.incomingAdvertisedMaxStreams-this.incomingStreamCount>this.incomingInitialMaxOpenStreams/J)return}if(this.delegate.canSendMaxStreams()&&this.incomingAdvertisedMaxStreams<this.incomingActualMaxStreams)this.sendMaxStreamsFrame()}sendMaxStreamsFrame(){if(this.incomingAdvertisedMaxStreams>=this.incomingActualMaxStreams)throw Error("this.incomingAdvertisedMaxStreams >= this.incomingActualMaxStreams"+this.incomingAdvertisedMaxStreams+"vs."+this.incomingActualMaxStreams);this.incomingAdvertisedMaxStreams=this.incomingActualMaxStreams,this.delegate.sendMaxStreams(this.incomingAdvertisedMaxStreams,this.unidirectional)}sendMaxStreamsFrameInitial(){this.delegate.sendMaxStreams(this.incomingAdvertisedMaxStreams,this.unidirectional)}onStreamClosed(J){if(this.isclient&&J&0x1n||!this.isclient&&!(J&0x1n))return;if(this.incomingActualMaxStreams===aR1())return;if(!this.stopIncreasingIncomingMaxStreams)this.incomingActualMaxStreams++,this.maybeSendMaxStreamsFrame()}getNextOutgoingStreamId(){if(this.outgoingStreamCount>=this.outgoingMaxStreams)throw Error("Attempt to allocate a new outgoing stream that would exceed the limit ("+ +Number(this.outgoingMaxStreams)+")");let J=this.nextOutgoingStreamId;return this.nextOutgoingStreamId+=1n<<2n,this.outgoingStreamCount++,J}canOpenNextOutgoingStream(){return this.outgoingStreamCount<this.outgoingMaxStreams}isMaxStreamSet(){return this.outgoingMaxStreams>0n}maybeIncreaseLargestPeerStreamId(J){if(this.availableStreams.has(J))return this.availableStreams.delete(J),!0;let $=1n<<2n,X=this.largestPeerCreatedStreamId===BigInt(Number.MAX_SAFE_INTEGER)?this.getFirstIncomingStreamId():this.largestPeerCreatedStreamId+$,Y=(J-X)/$+1n;if(this.incomingStreamCount+Y>this.incomingAdvertisedMaxStreams)return sR1("Failed to create a new incoming stream with id:"+J+", reaching MAX_STREAMS limit: "+this.incomingAdvertisedMaxStreams+"."),{error:"Stream id "+J+" would exceed stream count limit "+this.incomingAdvertisedMaxStreams};for(let Q=X;Q<J;Q+=$)this.availableStreams.add(Q);return this.incomingStreamCount+=Y,this.largestPeerCreatedStreamId=J,!0}isAvailableStream(J){if(this.isclient&&J&1||!this.isclient&&!(J&1))return J>=this.nextOutgoingStreamId;return this.largestPeerCreatedStreamId===BigInt(Number.MAX_SAFE_INTEGER)||J>this.largestPeerCreatedStreamId||this.availableStreams.has(J)}getFirstOutgoingStreamId(){let J=0n;if(this.isclient)J|=0x1n;if(this.unidirectional)J|=0x2n;return J}getFirstIncomingStreamId(){let J=0n;if(!this.isclient)J|=0x1n;if(this.unidirectional)J|=0x2n;return J}get availableIncomingStreams(){return this.incomingAdvertisedMaxStreams-this.incomingStreamCount}}var lT6=typeof process<"u"?process.pid:0,dT6=G6(`webtransport:http2webtransportsession(${lT6})`),fn=(J)=>setTimeout(J,0);if(typeof process<"u")fn=process.nextTick;class C3{constructor({stream:J,ws:$,isclient:X,createParser:Y,sendWindowOffset:Q,receiveWindowOffset:K,shouldAutoTuneReceiveWindow:W,receiveWindowSizeLimit:Z,initialBidirectionalSendStreams:G,initialBidirectionalReceiveStreams:V,initialUnidirectionalSendStreams:q,initialUnidirectionalReceiveStreams:z}){if(this.jsobj=void 0,J)this.stream=J;else if($)this.ws=$;else throw Error("Neither stream or websocket supplied");if(this.capsParser=Y(this),this.isclient=X,this.flowController=new wz({tocontrol:this,sendWindowOffset:Q,receiveWindowOffset:K,shouldAutoTuneReceiveWindow:W,receiveWindowSizeLimit:Z}),this.streamIdMngrUni=new ZT({delegate:this,unidirectional:!0,isclient:X,maxAllowedIncomingStreams:z,maxAllowedOutgoingStreams:q}),this.streamIdMngrBi=new ZT({delegate:this,unidirectional:!1,isclient:X,maxAllowedIncomingStreams:V,maxAllowedOutgoingStreams:G}),this.datagramsWaiting_=[],this.orderUniStreams=[],this.orderBiStreams=[],J)if(X)J.on("response",(H)=>{fn(()=>{if(H[":status"]===200){let v={};if(J&&H["wt-protocol"])v.protocol=H["wt-protocol"];this.jsobj.onReady(v)}else this.jsobj.onClose({errorcode:H[":status"],error:"Session stream errored"})})});else fn(()=>{this.jsobj.onReady({})})}sendInitialParameters(){let J=!1;if(process){if(process.version){if(parseInt(process.version.split(".")[0].substring(1))>=20)J=!0}}if(!J||this.capsParser.initialParametersMandatory())this.flowController.sendWindowUpdate(),this.streamIdMngrBi.sendMaxStreamsFrameInitial(),this.streamIdMngrUni.sendMaxStreamsFrameInitial()}drainWrites(){while(!this.capsParser.blocked&&this.datagramsWaiting_.length>0){let J=this.datagramsWaiting_.shift();this.capsParser.writeCapsule({type:x1.DATAGRAM,headerVints:[],payload:J})}if(this.datagramsWaiting_.length>0)this.capsParser.scheduleDrainWrites()}writeDatagram(J){if(J.byteLength>this.getMaxDatagramSize())return{code:"tooBig"};if(this.capsParser.blocked)return this.datagramsWaiting_.push(J),this.capsParser.scheduleDrainWrites(),{code:"blocked"};return this.capsParser.writeCapsule({type:x1.DATAGRAM,headerVints:[],payload:J}),{code:"success"}}trySendingUnidirectionalStreams(){while(this.orderUniStreams.length>0&&this.streamIdMngrUni.canOpenNextOutgoingStream()){let J=this.streamIdMngrUni.getNextOutgoingStreamId(),$=this.orderUniStreams.pop();this.capsParser.writeCapsule({type:x1.WT_STREAM_WOFIN,headerVints:[J],payload:void 0}),this.capsParser.newStream(J,$||{sendGroupId:0n,sendOrder:0n})}}orderUnidiStream({sendGroup:J,sendOrder:$,waitUntilAvailable:X}){let Y=this.streamIdMngrUni.canOpenNextOutgoingStream(),Q=this.streamIdMngrUni.isMaxStreamSet();if(Y||X||!Q)return this.orderUniStreams.push({sendGroupId:J?._sendGroupId||0n,sendOrder:$??0n}),this.trySendingUnidirectionalStreams(),!0;return!1}trySendingBidirectionalStreams(){while(this.orderBiStreams.length>0&&this.streamIdMngrBi.canOpenNextOutgoingStream()){let J=this.streamIdMngrBi.getNextOutgoingStreamId(),$=this.orderBiStreams.pop();this.capsParser.writeCapsule({type:x1.WT_STREAM_WOFIN,headerVints:[J],payload:void 0}),this.capsParser.newStream(J,$||{sendGroupId:0n,sendOrder:0n})}}orderBidiStream({sendGroup:J,sendOrder:$,waitUntilAvailable:X}){let Y=this.streamIdMngrBi.canOpenNextOutgoingStream(),Q=this.streamIdMngrBi.isMaxStreamSet();if(Y||X||!Q)return this.orderBiStreams.push({sendGroupId:J?._sendGroupId||0n,sendOrder:$??0n}),this.trySendingBidirectionalStreams(),!0;return!1}orderSessionStats(){this.jsobj.onSessionStats({timestamp:0,expiredOutgoing:0n,lostOutgoing:0n,minRtt:0,smoothedRtt:0,rttVariation:0,estimatedSendRateBps:0n})}orderDatagramStats(){this.jsobj.onDatagramStats({timestamp:0,expiredOutgoing:0n,lostOutgoing:0n})}getMaxDatagramSize(){return 16384}notifySessionDraining(){}close({code:J,reason:$}){this.capsParser.sendClose({code:J,reason:$})}sendWindowUpdate(J){this.capsParser.writeCapsule({type:x1.WT_MAX_DATA,headerVints:[J],payload:void 0})}reportBlocked(J){dT6("Session was blocked at:",J)}sendBlocked(J){this.capsParser.writeCapsule({type:x1.WT_DATA_BLOCKED,headerVints:[J],payload:void 0})}connected(){return this.jsobj.state==="connected"}closeConnection({code:J,reason:$}){this.jsobj.onClose({errorcode:J,error:$}),this.close({code:J,reason:$})}smoothedRtt(){let J;if(this.stream)J=this.stream.session?.WTrtt||25;else if(this.ws)J=navigator?.connection?.rtt||25;return J=Math.ceil(J/25)*25,J}canSendMaxStreams(){return!0}sendMaxStreams(J,$){this.capsParser.writeCapsule({type:$?x1.WT_MAX_STREAMS_UNIDI:x1.WT_MAX_STREAMS_BIDI,headerVints:[J],payload:void 0})}}function GT(J){if(J.offset+4>J.size)return;let $=J.buffer.readUInt32BE(J.offset);return J.offset+=4,$}function R8(J){if(J.offset+1>J.size)return;let $=BigInt(J.buffer.readUInt8(J.offset));J.offset++;let Y=1<<(Number($)>>>6);if(J.offset+Y-1>J.size)return;$=$&0x3fn;for(let Q=0;Q<Y-1;Q++)$=$<<8n|BigInt(J.buffer.readUInt8(J.offset)),J.offset++;return $}function T3(J,$){let X=8n,Y=0xc0n,Q=BigInt($);if(Q<64)X=1n,Y=0x0n;else if(Q<16384)X=2n,Y=0x40n;else if(Q<1073741824)X=4n,Y=0x80n;J.buffer.writeUInt8(Number(Y|Q>>(X-1n)*8n&0xffn),J.offset),J.offset++;for(let K=X-2n;K>=0;K--)J.buffer.writeUInt8(Number(Q>>K*8n&0xffn),J.offset),J.offset++}class PB extends x1{constructor({stream:J,nativesession:$,isclient:X,initialStreamSendWindowOffsetBidi:Y,initialStreamSendWindowOffsetUnidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z}){super({nativesession:$,isclient:X,initialStreamSendWindowOffsetBidi:Y,initialStreamSendWindowOffsetUnidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z});this.stream=J,this.session=$,this.isclient=X,this.stream.on("readable",()=>{let G;while((G=this.stream.read())!==null)this.parseData(G)}),this.stream.on("end",()=>{}),this.stream.on("error",(G)=>{this.session.jsobj.onClose({errorcode:this.stream.rstCode,error:G.toString()})}),this.stream.on("drain",()=>{this.blocked=!1,this.drainWrites()}),this.stream.on("close",()=>{if(!(this.session.jsobj.state==="failed"||this.session.jsobj.state==="closed"))this.session.jsobj.onClose({errorcode:this.stream.rstCode||0,error:""})})}}class C8 extends PB{constructor({stream:J,nativesession:$,isclient:X,initialStreamSendWindowOffsetBidi:Y,initialStreamSendWindowOffsetUnidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z}){super({stream:J,nativesession:$,isclient:X,initialStreamSendWindowOffsetBidi:Y,initialStreamSendWindowOffsetUnidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z});this.mode="s",this.saveddata=void 0,this.rtype=void 0}parseData(J){let $=J;if(this.saveddata)$=Buffer.concat([this.saveddata,$]),delete this.saveddata;let X={offset:0,size:$.length,buffer:$};while(X.size-X.offset>0)switch(this.mode){case"s":{let Y=X.offset+X.buffer.byteOffset,Q=X.buffer.byteLength-X.offset;if(X.size<2+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}let K=R8(X);if(typeof K>"u"||X.size<1+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}let W=Number(K),Z=R8(X);if(typeof Z>"u"){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}let G=Number(Z),V=G,q=Math.min(X.offset+G,X.size),z=X.offset;if(W===C8.PADDING||W===C8.WT_STREAM_WOFIN||W===C8.WT_STREAM_WFIN)V=Math.min(G,64);if(V>4*Number(this.session.flowController.receiveWindowSize)||G>8*Number(this.session.flowController.receiveWindowSize)){this.session.closeConnection({code:63,reason:"Frame length too big :"+G});return}if(X.size<V+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}let H;switch(W){case C8.PADDING:break;case C8.WT_RESET_STREAM:case C8.WT_STOP_SENDING:{let v=R8(X);if(typeof v<"u"){let F=this.wtstreams.get(v),U=R8(X);if(F&&typeof U<"u")F.onStreamSignal(W===C8.WT_RESET_STREAM?"resetStream":"stopSending"),F.jsobj.onStreamRecvSignal({code:Number(U),nettask:W===C8.WT_RESET_STREAM?"resetStream":"stopSending"})}}break;case C8.WT_STREAM_WOFIN:case C8.WT_STREAM_WFIN:if(H=R8(X),typeof H<"u"){let v=this.wtstreams.get(H);if(!v){if(v=this.newStream(H,{sendOrder:0n,sendGroupId:0n}),!v)return}if(q-X.offset>=0){let F=W===C8.WT_STREAM_WFIN&&X.size>=G+z;if(F)v.onFin();v.recvData({data:q-X.offset>0?new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,q-X.offset):void 0,fin:F})}}break;case C8.WT_MAX_DATA:this.onMaxData(R8(X));break;case C8.WT_MAX_STREAM_DATA:{let v=R8(X),F=R8(X);if(typeof v<"u"&&typeof F<"u")this.onMaxStreamData(v,F)}break;case C8.WT_MAX_STREAMS_BIDI:this.onMaxStreamBiDi(R8(X));break;case C8.WT_MAX_STREAMS_UNIDI:this.onMaxStreamUniDi(R8(X));break;case C8.WT_DATA_BLOCKED:this.onDataBlocked(R8(X));break;case C8.WT_STREAM_DATA_BLOCKED:{let v=R8(X),F=R8(X);if(typeof v<"u"&&typeof F<"u")this.onStreamDataBlocked(v,F)}break;case C8.WT_STREAMS_BLOCKED_UNIDI:this.onStreamsBlockedUnidi(R8(X));break;case C8.WT_STREAMS_BLOCKED_BIDI:this.onStreamsBlockedBidi(R8(X));break;case C8.WT_CLOSE_SESSION:{let v=GT(X)||0,U=new TextDecoder().decode(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,q-X.offset));this.onCloseWebTransportSession({code:v,reason:U})}break;case C8.WT_DRAIN_SESSION:this.onDrain();break;case C8.DATAGRAM:this.session.jsobj.onDatagramReceived({datagram:new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,q-X.offset)});break;default:}if(X.size<G+z){if(this.remainlength=G+z-X.size,this.mode="c",H)this.rstreamid=H,this.rfin=W===C8.WT_STREAM_WFIN}X.offset=q}break;case"c":{let Y=Math.min(X.size-X.offset,this.remainlength);if(this.rstreamid){let Q=this.wtstreams.get(this.rstreamid),K=this.rtype===C8.WT_STREAM_WFIN&&this.remainlength===Y;if(Q){if(K)Q.onFin();Q.recvData({data:new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,Y),fin:K})}}if(this.remainlength=this.remainlength-Y,X.offset+=Y,this.remainlength===0)this.mode="s",delete this.rfin,delete this.rstreamid}break}}writeCapsule({type:J,headerVints:$,payload:X,end:Y}){let Q=0;for(let G in $)Q+=P3($[G]);let K=Q;if(X)Q+=X.byteLength;K+=P3(Q)+P3(J);let W=Buffer.alloc(K),Z={offset:0,size:W.length,buffer:W};T3(Z,J),T3(Z,Q);for(let G in $)T3(Z,$[G]);if(!this.stream)return;if(!Y){let G=!this.stream.write(W);if(X)G=!this.stream.write(X)||G;if(G)this.blocked=!0;return G}else{if(!X)this.stream.end(W,Y);else this.stream.write(W);if(X)this.stream.end(X,Y)}}closeHttp2Stream(J){this.stream.close(J),this.stream.destroy()}initialParametersMandatory(){return!1}}var lm5=G6(`webtransport:http2:node:client(${process?.pid})`);import{createSecureServer as rT6,constants as CB}from"node:http2";import{randomBytes as iT6}from"node:crypto";var oR1=G6(`webtransport:http2:node:websocketparser(${process?.pid})`);function rR1(J){let $=J.buffer.readUInt8(J.offset);return J.offset++,$}function nT6(J){let $=J.buffer.readUInt8(J.offset);return J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$}function aT6(J,$){let X=J.buffer.readUInt8(J.offset)^$.mask[$.offset%4];J.offset++,$.offset++;let Q=1<<(X>>>6);if(J.offset+Q-1>J.size)return;X=X&63;for(let K=0;K<Q-1;K++)X=X<<8|J.buffer.readUInt8(J.offset)^$.mask[$.offset%4],J.offset++,$.offset++;return X}function sT6(J){let $=J.buffer.readUInt8(J.offset);return J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$}function k3(J,$,X,Y){if(Y>24){let Q=0,K=new Uint8Array($.buffer);while(Q<Y&&(X+Q)%8)K[Q+X]^=J.mask[(Q+J.offset)%4],Q++;let W=new Uint8Array(8);W[0]=J.mask[(0+Q+J.offset)%4],W[1]=J.mask[(1+Q+J.offset)%4],W[2]=J.mask[(2+Q+J.offset)%4],W[3]=J.mask[(3+Q+J.offset)%4],W[4]=J.mask[(4+Q+J.offset)%4],W[5]=J.mask[(5+Q+J.offset)%4],W[6]=J.mask[(6+Q+J.offset)%4],W[7]=J.mask[(7+Q+J.offset)%4];let Z=new BigUint64Array($.buffer,Q+X,Math.floor((Y-Q)/8)),G=new BigUint64Array(W.buffer),V=0;while(Q+8<Y)Z[V]^=G[0],Q+=8,V++;while(Q<Y)K[Q+X]^=J.mask[(Q+J.offset)%4],Q++}else{let Q=new Uint8Array(4);Q[0]=J.mask[(0+J.offset)%4],Q[1]=J.mask[(1+J.offset)%4],Q[2]=J.mask[(2+J.offset)%4],Q[3]=J.mask[(3+J.offset)%4];let K=new Uint8Array($.buffer,X,Y);for(let W=0;W<Y;W++)K[W]^=Q[W%4]}J.offset+=Y}function oT6(J){let $=new Uint8Array(4);return $[0]=J.buffer.readUInt8(J.offset),J.offset++,$[1]=J.buffer.readUInt8(J.offset),J.offset++,$[2]=J.buffer.readUInt8(J.offset),J.offset++,$[3]=J.buffer.readUInt8(J.offset),J.offset++,$}class q5 extends PB{static WS_CONTINUE=0;static WS_TEXT=1;static WS_BINARY=2;static WS_CLOSE=8;static WS_PING=9;static WS_PONG=10;constructor({stream:J,nativesession:$,isclient:X,initialStreamSendWindowOffsetUnidi:Y,initialStreamSendWindowOffsetBidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z}){super({stream:J,nativesession:$,isclient:X,initialStreamSendWindowOffsetUnidi:Y,initialStreamSendWindowOffsetBidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z});this.mode="s",this.saveddata=void 0,this.rtype=void 0,this.bidirectionalLimitsSet=!1,this.unidirectionalLimitsSet=!1}parseData(J){let $=J;if(this.saveddata)$=Buffer.concat([this.saveddata,$]),delete this.saveddata;let X={offset:0,size:$.length,buffer:$};while(X.size-X.offset>0)switch(this.mode){case"s":{let Y=X.offset+X.buffer.byteOffset,Q=X.buffer.byteLength-X.offset;if(X.size<2+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}let K=rR1(X),W=(K&128)>>>7;if((K&48)>>>4!==0)oR1("Rsv bits set, should not happen!");let G=K&15;K=rR1(X);let V=(K&128)>>>7,q=V?4:0,z=K&127;if(z===126){if(X.size<2+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}z=nT6(X)}else if(z===127){if(X.size<8+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}z=sT6(X)}if(X.size<q+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}if(V)this.maskcontext={mask:oT6(X),offset:0};else this.maskcontext=void 0;if(!W&&G!==q5.WS_CONTINUE)this.lastopcode=G;if(W)this.lastopcode=void 0;if(G===q5.WS_CLOSE||G===q5.WS_PING||G===q5.WS_PONG){let H=z;if(H>4*Number(this.session.flowController.receiveWindowSize)){this.session.closeConnection({code:63,reason:"Frame length too big :"+H});return}else if(X.size<H+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}switch(G){case q5.WS_CLOSE:if(!this.closesend){if(this.maskcontext)k3(this.maskcontext,X.buffer,X.buffer.byteOffset+X.offset,H);this.sendCloseInt(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,H));let v=0,F="Session websocket closed";if(H>2){let U=Buffer.from(X.buffer.buffer,X.buffer.byteOffset+X.offset,H);v=U.readUint16BE(0);let B=U.toString("utf8",2).split(":");if(B.length>1)v=parseInt(B[0]),B=B.slice(1);F=B.join(":")}this.session.jsobj.onClose({errorcode:v,error:F})}break;case q5.WS_PING:if(this.maskcontext)k3(this.maskcontext,X.buffer,X.buffer.byteOffset+X.offset,H);this.sendPong(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,H));break;default:}X.offset+=H}else if(G===q5.WS_BINARY||G===q5.WS_CONTINUE&&this.lastopcode===q5.WS_BINARY){let H,v,F;if(z===0){oR1("warning empty data frame"),X.offset+=z;continue}if(G===q5.WS_BINARY){if(X.size<2+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}if(F=!1,H=-X.offset,this.maskcontext)v=aT6(X,this.maskcontext);else v=R8(X);if(H+=X.offset,typeof v>"u"||X.size<1+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}this.curtype=v}else F=!0,H=0,v=this.curtype;let U=z-H,j=U,B=Math.min(X.offset+U,X.size),L=X.offset;if(v===x1.PADDING||v===x1.WT_STREAM_WOFIN||v===x1.WT_STREAM_WFIN)j=Math.min(U,64);if(X.size<j+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}if(this.maskcontext)k3(this.maskcontext,X.buffer,X.buffer.byteOffset+X.offset,B-X.offset);let M,O;if(v!==x1.WT_STREAM_WOFIN||v!==x1.WT_STREAM_WFIN)if(W){if(O=X,this.contframes){this.contframes.push(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,B-X.offset));let N=this.contframes.reduce((R,x)=>R+x.byteLength,0),w=Buffer.allocUnsafe(N);this.contframes.reduce((R,x)=>{return Buffer.from(x.buffer,x.byteOffset,x.byteLength).copy(w,R),R+x.byteLength},0),O={offset:0,size:N,buffer:w}}}else{if(!this.contframes)this.contframes=[];this.contframes.push(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,B-X.offset))}switch(v){case x1.PADDING:break;case x1.WT_RESET_STREAM:case x1.WT_STOP_SENDING:if(O){let N=R8(O);if(typeof N<"u"){let w=this.wtstreams.get(N),R=R8(O);if(w&&typeof R<"u")w.onStreamSignal(v===x1.WT_RESET_STREAM?"resetStream":"stopSending"),w.jsobj.onStreamRecvSignal({code:Number(R),nettask:v===x1.WT_RESET_STREAM?"resetStream":"stopSending"})}}break;case x1.WT_STREAM_WOFIN:case x1.WT_STREAM_WFIN:if(!F)M=R8(X),this.cstreamid=M;else M=this.cstreamid;if(typeof M<"u"){let N=this.wtstreams.get(M);if(!N){if(N=this.newStream(M,{sendOrder:0n,sendGroupId:0n}),!N)return}if(B-X.offset>=0){let w=v===x1.WT_STREAM_WFIN&&X.size>=U+L;if(w)N.onFin();N.recvData({data:B-X.offset>0?new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,B-X.offset):void 0,fin:w})}}break;case x1.WT_MAX_DATA:this.onMaxData(R8(X));break;case x1.WT_MAX_STREAM_DATA:{let N=R8(X),w=R8(X);if(typeof N<"u"&&typeof w<"u")this.onMaxStreamData(N,w)}break;case x1.WT_MAX_STREAMS_BIDI:this.onMaxStreamBiDi(R8(X));break;case x1.WT_MAX_STREAMS_UNIDI:this.onMaxStreamUniDi(R8(X));break;case x1.WT_DATA_BLOCKED:this.onDataBlocked(R8(X));break;case x1.WT_STREAM_DATA_BLOCKED:{let N=R8(X),w=R8(X);if(typeof N<"u"&&typeof w<"u")this.onStreamDataBlocked(N,w)}break;case x1.WT_STREAMS_BLOCKED_UNIDI:this.onStreamsBlockedUnidi(R8(X));break;case x1.WT_STREAMS_BLOCKED_BIDI:this.onStreamsBlockedBidi(R8(X));break;case x1.WT_CLOSE_SESSION:{let N=GT(X)||0,R=new TextDecoder().decode(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,B-X.offset));this.onCloseWebTransportSession({code:N,reason:R})}break;case x1.WT_DRAIN_SESSION:this.onDrain();break;case x1.DATAGRAM:if(O)this.session.jsobj.onDatagramReceived({datagram:new Uint8Array(O.buffer.buffer,O.buffer.byteOffset+O.offset,B-O.offset)});break;default:}if(X.size<U+L){if(this.remainlength=U+L-X.size,this.mode="c",M)this.rstreamid=M,this.rfin=v===x1.WT_STREAM_WFIN}X.offset=B}else{let H=z;if(X.offset+H>X.size)this.mode="c",this.rstreamid=void 0,this.remainlength=X.offset+H-X.size,X.offset=X.size;else X.offset+=H}}break;case"c":{let Y=Math.min(X.size-X.offset,this.remainlength);if(this.rstreamid){let Q=this.wtstreams.get(this.rstreamid),K=this.rtype===x1.WT_STREAM_WFIN&&this.remainlength===Y;if(Q){if(K)Q.onFin();if(this.maskcontext)k3(this.maskcontext,X.buffer,X.buffer.byteOffset+X.offset,Y);Q.recvData({data:new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,Y),fin:K})}}if(this.remainlength=this.remainlength-Y,X.offset+=Y,this.remainlength===0)this.maskcontext=void 0,this.mode="s",delete this.rfin,delete this.rstreamid}break}}sendClose({code:J,reason:$}){super.sendClose({code:J,reason:$}),this.sendCloseInt()}sendCloseInt(J){this.writeWSFrame({opcode:q5.WS_CLOSE,payload:J}),this.closesend=!0}sendPong(J){this.writeWSFrame({opcode:q5.WS_PONG,payload:J})}writeCapsule({type:J,headerVints:$,payload:X,end:Y}){let Q=0;for(let v in $)Q+=P3($[v]);Q+=P3(J);let K=Q+2,W=0;if(this.isclient)K+=4,W=1;if(X)Q+=X.byteLength;if(Q>65535)K+=8;else if(Q>125)K+=2;let Z=Buffer.alloc(K),G={offset:0,size:Z.length,buffer:Z},V=this.writeHeader(G,{opcode:q5.WS_BINARY,plength:Q,mask:W}),q=G.offset;T3(G,J);for(let v in $)T3(G,$[v]);let z=G.offset;if(V){if(k3(V,G.buffer,G.offset+G.buffer.byteOffset,z-q),X)k3(V,Buffer.from(X.buffer,X.byteOffset,X.byteLength),X.byteOffset,X.byteLength)}let H=!1;if(X)H=!this.stream.write(Z),H=!this.stream.write(X,Y)||H;else H=!this.stream.write(Z,Y);if(H)this.blocked=!0;return H}writeHeader(J,{opcode:$,plength:X,mask:Y}){J.buffer.writeUint8(128|$&15,J.offset),J.offset++;let Q=X;if(X>65535)Q=127;else if(X>125)Q=126;if(J.buffer.writeUint8((Y&&128)|Q&127,J.offset),J.offset++,X>65535)J.buffer.writeBigInt64BE(BigInt(X),J.offset),J.offset+=8;else if(X>125)J.buffer.writeUint16BE(X,J.offset),J.offset+=2;let K;if(Y)K={offset:0,mask:iT6(4)},J.buffer.writeUint32BE(K.mask.readUInt32BE(0),J.offset),J.offset+=4;return K}writeWSFrame({opcode:J,payload:$}){let X=$?.byteLength||0,Y=2,Q=0;if(this.isclient)Y+=4,Q=1;if(X>65535)Y+=8;else if(X>125)Y+=2;let K=Buffer.alloc(Y),W={offset:0,size:K.length,buffer:K},Z=this.writeHeader(W,{opcode:J,plength:X,mask:Q});if(W.offset!==Y)throw Error("Headlength does not match pos");let G=!this.stream.write(K);if(Z&&$)k3(Z,Buffer.from($.buffer,$.byteOffset,$.byteLength),0,$.byteLength);if($)G=!this.stream.write($)||G;if(G)this.blocked=!0;return G}closeHttp2Stream(J){let $=this.stream;if($.close)$.setTimeout(1000,()=>$.close(0));else if($.end)$.end();else throw Error("http2:session not close method")}initialParametersMandatory(){return!0}}import{log as yn}from"node:console";import{webcrypto as tT6}from"crypto";var tR1=["kDraft1","kDraft2"];import{clearInterval as eR1}from"node:timers";class TB{constructor(J){let $=J?.port;if(typeof $>"u")$=443;if(this.port=Number($),this.secret=J?.secret,!this.secret)throw Error("No secret set for Http2Server");this.host=J?.host||"localhost";let X=J?.certhttp2?J?.certhttp2:J?.cert;if(!X)throw Error("No cert set for Http2Server");let Y=J?.privKeyhttp2?J?.privKeyhttp2:J?.privKey;if(!Y)throw Error("No privKey set for Http2Server");this.initialStreamFlowControlWindow=J?.initialStreamFlowControlWindow||16384,this.initialSessionFlowControlWindow=J?.initialSessionFlowControlWindow||16384,this.initialBidirectionalStreams=J?.initialBidirectionalStreams||100,this.initialUnidirectionalStreams=J?.initialUnidirectionalStreams||100,this.streamShouldAutoTuneReceiveWindow=J.streamShouldAutoTuneReceiveWindow||!0,this.streamFlowControlWindowSizeLimit=J?.streamFlowControlWindowSizeLimit||6291456,this.sessionShouldAutoTuneReceiveWindow=J.sessionShouldAutoTuneReceiveWindow||!0,this.sessionFlowControlWindowSizeLimit=J?.sessionFlowControlWindowSizeLimit||15728640,this.paths={},this.hasrequesthandler=!1,this.jsobj=void 0,this.canHandleSettings=!1,this.serverInt=rT6({key:Y,cert:X,allowHTTP1:!0,settings:{enableConnectProtocol:!0,customSettings:{11104:1,11105:this.initialSessionFlowControlWindow,11106:this.initialStreamFlowControlWindow,11107:this.initialStreamFlowControlWindow,11108:this.initialUnidirectionalStreams,11109:this.initialBidirectionalStreams}},remoteCustomSettings:[11104,11105,11106,11107,11108,11109]}),this.serverInt.on("listening",()=>{let Q=this.serverInt.address(),K={port:Q?.port,host:Q?.address};this.jsobj.onServerListening(K)}),this.serverInt.on("error",()=>{let Q={};this.jsobj.onServerError(Q)}),this.serverInt.on("session",(Q)=>{let K=100,W=1,Z=()=>{if(!Q.closed)Q.ping((V,q,z)=>{if(!V)K=W*q+(1-W)*K,W=0.2,Q.WTrtt=K});else eR1(G),G=void 0},G=setInterval(Z,1000);Z(),Q.on("close",()=>{if(G)eR1(G)})}),this.serverInt.on("close",()=>{let Q={};this.jsobj.onServerClose(Q)}),this.serverInt.on("upgrade",(Q,K,W)=>{let Z=Q.url;if(!Z){K.destroy();return}while(Z.length>1&&Z[0]==="/"&&Z[1]==="/")Z=Z?.slice(1);let G={...Q.headers,":path":Z},{websocketProt:V,webtransportProt:q}=this.checkProtocolHeader(G);if(q)G["wt-available-protocols"]=q;if(!V){K.destroy();return}if(this.hasrequesthandler){K.head=W;let z={header:G,peerAddress:K.remoteAddress+":"+K.remotePort,session:K,protocol:"websocketoverhttp1",head:W,transportPrivate:{websocketProt:V}};this.jsobj.onSessionRequest(z)}else if(this.paths[Z])this.sendHttp1Headers({stream:K,header:G,protocol:V}).then(()=>{let z={session:new C3({stream:K,isclient:!1,createParser:(H)=>{let v=this.capsParser=new q5({stream:K,nativesession:H,isclient:!1,initialStreamSendWindowOffsetBidi:0,initialStreamSendWindowOffsetUnidi:0,initialStreamReceiveWindowOffset:this.initialStreamFlowControlWindow,streamShouldAutoTuneReceiveWindow:this.streamShouldAutoTuneReceiveWindow,streamReceiveWindowSizeLimit:this.streamFlowControlWindowSizeLimit});if(W.byteLength>0)v.parseData(W);return v},initialBidirectionalSendStreams:0,initialBidirectionalReceiveStreams:this.initialBidirectionalStreams,initialUnidirectionalSendStreams:0,initialUnidirectionalReceiveStreams:this.initialUnidirectionalStreams,sendWindowOffset:0,receiveWindowOffset:this.sessionFlowControlWindowSizeLimit,shouldAutoTuneReceiveWindow:this.sessionShouldAutoTuneReceiveWindow,receiveWindowSizeLimit:this.sessionFlowControlWindowSizeLimit}),path:Z,header:G,peerAddress:K.remoteAddress+":"+K.remotePort,reliable:!0,object:this};this.jsobj.onHttpWTSessionVisitor(z)}).catch((z)=>{yn("Problem sendHttp1Header",z),K.destroy()});else K.destroy()}),this.serverInt.on("stream",(Q,K)=>{if(Q.on("error",()=>{}),K[":method"]!=="CONNECT"){Q.respond({":status":"406"}),Q.close(CB.NGHTTP2_REFUSED_STREAM);return}let W;if(K[":protocol"]==="websocket"&&K["sec-websocket-protocol"]){let G=this.checkProtocolHeader(K);if(W=G.websocketProt,G.webtransportProt)K["wt-available-protocols"]=G.webtransportProt}if(K[":protocol"]==="webtransport"&&K["wt-available-protocols"]){let G=K["wt-available-protocols"].split(",").map((V)=>V.trim());if(G.some((V)=>typeof V!=="string"||V.length<2||V[0]!=='"'||V.at(-1)!=='"')){Q.respond({":status":"406"}),Q.close(CB.NGHTTP2_REFUSED_STREAM);return}if(G=G.map((V)=>V.slice(1,-1)),G.some((V)=>/\\([^"\\])/.test(V))){Q.close(CB.NGHTTP2_REFUSED_STREAM);return}K["wt-available-protocols"]=G.map((V)=>V.replace(/\\(["\\])/g,"$1"))}if(K[":protocol"]!=="webtransport"&&!W){Q.respond({":status":"406"}),Q.close(CB.NGHTTP2_REFUSED_STREAM);return}if(!K[":path"]){Q.respond({":status":"406"}),Q.close(CB.NGHTTP2_REFUSED_STREAM);return}let Z=K[":path"];while(Z.length>1&&Z[0]==="/"&&Z[1]==="/")Z=Z?.slice(1);if(K[":path"]=Z,this.hasrequesthandler){let G=Q.session?.socket,V={header:K,peerAddress:G?.remoteAddress+":"+G?.remotePort,session:Q,protocol:W?"websocket":"capsule",transportPrivate:{websocketProt:W}};this.jsobj.onSessionRequest(V)}else if(this.paths[Z]){let G=Q.session?.socket,{11109:V=void 0,11108:q=void 0,11107:z=void 0,11106:H=void 0,11105:v=void 0}=Q?.session?.remoteSettings?.customSettings||{},F={session:new C3({stream:Q,isclient:!1,createParser:(j)=>{if(!W)return new C8({stream:Q,nativesession:j,isclient:!1,initialStreamSendWindowOffsetBidi:z||this.initialStreamFlowControlWindow,initialStreamSendWindowOffsetUnidi:H||this.initialStreamFlowControlWindow,initialStreamReceiveWindowOffset:this.initialStreamFlowControlWindow,streamShouldAutoTuneReceiveWindow:this.streamShouldAutoTuneReceiveWindow,streamReceiveWindowSizeLimit:this.streamFlowControlWindowSizeLimit});else return this.capsParser=new q5({stream:Q,nativesession:j,isclient:!1,initialStreamSendWindowOffsetBidi:0,initialStreamSendWindowOffsetUnidi:0,initialStreamReceiveWindowOffset:this.initialStreamFlowControlWindow,streamShouldAutoTuneReceiveWindow:this.streamShouldAutoTuneReceiveWindow,streamReceiveWindowSizeLimit:this.streamFlowControlWindowSizeLimit})},initialBidirectionalSendStreams:W?0:V||this.initialBidirectionalStreams,initialBidirectionalReceiveStreams:this.initialBidirectionalStreams,initialUnidirectionalSendStreams:W?0:q||this.initialUnidirectionalStreams,initialUnidirectionalReceiveStreams:this.initialUnidirectionalStreams,sendWindowOffset:!W?v||this.sessionFlowControlWindowSizeLimit:0,receiveWindowOffset:this.sessionFlowControlWindowSizeLimit,shouldAutoTuneReceiveWindow:this.sessionShouldAutoTuneReceiveWindow,receiveWindowSizeLimit:this.sessionFlowControlWindowSizeLimit}),path:Z,header:K,peerAddress:G?.remoteAddress+":"+G?.remotePort,reliable:!0,object:this},U={":status":"200"};if(W)U["sec-websocket-protocol"]=W;Q.respond(U),this.jsobj.onHttpWTSessionVisitor(F)}else{Q.respond({":status":"404"}),Q.end(),Q.close();return}})}checkProtocolHeader(J){let $=J["sec-websocket-protocol"]?.split?.(",")?.map?.((Y)=>Y.trim()),X;if(!Array.isArray($))X=[$];else X=$;if(X=X.map((Y)=>Y?Y.split("_"):[void 0,void 0]).filter((Y)=>Y[0]==="webtransport").filter((Y)=>Y[1]?tR1.includes(Y[1]):!1),X.length>0){let Y=X[0][1];X=X.filter((K)=>K[1]===Y);let Q={websocketProt:X[0].slice(0,2).join("_")};if(X.some((K)=>K[2]))Q.webtransportProt=[...new Set(X.filter((K)=>K[2]).map((K)=>K.slice(2).join("_")))];return Q}else return{websocketProt:void 0}}startServer(){this.serverInt.listen(this.port,this.host)}stopServer(){this.serverInt.close()}updateCert(J,$,X){this.serverInt.setSecureContext({key:$,cert:J})}setJSRequestHandler(J){this.hasrequesthandler=J}addPath(J){this.paths[J]=!0}async sendHttp1Headers({stream:J,header:$,protocol:X}){try{let Y=await tT6.subtle.digest("SHA-1",new TextEncoder().encode($["sec-websocket-key"]+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")),Q=Buffer.from(Y).toString("base64");J.write(`HTTP/1.1 101 Switching Protocols\r
|
|
551
|
+
-----END RSA PRIVATE KEY-----`;var JT=process.env.PORT??8080,On="0.12.0-prerelease-3",Dn;((Q)=>{Q.READY="WEBSERVER.READY";Q.STOPPED="WEBSERVER.STOPPED";Q.ERROR="WEBSERVER.ERROR";Q.UPGRADE="WEBSERVER.UPGRADE"})(Dn||={});class Bz extends $1{static instance=new Bz;_webserver=eC.default();_internalHttpServer;constructor(){super();this._webserver.use(($,X,Y)=>{X.header("Access-Control-Allow-Origin","*"),Y()}),this._webserver.get("/",($,X)=>{X.json({status:"OK",version:On,runtime:"node"})}),this._webserver.use(eC.default.static("assets",{dotfiles:"allow"}));let J=eW.instance.assetsLibraryPath;if(process.env.NODE_ENV!=="production"&&J)this._webserver.use(($,X,Y)=>{let Q=kT6.join(J,$.path);eW.instance.syncAsset(Q),Y()}),this._webserver.use(eC.default.static(J,{dotfiles:"allow"}))}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?CT6.createServer(this._webserver):TT6.createServer({key:tC,cert:rC},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else s.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(JT,this._onStarted),console.info(`WebServer.start(): Server running on port ${JT}.`)}stop(){if(this._internalHttpServer)return new Promise((J,$)=>{this._internalHttpServer.close((X)=>{if(X)$(X);else J(!0)})});else return s.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=(J,$,X)=>{this.emitWithGlobal("WEBSERVER.UPGRADE",{req:J,socket:$,head:X})};_onError=(J)=>{s.error(`WebServer._onError(): ${J.message}`),this.emitWithGlobal("WEBSERVER.ERROR",{error:J})};_onStopped=()=>{this.emitWithGlobal("WEBSERVER.STOPPED",{})}}var x3;((U)=>{U.BUILD_PACKETS="build_packets";U.ENTITIES_EMIT_UPDATES="entities_emit_updates";U.ENTITIES_TICK="entities_tick";U.NETWORK_SYNCHRONIZE="network_synchronize";U.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";U.PHYSICS_CLEANUP="physics_cleanup";U.PHYSICS_STEP="physics_step";U.SEND_ALL_PACKETS="send_all_packets";U.SEND_PACKETS="send_packets";U.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";U.SERIALIZE_PACKETS="serialize_packets";U.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";U.SIMULATION_STEP="simulation_step";U.TICKER_TICK="ticker_tick";U.WORLD_TICK="world_tick"})(x3||={});class I6{static getProcessStats(J=!1){let $=process.memoryUsage(),X={jsHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:$.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:$.heapUsed/$.heapTotal,unit:"percent"},processHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:$.rss/1024/1024,unit:"megabyte"}};if(J)return X;return Object.fromEntries(Object.entries(X).map(([Y,Q])=>[Y,Q.value]))}static initializeSentry(J,$=50){YC({dsn:J,release:On,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=I6.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let Q=X?.start_timestamp,K=X?.timestamp;if(!Q||!K)return null;if((K-Q)*1000>$)return X.measurements=I6.getProcessStats(!0),X}return null}})}static startSpan(J,$){if(VU())return l7({attributes:J.attributes,name:J.operation,op:J.operation},$);else return $()}static sentry(){return zd}}if(!HO)console.warn("Connection: msgpackr native acceleration is not enabled, using fallback implementation.");var yR1=new XG({useFloat32:b2.ALWAYS}),ST6=5000;class R$ extends $1{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_ws;_wsBinding=!1;_wt;_wtBinding=!1;_wtReliableReader;_wtReliableWriter;_wtUnreliableReader;_wtUnreliableWriter;id;constructor(J,$,X){super();this.id=Fz0(),this.onPacket(c0.PacketId.HEARTBEAT,this._onHeartbeatPacket);let Y=()=>{$1.globalInstance.emit("CONNECTION.OPENED",{connection:this,session:X})};if(J)this.bindWs(J),Y();else if($)this.bindWt($).then(Y).catch((Q)=>{this._onClose(),s.error(`Connection.constructor(): Failed to bind WebTransport. Error: ${Q}`)})}static clearCachedPacketsSerializedBuffers(){if(R$._cachedPacketsSerializedBuffer.size>0)R$._cachedPacketsSerializedBuffer.clear()}static serializePackets(J){for(let X of J)if(!c0.isValidPacket(X))return s.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let $=R$._cachedPacketsSerializedBuffer.get(J);if($)return $;return I6.startSpan({operation:"serialize_packets",attributes:{packets:J.length,packetIds:J.map((X)=>X[0]).join(",")}},(X)=>{let Y=yR1.pack(J);if(Y.byteLength>65536)Y=ET6(Y,{level:1});return X?.setAttribute("serializedBytes",Y.byteLength),R$._cachedPacketsSerializedBuffer.set(J,Y),Y})}bindWs(J){this._wsBinding=!0;let $=this._handleReconnect();if(this._cleanupConnections(),this._ws=J,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onClose,this._ws.onerror=this._onError,this._wsBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}async bindWt(J){this._wtBinding=!0;let $=this._handleReconnect();this._cleanupConnections(),J.userData.onclose=this._onClose,J.closed.catch(()=>{}).finally(()=>J.userData.onclose?.()),this._wt=J,await this._wt.ready;let X=this._wt.incomingBidirectionalStreams.getReader();try{let{value:Y}=await X.read();if(Y)this._wtReliableReader=Y.readable,this._wtReliableWriter=Y.writable.getWriter()}finally{X.releaseLock()}if(this._wtUnreliableReader=this._wt.datagrams.readable,this._wtUnreliableWriter=this._wt.datagrams.createWritable().getWriter(),(async()=>{if(!this._wtReliableReader)return;let Y=this._wt,Q=c0.createPacketBufferUnframer();for await(let K of this._wtReliableReader){if(Y!==this._wt)return;for(let W of Q(K))this._onMessage(W)}})().catch(()=>this._wt?.close()),(async()=>{if(!this._wtUnreliableReader)return;let Y=this._wt;for await(let Q of this._wtUnreliableReader){if(Y!==this._wt)return;this._onMessage(Q)}})().catch(()=>this._wt?.close()),this._wtBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}disconnect(){try{this._ws?.close(),this._wt?.close()}catch(J){s.error(`Connection.disconnect(): Connection disconnect failed. Error: ${J}`)}}onPacket(J,$){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===J)$(X)})}send(J,$=!0){if(this._closeTimeout||this._wsBinding||this._wtBinding)return;if(!this._ws&&!this._wt)return;let X=this._ws&&this._ws.readyState===bq.default.OPEN,Y=this._wt&&(this._wt.state==="connected"||this._wt.state==="draining");if(!X&&!Y)return;I6.startSpan({operation:"send_packets"},()=>{try{let Q=R$.serializePackets(J);if(!Q)return;if(Y)if($)this._wtReliableWriter?.write(c0.framePacketBuffer(Q)).catch(()=>{s.error("Connection.send(): WebTransport reliable write failed, connection closing?")});else this._wtUnreliableWriter?.write(Q).catch(()=>{s.error("Connection.send(): WebTransport unreliable write failed, connection closing?")});else this._ws.send(Q);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:J})}catch(Q){s.error(`Connection.send(): Packet send failed. Error: ${Q}`)}})}_onHeartbeatPacket=()=>{this.send([c0.createPacket(c0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0)};_onMessage=(J)=>{try{let $=this._deserialize(J);if(!$)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:$})}catch($){s.error(`Connection._ws.onmessage(): Error: ${$}`)}};_onClose=()=>{this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},ST6)};_onError=(J)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:J})};_cleanupConnections(){if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{};if(this._wt)this._wt.userData.onclose=()=>{};this._signalKill(),this._ws=void 0,this._wt=void 0,this._wtReliableReader=void 0,this._wtReliableWriter=void 0,this._wtUnreliableReader=void 0,this._wtUnreliableWriter=void 0}_deserialize(J){let $=yR1.unpack(J);if(!$||typeof $!=="object"||typeof $[0]!=="number")return s.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify($)}`);if(!c0.isValidPacket($))return s.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify($)}`);return $}_handleReconnect(){let J=!!this._ws||!!this._wt;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;return J}_signalConnectionId(){this.send([c0.createPacket(c0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})])}_signalKill(){this.send([c0.createPacket(c0.bidirectionalPackets.connectionPacketDefinition,{k:!0})])}}class jB{_lights=new Map;_nextLightId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedLights(J){this.getAllEntityAttachedLights(J).forEach(($)=>{$.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(J){return this.getAllLights().filter(($)=>$.attachedToEntity===J)}registerLight(J){if(J.id!==void 0)return J.id;let $=this._nextLightId;return this._lights.set($,J),this._nextLightId++,$}unregisterLight(J){if(J.id===void 0)return;this._lights.delete(J.id)}}class O5{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(J){return this._map.get(J)}set(J,$){let X=this._map.has(J);if(this._map.set(J,$),!X)this._values.push($);else this._isDirty=!0;return this}has(J){return this._map.has(J)}delete(J){let $=this._map.delete(J);if($)this._isDirty=!0;return $}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(J,$){this._map.forEach((X,Y)=>{J.call($,X,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let J of this._map.values())this._values.push(J);this._isDirty=!1}}var bR1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(bR1||={});var xn;((H)=>{H.DESPAWN="LIGHT.DESPAWN";H.SET_ANGLE="LIGHT.SET_ANGLE";H.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";H.SET_COLOR="LIGHT.SET_COLOR";H.SET_DISTANCE="LIGHT.SET_DISTANCE";H.SET_INTENSITY="LIGHT.SET_INTENSITY";H.SET_OFFSET="LIGHT.SET_OFFSET";H.SET_PENUMBRA="LIGHT.SET_PENUMBRA";H.SET_POSITION="LIGHT.SET_POSITION";H.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";H.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";H.SPAWN="LIGHT.SPAWN"})(xn||={});class Pn extends $1{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)s.fatalError("Either attachedToEntity or position must be set, but not both.");super();s.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=J.angle,this._attachedToEntity=J.attachedToEntity,this._color=J.color??{r:255,g:255,b:255},this._distance=J.distance,this._intensity=J.intensity??1,this._offset=J.offset,this._penumbra=J.penumbra,this._position=J.position,this._trackedEntity=J.trackedEntity,this._trackedPosition=J.trackedPosition,this._type=J.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(J){if(this._angle===J)return;if(this._angle=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:J})}setAttachedToEntity(J){if(!J.isSpawned)return s.error(`Light.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:J})}setColor(J){if(this._color.r===J.r&&this._color.g===J.g&&this._color.b===J.b)return;if(this._color=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:J})}setDistance(J){if(this._distance===J)return;if(this._distance=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:J})}setIntensity(J){if(this._intensity===J)return;if(this._intensity=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:J})}setPenumbra(J){if(this._penumbra===J)return;if(this._penumbra=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:J})}setTrackedEntity(J){if(!J.isSpawned)return s.error(`Light.setTrackedEntity(): Entity ${J.id} is not spawned!`);if(this._trackedEntity===J)return;if(this._trackedEntity=J,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:J})}setTrackedPosition(J){if(this._trackedPosition===J)return;if(this._trackedPosition=J,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:J})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return s.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=J.lightManager.registerLight(this),this._world=J,this.emitWithWorld(J,"LIGHT.SPAWN",{light:this})}serialize(){return H1.serializeLight(this)}}var Cn;((A)=>{A.BURST="PARTICLE_EMITTER.BURST";A.DESPAWN="PARTICLE_EMITTER.DESPAWN";A.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";A.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";A.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";A.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";A.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";A.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";A.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";A.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";A.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";A.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";A.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";A.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";A.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";A.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";A.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";A.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";A.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";A.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";A.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";A.SET_RATE="PARTICLE_EMITTER.SET_RATE";A.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";A.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";A.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";A.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";A.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";A.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";A.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";A.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";A.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";A.SPAWN="PARTICLE_EMITTER.SPAWN"})(Cn||={});class Tn extends $1{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)s.fatalError("Either attachedToEntity or position must be set, but not both.");if(!J.textureUri)s.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=J.alphaTest??0.05,this._attachedToEntity=J.attachedToEntity,this._attachedToEntityNodeName=J.attachedToEntityNodeName,this._colorEnd=J.colorEnd,this._colorEndVariance=J.colorEndVariance,this._colorStart=J.colorStart,this._colorStartVariance=J.colorStartVariance,this._gravity=J.gravity,this._lifetime=J.lifetime,this._lifetimeVariance=J.lifetimeVariance,this._maxParticles=J.maxParticles,this._offset=J.offset,this._opacityEnd=J.opacityEnd,this._opacityEndVariance=J.opacityEndVariance,this._opacityStart=J.opacityStart,this._opacityStartVariance=J.opacityStartVariance,this._paused=!1,this._position=J.position,this._positionVariance=J.positionVariance,this._rate=J.rate,this._rateVariance=J.rateVariance,this._sizeEnd=J.sizeEnd,this._sizeEndVariance=J.sizeEndVariance,this._sizeStart=J.sizeStart,this._sizeStartVariance=J.sizeStartVariance,this._textureUri=J.textureUri,this._transparent=J.transparent,this._velocity=J.velocity,this._velocityVariance=J.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(J){if(this._alphaTest===J)return;if(this._alphaTest=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:J})}setAttachedToEntity(J){if(!J.isSpawned)return s.error(`ParticleEmitter.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:J})}setAttachedToEntityNodeName(J){if(this._attachedToEntityNodeName===J)return;if(this._attachedToEntityNodeName=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:J})}setColorEnd(J){if(this._colorEnd&&this._colorEnd.r===J.r&&this._colorEnd.g===J.g&&this._colorEnd.b===J.b)return;if(this._colorEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:J})}setColorEndVariance(J){if(this._colorEndVariance&&this._colorEndVariance.r===J.r&&this._colorEndVariance.g===J.g&&this._colorEndVariance.b===J.b)return;if(this._colorEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:J})}setColorStart(J){if(this._colorStart&&this._colorStart.r===J.r&&this._colorStart.g===J.g&&this._colorStart.b===J.b)return;if(this._colorStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:J})}setColorStartVariance(J){if(this._colorStartVariance&&this._colorStartVariance.r===J.r&&this._colorStartVariance.g===J.g&&this._colorStartVariance.b===J.b)return;if(this._colorStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:J})}setGravity(J){if(this._gravity&&this._gravity.x===J.x&&this._gravity.y===J.y&&this._gravity.z===J.z)return;if(this._gravity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:J})}setLifetime(J){if(this._lifetime===J)return;if(this._lifetime=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:J})}setLifetimeVariance(J){if(this._lifetimeVariance===J)return;if(this._lifetimeVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:J})}setMaxParticles(J){if(this._maxParticles===J)return;if(this._maxParticles=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:J})}setOpacityEnd(J){if(this._opacityEnd===J)return;if(this._opacityEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:J})}setOpacityEndVariance(J){if(this._opacityEndVariance===J)return;if(this._opacityEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:J})}setOpacityStart(J){if(this._opacityStart===J)return;if(this._opacityStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:J})}setOpacityStartVariance(J){if(this._opacityStartVariance===J)return;if(this._opacityStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:J})}setPositionVariance(J){if(this._positionVariance&&this._positionVariance.x===J.x&&this._positionVariance.y===J.y&&this._positionVariance.z===J.z)return;if(this._positionVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:J})}setRate(J){if(this._rate===J)return;if(this._rate=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:J})}setRateVariance(J){if(this._rateVariance===J)return;if(this._rateVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:J})}setSizeEnd(J){if(this._sizeEnd===J)return;if(this._sizeEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:J})}setSizeEndVariance(J){if(this._sizeEndVariance===J)return;if(this._sizeEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:J})}setSizeStart(J){if(this._sizeStart===J)return;if(this._sizeStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:J})}setSizeStartVariance(J){if(this._sizeStartVariance===J)return;if(this._sizeStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:J})}setTextureUri(J){if(this._textureUri===J)return;if(this._textureUri=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:J})}setTransparent(J){if(this._transparent===J)return;if(this._transparent=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:J})}setVelocity(J){if(this._velocity&&this._velocity.x===J.x&&this._velocity.y===J.y&&this._velocity.z===J.z)return;if(this._velocity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:J})}setVelocityVariance(J){if(this._velocityVariance&&this._velocityVariance.x===J.x&&this._velocityVariance.y===J.y&&this._velocityVariance.z===J.z)return;if(this._velocityVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:J})}burst(J){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:J})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return s.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=J.particleEmitterManager.registerParticleEmitter(this),this._world=J,this.emitWithWorld(J,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return H1.serializeParticleEmitter(this)}}var IT6={x:0,y:-32,z:0},kn=60,En;((Q)=>{Q.STEP_START="SIMULATION.STEP_START";Q.STEP_END="SIMULATION.STEP_END";Q.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";Q.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(En||={});class BB extends $1{_colliderMap=new I2;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(J,$=kn,X=IT6){super();this._rapierEventQueue=new W8.EventQueue(!0),this._rapierSimulation=new W8.World(X),this._rapierSimulation.timestep=Math.fround(1/$),this._world=J}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(J,$){return this._rapierSimulation.createCollider(J,$)}createRawRigidBody(J){return this._rapierSimulation.createRigidBody(J)}enableDebugRaycasting(J){this._debugRaycastingEnabled=J}enableDebugRendering(J,$=W8.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=J,this._debugRenderingFilterFlags=$}getContactManifolds(J,$){let X=[];return this._rapierSimulation.narrowPhase.contactPair(J,$,(Y,Q)=>{if(Y.numContacts()===0)return;let K=Y.normal(),W=[];for(let Z=0;Z<Y.numSolverContacts();Z++)W.push(Y.solverContactPoint(Z));X.push({contactPoints:W,localNormalA:!Q?Y.localNormal1():Y.localNormal2(),localNormalB:!Q?Y.localNormal2():Y.localNormal1(),normal:!Q?K:{x:-K.x,y:-K.y,z:-K.z}})}),X}intersectionsWithRawShape(J,$,X,Y={}){let Q=new Set,K=[];return this._rapierSimulation.intersectionsWithShape($,X,J,(W)=>{let Z=this._colliderMap.getColliderHandleBlockType(W.handle);if(Z&&!Q.has(Z))return Q.add(Z),K.push({intersectedBlockType:Z}),!0;let G=this._colliderMap.getColliderHandleEntity(W.handle);if(G&&!Q.has(G))return Q.add(G),K.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),K}raycast(J,$,X,Y={}){let Q=new W8.Ray(J,$),K=this._rapierSimulation.castRay(Q,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:J,direction:$,length:X,hit:!!K});if(!K)return null;let W=Q.pointAt(K.timeOfImpact),Z=K.timeOfImpact,G=K.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:c3.fromGlobalCoordinate({x:Math.floor(W.x-(Q.dir.x<0?0.0001:-0.0001)),y:Math.floor(W.y-(Q.dir.y<0?0.0001:-0.0001)),z:Math.floor(W.z-(Q.dir.z<0?0.0001:-0.0001))},V),hitPoint:W,hitDistance:Z};let q=this._colliderMap.getColliderHandleEntity(G.handle);if(q)return{hitEntity:q,hitPoint:W,hitDistance:Z};return null}removeRawCollider(J){this._colliderMap.queueColliderHandleForCleanup(J.handle),this._rapierSimulation.removeCollider(J,!1)}removeRawRigidBody(J){this._rapierSimulation.removeRigidBody(J)}setGravity(J){this._rapierSimulation.gravity=J}step=(J)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:J});let $=performance.now();if(I6.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),I6.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-$}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(J,$,X)=>{let[Y,Q]=this._getCollisionObjects(J,$);if(!Y||!Q)return;let K=(W,Z)=>{if(W instanceof g9&&Z instanceof g6&&W.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))W.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:W,entity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(W instanceof g6&&Z instanceof g9&&W.hasListeners("ENTITY.BLOCK_COLLISION"))W.emit("ENTITY.BLOCK_COLLISION",{entity:W,blockType:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(W instanceof g6&&Z instanceof g6&&W.hasListeners("ENTITY.ENTITY_COLLISION"))W.emit("ENTITY.ENTITY_COLLISION",{entity:W,otherEntity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(typeof W==="function"&&(Z instanceof g6||Z instanceof g9))W(Z,X,J,$)};K(Y,Q),K(Q,Y)};_onContactForceEvent=(J)=>{let[$,X]=this._getCollisionObjects(J.collider1(),J.collider2());if(!$||typeof $==="function"||!X||typeof X==="function")return;let Y={totalForce:J.totalForce(),totalForceMagnitude:J.totalForceMagnitude(),maxForceDirection:J.maxForceDirection(),maxForceMagnitude:J.maxForceMagnitude()},Q=(K,W)=>{if(K instanceof g9&&W instanceof g6&&K.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))K.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:K,entity:W,contactForceData:Y});else if(K instanceof g6&&W instanceof g9&&K.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))K.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:K,blockType:W,contactForceData:Y});else if(K instanceof g6&&W instanceof g6&&K.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))K.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:K,otherEntity:W,contactForceData:Y})};Q($,X),Q(X,$)};_getCollisionObjects(J,$){let X=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J),Y=this._colliderMap.getColliderHandleBlockType($)??this._colliderMap.getColliderHandleCollisionCallback($)??this._colliderMap.getColliderHandleEntity($);return[X,Y]}}class $T{_synchronizedPlayerReliablePackets=new O5;_queuedBroadcasts=[];_queuedAudioSynchronizations=new O5;_queuedBlockSynchronizations=new O5;_queuedBlockTypeSynchronizations=new O5;_queuedChunkSynchronizations=new O5;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new O5;_queuedLightSynchronizations=new O5;_queuedParticleEmitterSynchronizations=new O5;_queuedPerPlayerSynchronizations=new O5;_queuedPerPlayerCameraSynchronizations=new O5;_queuedPerPlayerUISynchronizations=new O5;_queuedPerPlayerUIDatasSynchronizations=new O5;_queuedPlayerSynchronizations=new O5;_queuedSceneUISynchronizations=new O5;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(J){this._world=J,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let J=[],$=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(...Q);if(this._queuedEntitySynchronizations.size>0){let Y=[],Q=[];for(let K of this._queuedEntitySynchronizations.valuesArray){let W=!1;for(let Z in K)if(Z!=="i"&&Z!=="p"&&Z!=="r"){W=!0;break}if(W)Y.push(K);else Q.push(K)}if(Q.length>0){let K=c0.createPacket(c0.outboundPackets.entitiesPacketDefinition,Q,X);$.push(K)}if(Y.length>0){let K=c0.createPacket(c0.outboundPackets.entitiesPacketDefinition,Y,X);J.push(K);for(let W of this._synchronizedPlayerReliablePackets.valuesArray)W.push(K)}}if(this._queuedAudioSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUISynchronizations){let K=c0.createPacket(c0.outboundPackets.uiPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(K)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUIDatasSynchronizations){let K=c0.createPacket(c0.outboundPackets.uiDatasPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(K)}if(this._queuedSceneUISynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedWorldSynchronization){let Y=c0.createPacket(c0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerCameraSynchronizations){let K=c0.createPacket(c0.outboundPackets.cameraPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(K)}if(this._queuedPlayerSynchronizations.size>0){let Y=c0.createPacket(c0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=c0.createPacket(c0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}I6.startSpan({operation:"send_all_packets"},()=>{for(let Y of O$.instance.getConnectedPlayersByWorld(this._world)){let Q=this._synchronizedPlayerReliablePackets.get(Y)??J;if(Q.length>0)Y.connection.send(Q);if($.length>0)Y.connection.send($,!1)}}),I6.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();R$.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_NOTIFICATION_PERMISSION",this._onPlayerRequestNotificationPermission),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity),this._world.final("WORLD.SET_SKYBOX_URI",this._onWorldSetSkyboxUri)}_onAudioPause=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pa=!0,delete $.pl,delete $.r};_onAudioPlay=(J)=>{let $=J.audio.serialize();$.pl=!0,delete $.pa,delete $.r,this._queuedAudioSynchronizations.set($.i,$)};_onAudioPlayRestart=(J)=>{let $=J.audio.serialize();$.r=!0,delete $.pa,delete $.pl,this._queuedAudioSynchronizations.set($.i,$)};_onAudioSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onAudioSetCutoffDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.cd=J.cutoffDistance};_onAudioSetDetune=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.de=J.detune};_onAudioSetDistortion=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.di=J.distortion};_onAudioSetPosition=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.position?void 0:$.e,$.p=J.position?H1.serializeVector(J.position):void 0};_onAudioSetPlaybackRate=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pr=J.playbackRate};_onAudioSetReferenceDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.rd=J.referenceDistance};_onAudioSetVolume=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.v=J.volume};_onBlockTypeRegistryRegisterBlockType=(J)=>{let $=J.blockType.serialize();this._queuedBlockTypeSynchronizations.set(J.blockType.id,$)};_onChatSendBroadcastMessage=(J)=>{let{player:$,message:X,color:Y}=J;this._queuedBroadcasts.push(c0.createPacket(c0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:$?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(J)=>{let{player:$,message:X,color:Y}=J,Q=this._queuedPerPlayerSynchronizations.get($)??[];Q.push(c0.createPacket(c0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,Q)};_onChunkLatticeAddChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk);$.b=Array.from(J.chunk.blocks),$.rm=void 0,this._spawnedChunks.add($.c.join(","))};_onChunkLatticeRemoveChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk),X=$.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else $.rm=!0};_onChunkLatticeSetBlock=(J)=>{let $=this._createOrGetQueuedBlockSync(J.globalCoordinate);$.i=J.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.ap=J.playbackRate};_onEntitySpawn=(J)=>{let $=J.entity.serialize();this._queuedEntitySynchronizations.set($.i,$),this._spawnedEntities.add($.i)};_onEntityDespawn=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if(this._spawnedEntities.has($.i))this._queuedEntitySynchronizations.delete($.i),this._spawnedEntities.delete($.i);else $.rm=!0};_onEntitySetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.h=Array.from(J.modelHiddenNodes)};_onEntitySetModelScale=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.s=J.modelScale};_onEntitySetModelShownNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.sn=Array.from(J.modelShownNodes)};_onEntitySetModelTextureUri=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.mt=J.modelTextureUri};_onEntitySetOpacity=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.o=J.opacity};_onEntitySetParent=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.pe=J.parent?J.parent.id:void 0,$.pn=J.parentNodeName};_onEntitySetTintColor=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.t=J.tintColor?H1.serializeRgbColor(J.tintColor):void 0};_onEntityStartModelLoopedAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al=Array.from(new Set([...$.al??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.ao=Array.from(new Set([...$.ao??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al)$.al=$.al.filter((X)=>!J.animations.has(X)).filter(Boolean);if($.ao)$.ao=$.ao.filter((X)=>!J.animations.has(X)).filter(Boolean);$.as=Array.from(new Set([...$.as??[],...J.animations]))};_onEntityUpdateRotation=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.r=[J.rotation.x,J.rotation.y,J.rotation.z,J.rotation.w]};_onEntityUpdatePosition=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.p=[J.position.x,J.position.y,J.position.z]};_onLightDespawn=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.rm=!0};_onLightSetAngle=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.a=J.angle};_onLightSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onLightSetColor=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.c=H1.serializeRgbColor(J.color)};_onLightSetDistance=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.d=J.distance};_onLightSetIntensity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.n=J.intensity};_onLightSetOffset=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.o=J.offset?H1.serializeVector(J.offset):void 0};_onLightSetPenumbra=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.pe=J.penumbra};_onLightSetPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.p=J.position?H1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onLightSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.te=J.entity?J.entity.id:void 0,$.tp=J.entity?void 0:$.tp};_onLightSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.tp=J.position?H1.serializeVector(J.position):void 0,$.te=J.position?void 0:$.te};_onLightSpawn=(J)=>{let $=J.light.serialize();this._queuedLightSynchronizations.set($.i,$)};_onParticleEmitterBurst=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.b=J.count};_onParticleEmitterDespawn=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rm=!0};_onParticleEmitterSetAlphaTest=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.at=J.alphaTest};_onParticleEmitterSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onParticleEmitterSetAttachedToEntityNodeName=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.en=J.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ce=J.colorEnd?H1.serializeRgbColor(J.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cev=J.colorEndVariance?H1.serializeRgbColor(J.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cs=J.colorStart?H1.serializeRgbColor(J.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.csv=J.colorStartVariance?H1.serializeRgbColor(J.colorStartVariance):void 0};_onParticleEmitterSetGravity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.g=J.gravity?H1.serializeVector(J.gravity):void 0};_onParticleEmitterSetLifetime=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.l=J.lifetime};_onParticleEmitterSetLifetimeVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.lv=J.lifetimeVariance};_onParticleEmitterSetMaxParticles=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.mp=J.maxParticles};_onParticleEmitterSetOffset=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.o=J.offset?H1.serializeVector(J.offset):void 0};_onParticleEmitterSetOpacityEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oe=J.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oev=J.opacityEndVariance};_onParticleEmitterSetOpacityStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.os=J.opacityStart};_onParticleEmitterSetOpacityStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.osv=J.opacityStartVariance};_onParticleEmitterSetPaused=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pa=J.paused};_onParticleEmitterSetPosition=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.p=J.position?H1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e,$.en=J.position?void 0:$.en};_onParticleEmitterSetPositionVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pv=J.positionVariance?H1.serializeVector(J.positionVariance):void 0};_onParticleEmitterSetRate=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.r=J.rate};_onParticleEmitterSetRateVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rv=J.rateVariance};_onParticleEmitterSetSizeEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.se=J.sizeEnd};_onParticleEmitterSetSizeEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.sev=J.sizeEndVariance};_onParticleEmitterSetSizeStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ss=J.sizeStart};_onParticleEmitterSetSizeStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ssv=J.sizeStartVariance};_onParticleEmitterSetTextureUri=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.tu=J.textureUri};_onParticleEmitterSetTransparent=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.t=J.transparent};_onParticleEmitterSetVelocity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.v=J.velocity?H1.serializeVector(J.velocity):void 0};_onParticleEmitterSetVelocityVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.vv=J.velocityVariance?H1.serializeVector(J.velocityVariance):void 0};_onParticleEmitterSpawn=(J)=>{let $=J.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set($.i,$)};_onPlayerCameraLookAtEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=H1.serializeVector(J.entity.position),delete $.et,delete $.pt};_onPlayerCameraLookAtPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=J.position?H1.serializeVector(J.position):void 0,delete $.et,delete $.pt};_onPlayerCameraSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.e=J.entity.id,delete $.p};_onPlayerCameraSetAttachedToPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.p=J.position?H1.serializeVector(J.position):void 0,delete $.e};_onPlayerCameraSetFilmOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fo=J.filmOffset};_onPlayerCameraSetForwardOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.ffo=J.forwardOffset};_onPlayerCameraSetFov=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fv=J.fov};_onPlayerCameraSetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.h=Array.from(J.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.s=Array.from(J.modelShownNodes)};_onPlayerCameraSetMode=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.m=J.mode};_onPlayerCameraSetOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.o=J.offset?H1.serializeVector(J.offset):void 0};_onPlayerCameraSetShoulderAngle=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.sa=J.shoulderAngle};_onPlayerCameraSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.et=J.entity?J.entity.id:void 0,delete $.pl,delete $.pt};_onPlayerCameraSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pt=J.position?H1.serializeVector(J.position):void 0,delete $.et,delete $.pl};_onPlayerCameraSetZoom=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.z=J.zoom};_onPlayerJoinedWorld=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(c0.createPacket(c0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((Q)=>{if($.camera.attachedToEntity===void 0&&Q instanceof KX&&Q.player===$)$.camera.setAttachedToEntity(Q);return Q.serialize()}),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(c0.createPacket(c0.outboundPackets.playersPacketDefinition,O$.instance.getConnectedPlayers().map((Q)=>Q.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync($.camera);this._queuedPerPlayerCameraSynchronizations.set($,{...$.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set($,X),this._queuedPlayerSynchronizations.set($.id,$.serialize())};_onPlayerLeftWorld=(J)=>{let $=this._createOrGetQueuedPlayerSync(J.player);$.rm=!0};_onPlayerReconnectedWorld=(J)=>{this._onPlayerJoinedWorld(J)};_onPlayerRequestNotificationPermission=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(c0.createPacket(c0.outboundPackets.notificationPermissionRequestPacketDefinition,null,this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,X)};_onPlayerRequestSync=(J)=>{J.player.connection.send([c0.createPacket(c0.outboundPackets.syncResponsePacketDefinition,{r:J.receivedAt,s:Date.now(),p:performance.now()-J.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.u=J.htmlUri};_onPlayerUILockPointer=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.p=J.lock};_onPlayerUISendData=(J)=>{this._createOrGetQueuedPlayerUIDatasSync(J.playerUI).push(J.data)};_onSceneUILoad=(J)=>{let $=J.sceneUI.serialize();this._queuedSceneUISynchronizations.set($.i,$),this._loadedSceneUIs.add($.i)};_onSceneUISetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onSceneUISetOffset=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.o=J.offset?H1.serializeVector(J.offset):void 0};_onSceneUISetPosition=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.p=J.position?H1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onSceneUISetState=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.s=J.state};_onSceneUISetViewDistance=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.v=J.viewDistance};_onSceneUIUnload=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);if(this._loadedSceneUIs.has($.i))this._queuedSceneUISynchronizations.delete($.i),this._loadedSceneUIs.delete($.i);else $.rm=!0};_onSimulationDebugRaycast=(J)=>{this._queuedDebugRaycastSynchronizations.push(H1.serializePhysicsDebugRaycast(J))};_onSimulationDebugRender=(J)=>{this._queuedBroadcasts.push(c0.createPacket(c0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(J.vertices),c:Array.from(J.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ac=H1.serializeRgbColor(J.color)};_onWorldSetAmbientLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ai=J.intensity};_onWorldSetDirectionalLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dc=H1.serializeRgbColor(J.color)};_onWorldSetDirectionalLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.di=J.intensity};_onWorldSetDirectionalLightPosition=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dp=H1.serializeVector(J.position)};_onWorldSetFogColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fc=H1.serializeRgbColor(J.color)};_onWorldSetFogFar=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ff=J.far};_onWorldSetFogNear=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fn=J.near};_onWorldSetSkyboxIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.si=J.intensity};_onWorldSetSkyboxUri=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.s=J.uri};_createOrGetQueuedAudioSync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let $=this._queuedAudioSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedAudioSynchronizations.set(J.id,$);return $}_createOrGetQueuedBlockSync(J){let{x:$,y:X,z:Y}=J,Q=`${$},${X},${Y}`,K=this._queuedBlockSynchronizations.get(Q);if(!K)K={i:0,c:[$,X,Y]},this._queuedBlockSynchronizations.set(Q,K);return K}_createOrGetQueuedChunkSync(J){if(!J.originCoordinate)s.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:$,y:X,z:Y}=J.originCoordinate,Q=`${$},${X},${Y}`,K=this._queuedChunkSynchronizations.get(Q);if(!K)K={c:[$,X,Y]},this._queuedChunkSynchronizations.set(Q,K);return K}_createOrGetQueuedEntitySync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let $=this._queuedEntitySynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedEntitySynchronizations.set(J.id,$);return $}_createOrGetQueuedLightSync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let $=this._queuedLightSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedLightSynchronizations.set(J.id,$);return $}_createOrGetQueuedParticleEmitterSync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let $=this._queuedParticleEmitterSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedParticleEmitterSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerSync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let $=this._queuedPlayerSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedPlayerSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerCameraSync(J){let $=this._queuedPerPlayerCameraSynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerCameraSynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUISync(J){let $=this._queuedPerPlayerUISynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerUISynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUIDatasSync(J){let $=this._queuedPerPlayerUIDatasSynchronizations.get(J.player);if(!$)$=[],this._queuedPerPlayerUIDatasSynchronizations.set(J.player,$);return $}_createOrGetQueuedSceneUISync(J){if(J.id===void 0)s.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let $=this._queuedSceneUISynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedSceneUISynchronizations.set(J.id,$);return $}_createOrGetQueuedWorldSync(J){if(J.id!==this._world.id)s.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:J.id}}_createOrGetSynchronizedPlayerReliablePackets(J,$){let X=this._synchronizedPlayerReliablePackets.get(J);if(!X)X=[...$],this._synchronizedPlayerReliablePackets.set(J,X);return X}}class LB{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedParticleEmitters(J){this.getAllEntityAttachedParticleEmitters(J).forEach(($)=>{$.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(J){return this.getAllParticleEmitters().filter(($)=>$.attachedToEntity===J)}registerParticleEmitter(J){if(J.id!==void 0)return J.id;let $=this._nextParticleEmitterId;return this._particleEmitters.set($,J),this._nextParticleEmitterId++,$}unregisterParticleEmitter(J){if(J.id===void 0)return;this._particleEmitters.delete(J.id)}}class wB{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(J){this._world=J}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(J){return this.getAllSceneUIs().filter(($)=>$.attachedToEntity===J)}getSceneUIById(J){return this._sceneUIs.get(J)}registerSceneUI(J){if(J.id!==void 0)return J.id;let $=this._nextSceneUIId;return this._sceneUIs.set($,J),this._nextSceneUIId++,$}unloadEntityAttachedSceneUIs(J){this.getAllEntityAttachedSceneUIs(J).forEach(($)=>{$.unload()})}unregisterSceneUI(J){if(J.id===void 0)return;this._sceneUIs.delete(J.id)}}var AT6=2,_T6=3;class MB{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(J,$,X){this._targetTicksPerSecond=J,this._fixedTimestepS=Math.fround(1/J),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*_T6,this._tickFunction=$,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let J=()=>{let $=performance.now(),X=$-this._lastLoopTimeMs;if(this._lastLoopTimeMs=$,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)I6.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<AT6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(J,this._nextTickMs)};J()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(J){try{this._tickFunction(J)}catch($){if($ instanceof Error&&this._tickErrorCallback)this._tickErrorCallback($);else s.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${$}`)}}}var mR1;((K)=>{K.START="WORLD_LOOP.START";K.STOP="WORLD_LOOP.STOP";K.TICK_START="WORLD_LOOP.TICK_START";K.TICK_END="WORLD_LOOP.TICK_END";K.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(mR1||={});class NB extends $1{_currentTick=0;_ticker;_world;constructor(J,$=kn){super();this._ticker=new MB($,this._tick,this._onTickError),this._world=J}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(J)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:J});let $=performance.now();I6.startSpan({operation:"world_tick",attributes:{serverPlayerCount:O$.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{I6.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(J)),I6.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(J)),I6.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),I6.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-$})};_onTickError=(J)=>{s.error(`WorldLoop._onTickError(): Error: ${J}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:J})}}var Sn;((H)=>{H.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";H.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";H.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";H.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";H.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";H.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";H.SET_FOG_FAR="WORLD.SET_FOG_FAR";H.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";H.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";H.SET_SKYBOX_URI="WORLD.SET_SKYBOX_URI";H.START="WORLD.START";H.STOP="WORLD.STOP"})(Sn||={});class RB extends $1{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;constructor(J){super();if(this._id=J.id,this._ambientLightColor=J.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=J.ambientLightIntensity??1,this._directionalLightColor=J.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=J.directionalLightIntensity??3,this._directionalLightPosition=J.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=J.fogColor,this._fogFar=J.fogFar??550,this._fogNear=J.fogNear??500,this._name=J.name,this._skyboxIntensity=J.skyboxIntensity??1,this._skyboxUri=J.skyboxUri,this._tag=J.tag,this._audioManager=new kz(this),this._blockTypeRegistry=new iF(this),this._chatManager=new E2(this),this._chunkLattice=new S2(this),this._entityManager=new c2(this),this._lightManager=new jB(this),this._loop=new NB(this,J.tickRate),this._networkSynchronizer=new $T(this),this._particleEmitterManager=new LB(this),this._sceneUIManager=new wB(this),this._simulation=new BB(this,J.tickRate,J.gravity),J.map)this.loadMap(J.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}loadMap(J){if(this.chunkLattice.clear(),J.blockTypes)for(let $ of J.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:$.id,isLiquid:$.isLiquid,lightLevel:$.lightLevel,name:$.name,textureUri:$.textureUri});if(J.blocks){let $={};for(let X in J.blocks){let Y=J.blocks[X],Q=X.indexOf(","),K=X.indexOf(",",Q+1),W=Number(X.slice(0,Q)),Z=Number(X.slice(Q+1,K)),G=Number(X.slice(K+1));if(!$[Y])$[Y]=[];$[Y].push({x:W,y:Z,z:G})}this.chunkLattice.initializeBlocks($)}if(J.entities)for(let $ in J.entities){let X=J.entities[$],Y=$.indexOf(","),Q=$.indexOf(",",Y+1),K=Number($.slice(0,Y)),W=Number($.slice(Y+1,Q)),Z=Number($.slice(Q+1));new g6({isEnvironmental:!0,...X}).spawn(this,{x:K,y:W,z:Z})}}setAmbientLightColor(J){this._ambientLightColor=J,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:J})}setAmbientLightIntensity(J){this._ambientLightIntensity=J,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightColor(J){this._directionalLightColor=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:J})}setDirectionalLightIntensity(J){this._directionalLightIntensity=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightPosition(J){this._directionalLightPosition=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:J})}setFogColor(J){this._fogColor=J,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:J})}setFogFar(J){this._fogFar=J,this.emit("WORLD.SET_FOG_FAR",{world:this,far:J})}setFogNear(J){this._fogNear=J,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:J})}setSkyboxIntensity(J){this._skyboxIntensity=J,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:J})}setSkyboxUri(J){this._skyboxUri=J,this.emit("WORLD.SET_SKYBOX_URI",{world:this,uri:J})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return H1.serializeWorld(this)}}var uR1;(($)=>$.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(uR1||={});class iW{static instance=new iW;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(J){let $=new RB({...J,id:this._nextWorldId++});return $.start(),this._worlds.set($.id,$),$1.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:$}),$}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(J){let $=[];return this._worlds.forEach((X)=>{if(X.tag===J)$.push(X)}),$}getWorld(J){return this._worlds.get(J)}setDefaultWorld(J){this._defaultWorld=J}}var gR1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(gR1||={});class O${static instance=new O$;worldSelectionHandler;_connectionPlayers=new Map;constructor(){$1.globalInstance.on("CONNECTION.OPENED",({connection:J,session:$})=>{this._onConnectionOpened(J,$)}),$1.globalInstance.on("CONNECTION.DISCONNECTED",({connection:J})=>{this._onConnectionDisconnected(J)}),$1.globalInstance.on("CONNECTION.RECONNECTED",({connection:J})=>{this._onConnectionReconnected(J)}),$1.globalInstance.on("CONNECTION.CLOSED",({connection:J})=>{this._onConnectionClosed(J)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(J){return this.getConnectedPlayers().filter(($)=>$.world===J)}getConnectedPlayerByUsername(J){return Array.from(this._connectionPlayers.values()).find(($)=>{return $.username.toLowerCase()===J.toLowerCase()})}async _onConnectionOpened(J,$){let X=new gq(J,$);await X.loadInitialPersistedData(),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??iW.instance.getDefaultWorld()),this._connectionPlayers.set(J,X)}_onConnectionDisconnected(J){let $=this._connectionPlayers.get(J);if($)$.resetInputs(),$.camera.reset()}_onConnectionReconnected(J){let $=this._connectionPlayers.get(J);if($)$.reconnected(),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:$});else s.warning(`PlayerManager._onConnectionReconnected(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(J){let $=this._connectionPlayers.get(J);if($)$.disconnect(),this._connectionPlayers.delete(J),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:$});else s.warning(`PlayerManager._onConnectionClosed(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}}import{randomBytes as qk6}from"crypto";import{ReadableStream as Jk6}from"node:stream/web";import{ReadableStream as hT6,WritableStream as fT6}from"node:stream/web";var Lz=hT6,XT=fT6;var YT=L0(L9(),1);function In(){let J=()=>{},$=()=>{};return{promise:new Promise((Y,Q)=>{J=Y,$=Q}),resolve:J,reject:$}}function G6(J){let $=!!(typeof process>"u"||process.env.DEBUG_TRACE);return Object.assign(YT.default(J),{error:YT.default(`${J}:error`),trace:$?YT.default(`${J}:trace`):()=>{}})}class O9 extends Error{constructor(J){super(J);this.name=this[Symbol.toStringTag]="WebTransportError"}}var pR1=!0;try{let J=new ReadableStream({start:($)=>{},type:"bytes"})}catch(J){pR1=!1}var QT=pR1;var yT6=typeof process<"u"?process.pid:0,BJ=G6(`webtransport:http3wtstream(${yT6})`);class An{constructor(J){if(this.objint=J.object,this.objint.jsobj=this,this.parentobj=J.parentobj,this.transport=J.transport,this.bidirectional=J.bidirectional,this.incoming=J.incoming,this.closed=!1,this._sendGroup=J.sendGroup,this._sendOrder=J.sendOrder,this.objint.sendInitialParameters)this.objint.sendInitialParameters();if(this.pendingoperation=null,this.pendingres=null,this.readable,this.writable,this.pendingoperationRead=null,this.pendingresRead=null,this.bidirectional||this.incoming){let $={start:(X)=>{this.readableController=X,this.objint.startReading()},pull:async(X)=>{if(this.readableclosed)return Promise.resolve();this.pendingoperationRead=new Promise((Y,Q)=>{this.pendingresRead=Y}),this.objint.startReading(),await this.pendingoperationRead},cancel:(X)=>{let Y=new Promise((K,W)=>{this.cancelres=K}),Q=0;if(X&&X.code)if(X.code<0)Q=0;else if(X.code>255)Q=255;else Q=X.code;return this.readableclosed=!0,this.objint.stopSending(Q),Y},type:"bytes",autoAllocateChunkSize:4096};if(!QT)delete $.type;this.readable=new Lz($),this.readable.getStats=()=>{return Promise.resolve({timestamp:0,bytesReceived:0n,bytesRead:0n})},this.parentobj.addReceiveStream(this.readable,this.readableController)}if(this.bidirectional||!this.incoming)this.writable=new XT({start:($)=>{this.writableController=$},write:($,X)=>{if(this.writableclosed)return Promise.resolve();let Y=$;if(Y instanceof ArrayBuffer)Y=new Uint8Array(Y);if(Y instanceof Uint8Array){if(Y.byteLength===0)return;return this.pendingoperation=new Promise((Q,K)=>{this.pendingres=Q}),this.objint.writeChunk(Y),this.pendingoperation}else throw BJ.trace("chunk info:",$),Error("chunk is not of instanceof Uint8Array or Arraybuffer")},close:()=>{if(this.writableclosed)return Promise.resolve();return this.objint.streamFinal(),this.pendingoperation=new Promise(($,X)=>{this.pendingres=$}),this.pendingoperation},abort:($)=>{if(this.writableclosed)return new Promise((Q,K)=>{Q()});let X=0;if($&&$.code)if($.code<0)X=0;else if($.code>255)X=255;else X=$.code;let Y=new Promise((Q,K)=>{this.abortres=Q});return this.objint.resetStream(X),Y}},{highWaterMark:4}),this.writable.getStats=()=>{return Promise.resolve({timestamp:0,bytesWritten:0n,bytesSent:0n,bytesAcknowledged:0n})},Object.defineProperties(this.writable,{sendOrder:{get:()=>{return this._sendOrder},set:($)=>{if($!==this._sendOrder)this._sendOrder=J.sendOrder,this.updateSendOrderAndGroup()}},sendGroup:{get:()=>{return this._sendGroup},set:($)=>{if($!==this._sendGroup)this._sendGroup=$,this.updateSendOrderAndGroup()}}}),this.parentobj.addSendStream(this.writable,this.writableController);this.cancelres=null,this.pendingres=null,this.abortres=null,this.finaldrain_=!1}getReadBuffer({byteSize:J}){let $=this.readableController.byobRequest;if($){let X=$?.view;if(!(X instanceof Uint8Array))throw Error("byob view is not a Uint8Array");return{buffer:X,byob:$,readBytes:0,fin:!1}}else return{buffer:new Uint8Array(J),byob:void 0,readBytes:0,fin:!1}}commitReadBuffer({buffer:J,byob:$,drained:X,readBytes:Y,fin:Q}){if(!this.readableclosed){if($&&Y!==void 0)$.respond(Y);else if(J)this.readableController.enqueue(J)}let K={};if(Y!==void 0&&Y>0&&!this.readableclosed){if(BJ.trace("commitReadbuffer",Y),this.pendingoperationRead&&X){if(this.readableController.desiredSize!=null&&!this.finaldrain_){if(this.readableController.desiredSize<0)K.stopReading=!0}let W=this.pendingresRead;if(this.pendingoperationRead=null,this.pendingresRead=null,W)W()}}if(Q){if(this.cancelres){let Z=this.cancelres;this.cancelres=null,Z()}let W=this.parentobj.state;if(W==="closed"||W==="failed")BJ("no parent cleanup for fin as parent was closed or failed");else this.parentobj.removeReceiveStream(this.readable,this.readableController);if(!this.readableclosed)this.readableController.close(),this.readableclosed=!0}return K}updateSendOrderAndGroup(){this.objint.updateSendOrderAndGroup({sendOrder:this._sendOrder,sendGroupId:this._sendGroup._sendGroupId})}onStreamRecvSignal(J){BJ("callback",J?.nettask),BJ.trace("onStreamRecvSignal",J);let $=!0,X=this.parentobj.state;if(X==="closed"||X==="failed")BJ("no parent cleanup as parent was closed or failed"),$=!1;switch(J.nettask){case"resetStream":if(this.readable){if(this.finalDrain(),$)this.parentobj.removeReceiveStream(this.readable,this.readableController);if(!this.readableclosed)this.readableclosed=!0,this.readableController.error(new O9("Resetstream with code:"+(J.code||0)))}else BJ.error("resetStream without readable");break;case"stopSending":if(this.writable){if($)this.parentobj.removeSendStream(this.writable,this.writableController);if(!this.writableclosed)this.writableclosed=!0,this.writableController.error(new O9("StopSending with code:"+(J.code||0)))}else BJ.error("stopSending without writable");break;default:BJ.error("unhandled onStreamRecvSignal")}if(this.pendingoperation){let Y=this.pendingres;if(this.pendingoperation=null,this.pendingres=null,Y!=null)Y()}if(this.pendingoperationRead){let Y=this.pendingresRead;if(this.pendingoperationRead=null,this.pendingresRead=null,Y!=null)Y()}}finalDrain(){this.finaldrain_=!0,this.objint.drainReads()}onStreamWrite(J){if(this.pendingoperation){let $=this.pendingres;if(this.pendingoperation=null,this.pendingres=null,$!=null)$()}}onStreamNetworkFinish(J){switch(BJ("callback",J?.nettask),BJ.trace("networkfinish args",J),J.nettask){case"stopSending":if(this.cancelres){let $=this.cancelres;this.cancelres=null,$()}this.stopSendingRecv=!0;break;case"resetStream":if(this.abortres){let $=this.abortres;if(this.abortres=null,$(),this.readable)this.parentobj.removeReceiveStream(this.readable,this.readableController);if(this.writable)this.parentobj.removeSendStream(this.writable,this.writableController);this.readableclosed=!0,this.parentobj.removeStreamObj(this)}break;case"streamFinal":if(this.pendingoperation){let $=this.pendingres;if(this.pendingoperation=null,this.pendingres=null,$!=null)$()}break;default:BJ.error("onStreamNetworkFinish unknown task",J.nettask)}}}var lR1=typeof process<"u"?process.pid:0,OB=G6(`webtransport:httpwtsession(${lR1})`);class KT{constructor(J){if(J.object){if(this.objint=J.object,this.objint.jsobj=this,this.objint.sendInitialParameters)this.objint.sendInitialParameters()}this.parentobj=J.parentobj,this.state="connecting",this.readyResolve=null,this.closeHook=null,this.header=J.header,this.userData=J.userData,this.peerAddress_=J.peerAddress,this.datagramsReadableMode_=J.datagramsReadableMode,this.ready=new Promise((X,Y)=>{this.readyResolve=X,this.readyReject=Y}),this.reliability="pending",this.congestionControl="default",this.closed=new Promise((X,Y)=>{this.closedResolve=X,this.closedReject=Y}),this.draining=new Promise((X,Y)=>{this.drainingResolve=X,this.drainingReject=Y}),this.incomingBidirectionalStreams=new Lz({start:(X)=>{this.incomBiDiController=X}}),this.incomingUnidirectionalStreams=new Lz({start:(X)=>{this.incomUniDiController=X}}),this.incomDatagramControllerBytes_=void 0,this.incomDatagramController_=void 0;let $={start:(X)=>{if(this.datagramsReadableMode_==="bytes")this.incomDatagramControllerBytes_=X;else this.incomDatagramController_=X},type:void 0};if(this.datagramsReadableMode_==="bytes")$.type="bytes";if(!QT)delete $.type;this._lastGetMaxDatagramSize=0,this.datagrams={readable:new Lz($),createWritable:(X)=>{let Y=X?.sendOrder??0n,Q=X?.sendGroup,K=new XT({start:(W)=>{this.outgoDatagramController=W},write:(W,Z)=>{if(this.state==="closed")throw Error("Session is closed");if(W instanceof Uint8Array){if(this.objint==null)throw Error("this.objint is not set");let{code:G,message:V}=this.objint.writeDatagram(W);if(G!=="success"&&G!=="blocked"&&G!=="tooBig")throw new O9(G+":"+V)}else throw Error("chunk is not of type Uint8Array")},close:()=>{}});return Object.defineProperties(K,{sendOrder:{get:()=>{return Y},set:(W)=>{Y=W}},sendGroup:{get:()=>{return Q},set:(W)=>{if(W!==Q)Q=W}}}),K},get writable(){if(!this.datagramwritablepolyfilled_)console.warn("datagrams.writable is deprecated");return this.datagramwritablepolyfilled_||=this.createWritable()},get maxDatagramSize(){return this._getMaxDatagramSize()},_getMaxDatagramSize:()=>{if(this.objint)this._lastGetMaxDatagramSize=this.objint.getMaxDatagramSize();return this._lastGetMaxDatagramSize}},this.resolveBiDi=[],this.resolveUniDi=[],this.rejectBiDi=[],this.rejectUniDi=[],this.resolveSessionStats=[],this.rejectSessionStats=[],this.resolveDatagramStats=[],this.rejectDatagramStats=[],this.sendStreams=new Set,this.receiveStreams=new Set,this.streamObjs=new Set,this.sendStreamsController=new Set,this.receiveStreamsController=new Set,this._sendGroupNum=1n,this._sendGroupIndex=new Map,this._selectedProtocol=void 0}setSessionObj(J,$){if(J){if(this.objint=J,this.objint.jsobj=this,this.reliable=!!$,this.objint.sendInitialParameters)this.objint.sendInitialParameters()}}get protocol(){return this._selectedProtocol}getStats(){if(this.objint==null)throw Error("this.objint not set");let J=new Promise(($,X)=>{this.resolveSessionStats.push($),this.rejectSessionStats.push(X)});return this.objint.orderSessionStats(),J}onSessionStats({timestamp:J,expiredOutgoing:$=BigInt(0),lostOutgoing:X=BigInt(0),minRtt:Y=0,smoothedRtt:Q=0,rttVariation:K=0,estimatedSendRateBps:W}){let Z=this.resolveSessionStats.pop();if(this.rejectSessionStats.pop(),Z)Z({timestamp:J,bytesSent:BigInt(0),packetsSent:BigInt(0),packetsLost:BigInt(0),numOutgoingStreamsCreated:0,numIncomingStreamsCreated:0,bytesReceived:BigInt(0),packetsReceived:BigInt(0),smoothedRtt:Q,rttVariation:K,minRtt:Y,estimatedSendRate:W,datagrams:{timestamp:J,expiredOutgoing:$,droppedIncoming:BigInt(0),lostOutgoing:X}})}onDatagramStats({timestamp:J,expiredOutgoing:$=BigInt(0),lostOutgoing:X=BigInt(0)}){let Y=this.resolveDatagramStats.pop();if(this.rejectDatagramStats.pop(),Y)Y({timestamp:J,expiredOutgoing:$,droppedIncoming:BigInt(0),lostOutgoing:X})}notifySessionDraining(){if(this.objint==null)throw Error("this.objint not set");this.objint.notifySessionDraining()}addStreamObj(J){this.streamObjs.add(J)}removeStreamObj(J){this.streamObjs.delete(J)}addSendStream(J,$){this.sendStreams.add(J),this.sendStreamsController.add($)}removeSendStream(J,$){this.sendStreams.delete(J),this.sendStreamsController.delete($)}addReceiveStream(J,$){this.receiveStreams.add(J),this.receiveStreamsController.add($)}removeReceiveStream(J,$){this.receiveStreams.delete(J),this.receiveStreamsController.delete($)}createBidirectionalStream(J){if(this.objint==null)throw Error("this.objint not set");let $=new Promise((Y,Q)=>{this.resolveBiDi.push(Y),this.rejectBiDi.push(Q)});if(!this.objint.orderBidiStream({sendGroup:J?.sendGroup||null,sendOrder:BigInt(J?.sendOrder||0n),waitUntilAvailable:J?.waitUntilAvailable||!1})){let Y=this.rejectBiDi.pop();if(this.resolveBiDi.pop(),Y)Y(new DOMException("No streams available","QuotaExceededError"))}return $}createUnidirectionalStream(J){if(this.objint==null)throw Error("this.objint not set");let $=new Promise((Y,Q)=>{this.resolveUniDi.push(Y),this.rejectUniDi.push(Q)});if(!this.objint.orderUnidiStream({sendGroup:J?.sendGroup||null,sendOrder:J?.sendOrder||0n,waitUntilAvailable:J?.waitUntilAvailable||!1})){let Y=this.rejectUniDi.pop();if(this.resolveUniDi.pop(),Y)Y(new DOMException("No streams available","QuotaExceededError"))}return $}close(J){if(OB("closeinfo",J),this.state==="closed"||this.state==="failed")return;if(this.objint)this.objint.close({code:J?.closeCode??0,reason:J?.reason.substring(0,1023)??""})}createSendGroup(){if(this.state==="closed"||this.state==="failed")throw Error("InvalidState");let J=this._sendGroupNum++,$={_sendGroupId:J,getStats:async()=>{return{bytesWritten:0n,bytesSent:0n,bytesAcknowledged:0n}}};return this._sendGroupIndex.set(J,$),$}onReady({protocol:J}){if(J)this._selectedProtocol=J;if(this.state="connected",!this.reliable)this.reliability="supports-unreliable";else this.reliability="reliable-only";if(this.readyResolve)this.readyResolve();delete this.readyResolve}onClose(J){if(delete this.objint,this.state!=="connected"){if(OB.error('session was closed before state was "connected" - it was "%s"',this.state),this.state="failed",this.closeHook)this.closeHook(),delete this.closeHook;let Y=new O9("Opening handshake failed.");this.readyReject(Y),this.closedReject(Y);return}OB("onClose"),this.streamObjs.forEach((Y)=>Y.finalDrain());let $=new O9("Session closed");for(let Y of this.rejectBiDi)Y($);for(let Y of this.rejectUniDi)Y($);for(let Y of this.rejectSessionStats)Y($);for(let Y of this.rejectDatagramStats)Y($);this.resolveBiDi=[],this.resolveUniDi=[],this.rejectBiDi=[],this.rejectUniDi=[],this.resolveSessionStats=[],this.rejectSessionStats=[],this.resolveDatagramStats=[],this.rejectDatagramStats=[],this.incomBiDiController.close(),this.incomUniDiController.close(),(this.incomDatagramController_||this.incomDatagramControllerBytes_).close(),this.state="closed";let X=new O9(`Session closed (on process ${lR1}) with code `+J.errorcode+" and reason "+J.error);if(this.sendStreamsController.forEach((Y)=>Y.error(X)),this.receiveStreamsController.forEach((Y)=>Y.error(X)),this.streamObjs.forEach((Y)=>Y.readableclosed=!0),this.sendStreams.clear(),this.receiveStreams.clear(),this.sendStreamsController.clear(),this.receiveStreamsController.clear(),this.streamObjs.clear(),this.closedResolve)this.closedResolve({closeCode:J.errorcode,reason:J.error?J.error:""});if(this.closeHook)this.closeHook(),delete this.closeHook}onStream(J){let $=new An({object:J.stream,parentobj:this,transport:this.parentobj,bidirectional:J.bidirectional,incoming:J.incoming,sendGroup:this._sendGroupIndex.get(J.sendGroupId||0n),sendOrder:J.sendOrder});if(this.addStreamObj($),J.incoming)if(J.bidirectional)this.incomBiDiController.enqueue($);else this.incomUniDiController.enqueue($.readable);else if(J.bidirectional){if(this.resolveBiDi.length===0)throw Error("Got bidirectional stream without asking for it");this.rejectBiDi.shift();let X=this.resolveBiDi.shift();if(X!=null&&$.readable!=null&&$.writable!=null)X({readable:$.readable,writable:$.writable})}else{if(this.resolveUniDi.length===0)throw Error("Got unidirectional stream without asking for it");this.rejectUniDi.shift();let X=this.resolveUniDi.shift();if(X!=null&&$.writable!=null)X($.writable)}}onDatagramReceived(J){if(OB("datagram received",J.datagram),J.datagram.byteLength===0&&this.datagramsReadableMode_==="bytes"){OB("zerolength datagram dropped for a byte stream");return}if(this.incomDatagramControllerBytes_?.byobRequest){let $=this.incomDatagramControllerBytes_.byobRequest,X=$?.view;if(!(X instanceof Uint8Array))throw Error("byob view is not a Uint8Array");if(X.byteLength<J.datagram.byteLength)throw Error("supplied view is not large enough.");new Uint8Array(X.buffer,0+X.byteOffset,J.datagram.byteLength).set(J.datagram),$.respond(J.datagram.byteLength)}else(this.incomDatagramController_||this.incomDatagramControllerBytes_).enqueue(new Uint8Array(J.datagram))}onGoAwayReceived(J){if(this.drainingResolve)this.drainingResolve(void 0);this.state="draining"}get peerAddress(){return this.peerAddress_}}var bT6=typeof process<"u"?process.pid:0,z4=G6(`webtransport:flowcontroller(${bT6})`);class wz{static kSessionFlowControlMultiplier=1.5;constructor({tocontrol:J,sendWindowOffset:$,receiveWindowOffset:X,receiveWindowSizeLimit:Y,shouldAutoTuneReceiveWindow:Q,sessionFlowController:K}){this.tocontrol=J,this.bytesSent=0n,this.sendWindowOffset=BigInt($),this.bytesConsumed=0n,this.highestReceivedByteOffset=0n,this.receiveWindowOffset=BigInt(X),this.receiveWindowSize=BigInt(X),this.receiveWindowSizeLimit=BigInt(Y),this.autoTuneReceiveWindow=Q,this.sessionFlowController=K,this.lastBlockedSendWindowOffset=0n,this.prevWindowUpdateTime=void 0,z4("Created flow controller , setting initial receive window offset to: "+this.receiveWindowOffset+", max receive window to: "+this.receiveWindowSize+", max receive window limit to: "+this.receiveWindowSizeLimit+", setting send window offset to: "+this.sendWindowOffset)}addBytesConsumed(J){this.bytesConsumed+=BigInt(J),z4(" consumed "+J+" bytes."),this.maybeSendWindowUpdate()}updateHighestReceivedOffset(J){return z4(" highest byte offset increased from "+this.highestReceivedByteOffset," to ",this.highestReceivedByteOffset+BigInt(J)),this.highestReceivedByteOffset+=BigInt(J),!0}addBytesSent(J){let $=BigInt(J);if(this.bytesSent+$>this.sendWindowOffset){z4(" Trying to send an extra "+$+" bytes, when bytes_sent = "+this.bytesSent+", and send_window_offset_ = "+this.sendWindowOffset),this.bytesSent=this.sendWindowOffset,this.tocontrol.closeConnection({code:63,reason:this.sendWindowOffset-(this.bytesSent+$)+"bytes over send window offset"});return}this.bytesSent+=$,z4(" sent "+$+" bytes.")}flowControlViolation(){if(this.highestReceivedByteOffset>this.receiveWindowOffset)return z4("Flow control violation on , receive window offset: "+this.receiveWindowOffset+", highest received byte offset: "+this.highestReceivedByteOffset),!0;return!1}maybeIncreaseMaxWindowSize(){let J=Date.now(),$=this.prevWindowUpdateTime;if(this.prevWindowUpdateTime=J,!$){z4("first window update for ");return}if(!this.autoTuneReceiveWindow)return;let X=this.tocontrol.smoothedRtt();if(X===0){z4("rtt zero for ");return}let Y=J-$,Q=2*X;if(Y>=Q)return;let K=this.receiveWindowSize;if(this.increaseWindowSize(),this.receiveWindowSize>K){if(z4("New max window increase for NaN"+Y+" us, and RTT is "+X+"us. max wndw: "+this.receiveWindowSize),this.sessionFlowController!==void 0)this.sessionFlowController.ensureWindowAtLeast(BigInt(wz.kSessionFlowControlMultiplier*Number(this.receiveWindowSize)))}else z4("Max window at limit for after "+Y+" us, and RTT is "+X+"us. Limit size: "+this.receiveWindowSize)}increaseWindowSize(){this.receiveWindowSize*=2n,this.receiveWindowSize=this.receiveWindowSize>this.receiveWindowSizeLimit?this.receiveWindowSizeLimit:this.receiveWindowSize}windowUpdateThreshold(){return this.receiveWindowSize/2n}maybeSendWindowUpdate(){if(!this.tocontrol.connected())return;let J=this.receiveWindowOffset-this.bytesConsumed,$=this.windowUpdateThreshold();if(!this.prevWindowUpdateTime)this.prevWindowUpdateTime=Date.now();if(J>=$){z4("Not sending WindowUpdate for , available window: "+J+" >= threshold: "+$);return}this.maybeIncreaseMaxWindowSize(),this.updateReceiveWindowOffsetAndSendWindowUpdate(J)}updateReceiveWindowOffsetAndSendWindowUpdate(J){this.receiveWindowOffset+=this.receiveWindowSize-J,z4("Sending WindowUpdate frame for , consumed bytes: "+this.bytesConsumed+", available window: "+J+", and threshold: "+this.windowUpdateThreshold()+", and receive window size: "+this.receiveWindowSize+". New receive window offset is: "+this.receiveWindowOffset),this.sendWindowUpdate()}maybeSendBlocked(){if(this.sendWindowSize()!==0n||this.lastBlockedSendWindowOffset>=this.sendWindowOffset)return;z4(" is flow control blocked. Send window: "+this.sendWindowSize()+", bytes sent: "+this.bytesSent+", send limit: "+this.sendWindowOffset),this.lastBlockedSendWindowOffset=this.sendWindowOffset,this.tocontrol.sendBlocked(this.lastBlockedSendWindowOffset)}updateSendWindowOffset(J){if(J<=this.sendWindowOffset)return!1;z4("UpdateSendWindowOffset for with new offset "+J+" current offset: "+this.sendWindowOffset+" bytes_sent: "+this.bytesSent);let $=this.isBlocked();return this.sendWindowOffset=J,$}ensureWindowAtLeast(J){if(this.receiveWindowSizeLimit>=J)return;let $=this.receiveWindowOffset-this.bytesConsumed;this.increaseWindowSize(),this.updateReceiveWindowOffsetAndSendWindowUpdate($)}isBlocked(){return this.sendWindowSize()===0n}sendWindowSize(){if(this.bytesSent>this.sendWindowOffset)return 0n;return this.sendWindowOffset-this.bytesSent}updateReceiveWindowSize(J){if(z4("UpdateReceiveWindowSize for : "+J),this.receiveWindowSize!==this.receiveWindowOffset){z4("receive_window_size_:"+this.receiveWindowSize+" != receive_window_offset:"+this.receiveWindowOffset);return}this.receiveWindowSize=J,this.receiveWindowOffset=J}sendWindowUpdate(){this.tocontrol.sendWindowUpdate(this.receiveWindowOffset)}}var mT6=typeof process<"u"?process.pid:0,dR1=G6(`webtransport:http2webtransportstream(${mT6})`),WT=(J)=>setTimeout(J,0);if(typeof process<"u")WT=process.nextTick;class _n{constructor({streamid:J,unidirectional:$,incoming:X,capsuleParser:Y,sendWindowOffset:Q,receiveWindowOffset:K,shouldAutoTuneReceiveWindow:W,receiveWindowSizeLimit:Z,sessionFlowController:G,streamIdManager:V}){if(this.jsobj=void 0,this.streamid=J,this.incomdata=[],this.capsuleParser=Y,this.outgochunks=[],this.flowController=new wz({tocontrol:this,sendWindowOffset:Q,receiveWindowOffset:K,shouldAutoTuneReceiveWindow:W,receiveWindowSizeLimit:Z,sessionFlowController:G}),this.sessionFlowController=G,this.streamIdManager=V,this.final=!1,this.finalmessagesend=!1,this.stopReading_=!0,this.drainReads_=!0,this.recvBytes=0,this.outgoingClosed_=!1,this.incomingClosed_=!1,$)if(X)this.outgoingClosed_=!0;else this.incomingClosed_=!0}sendInitialParameters(){this.flowController.sendWindowUpdate()}recvData({data:J,fin:$}){if(this.incomdata.push({data:J,fin:$}),J&&J?.byteLength>0){let X=this.flowController.updateHighestReceivedOffset(J?.byteLength);if(this.sessionFlowController.updateHighestReceivedOffset(J?.byteLength)&&X){if(this.flowController.flowControlViolation()||this.sessionFlowController.flowControlViolation()){this.closeConnection({code:63,reason:"Flow control violation after increasing offset"});return}}}if(this.processRead(),this.incomdata.length>0){if(!this.stopReading_)this.processRead()}}processRead(){if(!this.jsobj)return;let J,$=0;while(this.incomdata.length>0&&(!this.stopReading_||this.drainReads_)){if(!J){if(this.incomdata.reduce((Q,K)=>Q+(K&&K.data?.byteLength||0),0)>0)J=this.jsobj.getReadBuffer({byteSize:this.incomdata.reduce((Q,K)=>Q+(K&&K.data?.byteLength||0),0)}),J.readBytes=0,$=0}let X=this.incomdata.shift();if(X?.data&&X.data.byteLength>0&&J&&J.buffer){let Y=Math.min(J.buffer.byteLength-$,X.data.byteLength),Q=new Uint8Array(X.data.buffer,X.data.byteOffset,Y);if(new Uint8Array(J.buffer.buffer,$,Y).set(Q),$+=Y,J.readBytes+=Y,J.drained=!0,X.data.byteLength!==Y)J.drained=!1,this.incomdata.unshift({data:new Uint8Array(X.data.buffer,X.data.byteOffset+Y,X.data.byteLength-Y),fin:X.fin}),J.fin=!1;else J.fin||=X.fin;if(this.incomdata.length>0)J.drained=!1;if($===J.buffer.byteLength||this.incomdata.length===0){this.flowController.addBytesConsumed(J.readBytes||0),this.sessionFlowController.addBytesConsumed(J.readBytes||0);let{stopReading:W}=this.jsobj.commitReadBuffer(J);if(W)this.stopReading_=!0;J=void 0,$=0}this.recvBytes+=Y}else if(X?.fin)this.jsobj.commitReadBuffer({fin:!0})}}startReading(){this.stopReading_=!1,this.processRead()}drainReads(){this.drainReads_=!0,this.stopReading_=!1,this.processRead()}stopReading(){this.stopReading_=!0}onStreamSignal(J){switch(J){case"resetStream":this.closeIncoming();break;case"stopSending":this.closeOutgoing();break}}closeIncoming(){if(this.incomingClosed_=!0,this.outgoingClosed_)this.onClose()}closeOutgoing(){if(this.outgoingClosed_=!0,this.incomingClosed_)this.onClose()}onClose(){this.streamIdManager.onStreamClosed(this.streamid)}stopSending(J){this.closeIncoming(),this.capsuleParser.writeCapsule({type:x1.WT_STOP_SENDING,headerVints:[this.streamid,J],payload:void 0}),WT(()=>this.jsobj.onStreamNetworkFinish({nettask:"stopSending"}))}onFin(){this.closeIncoming()}resetStream(J){this.closeOutgoing(),this.capsuleParser.writeCapsule({type:x1.WT_RESET_STREAM,headerVints:[this.streamid,J],payload:void 0}),WT(()=>this.jsobj.onStreamNetworkFinish({nettask:"resetStream"}))}writeChunk(J){this.outgochunks.push({buf:J,fin:!1}),this.capsuleParser.scheduler.Schedule(this.streamid),this.capsuleParser.scheduleDrainWrites()}hasPendingData(){return this.outgochunks.length>0}drainWrites(){let J=!1;while(this.outgochunks.length>0&&(!this.capsuleParser.blocked||this.final||!this.capsuleParser.shouldYieldStream(this.streamid))&&this.flowController.sendWindowSize()>0n&&this.sessionFlowController.sendWindowSize()>0n){let $=this.outgochunks.shift(),X=!0;if($){let Y=$.buf;if(Y){if(Y.byteLength===0&&!$.fin)throw new O9("Trying to send zero length capsule without a fin");let Q=this.sessionFlowController.sendWindowSize(),K=this.flowController.sendWindowSize();if(Y?.byteLength>K||Y?.byteLength>Q){let W=Q>K?Number(K):Number(Q);{let Z=new Uint8Array(Y.buffer,Y.byteOffset+W,Y.byteLength-W),G=new Uint8Array(Y.byteLength-W);G.set(Z),this.outgochunks.unshift({fin:$.fin,buf:G}),X=!1}$.fin=!1,Y=$.buf=new Uint8Array(Y.buffer,Y.byteOffset,W)}}if(this.capsuleParser.writeCapsule({type:$?.fin?x1.WT_STREAM_WFIN:x1.WT_STREAM_WOFIN,headerVints:[this.streamid],payload:Y}),J||=!!$?.fin,Y)this.flowController.addBytesSent(Y?.byteLength),this.sessionFlowController.addBytesSent(Y?.byteLength)}if(X)this.jsobj.onStreamWrite({success:!0})}if(J){this.capsuleParser.removeStream(this.streamid);return}if(!(!this.capsuleParser.blocked||this.final||!this.capsuleParser.shouldYieldStream(this.streamid))&&this.outgochunks.length>0)this.capsuleParser.scheduleDrainWriteStream(this.streamid);if(this.final&&this.outgochunks.length===0&&!this.finalmessagesend)WT(()=>{this.jsobj.onStreamNetworkFinish({nettask:"streamFinal"})}),this.finalmessagesend=!0}streamFinal(){this.final=!0,this.outgochunks.push({fin:!0}),this.capsuleParser.scheduleDrainWriteStream(this.streamid),this.capsuleParser.scheduleDrainWrites()}updateSendOrderAndGroup({sendOrder:J,sendGroupId:$}){this.capsuleParser.streamUpdateSendOrderAndGroup(this.streamid,{sendOrder:J,sendGroupId:$})}sendWindowUpdate(J){dR1("sendwindow offset stream:",J),this.capsuleParser.writeCapsule({type:x1.WT_MAX_STREAM_DATA,headerVints:[this.streamid,J],payload:void 0})}sendBlocked(J){this.capsuleParser.writeCapsule({type:x1.WT_STREAM_DATA_BLOCKED,headerVints:[this.streamid,J],payload:void 0})}reportBlocked(J){dR1("Stream id: ",this.streamid," was blocked at:",J)}connected(){return this.jsobj.parentobj.state==="connected"}closeConnection({code:J,reason:$}){if(this.jsobj.parentobj?.objint)this.jsobj.parentobj.objint.closeConnection({code:J,reason:$})}smoothedRtt(){if(this.jsobj.parentobj?.objint)return this.jsobj.parentobj.objint.smoothedRtt()}}function DB(J){return J.toString()}function D5(J){return J.toString()}class nR1{constructor(J){this.priority=J,this.currentSequenceNumber=void 0}scheduled(){return typeof this.currentSequenceNumber<"u"}}function uT6(J,$){if(J.priority>$.priority)return-1;else if(J.priority===$.priority)if(J.sequenceNumber>$.sequenceNumber)return-1;else if(J.sequenceNumber===$.sequenceNumber)return 0;else return 1;else return 1}function iR1(J,$){return uT6(J.scheduleKey,$.scheduleKey)}class xB{constructor(){this.streams_={},this.schedule_=[],this.currentWriteSequenceNumber_=0}HasRegistered(){return Object.keys(this.streams_).length!==0}HasScheduled(){return Object.keys(this.schedule_).length!==0}NumScheduled(){return Object.keys(this.schedule_).length}NumRegistered(){return Object.keys(this.streams_).length}NumScheduledInPriorityRange(J,$){let X=typeof $<"u"?this.schedule_.findIndex((Q)=>Q.scheduleKey.priority<=$):0;return(typeof J<"u"?this.schedule_.findIndex((Q)=>Q.scheduleKey.priority>=J):this.schedule_.length)-X}ShouldYield(J){let $=this.streams_[D5(J)];if(!$)throw Error("ID not registered");if(this.schedule_.length===0)return!1;let X=this.schedule_[0];if(xB.StreamId(X)==J)return!1;return X.scheduleKey.priority>=$.priority}GetPriorityFor(J){let $=this.streams_[D5(J)];if(!$)return;return $.priority}PopFront(){if(this.schedule_.length===0)return;let J=this.schedule_[0];J.fullStreamEntry.streamEntry.currentSequenceNumber=void 0;let $=xB.StreamId(J);return this.schedule_.shift(),$}Register(J,$){if(this.streams_[D5(J)])throw Error("ID already registered");this.streams_[D5(J)]=new nR1($.sendOrder)}Unregister(J){let $=this.streams_[D5(J)];if(!$)throw Error("Stream not registered");if($.scheduled())this.DescheduleStream($);delete this.streams_[D5(J)]}UpdatePriority(J,$){let X=this.streams_[D5(J)];if(!X)return Error("ID not registered");let Y;if(X.scheduled())Y=this.DescheduleStream(X).scheduleKey.sequenceNumber;if(X.priority=$,Y)this.schedule_.push({scheduleKey:{priority:X.priority,sequenceNumber:Y},fullStreamEntry:{iD:J,streamEntry:X}}),this.schedule_.sort(iR1)}Schedule(J){let $=this.streams_[D5(J)];if(!$)return Error("ID not registered");if($.scheduled())return;let X={scheduleKey:{priority:$.priority,sequenceNumber:--this.currentWriteSequenceNumber_},fullStreamEntry:{iD:J,streamEntry:$}};this.schedule_.push(X),this.schedule_.sort(iR1),$.currentSequenceNumber=X.scheduleKey.sequenceNumber}Deschedule(J){let $=this.streams_[D5(J)];if(!$)throw Error("Stream not registered");if(!$.scheduled())throw Error("Stream not scheduled");this.DescheduleStream($),$.currentSequenceNumber=void 0}IsScheduled(J){let $=this.streams_[D5(J)];if(!$)return!1;return $.scheduled()}static StreamId(J){return J.fullStreamEntry.iD}DescheduleStream(J){let $=this.schedule_.findIndex((Y)=>J.priority===Y.scheduleKey.priority&&J.currentSequenceNumber===Y.fullStreamEntry.streamEntry.currentSequenceNumber);if($===-1)throw Error("Calling DescheduleStream() on an entry that is not in the schedule at the expected key.");let X=this.schedule_[$];return this.schedule_.splice($,1),X}}class cn{constructor(){this.activeGroups_=new xB,this.perGroupSchedulers_={},this.streamToGroupMap_={}}HasRegistered(){return this.activeGroups_.HasRegistered()}HasScheduled(){return this.activeGroups_.HasScheduled()}NumScheduled(){let J=0;for(let[,$]of Object.entries(this.perGroupSchedulers_))J+=$.NumScheduled();return J}Register(J,$){if(this.streamToGroupMap_[D5(J)])throw Error("Provided stream ID already registered");if(!this.perGroupSchedulers_[DB($.sendGroupId)])this.perGroupSchedulers_[DB($.sendGroupId)]=new xB,this.activeGroups_.Register($.sendGroupId,$);let X=this.perGroupSchedulers_[DB($.sendGroupId)];this.streamToGroupMap_[D5(J)]={sendGroupId:$.sendGroupId,perGroupScheduler:X},X.Register(J,$)}Unregister(J){let $=this.streamToGroupMap_[D5(J)];if(!$)throw Error("Stream ID not registered");let{sendGroupId:X,perGroupScheduler:Y}=$;if(delete this.streamToGroupMap_[D5(J)],Y.Unregister(J),!Y.HasRegistered())delete this.perGroupSchedulers_[DB(X)],this.activeGroups_.Unregister(X)}UpdateSendOrder(J,$){let X=this.SchedulerForStream(J);if(!X)throw Error("Stream ID not registered");return X.UpdatePriority(J,$)}UpdateSendGroup(J,$){let X=this.SchedulerForStream(J);if(!X)throw Error("Stream ID not registered");let Y=X.IsScheduled(J),Q=X.GetPriorityFor(J);if(!Q)throw Error("Stream registered at the top level scheduler, but not at the per-group one");if(this.Unregister(J),this.Register(J,{sendGroupId:$,sendOrder:Q}),Y)this.Schedule(J)}ShouldYield(J){let $=this.streamToGroupMap_[D5(J)];if(!$)throw Error("Stream ID not registered");let{sendGroupId:X,perGroupScheduler:Y}=$;if(this.activeGroups_.ShouldYield(X))return!0;return Y.ShouldYield(J)}GetPriorityFor(J){let $=this.streamToGroupMap_[D5(J)];if(!$)return null;let{sendGroupId:X,perGroupScheduler:Y}=$,Q=Y.GetPriorityFor(J);if(!Q)return null;return{sendGroupId:X,sendOrder:Q}}PopFront(){let J=this.activeGroups_.PopFront();if(typeof J>"u")return;let $=this.perGroupSchedulers_[DB(J)];if(!$)throw Error("Scheduled a group with no per-group scheduler attached");let X=$.PopFront();if(typeof X>"u")return;if($.HasScheduled())this.activeGroups_.Schedule(J);return X}Schedule(J){let $=this.streamToGroupMap_[D5(J)];if(!$)return Error("Stream ID not registered");let{sendGroupId:X,perGroupScheduler:Y}=$;return this.activeGroups_.Schedule(X),Y.Schedule(J)}IsScheduled(J){let $=this.SchedulerForStream(J);if(!$)return!1;return $.IsScheduled(J)}SchedulerForStream(J){let $=this.streamToGroupMap_[D5(J)];if(!$)return;return $.perGroupScheduler}}var gT6=typeof process<"u"?process.pid:0,hn=G6(`webtransport:parserbase(${gT6})`);function P3(J){if(BigInt(J)<64n)return 1;if(BigInt(J)<16384n)return 2;if(BigInt(J)<1073741824n)return 4;return 8}class x1{static PADDING=420171064;static WT_RESET_STREAM=420171065;static WT_STOP_SENDING=420171066;static WT_STREAM_WOFIN=420171067;static WT_STREAM_WFIN=420171068;static WT_MAX_DATA=420171069;static WT_MAX_STREAM_DATA=420171070;static WT_MAX_STREAMS_BIDI=420171071;static WT_MAX_STREAMS_UNIDI=420171072;static WT_DATA_BLOCKED=420171073;static WT_STREAM_DATA_BLOCKED=420171074;static WT_STREAMS_BLOCKED_UNIDI=420171075;static WT_STREAMS_BLOCKED_BIDI=420171076;static WT_CLOSE_SESSION=10307;static WT_DRAIN_SESSION=30894;static DATAGRAM=0;constructor({nativesession:J,isclient:$,initialStreamSendWindowOffsetBidi:X,initialStreamSendWindowOffsetUnidi:Y,initialStreamReceiveWindowOffset:Q,streamShouldAutoTuneReceiveWindow:K,streamReceiveWindowSizeLimit:W}){this.session=J,this.isclient=$,this.blocked=!1,this.initialStreamSendWindowOffsetUnidi=Y,this.initialStreamSendWindowOffsetBidi=X,this.initialStreamReceiveWindowOffset=Q,this.streamShouldAutoTuneReceiveWindow=K,this.streamReceiveWindowSizeLimit=W,this.wtstreams=new Map,this.scheduler=new cn}parseData(J){throw Error("Implement parseData in derived Class")}writeCapsule({type:J,headerVints:$,payload:X,end:Y}){throw Error("Implement writeCapsule in derived Class")}initialParametersMandatory(){throw Error("Implement initialParametersMandatory in derived Class")}sendClose({code:J,reason:$}){let Y=new TextEncoder().encode("AAAA"+$);Y[0]=J>>24&255,Y[1]=J>>16&255,Y[2]=J>>8&255,Y[3]=J&255,this.writeCapsule({type:x1.WT_CLOSE_SESSION,headerVints:[],payload:Y,end:()=>{this.closeHttp2Stream(J)}})}newStream(J,$){let X=this.isclient?!(J&0x1n):!!(J&0x1n),Y=J&0x2n?this.session.streamIdMngrUni:this.session.streamIdMngrBi;if(X){let W=Y.maybeIncreaseLargestPeerStreamId(J);if(W.error){this.session.closeConnection({code:20,reason:W.error});return}}let Q=!!(J&0x2n),K=new _n({streamid:J,unidirectional:Q,incoming:X,capsuleParser:this,sendWindowOffset:Q?this.initialStreamSendWindowOffsetUnidi:this.initialStreamSendWindowOffsetBidi,receiveWindowOffset:this.initialStreamReceiveWindowOffset,shouldAutoTuneReceiveWindow:this.streamShouldAutoTuneReceiveWindow,receiveWindowSizeLimit:this.streamReceiveWindowSizeLimit,sessionFlowController:this.session.flowController,streamIdManager:Y});return this.wtstreams.set(J,K),this.scheduler.Register(J,$),this.session.jsobj.onStream({bidirectional:!(J&0x2n),incoming:X,stream:K,sendGroupId:$.sendGroupId,sendOrder:$.sendOrder}),K}scheduleDrainWrites(){if(this._scheduledDrainWriteCall)return;let J=Promise.resolve();this._scheduledDrainWriteCall=J,J.then(()=>{delete this._scheduledDrainWriteCall,this.drainWrites()}).catch(($)=>hn("Error in drainWrites",$))}drainWrites(){if(!this.blocked)this.session.drainWrites();while(!this.blocked){let J=this.scheduler.PopFront();if(typeof J>"u")break;let $=this.wtstreams.get(J);if(!$)break;$.drainWrites()}}onMaxData(J){if(J&&this.session.flowController.updateSendWindowOffset(J)){let $=!1;if(this.wtstreams.forEach((X,Y)=>{if(X.hasPendingData())$=!0,this.scheduleDrainWriteStream(Y)}),$)this.drainWrites()}}onMaxStreamData(J,$){let X=this.wtstreams.get(J);if(X&&$){if(X.flowController.updateSendWindowOffset($))this.scheduleDrainWriteStream(J),this.drainWrites()}}onMaxStreamUniDi(J){if(typeof J>"u")return;this.session.streamIdMngrUni.maybeAllowNewOutgoingStreams(J),this.session.trySendingUnidirectionalStreams()}onMaxStreamBiDi(J){if(typeof J>"u")return;this.session.streamIdMngrBi.maybeAllowNewOutgoingStreams(J),this.session.trySendingBidirectionalStreams()}onDataBlocked(J){hn("Session received blocked frame "+J)}onStreamDataBlocked(J,$){hn("Stream "+J+" received blocked frame "+$)}onStreamsBlockedBidi(J){if(typeof J>"u")return;let $=this.session.streamIdMngrBi.onStreamsBlockedFrame(J);if($.error)this.session.closeConnection({code:105,reason:$.error})}onStreamsBlockedUnidi(J){if(typeof J>"u")return;let $=this.session.streamIdMngrUni.onStreamsBlockedFrame(J);if($.error)this.session.closeConnection({code:105,reason:$.error})}onCloseWebTransportSession({code:J,reason:$}){this.session.jsobj.onClose({errorcode:J,error:$}),this.closeHttp2Stream(J)}onDrain(){this.session.jsobj.onGoAwayReceived()}shouldYieldStream(J){return this.scheduler.ShouldYield(J)}scheduleDrainWriteStream(J){this.scheduler.Schedule(J)}removeStream(J){this.scheduler.Unregister(J)}streamUpdateSendOrderAndGroup(J,{sendOrder:$,sendGroupId:X}){this.scheduler.UpdateSendGroup(J,X),this.scheduler.UpdateSendOrder(J,$)}closeHttp2Stream(J){throw Error("Implement closeHttp2Stream in derived Class")}}function aR1(){return(0xffffffffn>>2n)+1n}var pT6=typeof process<"u"?process.pid:0,sR1=G6(`webtransport:streamidmanager(${pT6})`);class ZT{constructor({delegate:J,unidirectional:$,isclient:X,maxAllowedOutgoingStreams:Y,maxAllowedIncomingStreams:Q}){this.delegate=J,this.unidirectional=$,this.isclient=X,this.outgoingMaxStreams=BigInt(Y),this.nextOutgoingStreamId=this.getFirstOutgoingStreamId(),this.outgoingStreamCount=0n,this.incomingActualMaxStreams=BigInt(Q),this.incomingAdvertisedMaxStreams=BigInt(Q),this.incomingInitialMaxOpenStreams=BigInt(Q),this.incomingStreamCount=0n,this.availableStreams=new Set,this.largestPeerCreatedStreamId=BigInt(Number.MAX_SAFE_INTEGER),this.stopIncreasingIncomingMaxStreams=!1}onStreamsBlockedFrame(J){if(J>this.incomingAdvertisedMaxStreams)return{error:"StreamsBlockedFrame's stream count "+J+" exceeds incoming max stream "+this.incomingAdvertisedMaxStreams};if(this.incomingAdvertisedMaxStreams===this.incomingActualMaxStreams)return{success:!0};if(J<this.incomingActualMaxStreams&&this.delegate.canSendMaxStreams())this.sendMaxStreamsFrame();return{success:!0}}maybeAllowNewOutgoingStreams(J){if(J<=this.outgoingMaxStreams)return!1;let $=aR1();if(J<$)this.outgoingMaxStreams=J;else this.outgoingMaxStreams=$;return!0}setMaxOpenIncomingStreams(J){if(this.incomingStreamCount>0)throw Error("non-zero incoming stream count "+this.incomingStreamCount+NaN+J);if(this.incomingInitialMaxOpenStreams!==J)sR1(this.unidirectional?"unidirectional ":"bidirectional: ","incoming stream limit changed from ",this.incomingInitialMaxOpenStreams," to ",J);this.incomingActualMaxStreams=J,this.incomingAdvertisedMaxStreams=J,this.incomingInitialMaxOpenStreams=J}maybeSendMaxStreamsFrame(){let J=2n;if(J>0n){if(this.incomingAdvertisedMaxStreams-this.incomingStreamCount>this.incomingInitialMaxOpenStreams/J)return}if(this.delegate.canSendMaxStreams()&&this.incomingAdvertisedMaxStreams<this.incomingActualMaxStreams)this.sendMaxStreamsFrame()}sendMaxStreamsFrame(){if(this.incomingAdvertisedMaxStreams>=this.incomingActualMaxStreams)throw Error("this.incomingAdvertisedMaxStreams >= this.incomingActualMaxStreams"+this.incomingAdvertisedMaxStreams+"vs."+this.incomingActualMaxStreams);this.incomingAdvertisedMaxStreams=this.incomingActualMaxStreams,this.delegate.sendMaxStreams(this.incomingAdvertisedMaxStreams,this.unidirectional)}sendMaxStreamsFrameInitial(){this.delegate.sendMaxStreams(this.incomingAdvertisedMaxStreams,this.unidirectional)}onStreamClosed(J){if(this.isclient&&J&0x1n||!this.isclient&&!(J&0x1n))return;if(this.incomingActualMaxStreams===aR1())return;if(!this.stopIncreasingIncomingMaxStreams)this.incomingActualMaxStreams++,this.maybeSendMaxStreamsFrame()}getNextOutgoingStreamId(){if(this.outgoingStreamCount>=this.outgoingMaxStreams)throw Error("Attempt to allocate a new outgoing stream that would exceed the limit ("+ +Number(this.outgoingMaxStreams)+")");let J=this.nextOutgoingStreamId;return this.nextOutgoingStreamId+=1n<<2n,this.outgoingStreamCount++,J}canOpenNextOutgoingStream(){return this.outgoingStreamCount<this.outgoingMaxStreams}isMaxStreamSet(){return this.outgoingMaxStreams>0n}maybeIncreaseLargestPeerStreamId(J){if(this.availableStreams.has(J))return this.availableStreams.delete(J),!0;let $=1n<<2n,X=this.largestPeerCreatedStreamId===BigInt(Number.MAX_SAFE_INTEGER)?this.getFirstIncomingStreamId():this.largestPeerCreatedStreamId+$,Y=(J-X)/$+1n;if(this.incomingStreamCount+Y>this.incomingAdvertisedMaxStreams)return sR1("Failed to create a new incoming stream with id:"+J+", reaching MAX_STREAMS limit: "+this.incomingAdvertisedMaxStreams+"."),{error:"Stream id "+J+" would exceed stream count limit "+this.incomingAdvertisedMaxStreams};for(let Q=X;Q<J;Q+=$)this.availableStreams.add(Q);return this.incomingStreamCount+=Y,this.largestPeerCreatedStreamId=J,!0}isAvailableStream(J){if(this.isclient&&J&1||!this.isclient&&!(J&1))return J>=this.nextOutgoingStreamId;return this.largestPeerCreatedStreamId===BigInt(Number.MAX_SAFE_INTEGER)||J>this.largestPeerCreatedStreamId||this.availableStreams.has(J)}getFirstOutgoingStreamId(){let J=0n;if(this.isclient)J|=0x1n;if(this.unidirectional)J|=0x2n;return J}getFirstIncomingStreamId(){let J=0n;if(!this.isclient)J|=0x1n;if(this.unidirectional)J|=0x2n;return J}get availableIncomingStreams(){return this.incomingAdvertisedMaxStreams-this.incomingStreamCount}}var lT6=typeof process<"u"?process.pid:0,dT6=G6(`webtransport:http2webtransportsession(${lT6})`),fn=(J)=>setTimeout(J,0);if(typeof process<"u")fn=process.nextTick;class C3{constructor({stream:J,ws:$,isclient:X,createParser:Y,sendWindowOffset:Q,receiveWindowOffset:K,shouldAutoTuneReceiveWindow:W,receiveWindowSizeLimit:Z,initialBidirectionalSendStreams:G,initialBidirectionalReceiveStreams:V,initialUnidirectionalSendStreams:q,initialUnidirectionalReceiveStreams:z}){if(this.jsobj=void 0,J)this.stream=J;else if($)this.ws=$;else throw Error("Neither stream or websocket supplied");if(this.capsParser=Y(this),this.isclient=X,this.flowController=new wz({tocontrol:this,sendWindowOffset:Q,receiveWindowOffset:K,shouldAutoTuneReceiveWindow:W,receiveWindowSizeLimit:Z}),this.streamIdMngrUni=new ZT({delegate:this,unidirectional:!0,isclient:X,maxAllowedIncomingStreams:z,maxAllowedOutgoingStreams:q}),this.streamIdMngrBi=new ZT({delegate:this,unidirectional:!1,isclient:X,maxAllowedIncomingStreams:V,maxAllowedOutgoingStreams:G}),this.datagramsWaiting_=[],this.orderUniStreams=[],this.orderBiStreams=[],J)if(X)J.on("response",(H)=>{fn(()=>{if(H[":status"]===200){let v={};if(J&&H["wt-protocol"])v.protocol=H["wt-protocol"];this.jsobj.onReady(v)}else this.jsobj.onClose({errorcode:H[":status"],error:"Session stream errored"})})});else fn(()=>{this.jsobj.onReady({})})}sendInitialParameters(){let J=!1;if(process){if(process.version){if(parseInt(process.version.split(".")[0].substring(1))>=20)J=!0}}if(!J||this.capsParser.initialParametersMandatory())this.flowController.sendWindowUpdate(),this.streamIdMngrBi.sendMaxStreamsFrameInitial(),this.streamIdMngrUni.sendMaxStreamsFrameInitial()}drainWrites(){while(!this.capsParser.blocked&&this.datagramsWaiting_.length>0){let J=this.datagramsWaiting_.shift();this.capsParser.writeCapsule({type:x1.DATAGRAM,headerVints:[],payload:J})}if(this.datagramsWaiting_.length>0)this.capsParser.scheduleDrainWrites()}writeDatagram(J){if(J.byteLength>this.getMaxDatagramSize())return{code:"tooBig"};if(this.capsParser.blocked)return this.datagramsWaiting_.push(J),this.capsParser.scheduleDrainWrites(),{code:"blocked"};return this.capsParser.writeCapsule({type:x1.DATAGRAM,headerVints:[],payload:J}),{code:"success"}}trySendingUnidirectionalStreams(){while(this.orderUniStreams.length>0&&this.streamIdMngrUni.canOpenNextOutgoingStream()){let J=this.streamIdMngrUni.getNextOutgoingStreamId(),$=this.orderUniStreams.pop();this.capsParser.writeCapsule({type:x1.WT_STREAM_WOFIN,headerVints:[J],payload:void 0}),this.capsParser.newStream(J,$||{sendGroupId:0n,sendOrder:0n})}}orderUnidiStream({sendGroup:J,sendOrder:$,waitUntilAvailable:X}){let Y=this.streamIdMngrUni.canOpenNextOutgoingStream(),Q=this.streamIdMngrUni.isMaxStreamSet();if(Y||X||!Q)return this.orderUniStreams.push({sendGroupId:J?._sendGroupId||0n,sendOrder:$??0n}),this.trySendingUnidirectionalStreams(),!0;return!1}trySendingBidirectionalStreams(){while(this.orderBiStreams.length>0&&this.streamIdMngrBi.canOpenNextOutgoingStream()){let J=this.streamIdMngrBi.getNextOutgoingStreamId(),$=this.orderBiStreams.pop();this.capsParser.writeCapsule({type:x1.WT_STREAM_WOFIN,headerVints:[J],payload:void 0}),this.capsParser.newStream(J,$||{sendGroupId:0n,sendOrder:0n})}}orderBidiStream({sendGroup:J,sendOrder:$,waitUntilAvailable:X}){let Y=this.streamIdMngrBi.canOpenNextOutgoingStream(),Q=this.streamIdMngrBi.isMaxStreamSet();if(Y||X||!Q)return this.orderBiStreams.push({sendGroupId:J?._sendGroupId||0n,sendOrder:$??0n}),this.trySendingBidirectionalStreams(),!0;return!1}orderSessionStats(){this.jsobj.onSessionStats({timestamp:0,expiredOutgoing:0n,lostOutgoing:0n,minRtt:0,smoothedRtt:0,rttVariation:0,estimatedSendRateBps:0n})}orderDatagramStats(){this.jsobj.onDatagramStats({timestamp:0,expiredOutgoing:0n,lostOutgoing:0n})}getMaxDatagramSize(){return 16384}notifySessionDraining(){}close({code:J,reason:$}){this.capsParser.sendClose({code:J,reason:$})}sendWindowUpdate(J){this.capsParser.writeCapsule({type:x1.WT_MAX_DATA,headerVints:[J],payload:void 0})}reportBlocked(J){dT6("Session was blocked at:",J)}sendBlocked(J){this.capsParser.writeCapsule({type:x1.WT_DATA_BLOCKED,headerVints:[J],payload:void 0})}connected(){return this.jsobj.state==="connected"}closeConnection({code:J,reason:$}){this.jsobj.onClose({errorcode:J,error:$}),this.close({code:J,reason:$})}smoothedRtt(){let J;if(this.stream)J=this.stream.session?.WTrtt||25;else if(this.ws)J=navigator?.connection?.rtt||25;return J=Math.ceil(J/25)*25,J}canSendMaxStreams(){return!0}sendMaxStreams(J,$){this.capsParser.writeCapsule({type:$?x1.WT_MAX_STREAMS_UNIDI:x1.WT_MAX_STREAMS_BIDI,headerVints:[J],payload:void 0})}}function GT(J){if(J.offset+4>J.size)return;let $=J.buffer.readUInt32BE(J.offset);return J.offset+=4,$}function R8(J){if(J.offset+1>J.size)return;let $=BigInt(J.buffer.readUInt8(J.offset));J.offset++;let Y=1<<(Number($)>>>6);if(J.offset+Y-1>J.size)return;$=$&0x3fn;for(let Q=0;Q<Y-1;Q++)$=$<<8n|BigInt(J.buffer.readUInt8(J.offset)),J.offset++;return $}function T3(J,$){let X=8n,Y=0xc0n,Q=BigInt($);if(Q<64)X=1n,Y=0x0n;else if(Q<16384)X=2n,Y=0x40n;else if(Q<1073741824)X=4n,Y=0x80n;J.buffer.writeUInt8(Number(Y|Q>>(X-1n)*8n&0xffn),J.offset),J.offset++;for(let K=X-2n;K>=0;K--)J.buffer.writeUInt8(Number(Q>>K*8n&0xffn),J.offset),J.offset++}class PB extends x1{constructor({stream:J,nativesession:$,isclient:X,initialStreamSendWindowOffsetBidi:Y,initialStreamSendWindowOffsetUnidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z}){super({nativesession:$,isclient:X,initialStreamSendWindowOffsetBidi:Y,initialStreamSendWindowOffsetUnidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z});this.stream=J,this.session=$,this.isclient=X,this.stream.on("readable",()=>{let G;while((G=this.stream.read())!==null)this.parseData(G)}),this.stream.on("end",()=>{}),this.stream.on("error",(G)=>{this.session.jsobj.onClose({errorcode:this.stream.rstCode,error:G.toString()})}),this.stream.on("drain",()=>{this.blocked=!1,this.drainWrites()}),this.stream.on("close",()=>{if(!(this.session.jsobj.state==="failed"||this.session.jsobj.state==="closed"))this.session.jsobj.onClose({errorcode:this.stream.rstCode||0,error:""})})}}class C8 extends PB{constructor({stream:J,nativesession:$,isclient:X,initialStreamSendWindowOffsetBidi:Y,initialStreamSendWindowOffsetUnidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z}){super({stream:J,nativesession:$,isclient:X,initialStreamSendWindowOffsetBidi:Y,initialStreamSendWindowOffsetUnidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z});this.mode="s",this.saveddata=void 0,this.rtype=void 0}parseData(J){let $=J;if(this.saveddata)$=Buffer.concat([this.saveddata,$]),delete this.saveddata;let X={offset:0,size:$.length,buffer:$};while(X.size-X.offset>0)switch(this.mode){case"s":{let Y=X.offset+X.buffer.byteOffset,Q=X.buffer.byteLength-X.offset;if(X.size<2+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}let K=R8(X);if(typeof K>"u"||X.size<1+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}let W=Number(K),Z=R8(X);if(typeof Z>"u"){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}let G=Number(Z),V=G,q=Math.min(X.offset+G,X.size),z=X.offset;if(W===C8.PADDING||W===C8.WT_STREAM_WOFIN||W===C8.WT_STREAM_WFIN)V=Math.min(G,64);if(V>4*Number(this.session.flowController.receiveWindowSize)||G>8*Number(this.session.flowController.receiveWindowSize)){this.session.closeConnection({code:63,reason:"Frame length too big :"+G});return}if(X.size<V+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}let H;switch(W){case C8.PADDING:break;case C8.WT_RESET_STREAM:case C8.WT_STOP_SENDING:{let v=R8(X);if(typeof v<"u"){let F=this.wtstreams.get(v),U=R8(X);if(F&&typeof U<"u")F.onStreamSignal(W===C8.WT_RESET_STREAM?"resetStream":"stopSending"),F.jsobj.onStreamRecvSignal({code:Number(U),nettask:W===C8.WT_RESET_STREAM?"resetStream":"stopSending"})}}break;case C8.WT_STREAM_WOFIN:case C8.WT_STREAM_WFIN:if(H=R8(X),typeof H<"u"){let v=this.wtstreams.get(H);if(!v){if(v=this.newStream(H,{sendOrder:0n,sendGroupId:0n}),!v)return}if(q-X.offset>=0){let F=W===C8.WT_STREAM_WFIN&&X.size>=G+z;if(F)v.onFin();v.recvData({data:q-X.offset>0?new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,q-X.offset):void 0,fin:F})}}break;case C8.WT_MAX_DATA:this.onMaxData(R8(X));break;case C8.WT_MAX_STREAM_DATA:{let v=R8(X),F=R8(X);if(typeof v<"u"&&typeof F<"u")this.onMaxStreamData(v,F)}break;case C8.WT_MAX_STREAMS_BIDI:this.onMaxStreamBiDi(R8(X));break;case C8.WT_MAX_STREAMS_UNIDI:this.onMaxStreamUniDi(R8(X));break;case C8.WT_DATA_BLOCKED:this.onDataBlocked(R8(X));break;case C8.WT_STREAM_DATA_BLOCKED:{let v=R8(X),F=R8(X);if(typeof v<"u"&&typeof F<"u")this.onStreamDataBlocked(v,F)}break;case C8.WT_STREAMS_BLOCKED_UNIDI:this.onStreamsBlockedUnidi(R8(X));break;case C8.WT_STREAMS_BLOCKED_BIDI:this.onStreamsBlockedBidi(R8(X));break;case C8.WT_CLOSE_SESSION:{let v=GT(X)||0,U=new TextDecoder().decode(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,q-X.offset));this.onCloseWebTransportSession({code:v,reason:U})}break;case C8.WT_DRAIN_SESSION:this.onDrain();break;case C8.DATAGRAM:this.session.jsobj.onDatagramReceived({datagram:new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,q-X.offset)});break;default:}if(X.size<G+z){if(this.remainlength=G+z-X.size,this.mode="c",H)this.rstreamid=H,this.rfin=W===C8.WT_STREAM_WFIN}X.offset=q}break;case"c":{let Y=Math.min(X.size-X.offset,this.remainlength);if(this.rstreamid){let Q=this.wtstreams.get(this.rstreamid),K=this.rtype===C8.WT_STREAM_WFIN&&this.remainlength===Y;if(Q){if(K)Q.onFin();Q.recvData({data:new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,Y),fin:K})}}if(this.remainlength=this.remainlength-Y,X.offset+=Y,this.remainlength===0)this.mode="s",delete this.rfin,delete this.rstreamid}break}}writeCapsule({type:J,headerVints:$,payload:X,end:Y}){let Q=0;for(let G in $)Q+=P3($[G]);let K=Q;if(X)Q+=X.byteLength;K+=P3(Q)+P3(J);let W=Buffer.alloc(K),Z={offset:0,size:W.length,buffer:W};T3(Z,J),T3(Z,Q);for(let G in $)T3(Z,$[G]);if(!this.stream)return;if(!Y){let G=!this.stream.write(W);if(X)G=!this.stream.write(X)||G;if(G)this.blocked=!0;return G}else{if(!X)this.stream.end(W,Y);else this.stream.write(W);if(X)this.stream.end(X,Y)}}closeHttp2Stream(J){this.stream.close(J),this.stream.destroy()}initialParametersMandatory(){return!1}}var lm5=G6(`webtransport:http2:node:client(${process?.pid})`);import{createSecureServer as rT6,constants as CB}from"node:http2";import{randomBytes as iT6}from"node:crypto";var oR1=G6(`webtransport:http2:node:websocketparser(${process?.pid})`);function rR1(J){let $=J.buffer.readUInt8(J.offset);return J.offset++,$}function nT6(J){let $=J.buffer.readUInt8(J.offset);return J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$}function aT6(J,$){let X=J.buffer.readUInt8(J.offset)^$.mask[$.offset%4];J.offset++,$.offset++;let Q=1<<(X>>>6);if(J.offset+Q-1>J.size)return;X=X&63;for(let K=0;K<Q-1;K++)X=X<<8|J.buffer.readUInt8(J.offset)^$.mask[$.offset%4],J.offset++,$.offset++;return X}function sT6(J){let $=J.buffer.readUInt8(J.offset);return J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$=$<<8|J.buffer.readUInt8(J.offset),J.offset++,$}function k3(J,$,X,Y){if(Y>24){let Q=0,K=new Uint8Array($.buffer);while(Q<Y&&(X+Q)%8)K[Q+X]^=J.mask[(Q+J.offset)%4],Q++;let W=new Uint8Array(8);W[0]=J.mask[(0+Q+J.offset)%4],W[1]=J.mask[(1+Q+J.offset)%4],W[2]=J.mask[(2+Q+J.offset)%4],W[3]=J.mask[(3+Q+J.offset)%4],W[4]=J.mask[(4+Q+J.offset)%4],W[5]=J.mask[(5+Q+J.offset)%4],W[6]=J.mask[(6+Q+J.offset)%4],W[7]=J.mask[(7+Q+J.offset)%4];let Z=new BigUint64Array($.buffer,Q+X,Math.floor((Y-Q)/8)),G=new BigUint64Array(W.buffer),V=0;while(Q+8<Y)Z[V]^=G[0],Q+=8,V++;while(Q<Y)K[Q+X]^=J.mask[(Q+J.offset)%4],Q++}else{let Q=new Uint8Array(4);Q[0]=J.mask[(0+J.offset)%4],Q[1]=J.mask[(1+J.offset)%4],Q[2]=J.mask[(2+J.offset)%4],Q[3]=J.mask[(3+J.offset)%4];let K=new Uint8Array($.buffer,X,Y);for(let W=0;W<Y;W++)K[W]^=Q[W%4]}J.offset+=Y}function oT6(J){let $=new Uint8Array(4);return $[0]=J.buffer.readUInt8(J.offset),J.offset++,$[1]=J.buffer.readUInt8(J.offset),J.offset++,$[2]=J.buffer.readUInt8(J.offset),J.offset++,$[3]=J.buffer.readUInt8(J.offset),J.offset++,$}class q5 extends PB{static WS_CONTINUE=0;static WS_TEXT=1;static WS_BINARY=2;static WS_CLOSE=8;static WS_PING=9;static WS_PONG=10;constructor({stream:J,nativesession:$,isclient:X,initialStreamSendWindowOffsetUnidi:Y,initialStreamSendWindowOffsetBidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z}){super({stream:J,nativesession:$,isclient:X,initialStreamSendWindowOffsetUnidi:Y,initialStreamSendWindowOffsetBidi:Q,initialStreamReceiveWindowOffset:K,streamShouldAutoTuneReceiveWindow:W,streamReceiveWindowSizeLimit:Z});this.mode="s",this.saveddata=void 0,this.rtype=void 0,this.bidirectionalLimitsSet=!1,this.unidirectionalLimitsSet=!1}parseData(J){let $=J;if(this.saveddata)$=Buffer.concat([this.saveddata,$]),delete this.saveddata;let X={offset:0,size:$.length,buffer:$};while(X.size-X.offset>0)switch(this.mode){case"s":{let Y=X.offset+X.buffer.byteOffset,Q=X.buffer.byteLength-X.offset;if(X.size<2+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}let K=rR1(X),W=(K&128)>>>7;if((K&48)>>>4!==0)oR1("Rsv bits set, should not happen!");let G=K&15;K=rR1(X);let V=(K&128)>>>7,q=V?4:0,z=K&127;if(z===126){if(X.size<2+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}z=nT6(X)}else if(z===127){if(X.size<8+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}z=sT6(X)}if(X.size<q+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}if(V)this.maskcontext={mask:oT6(X),offset:0};else this.maskcontext=void 0;if(!W&&G!==q5.WS_CONTINUE)this.lastopcode=G;if(W)this.lastopcode=void 0;if(G===q5.WS_CLOSE||G===q5.WS_PING||G===q5.WS_PONG){let H=z;if(H>4*Number(this.session.flowController.receiveWindowSize)){this.session.closeConnection({code:63,reason:"Frame length too big :"+H});return}else if(X.size<H+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}switch(G){case q5.WS_CLOSE:if(!this.closesend){if(this.maskcontext)k3(this.maskcontext,X.buffer,X.buffer.byteOffset+X.offset,H);this.sendCloseInt(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,H));let v=0,F="Session websocket closed";if(H>2){let U=Buffer.from(X.buffer.buffer,X.buffer.byteOffset+X.offset,H);v=U.readUint16BE(0);let B=U.toString("utf8",2).split(":");if(B.length>1)v=parseInt(B[0]),B=B.slice(1);F=B.join(":")}this.session.jsobj.onClose({errorcode:v,error:F})}break;case q5.WS_PING:if(this.maskcontext)k3(this.maskcontext,X.buffer,X.buffer.byteOffset+X.offset,H);this.sendPong(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,H));break;default:}X.offset+=H}else if(G===q5.WS_BINARY||G===q5.WS_CONTINUE&&this.lastopcode===q5.WS_BINARY){let H,v,F;if(z===0){oR1("warning empty data frame"),X.offset+=z;continue}if(G===q5.WS_BINARY){if(X.size<2+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}if(F=!1,H=-X.offset,this.maskcontext)v=aT6(X,this.maskcontext);else v=R8(X);if(H+=X.offset,typeof v>"u"||X.size<1+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}this.curtype=v}else F=!0,H=0,v=this.curtype;let U=z-H,j=U,B=Math.min(X.offset+U,X.size),L=X.offset;if(v===x1.PADDING||v===x1.WT_STREAM_WOFIN||v===x1.WT_STREAM_WFIN)j=Math.min(U,64);if(X.size<j+X.offset){this.saveddata=Buffer.from(X.buffer.buffer,Y,Q);return}if(this.maskcontext)k3(this.maskcontext,X.buffer,X.buffer.byteOffset+X.offset,B-X.offset);let M,O;if(v!==x1.WT_STREAM_WOFIN||v!==x1.WT_STREAM_WFIN)if(W){if(O=X,this.contframes){this.contframes.push(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,B-X.offset));let N=this.contframes.reduce((R,x)=>R+x.byteLength,0),w=Buffer.allocUnsafe(N);this.contframes.reduce((R,x)=>{return Buffer.from(x.buffer,x.byteOffset,x.byteLength).copy(w,R),R+x.byteLength},0),O={offset:0,size:N,buffer:w}}}else{if(!this.contframes)this.contframes=[];this.contframes.push(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,B-X.offset))}switch(v){case x1.PADDING:break;case x1.WT_RESET_STREAM:case x1.WT_STOP_SENDING:if(O){let N=R8(O);if(typeof N<"u"){let w=this.wtstreams.get(N),R=R8(O);if(w&&typeof R<"u")w.onStreamSignal(v===x1.WT_RESET_STREAM?"resetStream":"stopSending"),w.jsobj.onStreamRecvSignal({code:Number(R),nettask:v===x1.WT_RESET_STREAM?"resetStream":"stopSending"})}}break;case x1.WT_STREAM_WOFIN:case x1.WT_STREAM_WFIN:if(!F)M=R8(X),this.cstreamid=M;else M=this.cstreamid;if(typeof M<"u"){let N=this.wtstreams.get(M);if(!N){if(N=this.newStream(M,{sendOrder:0n,sendGroupId:0n}),!N)return}if(B-X.offset>=0){let w=v===x1.WT_STREAM_WFIN&&X.size>=U+L;if(w)N.onFin();N.recvData({data:B-X.offset>0?new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,B-X.offset):void 0,fin:w})}}break;case x1.WT_MAX_DATA:this.onMaxData(R8(X));break;case x1.WT_MAX_STREAM_DATA:{let N=R8(X),w=R8(X);if(typeof N<"u"&&typeof w<"u")this.onMaxStreamData(N,w)}break;case x1.WT_MAX_STREAMS_BIDI:this.onMaxStreamBiDi(R8(X));break;case x1.WT_MAX_STREAMS_UNIDI:this.onMaxStreamUniDi(R8(X));break;case x1.WT_DATA_BLOCKED:this.onDataBlocked(R8(X));break;case x1.WT_STREAM_DATA_BLOCKED:{let N=R8(X),w=R8(X);if(typeof N<"u"&&typeof w<"u")this.onStreamDataBlocked(N,w)}break;case x1.WT_STREAMS_BLOCKED_UNIDI:this.onStreamsBlockedUnidi(R8(X));break;case x1.WT_STREAMS_BLOCKED_BIDI:this.onStreamsBlockedBidi(R8(X));break;case x1.WT_CLOSE_SESSION:{let N=GT(X)||0,R=new TextDecoder().decode(new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,B-X.offset));this.onCloseWebTransportSession({code:N,reason:R})}break;case x1.WT_DRAIN_SESSION:this.onDrain();break;case x1.DATAGRAM:if(O)this.session.jsobj.onDatagramReceived({datagram:new Uint8Array(O.buffer.buffer,O.buffer.byteOffset+O.offset,B-O.offset)});break;default:}if(X.size<U+L){if(this.remainlength=U+L-X.size,this.mode="c",M)this.rstreamid=M,this.rfin=v===x1.WT_STREAM_WFIN}X.offset=B}else{let H=z;if(X.offset+H>X.size)this.mode="c",this.rstreamid=void 0,this.remainlength=X.offset+H-X.size,X.offset=X.size;else X.offset+=H}}break;case"c":{let Y=Math.min(X.size-X.offset,this.remainlength);if(this.rstreamid){let Q=this.wtstreams.get(this.rstreamid),K=this.rtype===x1.WT_STREAM_WFIN&&this.remainlength===Y;if(Q){if(K)Q.onFin();if(this.maskcontext)k3(this.maskcontext,X.buffer,X.buffer.byteOffset+X.offset,Y);Q.recvData({data:new Uint8Array(X.buffer.buffer,X.buffer.byteOffset+X.offset,Y),fin:K})}}if(this.remainlength=this.remainlength-Y,X.offset+=Y,this.remainlength===0)this.maskcontext=void 0,this.mode="s",delete this.rfin,delete this.rstreamid}break}}sendClose({code:J,reason:$}){super.sendClose({code:J,reason:$}),this.sendCloseInt()}sendCloseInt(J){this.writeWSFrame({opcode:q5.WS_CLOSE,payload:J}),this.closesend=!0}sendPong(J){this.writeWSFrame({opcode:q5.WS_PONG,payload:J})}writeCapsule({type:J,headerVints:$,payload:X,end:Y}){let Q=0;for(let v in $)Q+=P3($[v]);Q+=P3(J);let K=Q+2,W=0;if(this.isclient)K+=4,W=1;if(X)Q+=X.byteLength;if(Q>65535)K+=8;else if(Q>125)K+=2;let Z=Buffer.alloc(K),G={offset:0,size:Z.length,buffer:Z},V=this.writeHeader(G,{opcode:q5.WS_BINARY,plength:Q,mask:W}),q=G.offset;T3(G,J);for(let v in $)T3(G,$[v]);let z=G.offset;if(V){if(k3(V,G.buffer,G.offset+G.buffer.byteOffset,z-q),X)k3(V,Buffer.from(X.buffer,X.byteOffset,X.byteLength),X.byteOffset,X.byteLength)}let H=!1;if(X)H=!this.stream.write(Z),H=!this.stream.write(X,Y)||H;else H=!this.stream.write(Z,Y);if(H)this.blocked=!0;return H}writeHeader(J,{opcode:$,plength:X,mask:Y}){J.buffer.writeUint8(128|$&15,J.offset),J.offset++;let Q=X;if(X>65535)Q=127;else if(X>125)Q=126;if(J.buffer.writeUint8((Y&&128)|Q&127,J.offset),J.offset++,X>65535)J.buffer.writeBigInt64BE(BigInt(X),J.offset),J.offset+=8;else if(X>125)J.buffer.writeUint16BE(X,J.offset),J.offset+=2;let K;if(Y)K={offset:0,mask:iT6(4)},J.buffer.writeUint32BE(K.mask.readUInt32BE(0),J.offset),J.offset+=4;return K}writeWSFrame({opcode:J,payload:$}){let X=$?.byteLength||0,Y=2,Q=0;if(this.isclient)Y+=4,Q=1;if(X>65535)Y+=8;else if(X>125)Y+=2;let K=Buffer.alloc(Y),W={offset:0,size:K.length,buffer:K},Z=this.writeHeader(W,{opcode:J,plength:X,mask:Q});if(W.offset!==Y)throw Error("Headlength does not match pos");let G=!this.stream.write(K);if(Z&&$)k3(Z,Buffer.from($.buffer,$.byteOffset,$.byteLength),0,$.byteLength);if($)G=!this.stream.write($)||G;if(G)this.blocked=!0;return G}closeHttp2Stream(J){let $=this.stream;if($.close)$.setTimeout(1000,()=>$.close(0));else if($.end)$.end();else throw Error("http2:session not close method")}initialParametersMandatory(){return!0}}import{log as yn}from"node:console";import{webcrypto as tT6}from"crypto";var tR1=["kDraft1","kDraft2"];import{clearInterval as eR1}from"node:timers";class TB{constructor(J){let $=J?.port;if(typeof $>"u")$=443;if(this.port=Number($),this.secret=J?.secret,!this.secret)throw Error("No secret set for Http2Server");this.host=J?.host||"localhost";let X=J?.certhttp2?J?.certhttp2:J?.cert;if(!X)throw Error("No cert set for Http2Server");let Y=J?.privKeyhttp2?J?.privKeyhttp2:J?.privKey;if(!Y)throw Error("No privKey set for Http2Server");this.initialStreamFlowControlWindow=J?.initialStreamFlowControlWindow||16384,this.initialSessionFlowControlWindow=J?.initialSessionFlowControlWindow||16384,this.initialBidirectionalStreams=J?.initialBidirectionalStreams||100,this.initialUnidirectionalStreams=J?.initialUnidirectionalStreams||100,this.streamShouldAutoTuneReceiveWindow=J.streamShouldAutoTuneReceiveWindow||!0,this.streamFlowControlWindowSizeLimit=J?.streamFlowControlWindowSizeLimit||6291456,this.sessionShouldAutoTuneReceiveWindow=J.sessionShouldAutoTuneReceiveWindow||!0,this.sessionFlowControlWindowSizeLimit=J?.sessionFlowControlWindowSizeLimit||15728640,this.paths={},this.hasrequesthandler=!1,this.jsobj=void 0,this.canHandleSettings=!1,this.serverInt=rT6({key:Y,cert:X,allowHTTP1:!0,settings:{enableConnectProtocol:!0,customSettings:{11104:1,11105:this.initialSessionFlowControlWindow,11106:this.initialStreamFlowControlWindow,11107:this.initialStreamFlowControlWindow,11108:this.initialUnidirectionalStreams,11109:this.initialBidirectionalStreams}},remoteCustomSettings:[11104,11105,11106,11107,11108,11109]}),this.serverInt.on("listening",()=>{let Q=this.serverInt.address(),K={port:Q?.port,host:Q?.address};this.jsobj.onServerListening(K)}),this.serverInt.on("error",()=>{let Q={};this.jsobj.onServerError(Q)}),this.serverInt.on("session",(Q)=>{let K=100,W=1,Z=()=>{if(!Q.closed)Q.ping((V,q,z)=>{if(!V)K=W*q+(1-W)*K,W=0.2,Q.WTrtt=K});else eR1(G),G=void 0},G=setInterval(Z,1000);Z(),Q.on("close",()=>{if(G)eR1(G)})}),this.serverInt.on("close",()=>{let Q={};this.jsobj.onServerClose(Q)}),this.serverInt.on("upgrade",(Q,K,W)=>{let Z=Q.url;if(!Z){K.destroy();return}while(Z.length>1&&Z[0]==="/"&&Z[1]==="/")Z=Z?.slice(1);let G={...Q.headers,":path":Z},{websocketProt:V,webtransportProt:q}=this.checkProtocolHeader(G);if(q)G["wt-available-protocols"]=q;if(!V){K.destroy();return}if(this.hasrequesthandler){K.head=W;let z={header:G,peerAddress:K.remoteAddress+":"+K.remotePort,session:K,protocol:"websocketoverhttp1",head:W,transportPrivate:{websocketProt:V}};this.jsobj.onSessionRequest(z)}else if(this.paths[Z])this.sendHttp1Headers({stream:K,header:G,protocol:V}).then(()=>{let z={session:new C3({stream:K,isclient:!1,createParser:(H)=>{let v=this.capsParser=new q5({stream:K,nativesession:H,isclient:!1,initialStreamSendWindowOffsetBidi:0,initialStreamSendWindowOffsetUnidi:0,initialStreamReceiveWindowOffset:this.initialStreamFlowControlWindow,streamShouldAutoTuneReceiveWindow:this.streamShouldAutoTuneReceiveWindow,streamReceiveWindowSizeLimit:this.streamFlowControlWindowSizeLimit});if(W.byteLength>0)v.parseData(W);return v},initialBidirectionalSendStreams:0,initialBidirectionalReceiveStreams:this.initialBidirectionalStreams,initialUnidirectionalSendStreams:0,initialUnidirectionalReceiveStreams:this.initialUnidirectionalStreams,sendWindowOffset:0,receiveWindowOffset:this.sessionFlowControlWindowSizeLimit,shouldAutoTuneReceiveWindow:this.sessionShouldAutoTuneReceiveWindow,receiveWindowSizeLimit:this.sessionFlowControlWindowSizeLimit}),path:Z,header:G,peerAddress:K.remoteAddress+":"+K.remotePort,reliable:!0,object:this};this.jsobj.onHttpWTSessionVisitor(z)}).catch((z)=>{yn("Problem sendHttp1Header",z),K.destroy()});else K.destroy()}),this.serverInt.on("stream",(Q,K)=>{if(Q.on("error",()=>{}),K[":method"]!=="CONNECT"){Q.respond({":status":"406"}),Q.close(CB.NGHTTP2_REFUSED_STREAM);return}let W;if(K[":protocol"]==="websocket"&&K["sec-websocket-protocol"]){let G=this.checkProtocolHeader(K);if(W=G.websocketProt,G.webtransportProt)K["wt-available-protocols"]=G.webtransportProt}if(K[":protocol"]==="webtransport"&&K["wt-available-protocols"]){let G=K["wt-available-protocols"].split(",").map((V)=>V.trim());if(G.some((V)=>typeof V!=="string"||V.length<2||V[0]!=='"'||V.at(-1)!=='"')){Q.respond({":status":"406"}),Q.close(CB.NGHTTP2_REFUSED_STREAM);return}if(G=G.map((V)=>V.slice(1,-1)),G.some((V)=>/\\([^"\\])/.test(V))){Q.close(CB.NGHTTP2_REFUSED_STREAM);return}K["wt-available-protocols"]=G.map((V)=>V.replace(/\\(["\\])/g,"$1"))}if(K[":protocol"]!=="webtransport"&&!W){Q.respond({":status":"406"}),Q.close(CB.NGHTTP2_REFUSED_STREAM);return}if(!K[":path"]){Q.respond({":status":"406"}),Q.close(CB.NGHTTP2_REFUSED_STREAM);return}let Z=K[":path"];while(Z.length>1&&Z[0]==="/"&&Z[1]==="/")Z=Z?.slice(1);if(K[":path"]=Z,this.hasrequesthandler){let G=Q.session?.socket,V={header:K,peerAddress:G?.remoteAddress+":"+G?.remotePort,session:Q,protocol:W?"websocket":"capsule",transportPrivate:{websocketProt:W}};this.jsobj.onSessionRequest(V)}else if(this.paths[Z]){let G=Q.session?.socket,{11109:V=void 0,11108:q=void 0,11107:z=void 0,11106:H=void 0,11105:v=void 0}=Q?.session?.remoteSettings?.customSettings||{},F={session:new C3({stream:Q,isclient:!1,createParser:(j)=>{if(!W)return new C8({stream:Q,nativesession:j,isclient:!1,initialStreamSendWindowOffsetBidi:z||this.initialStreamFlowControlWindow,initialStreamSendWindowOffsetUnidi:H||this.initialStreamFlowControlWindow,initialStreamReceiveWindowOffset:this.initialStreamFlowControlWindow,streamShouldAutoTuneReceiveWindow:this.streamShouldAutoTuneReceiveWindow,streamReceiveWindowSizeLimit:this.streamFlowControlWindowSizeLimit});else return this.capsParser=new q5({stream:Q,nativesession:j,isclient:!1,initialStreamSendWindowOffsetBidi:0,initialStreamSendWindowOffsetUnidi:0,initialStreamReceiveWindowOffset:this.initialStreamFlowControlWindow,streamShouldAutoTuneReceiveWindow:this.streamShouldAutoTuneReceiveWindow,streamReceiveWindowSizeLimit:this.streamFlowControlWindowSizeLimit})},initialBidirectionalSendStreams:W?0:V||this.initialBidirectionalStreams,initialBidirectionalReceiveStreams:this.initialBidirectionalStreams,initialUnidirectionalSendStreams:W?0:q||this.initialUnidirectionalStreams,initialUnidirectionalReceiveStreams:this.initialUnidirectionalStreams,sendWindowOffset:!W?v||this.sessionFlowControlWindowSizeLimit:0,receiveWindowOffset:this.sessionFlowControlWindowSizeLimit,shouldAutoTuneReceiveWindow:this.sessionShouldAutoTuneReceiveWindow,receiveWindowSizeLimit:this.sessionFlowControlWindowSizeLimit}),path:Z,header:K,peerAddress:G?.remoteAddress+":"+G?.remotePort,reliable:!0,object:this},U={":status":"200"};if(W)U["sec-websocket-protocol"]=W;Q.respond(U),this.jsobj.onHttpWTSessionVisitor(F)}else{Q.respond({":status":"404"}),Q.end(),Q.close();return}})}checkProtocolHeader(J){let $=J["sec-websocket-protocol"]?.split?.(",")?.map?.((Y)=>Y.trim()),X;if(!Array.isArray($))X=[$];else X=$;if(X=X.map((Y)=>Y?Y.split("_"):[void 0,void 0]).filter((Y)=>Y[0]==="webtransport").filter((Y)=>Y[1]?tR1.includes(Y[1]):!1),X.length>0){let Y=X[0][1];X=X.filter((K)=>K[1]===Y);let Q={websocketProt:X[0].slice(0,2).join("_")};if(X.some((K)=>K[2]))Q.webtransportProt=[...new Set(X.filter((K)=>K[2]).map((K)=>K.slice(2).join("_")))];return Q}else return{websocketProt:void 0}}startServer(){this.serverInt.listen(this.port,this.host)}stopServer(){this.serverInt.close()}updateCert(J,$,X){this.serverInt.setSecureContext({key:$,cert:J})}setJSRequestHandler(J){this.hasrequesthandler=J}addPath(J){this.paths[J]=!0}async sendHttp1Headers({stream:J,header:$,protocol:X}){try{let Y=await tT6.subtle.digest("SHA-1",new TextEncoder().encode($["sec-websocket-key"]+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")),Q=Buffer.from(Y).toString("base64");J.write(`HTTP/1.1 101 Switching Protocols\r
|
|
552
552
|
Upgrade: websocket\r
|
|
553
553
|
Connection: Upgrade\r
|
|
554
554
|
Sec-WebSocket-Protocol: `+X+`\r
|