holostaff-widget 3.0.6 → 3.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/{CanvasRenderer-CNPW48Qw.js → CanvasRenderer-Bv-aQ5u9.js} +5 -5
  2. package/dist/{CanvasRenderer-CNPW48Qw.js.map → CanvasRenderer-Bv-aQ5u9.js.map} +1 -1
  3. package/dist/{Filter-AM8DWlqL.js → Filter-USG-3OWx.js} +2 -2
  4. package/dist/{Filter-AM8DWlqL.js.map → Filter-USG-3OWx.js.map} +1 -1
  5. package/dist/{GpuStencilModesToPixi-BR9JEV9O.js → GpuStencilModesToPixi-0Pv9HrNg.js} +3 -3
  6. package/dist/{GpuStencilModesToPixi-BR9JEV9O.js.map → GpuStencilModesToPixi-0Pv9HrNg.js.map} +1 -1
  7. package/dist/{RenderTargetSystem-BpbroGT3.js → RenderTargetSystem-BNInd2k4.js} +3 -3
  8. package/dist/{RenderTargetSystem-BpbroGT3.js.map → RenderTargetSystem-BNInd2k4.js.map} +1 -1
  9. package/dist/{WebGLRenderer-C8_IJOQx.js → WebGLRenderer-zb0jiqTg.js} +5 -5
  10. package/dist/{WebGLRenderer-C8_IJOQx.js.map → WebGLRenderer-zb0jiqTg.js.map} +1 -1
  11. package/dist/{WebGPURenderer-C9gHL4Xl.js → WebGPURenderer-fm_uBJOT.js} +6 -6
  12. package/dist/{WebGPURenderer-C9gHL4Xl.js.map → WebGPURenderer-fm_uBJOT.js.map} +1 -1
  13. package/dist/{browserAll-BHbeidFW.js → browserAll-CcRDLEJc.js} +3 -3
  14. package/dist/{browserAll-BHbeidFW.js.map → browserAll-CcRDLEJc.js.map} +1 -1
  15. package/dist/{getTextureBatchBindGroup-CNV1rYho.js → getTextureBatchBindGroup-DBv7jVal.js} +3 -3
  16. package/dist/{getTextureBatchBindGroup-CNV1rYho.js.map → getTextureBatchBindGroup-DBv7jVal.js.map} +1 -1
  17. package/dist/hs-widget.es.js +1 -1
  18. package/dist/hs-widget.umd.js +63 -63
  19. package/dist/hs-widget.umd.js.map +1 -1
  20. package/dist/{index-D4TjHcc0.js → index-CHnN3M8o.js} +1297 -1231
  21. package/dist/index-CHnN3M8o.js.map +1 -0
  22. package/dist/{webworkerAll-Cqn374qg.js → webworkerAll-CIC3WsZz.js} +3 -3
  23. package/dist/{webworkerAll-Cqn374qg.js.map → webworkerAll-CIC3WsZz.js.map} +1 -1
  24. package/package.json +1 -1
  25. package/dist/index-D4TjHcc0.js.map +0 -1
@@ -1,4 +1,4 @@
1
- (function(fi,$e){typeof exports=="object"&&typeof module<"u"?$e(exports):typeof define=="function"&&define.amd?define(["exports"],$e):(fi=typeof globalThis<"u"?globalThis:fi||self,$e(fi.HolostaffWidget={}))})(this,(function(fi){"use strict";const $e={mode:"floating",container:null,position:"bottom-center",trigger:"scroll",scrollThreshold:.3,delayMs:3e3,theme:"light",accentColor:null,language:"en",backendUrl:"https://us-central1-holostaff-ai.cloudfunctions.net",visionWsUrl:null,visionConsent:"auto"};function Rf(s){const e=s.dataset.staffId;if(!e)throw new Error("[HolostaffWidget] data-staff-id attribute is required");return{staffId:e,mode:s.dataset.mode??$e.mode,container:s.dataset.container??$e.container,position:s.dataset.position??$e.position,trigger:s.dataset.trigger??$e.trigger,scrollThreshold:parseFloat(s.dataset.scrollThreshold??"")||$e.scrollThreshold,delayMs:parseInt(s.dataset.delayMs??"",10)||$e.delayMs,theme:s.dataset.theme??$e.theme,accentColor:s.dataset.accentColor??$e.accentColor,language:s.dataset.language??$e.language,backendUrl:s.dataset.backendUrl??$e.backendUrl,visionWsUrl:s.dataset.visionWsUrl??$e.visionWsUrl,visionConsent:s.dataset.hsConsent??$e.visionConsent}}const Mf=["bottom-center","bottom-left","bottom-right"],Pf=["scroll","delay","immediate"],kf=["light","dark","auto"];function Of(s,e,t){const i={...s};return!e.dataset.trigger&&t.trigger&&Pf.includes(t.trigger)&&(i.trigger=t.trigger),!e.dataset.position&&t.position&&Mf.includes(t.position)&&(i.position=t.position),!e.dataset.theme&&t.theme&&kf.includes(t.theme)&&(i.theme=t.theme),!e.dataset.scrollThreshold&&t.scrollThreshold!=null&&(i.scrollThreshold=t.scrollThreshold),!e.dataset.delayMs&&t.delayMs!=null&&(i.delayMs=t.delayMs),!e.dataset.visionWsUrl&&t.visionWsUrl&&(i.visionWsUrl=t.visionWsUrl),i}const Nr="https://us-central1-holostaff-ai.cloudfunctions.net";async function Bf(s,e=Nr){const t=await fetch(`${e}/widgetSession`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:s})});if(!t.ok){const i=await t.json().catch(()=>({error:t.statusText}));throw new Error(i.error||`Session request failed: ${t.status}`)}return t.json()}class Df extends Error{constructor(e){super(e),this.name="WidgetDisabledError"}}async function Nf(s,e=Nr){const t=await fetch(`${e}/widgetConfig?staffId=${encodeURIComponent(s)}`);if(!t.ok){const i=await t.json().catch(()=>({error:t.statusText}));throw i.disabled===!0||t.status===404?new Df(i.error||"Agent not available"):new Error(i.error||`Config request failed: ${t.status}`)}return t.json()}async function Uf(s,e,t,i=Nr){const r=await fetch(`${i}/widgetPageAction`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:s,domSnapshot:e,instruction:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||`Page action request failed: ${r.status}`)}return r.json()}var A=(s=>(s.Application="application",s.WebGLPipes="webgl-pipes",s.WebGLPipesAdaptor="webgl-pipes-adaptor",s.WebGLSystem="webgl-system",s.WebGPUPipes="webgpu-pipes",s.WebGPUPipesAdaptor="webgpu-pipes-adaptor",s.WebGPUSystem="webgpu-system",s.CanvasSystem="canvas-system",s.CanvasPipesAdaptor="canvas-pipes-adaptor",s.CanvasPipes="canvas-pipes",s.Asset="asset",s.LoadParser="load-parser",s.ResolveParser="resolve-parser",s.CacheParser="cache-parser",s.DetectionParser="detection-parser",s.MaskEffect="mask-effect",s.BlendMode="blend-mode",s.TextureSource="texture-source",s.Environment="environment",s.ShapeBuilder="shape-builder",s.Batcher="batcher",s))(A||{});const Ur=s=>{if(typeof s=="function"||typeof s=="object"&&s.extension){if(!s.extension)throw new Error("Extension class must have an extension object");s={...typeof s.extension!="object"?{type:s.extension}:s.extension,ref:s}}if(typeof s=="object")s={...s};else throw new Error("Invalid extension type");return typeof s.type=="string"&&(s.type=[s.type]),s},Us=(s,e)=>Ur(s).priority??e,Q={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...s){return s.map(Ur).forEach(e=>{e.type.forEach(t=>{var i,r;return(r=(i=this._removeHandlers)[t])==null?void 0:r.call(i,e)})}),this},add(...s){return s.map(Ur).forEach(e=>{e.type.forEach(t=>{var n,o;const i=this._addHandlers,r=this._queue;i[t]?(o=i[t])==null||o.call(i,e):(r[t]=r[t]||[],(n=r[t])==null||n.push(e))})}),this},handle(s,e,t){var o;const i=this._addHandlers,r=this._removeHandlers;if(i[s]||r[s])throw new Error(`Extension type ${s} already has a handler`);i[s]=e,r[s]=t;const n=this._queue;return n[s]&&((o=n[s])==null||o.forEach(a=>e(a)),delete n[s]),this},handleByMap(s,e){return this.handle(s,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(s,e,t=-1){return this.handle(s,i=>{e.findIndex(n=>n.name===i.name)>=0||(e.push({name:i.name,value:i.ref}),e.sort((n,o)=>Us(o.value,t)-Us(n.value,t)))},i=>{const r=e.findIndex(n=>n.name===i.name);r!==-1&&e.splice(r,1)})},handleByList(s,e,t=-1){return this.handle(s,i=>{e.includes(i.ref)||(e.push(i.ref),e.sort((r,n)=>Us(n,t)-Us(r,t)))},i=>{const r=e.indexOf(i.ref);r!==-1&&e.splice(r,1)})},mixin(s,...e){for(const t of e)Object.defineProperties(s.prototype,Object.getOwnPropertyDescriptors(t))}};let Yi;function fa(){if(typeof Yi=="boolean")return Yi;try{Yi=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{Yi=!1}return Yi}function pa(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Fr={exports:{}},ma;function Ff(){return ma||(ma=1,(function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function r(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function n(l,c,h,u,f){if(typeof h!="function")throw new TypeError("The listener must be a function");var d=new r(h,u||l,f),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],d]:l._events[g].push(d):(l._events[g]=d,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},a.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,d=u.length,g=new Array(d);f<d;f++)g[f]=u[f].fn;return g},a.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},a.prototype.emit=function(c,h,u,f,d,g){var _=t?t+c:c;if(!this._events[_])return!1;var b=this._events[_],x=arguments.length,C,S;if(b.fn){switch(b.once&&this.removeListener(c,b.fn,void 0,!0),x){case 1:return b.fn.call(b.context),!0;case 2:return b.fn.call(b.context,h),!0;case 3:return b.fn.call(b.context,h,u),!0;case 4:return b.fn.call(b.context,h,u,f),!0;case 5:return b.fn.call(b.context,h,u,f,d),!0;case 6:return b.fn.call(b.context,h,u,f,d,g),!0}for(S=1,C=new Array(x-1);S<x;S++)C[S-1]=arguments[S];b.fn.apply(b.context,C)}else{var E=b.length,w;for(S=0;S<E;S++)switch(b[S].once&&this.removeListener(c,b[S].fn,void 0,!0),x){case 1:b[S].fn.call(b[S].context);break;case 2:b[S].fn.call(b[S].context,h);break;case 3:b[S].fn.call(b[S].context,h,u);break;case 4:b[S].fn.call(b[S].context,h,u,f);break;default:if(!C)for(w=1,C=new Array(x-1);w<x;w++)C[w-1]=arguments[w];b[S].fn.apply(b[S].context,C)}}return!0},a.prototype.on=function(c,h,u){return n(this,c,h,u,!1)},a.prototype.once=function(c,h,u){return n(this,c,h,u,!0)},a.prototype.removeListener=function(c,h,u,f){var d=t?t+c:c;if(!this._events[d])return this;if(!h)return o(this,d),this;var g=this._events[d];if(g.fn)g.fn===h&&(!f||g.once)&&(!u||g.context===u)&&o(this,d);else{for(var _=0,b=[],x=g.length;_<x;_++)(g[_].fn!==h||f&&!g[_].once||u&&g[_].context!==u)&&b.push(g[_]);b.length?this._events[d]=b.length===1?b[0]:b:o(this,d)}return this},a.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&o(this,h)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,s.exports=a})(Fr)),Fr.exports}var Gf=Ff();const lt=pa(Gf),Gr={default:-1};function be(s="default"){return Gr[s]===void 0&&(Gr[s]=-1),++Gr[s]}var ge=(s=>(s[s.MAP_READ=1]="MAP_READ",s[s.MAP_WRITE=2]="MAP_WRITE",s[s.COPY_SRC=4]="COPY_SRC",s[s.COPY_DST=8]="COPY_DST",s[s.INDEX=16]="INDEX",s[s.VERTEX=32]="VERTEX",s[s.UNIFORM=64]="UNIFORM",s[s.STORAGE=128]="STORAGE",s[s.INDIRECT=256]="INDIRECT",s[s.QUERY_RESOLVE=512]="QUERY_RESOLVE",s[s.STATIC=1024]="STATIC",s))(ge||{});let gt=class extends lt{constructor(e){let{data:t,size:i}=e;const{usage:r,label:n,shrinkToFit:o}=e;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=be("buffer"),this._resourceType="buffer",this._resourceId=be("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,t instanceof Array&&(t=new Float32Array(t)),this._data=t,i??(i=t==null?void 0:t.byteLength);const a=!!t;this.descriptor={size:i,usage:r,mappedAtCreation:a,label:n},this.shrinkToFit=o??!0}get data(){return this._data}set data(e){this.setDataWithSize(e,e.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&ge.STATIC)}set static(e){e?this.descriptor.usage|=ge.STATIC:this.descriptor.usage&=~ge.STATIC}setDataWithSize(e,t,i){if(this._updateID++,this._updateSize=t*e.BYTES_PER_ELEMENT,this._data===e){i&&this.emit("update",this);return}const r=this._data;if(this._data=e,this._dataInt32=null,!r||r.length!==e.length){!this.shrinkToFit&&r&&e.byteLength<r.byteLength?i&&this.emit("update",this):(this.descriptor.size=e.byteLength,this._resourceId=be("resource"),this.emit("change",this));return}i&&this.emit("update",this)}update(e){this._updateSize=e??this._updateSize,this._updateID++,this.emit("update",this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}};class Lr{constructor(e){this._syncFunctionHash=Object.create(null),this._adaptor=e,this._systemCheck()}_systemCheck(){if(!fa())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}ensureUniformGroup(e){const t=this.getUniformGroupData(e);e.buffer||(e.buffer=new gt({data:new Float32Array(t.layout.size/4),usage:ge.UNIFORM|ge.COPY_DST}))}getUniformGroupData(e){return this._syncFunctionHash[e._signature]||this._initUniformGroup(e)}_initUniformGroup(e){const t=e._signature;let i=this._syncFunctionHash[t];if(!i){const r=Object.keys(e.uniformStructures).map(a=>e.uniformStructures[a]),n=this._adaptor.createUboElements(r),o=this._generateUboSync(n.uboElements);i=this._syncFunctionHash[t]={layout:n,syncFunction:o}}return this._syncFunctionHash[t]}_generateUboSync(e){return this._adaptor.generateUboSync(e)}syncUniformGroup(e,t,i){const r=this.getUniformGroupData(e);e.buffer||(e.buffer=new gt({data:new Float32Array(r.layout.size/4),usage:ge.UNIFORM|ge.COPY_DST}));let n=null;return t||(t=e.buffer.data,n=e.buffer.dataInt32),i||(i=0),r.syncFunction(e.uniforms,t,n,i),!0}updateUniformGroup(e){if(e.isStatic&&!e._dirtyId)return!1;e._dirtyId=0;const t=this.syncUniformGroup(e);return e.buffer.update(),t}destroy(){this._syncFunctionHash=null}}const Wr={f32:4,i32:4,"vec2<f32>":8,"vec3<f32>":12,"vec4<f32>":16,"vec2<i32>":8,"vec3<i32>":12,"vec4<i32>":16,"mat2x2<f32>":32,"mat3x3<f32>":48,"mat4x4<f32>":64};function Lf(s){const e=s.map(n=>({data:n,offset:0,size:0})),t=16;let i=0,r=0;for(let n=0;n<e.length;n++){const o=e[n];if(i=Wr[o.data.type],!i)throw new Error(`Unknown type ${o.data.type}`);o.data.size>1&&(i=Math.max(i,t)*o.data.size);const a=i===12?16:i;o.size=i;const l=r%t;l>0&&t-l<a?r+=(t-l)%16:r+=(i-l%i)%i,o.offset=r,r+=i}return r=Math.ceil(r/16)*16,{uboElements:e,size:r}}const ct=[{type:"mat3x3<f32>",test:s=>s.value.a!==void 0,ubo:`
1
+ (function(fi,$e){typeof exports=="object"&&typeof module<"u"?$e(exports):typeof define=="function"&&define.amd?define(["exports"],$e):(fi=typeof globalThis<"u"?globalThis:fi||self,$e(fi.HolostaffWidget={}))})(this,(function(fi){"use strict";const $e={mode:"floating",container:null,position:"bottom-center",trigger:"scroll",scrollThreshold:.3,delayMs:3e3,theme:"light",accentColor:null,language:"en",backendUrl:"https://us-central1-holostaff-ai.cloudfunctions.net",visionWsUrl:null,visionConsent:"auto"};function Rf(s){const e=s.dataset.staffId;if(!e)throw new Error("[HolostaffWidget] data-staff-id attribute is required");return{staffId:e,mode:s.dataset.mode??$e.mode,container:s.dataset.container??$e.container,position:s.dataset.position??$e.position,trigger:s.dataset.trigger??$e.trigger,scrollThreshold:parseFloat(s.dataset.scrollThreshold??"")||$e.scrollThreshold,delayMs:parseInt(s.dataset.delayMs??"",10)||$e.delayMs,theme:s.dataset.theme??$e.theme,accentColor:s.dataset.accentColor??$e.accentColor,language:s.dataset.language??$e.language,backendUrl:s.dataset.backendUrl??$e.backendUrl,visionWsUrl:s.dataset.visionWsUrl??$e.visionWsUrl,visionConsent:s.dataset.hsConsent??$e.visionConsent}}const Mf=["bottom-center","bottom-left","bottom-right"],Pf=["scroll","delay","immediate"],kf=["light","dark","auto"];function Of(s,e,t){const i={...s};return!e.dataset.trigger&&t.trigger&&Pf.includes(t.trigger)&&(i.trigger=t.trigger),!e.dataset.position&&t.position&&Mf.includes(t.position)&&(i.position=t.position),!e.dataset.theme&&t.theme&&kf.includes(t.theme)&&(i.theme=t.theme),!e.dataset.scrollThreshold&&t.scrollThreshold!=null&&(i.scrollThreshold=t.scrollThreshold),!e.dataset.delayMs&&t.delayMs!=null&&(i.delayMs=t.delayMs),!e.dataset.visionWsUrl&&t.visionWsUrl&&(i.visionWsUrl=t.visionWsUrl),i}const Us="https://us-central1-holostaff-ai.cloudfunctions.net";async function Bf(s,e=Us){const t=await fetch(`${e}/widgetSession`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:s})});if(!t.ok){const i=await t.json().catch(()=>({error:t.statusText}));throw new Error(i.error||`Session request failed: ${t.status}`)}return t.json()}class Df extends Error{constructor(e){super(e),this.name="WidgetDisabledError"}}async function Nf(s,e=Us,t){let i=`${e}/widgetConfig?staffId=${encodeURIComponent(s)}`;t&&(i+=`&visitorId=${encodeURIComponent(t)}`);const r=await fetch(i);if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw n.disabled===!0||r.status===404?new Df(n.error||"Agent not available"):new Error(n.error||`Config request failed: ${r.status}`)}return r.json()}async function Uf(s,e,t,i=Us){try{await fetch(`${i}/flagVisitor`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:s,visitorId:e,reason:t})})}catch(r){console.warn("[backend] flagVisitor failed (fire-and-forget):",r)}}async function Ff(s,e,t,i=Us){const r=await fetch(`${i}/widgetPageAction`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:s,domSnapshot:e,instruction:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||`Page action request failed: ${r.status}`)}return r.json()}var A=(s=>(s.Application="application",s.WebGLPipes="webgl-pipes",s.WebGLPipesAdaptor="webgl-pipes-adaptor",s.WebGLSystem="webgl-system",s.WebGPUPipes="webgpu-pipes",s.WebGPUPipesAdaptor="webgpu-pipes-adaptor",s.WebGPUSystem="webgpu-system",s.CanvasSystem="canvas-system",s.CanvasPipesAdaptor="canvas-pipes-adaptor",s.CanvasPipes="canvas-pipes",s.Asset="asset",s.LoadParser="load-parser",s.ResolveParser="resolve-parser",s.CacheParser="cache-parser",s.DetectionParser="detection-parser",s.MaskEffect="mask-effect",s.BlendMode="blend-mode",s.TextureSource="texture-source",s.Environment="environment",s.ShapeBuilder="shape-builder",s.Batcher="batcher",s))(A||{});const Ur=s=>{if(typeof s=="function"||typeof s=="object"&&s.extension){if(!s.extension)throw new Error("Extension class must have an extension object");s={...typeof s.extension!="object"?{type:s.extension}:s.extension,ref:s}}if(typeof s=="object")s={...s};else throw new Error("Invalid extension type");return typeof s.type=="string"&&(s.type=[s.type]),s},Fs=(s,e)=>Ur(s).priority??e,Q={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...s){return s.map(Ur).forEach(e=>{e.type.forEach(t=>{var i,r;return(r=(i=this._removeHandlers)[t])==null?void 0:r.call(i,e)})}),this},add(...s){return s.map(Ur).forEach(e=>{e.type.forEach(t=>{var n,o;const i=this._addHandlers,r=this._queue;i[t]?(o=i[t])==null||o.call(i,e):(r[t]=r[t]||[],(n=r[t])==null||n.push(e))})}),this},handle(s,e,t){var o;const i=this._addHandlers,r=this._removeHandlers;if(i[s]||r[s])throw new Error(`Extension type ${s} already has a handler`);i[s]=e,r[s]=t;const n=this._queue;return n[s]&&((o=n[s])==null||o.forEach(a=>e(a)),delete n[s]),this},handleByMap(s,e){return this.handle(s,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(s,e,t=-1){return this.handle(s,i=>{e.findIndex(n=>n.name===i.name)>=0||(e.push({name:i.name,value:i.ref}),e.sort((n,o)=>Fs(o.value,t)-Fs(n.value,t)))},i=>{const r=e.findIndex(n=>n.name===i.name);r!==-1&&e.splice(r,1)})},handleByList(s,e,t=-1){return this.handle(s,i=>{e.includes(i.ref)||(e.push(i.ref),e.sort((r,n)=>Fs(n,t)-Fs(r,t)))},i=>{const r=e.indexOf(i.ref);r!==-1&&e.splice(r,1)})},mixin(s,...e){for(const t of e)Object.defineProperties(s.prototype,Object.getOwnPropertyDescriptors(t))}};let Yi;function fa(){if(typeof Yi=="boolean")return Yi;try{Yi=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{Yi=!1}return Yi}function pa(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Fr={exports:{}},ma;function Gf(){return ma||(ma=1,(function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function r(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function n(l,c,h,u,f){if(typeof h!="function")throw new TypeError("The listener must be a function");var d=new r(h,u||l,f),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],d]:l._events[g].push(d):(l._events[g]=d,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},a.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,d=u.length,g=new Array(d);f<d;f++)g[f]=u[f].fn;return g},a.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},a.prototype.emit=function(c,h,u,f,d,g){var _=t?t+c:c;if(!this._events[_])return!1;var y=this._events[_],x=arguments.length,C,S;if(y.fn){switch(y.once&&this.removeListener(c,y.fn,void 0,!0),x){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,u),!0;case 4:return y.fn.call(y.context,h,u,f),!0;case 5:return y.fn.call(y.context,h,u,f,d),!0;case 6:return y.fn.call(y.context,h,u,f,d,g),!0}for(S=1,C=new Array(x-1);S<x;S++)C[S-1]=arguments[S];y.fn.apply(y.context,C)}else{var E=y.length,w;for(S=0;S<E;S++)switch(y[S].once&&this.removeListener(c,y[S].fn,void 0,!0),x){case 1:y[S].fn.call(y[S].context);break;case 2:y[S].fn.call(y[S].context,h);break;case 3:y[S].fn.call(y[S].context,h,u);break;case 4:y[S].fn.call(y[S].context,h,u,f);break;default:if(!C)for(w=1,C=new Array(x-1);w<x;w++)C[w-1]=arguments[w];y[S].fn.apply(y[S].context,C)}}return!0},a.prototype.on=function(c,h,u){return n(this,c,h,u,!1)},a.prototype.once=function(c,h,u){return n(this,c,h,u,!0)},a.prototype.removeListener=function(c,h,u,f){var d=t?t+c:c;if(!this._events[d])return this;if(!h)return o(this,d),this;var g=this._events[d];if(g.fn)g.fn===h&&(!f||g.once)&&(!u||g.context===u)&&o(this,d);else{for(var _=0,y=[],x=g.length;_<x;_++)(g[_].fn!==h||f&&!g[_].once||u&&g[_].context!==u)&&y.push(g[_]);y.length?this._events[d]=y.length===1?y[0]:y:o(this,d)}return this},a.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&o(this,h)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,s.exports=a})(Fr)),Fr.exports}var Lf=Gf();const lt=pa(Lf),Gr={default:-1};function be(s="default"){return Gr[s]===void 0&&(Gr[s]=-1),++Gr[s]}var ge=(s=>(s[s.MAP_READ=1]="MAP_READ",s[s.MAP_WRITE=2]="MAP_WRITE",s[s.COPY_SRC=4]="COPY_SRC",s[s.COPY_DST=8]="COPY_DST",s[s.INDEX=16]="INDEX",s[s.VERTEX=32]="VERTEX",s[s.UNIFORM=64]="UNIFORM",s[s.STORAGE=128]="STORAGE",s[s.INDIRECT=256]="INDIRECT",s[s.QUERY_RESOLVE=512]="QUERY_RESOLVE",s[s.STATIC=1024]="STATIC",s))(ge||{});let gt=class extends lt{constructor(e){let{data:t,size:i}=e;const{usage:r,label:n,shrinkToFit:o}=e;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=be("buffer"),this._resourceType="buffer",this._resourceId=be("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,t instanceof Array&&(t=new Float32Array(t)),this._data=t,i??(i=t==null?void 0:t.byteLength);const a=!!t;this.descriptor={size:i,usage:r,mappedAtCreation:a,label:n},this.shrinkToFit=o??!0}get data(){return this._data}set data(e){this.setDataWithSize(e,e.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&ge.STATIC)}set static(e){e?this.descriptor.usage|=ge.STATIC:this.descriptor.usage&=~ge.STATIC}setDataWithSize(e,t,i){if(this._updateID++,this._updateSize=t*e.BYTES_PER_ELEMENT,this._data===e){i&&this.emit("update",this);return}const r=this._data;if(this._data=e,this._dataInt32=null,!r||r.length!==e.length){!this.shrinkToFit&&r&&e.byteLength<r.byteLength?i&&this.emit("update",this):(this.descriptor.size=e.byteLength,this._resourceId=be("resource"),this.emit("change",this));return}i&&this.emit("update",this)}update(e){this._updateSize=e??this._updateSize,this._updateID++,this.emit("update",this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}};class Lr{constructor(e){this._syncFunctionHash=Object.create(null),this._adaptor=e,this._systemCheck()}_systemCheck(){if(!fa())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}ensureUniformGroup(e){const t=this.getUniformGroupData(e);e.buffer||(e.buffer=new gt({data:new Float32Array(t.layout.size/4),usage:ge.UNIFORM|ge.COPY_DST}))}getUniformGroupData(e){return this._syncFunctionHash[e._signature]||this._initUniformGroup(e)}_initUniformGroup(e){const t=e._signature;let i=this._syncFunctionHash[t];if(!i){const r=Object.keys(e.uniformStructures).map(a=>e.uniformStructures[a]),n=this._adaptor.createUboElements(r),o=this._generateUboSync(n.uboElements);i=this._syncFunctionHash[t]={layout:n,syncFunction:o}}return this._syncFunctionHash[t]}_generateUboSync(e){return this._adaptor.generateUboSync(e)}syncUniformGroup(e,t,i){const r=this.getUniformGroupData(e);e.buffer||(e.buffer=new gt({data:new Float32Array(r.layout.size/4),usage:ge.UNIFORM|ge.COPY_DST}));let n=null;return t||(t=e.buffer.data,n=e.buffer.dataInt32),i||(i=0),r.syncFunction(e.uniforms,t,n,i),!0}updateUniformGroup(e){if(e.isStatic&&!e._dirtyId)return!1;e._dirtyId=0;const t=this.syncUniformGroup(e);return e.buffer.update(),t}destroy(){this._syncFunctionHash=null}}const Wr={f32:4,i32:4,"vec2<f32>":8,"vec3<f32>":12,"vec4<f32>":16,"vec2<i32>":8,"vec3<i32>":12,"vec4<i32>":16,"mat2x2<f32>":32,"mat3x3<f32>":48,"mat4x4<f32>":64};function Wf(s){const e=s.map(n=>({data:n,offset:0,size:0})),t=16;let i=0,r=0;for(let n=0;n<e.length;n++){const o=e[n];if(i=Wr[o.data.type],!i)throw new Error(`Unknown type ${o.data.type}`);o.data.size>1&&(i=Math.max(i,t)*o.data.size);const a=i===12?16:i;o.size=i;const l=r%t;l>0&&t-l<a?r+=(t-l)%16:r+=(i-l%i)%i,o.offset=r,r+=i}return r=Math.ceil(r/16)*16,{uboElements:e,size:r}}const ct=[{type:"mat3x3<f32>",test:s=>s.value.a!==void 0,ubo:`
2
2
  var matrix = uv[name].toArray(true);
3
3
  data[offset] = matrix[0];
4
4
  data[offset + 1] = matrix[1];
@@ -121,12 +121,12 @@
121
121
  data[offset + 10] = v[8];`,"mat4x4<f32>":`
122
122
  for (let i = 0; i < 16; i++) {
123
123
  data[offset + i] = v[i];
124
- }`,"mat3x2<f32>":pi(3,2),"mat4x2<f32>":pi(4,2),"mat2x3<f32>":pi(2,3),"mat4x3<f32>":pi(4,3),"mat2x4<f32>":pi(2,4),"mat3x4<f32>":pi(3,4)},Wf={..._a,"mat2x2<f32>":`
124
+ }`,"mat3x2<f32>":pi(3,2),"mat4x2<f32>":pi(4,2),"mat2x3<f32>":pi(2,3),"mat4x3<f32>":pi(4,3),"mat2x4<f32>":pi(2,4),"mat3x4<f32>":pi(3,4)},Hf={..._a,"mat2x2<f32>":`
125
125
  data[offset] = v[0];
126
126
  data[offset + 1] = v[1];
127
127
  data[offset + 2] = v[2];
128
128
  data[offset + 3] = v[3];
129
- `};function Hf(s,e){const t=Math.max(Wr[s.data.type]/16,1),i=s.data.value.length/s.data.size,r=(4-i%4)%4,n=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
129
+ `};function Vf(s,e){const t=Math.max(Wr[s.data.type]/16,1),i=s.data.value.length/s.data.size,r=(4-i%4)%4,n=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
130
130
  v = uv.${s.data.name};
131
131
  offset += ${e};
132
132
 
@@ -142,10 +142,10 @@
142
142
  }
143
143
  ${r!==0?`arrayOffset += ${r};`:""}
144
144
  }
145
- `}function Vf(s){return ga(s,"uboStd40",Hf,_a)}class Hr extends Lr{constructor(){super({createUboElements:Lf,generateUboSync:Vf})}}Hr.extension={type:[A.WebGLSystem],name:"ubo"};class Fs extends lt{constructor({buffer:e,offset:t,size:i}){super(),this.uid=be("buffer"),this._resourceType="bufferResource",this._touched=0,this._resourceId=be("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=e,this.offset=t|0,this.size=i,this.buffer.on("change",this.onBufferChange,this)}onBufferChange(){this._resourceId=be("resource"),this.emit("change",this)}destroy(e=!1){this.destroyed=!0,e&&this.buffer.destroy(),this.emit("change",this),this.buffer=null,this.removeAllListeners()}}const Vr=Object.create(null),ya=Object.create(null);function qi(s,e){let t=ya[s];return t===void 0&&(Vr[e]===void 0&&(Vr[e]=1),ya[s]=t=Vr[e]++),t}const ba=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],zf=ba.reduce((s,e)=>(s[e]=!0,s),{});function $f(s,e){switch(s){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*e);case"vec3<f32>":return new Float32Array(3*e);case"vec4<f32>":return new Float32Array(4*e);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const xa=class uf{constructor(e,t){this._touched=0,this.uid=be("uniform"),this._resourceType="uniformGroup",this._resourceId=be("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...uf.defaultOptions,...t},this.uniformStructures=e;const i={};for(const r in e){const n=e[r];if(n.name=r,n.size=n.size??1,!zf[n.type]){const o=n.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,l]=o;throw new Error(`Uniform type ${n.type} is not supported. Use type: '${a}', size: ${l} instead.`)}throw new Error(`Uniform type ${n.type} is not supported. Supported uniform types are: ${ba.join(", ")}`)}n.value??(n.value=$f(n.type,n.size)),i[r]=n.value}this.uniforms=i,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=qi(Object.keys(i).map(r=>`${r}-${e[r].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};xa.defaultOptions={ubo:!1,isStatic:!1};let ht=xa;function Gs(s){return s+=s===0?1:0,--s,s|=s>>>1,s|=s>>>2,s|=s>>>4,s|=s>>>8,s|=s>>>16,s+1}function va(s){return!(s&s-1)&&!!s}function Ca(s){const e={};for(const t in s)s[t]!==void 0&&(e[t]=s[t]);return e}const Sa=new Set,Be="8.0.0",jf="8.3.4",mi={quiet:!1,noColor:!1},ee=((s,e,t=3)=>{if(mi.quiet||Sa.has(e))return;let i=new Error().stack;const r=`${e}
145
+ `}function zf(s){return ga(s,"uboStd40",Vf,_a)}class Hr extends Lr{constructor(){super({createUboElements:Wf,generateUboSync:zf})}}Hr.extension={type:[A.WebGLSystem],name:"ubo"};class Gs extends lt{constructor({buffer:e,offset:t,size:i}){super(),this.uid=be("buffer"),this._resourceType="bufferResource",this._touched=0,this._resourceId=be("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=e,this.offset=t|0,this.size=i,this.buffer.on("change",this.onBufferChange,this)}onBufferChange(){this._resourceId=be("resource"),this.emit("change",this)}destroy(e=!1){this.destroyed=!0,e&&this.buffer.destroy(),this.emit("change",this),this.buffer=null,this.removeAllListeners()}}const Vr=Object.create(null),ya=Object.create(null);function qi(s,e){let t=ya[s];return t===void 0&&(Vr[e]===void 0&&(Vr[e]=1),ya[s]=t=Vr[e]++),t}const ba=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],$f=ba.reduce((s,e)=>(s[e]=!0,s),{});function jf(s,e){switch(s){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*e);case"vec3<f32>":return new Float32Array(3*e);case"vec4<f32>":return new Float32Array(4*e);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const xa=class uf{constructor(e,t){this._touched=0,this.uid=be("uniform"),this._resourceType="uniformGroup",this._resourceId=be("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...uf.defaultOptions,...t},this.uniformStructures=e;const i={};for(const r in e){const n=e[r];if(n.name=r,n.size=n.size??1,!$f[n.type]){const o=n.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,l]=o;throw new Error(`Uniform type ${n.type} is not supported. Use type: '${a}', size: ${l} instead.`)}throw new Error(`Uniform type ${n.type} is not supported. Supported uniform types are: ${ba.join(", ")}`)}n.value??(n.value=jf(n.type,n.size)),i[r]=n.value}this.uniforms=i,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=qi(Object.keys(i).map(r=>`${r}-${e[r].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};xa.defaultOptions={ubo:!1,isStatic:!1};let ht=xa;function Ls(s){return s+=s===0?1:0,--s,s|=s>>>1,s|=s>>>2,s|=s>>>4,s|=s>>>8,s|=s>>>16,s+1}function va(s){return!(s&s-1)&&!!s}function Ca(s){const e={};for(const t in s)s[t]!==void 0&&(e[t]=s[t]);return e}const Sa=new Set,Be="8.0.0",Xf="8.3.4",mi={quiet:!1,noColor:!1},ee=((s,e,t=3)=>{if(mi.quiet||Sa.has(e))return;let i=new Error().stack;const r=`${e}
146
146
  Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!mi.noColor;typeof i>"u"?console.warn("PixiJS Deprecation Warning: ",r):(i=i.split(`
147
147
  `).splice(t).join(`
148
- `),n?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",r),console.warn(i),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",r),console.warn(i))),Sa.add(e)});Object.defineProperties(ee,{quiet:{get:()=>mi.quiet,set:s=>{mi.quiet=s},enumerable:!0,configurable:!1},noColor:{get:()=>mi.noColor,set:s=>{mi.noColor=s},enumerable:!0,configurable:!1}});const Ea=Object.create(null);function Xf(s){const e=Ea[s];return e===void 0&&(Ea[s]=be("resource")),e}const Ta=class df extends lt{constructor(e={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,e={...df.defaultOptions,...e},this.addressMode=e.addressMode,this.addressModeU=e.addressModeU??this.addressModeU,this.addressModeV=e.addressModeV??this.addressModeV,this.addressModeW=e.addressModeW??this.addressModeW,this.scaleMode=e.scaleMode,this.magFilter=e.magFilter??this.magFilter,this.minFilter=e.minFilter??this.minFilter,this.mipmapFilter=e.mipmapFilter??this.mipmapFilter,this.lodMinClamp=e.lodMinClamp,this.lodMaxClamp=e.lodMaxClamp,this.compare=e.compare,this.maxAnisotropy=e.maxAnisotropy??1}set addressMode(e){this.addressModeU=e,this.addressModeV=e,this.addressModeW=e}get addressMode(){return this.addressModeU}set wrapMode(e){ee(Be,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=e}get wrapMode(){return this.addressMode}set scaleMode(e){this.magFilter=e,this.minFilter=e,this.mipmapFilter=e}get scaleMode(){return this.magFilter}set maxAnisotropy(e){this._maxAnisotropy=Math.min(e,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this._sharedResourceId=null,this.emit("change",this)}_generateResourceId(){const e=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=Xf(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};Ta.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let zr=Ta;const Aa=class ff extends lt{constructor(e={}){super(),this.options=e,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=be("textureSource"),this._resourceType="textureSource",this._resourceId=be("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.viewDimension="2d",this.arrayLayerCount=1,this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,e={...ff.defaultOptions,...e},this.label=e.label??"",this.resource=e.resource,this.autoGarbageCollect=e.autoGarbageCollect,this._resolution=e.resolution,e.width?this.pixelWidth=e.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,e.height?this.pixelHeight=e.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=e.format,this.dimension=e.dimensions,this.viewDimension=e.viewDimension??e.dimensions,this.arrayLayerCount=e.arrayLayerCount,this.mipLevelCount=e.mipLevelCount,this.autoGenerateMipmaps=e.autoGenerateMipmaps,this.sampleCount=e.sampleCount,this.antialias=e.antialias,this.alphaMode=e.alphaMode,this.style=new zr(Ca(e)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(e){var t,i;this.style!==e&&((t=this._style)==null||t.off("change",this._onStyleChange,this),this._style=e,(i=this._style)==null||i.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(e){this._style.maxAnisotropy=e}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(e){this._style.addressMode=e}get repeatMode(){return this._style.addressMode}set repeatMode(e){this._style.addressMode=e}get magFilter(){return this._style.magFilter}set magFilter(e){this._style.magFilter=e}get minFilter(){return this._style.minFilter}set minFilter(e){this._style.minFilter=e}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(e){this._style.mipmapFilter=e}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(e){this._style.lodMinClamp=e}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(e){this._style.lodMaxClamp=e}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const e=this._resolution;if(this.resize(this.resourceWidth/e,this.resourceHeight/e))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){var e,t;this._resourceId=be("resource"),this.emit("change",this),this.emit("unload",this);for(const i in this._gpuData)(t=(e=this._gpuData[i])==null?void 0:e.destroy)==null||t.call(e);this._gpuData=Object.create(null)}get resourceWidth(){const{resource:e}=this;return e.naturalWidth||e.videoWidth||e.displayWidth||e.width}get resourceHeight(){const{resource:e}=this;return e.naturalHeight||e.videoHeight||e.displayHeight||e.height}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this.width=this.pixelWidth/e,this.height=this.pixelHeight/e)}resize(e,t,i){i||(i=this._resolution),e||(e=this.width),t||(t=this.height);const r=Math.round(e*i),n=Math.round(t*i);return this.width=r/i,this.height=n/i,this._resolution=i,this.pixelWidth===r&&this.pixelHeight===n?!1:(this._refreshPOT(),this.pixelWidth=r,this.pixelHeight=n,this.emit("resize",this),this._resourceId=be("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(e){this._style.wrapMode=e}get wrapMode(){return this._style.wrapMode}set scaleMode(e){this._style.scaleMode=e}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=va(this.pixelWidth)&&va(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};Aa.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",viewDimension:"2d",arrayLayerCount:1,mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let De=Aa;function Yf(s,e){const t=[],i=[`
148
+ `),n?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",r),console.warn(i),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",r),console.warn(i))),Sa.add(e)});Object.defineProperties(ee,{quiet:{get:()=>mi.quiet,set:s=>{mi.quiet=s},enumerable:!0,configurable:!1},noColor:{get:()=>mi.noColor,set:s=>{mi.noColor=s},enumerable:!0,configurable:!1}});const Ea=Object.create(null);function Yf(s){const e=Ea[s];return e===void 0&&(Ea[s]=be("resource")),e}const Ta=class df extends lt{constructor(e={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,e={...df.defaultOptions,...e},this.addressMode=e.addressMode,this.addressModeU=e.addressModeU??this.addressModeU,this.addressModeV=e.addressModeV??this.addressModeV,this.addressModeW=e.addressModeW??this.addressModeW,this.scaleMode=e.scaleMode,this.magFilter=e.magFilter??this.magFilter,this.minFilter=e.minFilter??this.minFilter,this.mipmapFilter=e.mipmapFilter??this.mipmapFilter,this.lodMinClamp=e.lodMinClamp,this.lodMaxClamp=e.lodMaxClamp,this.compare=e.compare,this.maxAnisotropy=e.maxAnisotropy??1}set addressMode(e){this.addressModeU=e,this.addressModeV=e,this.addressModeW=e}get addressMode(){return this.addressModeU}set wrapMode(e){ee(Be,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=e}get wrapMode(){return this.addressMode}set scaleMode(e){this.magFilter=e,this.minFilter=e,this.mipmapFilter=e}get scaleMode(){return this.magFilter}set maxAnisotropy(e){this._maxAnisotropy=Math.min(e,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this._sharedResourceId=null,this.emit("change",this)}_generateResourceId(){const e=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=Yf(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};Ta.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let zr=Ta;const Aa=class ff extends lt{constructor(e={}){super(),this.options=e,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=be("textureSource"),this._resourceType="textureSource",this._resourceId=be("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.viewDimension="2d",this.arrayLayerCount=1,this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,e={...ff.defaultOptions,...e},this.label=e.label??"",this.resource=e.resource,this.autoGarbageCollect=e.autoGarbageCollect,this._resolution=e.resolution,e.width?this.pixelWidth=e.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,e.height?this.pixelHeight=e.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=e.format,this.dimension=e.dimensions,this.viewDimension=e.viewDimension??e.dimensions,this.arrayLayerCount=e.arrayLayerCount,this.mipLevelCount=e.mipLevelCount,this.autoGenerateMipmaps=e.autoGenerateMipmaps,this.sampleCount=e.sampleCount,this.antialias=e.antialias,this.alphaMode=e.alphaMode,this.style=new zr(Ca(e)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(e){var t,i;this.style!==e&&((t=this._style)==null||t.off("change",this._onStyleChange,this),this._style=e,(i=this._style)==null||i.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(e){this._style.maxAnisotropy=e}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(e){this._style.addressMode=e}get repeatMode(){return this._style.addressMode}set repeatMode(e){this._style.addressMode=e}get magFilter(){return this._style.magFilter}set magFilter(e){this._style.magFilter=e}get minFilter(){return this._style.minFilter}set minFilter(e){this._style.minFilter=e}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(e){this._style.mipmapFilter=e}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(e){this._style.lodMinClamp=e}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(e){this._style.lodMaxClamp=e}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const e=this._resolution;if(this.resize(this.resourceWidth/e,this.resourceHeight/e))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){var e,t;this._resourceId=be("resource"),this.emit("change",this),this.emit("unload",this);for(const i in this._gpuData)(t=(e=this._gpuData[i])==null?void 0:e.destroy)==null||t.call(e);this._gpuData=Object.create(null)}get resourceWidth(){const{resource:e}=this;return e.naturalWidth||e.videoWidth||e.displayWidth||e.width}get resourceHeight(){const{resource:e}=this;return e.naturalHeight||e.videoHeight||e.displayHeight||e.height}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this.width=this.pixelWidth/e,this.height=this.pixelHeight/e)}resize(e,t,i){i||(i=this._resolution),e||(e=this.width),t||(t=this.height);const r=Math.round(e*i),n=Math.round(t*i);return this.width=r/i,this.height=n/i,this._resolution=i,this.pixelWidth===r&&this.pixelHeight===n?!1:(this._refreshPOT(),this.pixelWidth=r,this.pixelHeight=n,this.emit("resize",this),this._resourceId=be("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(e){this._style.wrapMode=e}get wrapMode(){return this._style.wrapMode}set scaleMode(e){this._style.scaleMode=e}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=va(this.pixelWidth)&&va(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};Aa.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",viewDimension:"2d",arrayLayerCount:1,mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let De=Aa;function qf(s,e){const t=[],i=[`
149
149
  var g = s.groups;
150
150
  var sS = r.shader;
151
151
  var p = s.glProgram;
@@ -161,7 +161,7 @@ Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!mi.noColor
161
161
  );
162
162
  `)}else t.push(`
163
163
  ugS.updateUniformGroup(resources[${h}], p, sD);
164
- `);else if(u instanceof Fs){const f=s._uniformBindMap[l][Number(h)];t.push(`
164
+ `);else if(u instanceof Gs){const f=s._uniformBindMap[l][Number(h)];t.push(`
165
165
  sS.bindUniformBlock(
166
166
  resources[${h}],
167
167
  '${f}',
@@ -172,10 +172,10 @@ Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!mi.noColor
172
172
  `)),e._gl.uniform1i(d.location,n),t.push(`
173
173
  tS.bind(resources[${h}], ${n});
174
174
  `),n++)}}}const a=[...i,...t].join(`
175
- `);return new Function("r","s","sD",a)}let $r=0;const wa=500;function se(...s){$r!==wa&&($r++,$r===wa?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...s))}class qf{constructor(e,t){this.program=e,this.uniformData=t,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}function Ia(s,e,t){const i=s.createShader(e);return s.shaderSource(i,t),s.compileShader(i),i}function jr(s){const e=new Array(s);for(let t=0;t<e.length;t++)e[t]=!1;return e}function Ra(s,e){switch(s){case"float":return 0;case"vec2":return new Float32Array(2*e);case"vec3":return new Float32Array(3*e);case"vec4":return new Float32Array(4*e);case"int":case"uint":case"sampler2D":case"sampler2DArray":return 0;case"ivec2":return new Int32Array(2*e);case"ivec3":return new Int32Array(3*e);case"ivec4":return new Int32Array(4*e);case"uvec2":return new Uint32Array(2*e);case"uvec3":return new Uint32Array(3*e);case"uvec4":return new Uint32Array(4*e);case"bool":return!1;case"bvec2":return jr(2*e);case"bvec3":return jr(3*e);case"bvec4":return jr(4*e);case"mat2":return new Float32Array([1,0,0,1]);case"mat3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const Ma={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function At(s){return Ma[s]??Ma.float32}let Ls=null;const Pa={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"},Kf={float:"float32",vec2:"float32x2",vec3:"float32x3",vec4:"float32x4",int:"sint32",ivec2:"sint32x2",ivec3:"sint32x3",ivec4:"sint32x4",uint:"uint32",uvec2:"uint32x2",uvec3:"uint32x3",uvec4:"uint32x4",bool:"uint32",bvec2:"uint32x2",bvec3:"uint32x3",bvec4:"uint32x4"};function ka(s,e){if(!Ls){const t=Object.keys(Pa);Ls={};for(let i=0;i<t.length;++i){const r=t[i];Ls[s[r]]=Pa[r]}}return Ls[e]}function Zf(s,e){const t=ka(s,e);return Kf[t]||"float32"}function Jf(s,e,t=!1){const i={},r=e.getProgramParameter(s,e.ACTIVE_ATTRIBUTES);for(let o=0;o<r;o++){const a=e.getActiveAttrib(s,o);if(a.name.startsWith("gl_"))continue;const l=Zf(e,a.type);i[a.name]={location:0,format:l,stride:At(l).stride,offset:0,instance:!1,start:0}}const n=Object.keys(i);if(t){n.sort((o,a)=>o>a?1:-1);for(let o=0;o<n.length;o++)i[n[o]].location=o,e.bindAttribLocation(s,o,n[o]);e.linkProgram(s)}else for(let o=0;o<n.length;o++)i[n[o]].location=e.getAttribLocation(s,n[o]);return i}function Qf(s,e){if(!e.ACTIVE_UNIFORM_BLOCKS)return{};const t={},i=e.getProgramParameter(s,e.ACTIVE_UNIFORM_BLOCKS);for(let r=0;r<i;r++){const n=e.getActiveUniformBlockName(s,r),o=e.getUniformBlockIndex(s,n),a=e.getActiveUniformBlockParameter(s,r,e.UNIFORM_BLOCK_DATA_SIZE);t[n]={name:n,index:o,size:a}}return t}function ep(s,e){const t={},i=e.getProgramParameter(s,e.ACTIVE_UNIFORMS);for(let r=0;r<i;r++){const n=e.getActiveUniform(s,r),o=n.name.replace(/\[.*?\]$/,""),a=!!n.name.match(/\[.*?\]$/),l=ka(e,n.type);t[o]={name:o,index:r,type:l,size:n.size,isArray:a,value:Ra(l,n.size)}}return t}function Oa(s,e){const t=s.getShaderSource(e).split(`
175
+ `);return new Function("r","s","sD",a)}let $r=0;const wa=500;function se(...s){$r!==wa&&($r++,$r===wa?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...s))}class Kf{constructor(e,t){this.program=e,this.uniformData=t,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}function Ia(s,e,t){const i=s.createShader(e);return s.shaderSource(i,t),s.compileShader(i),i}function jr(s){const e=new Array(s);for(let t=0;t<e.length;t++)e[t]=!1;return e}function Ra(s,e){switch(s){case"float":return 0;case"vec2":return new Float32Array(2*e);case"vec3":return new Float32Array(3*e);case"vec4":return new Float32Array(4*e);case"int":case"uint":case"sampler2D":case"sampler2DArray":return 0;case"ivec2":return new Int32Array(2*e);case"ivec3":return new Int32Array(3*e);case"ivec4":return new Int32Array(4*e);case"uvec2":return new Uint32Array(2*e);case"uvec3":return new Uint32Array(3*e);case"uvec4":return new Uint32Array(4*e);case"bool":return!1;case"bvec2":return jr(2*e);case"bvec3":return jr(3*e);case"bvec4":return jr(4*e);case"mat2":return new Float32Array([1,0,0,1]);case"mat3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const Ma={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function At(s){return Ma[s]??Ma.float32}let Ws=null;const Pa={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"},Zf={float:"float32",vec2:"float32x2",vec3:"float32x3",vec4:"float32x4",int:"sint32",ivec2:"sint32x2",ivec3:"sint32x3",ivec4:"sint32x4",uint:"uint32",uvec2:"uint32x2",uvec3:"uint32x3",uvec4:"uint32x4",bool:"uint32",bvec2:"uint32x2",bvec3:"uint32x3",bvec4:"uint32x4"};function ka(s,e){if(!Ws){const t=Object.keys(Pa);Ws={};for(let i=0;i<t.length;++i){const r=t[i];Ws[s[r]]=Pa[r]}}return Ws[e]}function Jf(s,e){const t=ka(s,e);return Zf[t]||"float32"}function Qf(s,e,t=!1){const i={},r=e.getProgramParameter(s,e.ACTIVE_ATTRIBUTES);for(let o=0;o<r;o++){const a=e.getActiveAttrib(s,o);if(a.name.startsWith("gl_"))continue;const l=Jf(e,a.type);i[a.name]={location:0,format:l,stride:At(l).stride,offset:0,instance:!1,start:0}}const n=Object.keys(i);if(t){n.sort((o,a)=>o>a?1:-1);for(let o=0;o<n.length;o++)i[n[o]].location=o,e.bindAttribLocation(s,o,n[o]);e.linkProgram(s)}else for(let o=0;o<n.length;o++)i[n[o]].location=e.getAttribLocation(s,n[o]);return i}function ep(s,e){if(!e.ACTIVE_UNIFORM_BLOCKS)return{};const t={},i=e.getProgramParameter(s,e.ACTIVE_UNIFORM_BLOCKS);for(let r=0;r<i;r++){const n=e.getActiveUniformBlockName(s,r),o=e.getUniformBlockIndex(s,n),a=e.getActiveUniformBlockParameter(s,r,e.UNIFORM_BLOCK_DATA_SIZE);t[n]={name:n,index:o,size:a}}return t}function tp(s,e){const t={},i=e.getProgramParameter(s,e.ACTIVE_UNIFORMS);for(let r=0;r<i;r++){const n=e.getActiveUniform(s,r),o=n.name.replace(/\[.*?\]$/,""),a=!!n.name.match(/\[.*?\]$/),l=ka(e,n.type);t[o]={name:o,index:r,type:l,size:n.size,isArray:a,value:Ra(l,n.size)}}return t}function Oa(s,e){const t=s.getShaderSource(e).split(`
176
176
  `).map((c,h)=>`${h}: ${c}`),i=s.getShaderInfoLog(e),r=i.split(`
177
177
  `),n={},o=r.map(c=>parseFloat(c.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(c=>c&&!n[c]?(n[c]=!0,!0):!1),a=[""];o.forEach(c=>{t[c-1]=`%c${t[c-1]}%c`,a.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const l=t.join(`
178
- `);a[0]=l,console.error(i),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}function tp(s,e,t,i){s.getProgramParameter(e,s.LINK_STATUS)||(s.getShaderParameter(t,s.COMPILE_STATUS)||Oa(s,t),s.getShaderParameter(i,s.COMPILE_STATUS)||Oa(s,i),console.error("PixiJS Error: Could not initialize shader."),s.getProgramInfoLog(e)!==""&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",s.getProgramInfoLog(e)))}function ip(s,e){const t=Ia(s,s.VERTEX_SHADER,e.vertex),i=Ia(s,s.FRAGMENT_SHADER,e.fragment),r=s.createProgram();s.attachShader(r,t),s.attachShader(r,i);const n=e.transformFeedbackVaryings;n&&(typeof s.transformFeedbackVaryings!="function"?se("TransformFeedback is not supported but TransformFeedbackVaryings are given."):s.transformFeedbackVaryings(r,n.names,n.bufferMode==="separate"?s.SEPARATE_ATTRIBS:s.INTERLEAVED_ATTRIBS)),s.linkProgram(r),s.getProgramParameter(r,s.LINK_STATUS)||tp(s,r,t,i),e._attributeData=Jf(r,s,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertex)),e._uniformData=ep(r,s),e._uniformBlockData=Qf(r,s),s.deleteShader(t),s.deleteShader(i);const o={};for(const l in e._uniformData){const c=e._uniformData[l];o[l]={location:s.getUniformLocation(r,l),value:Ra(c.type,c.size)}}return new qf(r,o)}const Ws={textureCount:0,blockIndex:0};class Xr{constructor(e){this._activeProgram=null,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._renderer=e}contextChange(e){this._gl=e,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._activeProgram=null}bind(e,t){if(this._setProgram(e.glProgram),t)return;Ws.textureCount=0,Ws.blockIndex=0;let i=this._shaderSyncFunctions[e.glProgram._key];i||(i=this._shaderSyncFunctions[e.glProgram._key]=this._generateShaderSync(e,this)),this._renderer.buffer.nextBindBase(!!e.glProgram.transformFeedbackVaryings),i(this._renderer,e,Ws)}updateUniformGroup(e){this._renderer.uniformGroup.updateUniformGroup(e,this._activeProgram,Ws)}bindUniformBlock(e,t,i=0){const r=this._renderer.buffer,n=this._getProgramData(this._activeProgram),o=e._bufferResource;o||this._renderer.ubo.updateUniformGroup(e);const a=e.buffer,l=r.updateBuffer(a),c=r.freeLocationForBufferBase(l);if(o){const{offset:u,size:f}=e;u===0&&f===a.data.byteLength?r.bindBufferBase(l,c):r.bindBufferRange(l,c,u)}else r.getLastBindBaseLocation(l)!==c&&r.bindBufferBase(l,c);const h=this._activeProgram._uniformBlockData[t].index;n.uniformBlockBindings[i]!==c&&(n.uniformBlockBindings[i]=c,this._renderer.gl.uniformBlockBinding(n.program,h,c))}_setProgram(e){if(this._activeProgram===e)return;this._activeProgram=e;const t=this._getProgramData(e);this._gl.useProgram(t.program)}_getProgramData(e){return this._programDataHash[e._key]||this._createProgramData(e)}_createProgramData(e){const t=e._key;return this._programDataHash[t]=ip(this._gl,e),this._programDataHash[t]}destroy(){for(const e of Object.keys(this._programDataHash))this._programDataHash[e].destroy();this._programDataHash=null,this._shaderSyncFunctions=null,this._activeProgram=null,this._renderer=null,this._gl=null}_generateShaderSync(e,t){return Yf(e,t)}resetState(){this._activeProgram=null}}Xr.extension={type:[A.WebGLSystem],name:"shader"};const sp={f32:`if (cv !== v) {
178
+ `);a[0]=l,console.error(i),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}function ip(s,e,t,i){s.getProgramParameter(e,s.LINK_STATUS)||(s.getShaderParameter(t,s.COMPILE_STATUS)||Oa(s,t),s.getShaderParameter(i,s.COMPILE_STATUS)||Oa(s,i),console.error("PixiJS Error: Could not initialize shader."),s.getProgramInfoLog(e)!==""&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",s.getProgramInfoLog(e)))}function sp(s,e){const t=Ia(s,s.VERTEX_SHADER,e.vertex),i=Ia(s,s.FRAGMENT_SHADER,e.fragment),r=s.createProgram();s.attachShader(r,t),s.attachShader(r,i);const n=e.transformFeedbackVaryings;n&&(typeof s.transformFeedbackVaryings!="function"?se("TransformFeedback is not supported but TransformFeedbackVaryings are given."):s.transformFeedbackVaryings(r,n.names,n.bufferMode==="separate"?s.SEPARATE_ATTRIBS:s.INTERLEAVED_ATTRIBS)),s.linkProgram(r),s.getProgramParameter(r,s.LINK_STATUS)||ip(s,r,t,i),e._attributeData=Qf(r,s,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertex)),e._uniformData=tp(r,s),e._uniformBlockData=ep(r,s),s.deleteShader(t),s.deleteShader(i);const o={};for(const l in e._uniformData){const c=e._uniformData[l];o[l]={location:s.getUniformLocation(r,l),value:Ra(c.type,c.size)}}return new Kf(r,o)}const Hs={textureCount:0,blockIndex:0};class Xr{constructor(e){this._activeProgram=null,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._renderer=e}contextChange(e){this._gl=e,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._activeProgram=null}bind(e,t){if(this._setProgram(e.glProgram),t)return;Hs.textureCount=0,Hs.blockIndex=0;let i=this._shaderSyncFunctions[e.glProgram._key];i||(i=this._shaderSyncFunctions[e.glProgram._key]=this._generateShaderSync(e,this)),this._renderer.buffer.nextBindBase(!!e.glProgram.transformFeedbackVaryings),i(this._renderer,e,Hs)}updateUniformGroup(e){this._renderer.uniformGroup.updateUniformGroup(e,this._activeProgram,Hs)}bindUniformBlock(e,t,i=0){const r=this._renderer.buffer,n=this._getProgramData(this._activeProgram),o=e._bufferResource;o||this._renderer.ubo.updateUniformGroup(e);const a=e.buffer,l=r.updateBuffer(a),c=r.freeLocationForBufferBase(l);if(o){const{offset:u,size:f}=e;u===0&&f===a.data.byteLength?r.bindBufferBase(l,c):r.bindBufferRange(l,c,u)}else r.getLastBindBaseLocation(l)!==c&&r.bindBufferBase(l,c);const h=this._activeProgram._uniformBlockData[t].index;n.uniformBlockBindings[i]!==c&&(n.uniformBlockBindings[i]=c,this._renderer.gl.uniformBlockBinding(n.program,h,c))}_setProgram(e){if(this._activeProgram===e)return;this._activeProgram=e;const t=this._getProgramData(e);this._gl.useProgram(t.program)}_getProgramData(e){return this._programDataHash[e._key]||this._createProgramData(e)}_createProgramData(e){const t=e._key;return this._programDataHash[t]=sp(this._gl,e),this._programDataHash[t]}destroy(){for(const e of Object.keys(this._programDataHash))this._programDataHash[e].destroy();this._programDataHash=null,this._shaderSyncFunctions=null,this._activeProgram=null,this._renderer=null,this._gl=null}_generateShaderSync(e,t){return qf(e,t)}resetState(){this._activeProgram=null}}Xr.extension={type:[A.WebGLSystem],name:"shader"};const rp={f32:`if (cv !== v) {
179
179
  cu.value = v;
180
180
  gl.uniform1f(location, v);
181
181
  }`,"vec2<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
@@ -247,7 +247,7 @@ Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!mi.noColor
247
247
  cv[2] = v[2];
248
248
  cv[3] = v[3];
249
249
  gl.uniform4i(location, v[0], v[1], v[2], v[3]);
250
- }`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"},rp={f32:"gl.uniform1fv(location, v);","vec2<f32>":"gl.uniform2fv(location, v);","vec3<f32>":"gl.uniform3fv(location, v);","vec4<f32>":"gl.uniform4fv(location, v);","mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);",i32:"gl.uniform1iv(location, v);","vec2<i32>":"gl.uniform2iv(location, v);","vec3<i32>":"gl.uniform3iv(location, v);","vec4<i32>":"gl.uniform4iv(location, v);",u32:"gl.uniform1iv(location, v);","vec2<u32>":"gl.uniform2iv(location, v);","vec3<u32>":"gl.uniform3iv(location, v);","vec4<u32>":"gl.uniform4iv(location, v);",bool:"gl.uniform1iv(location, v);","vec2<bool>":"gl.uniform2iv(location, v);","vec3<bool>":"gl.uniform3iv(location, v);","vec4<bool>":"gl.uniform4iv(location, v);"};function np(s,e){const t=[`
250
+ }`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"},np={f32:"gl.uniform1fv(location, v);","vec2<f32>":"gl.uniform2fv(location, v);","vec3<f32>":"gl.uniform3fv(location, v);","vec4<f32>":"gl.uniform4fv(location, v);","mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);",i32:"gl.uniform1iv(location, v);","vec2<i32>":"gl.uniform2iv(location, v);","vec3<i32>":"gl.uniform3iv(location, v);","vec4<i32>":"gl.uniform4iv(location, v);",u32:"gl.uniform1iv(location, v);","vec2<u32>":"gl.uniform2iv(location, v);","vec3<u32>":"gl.uniform3iv(location, v);","vec4<u32>":"gl.uniform4iv(location, v);",bool:"gl.uniform1iv(location, v);","vec2<bool>":"gl.uniform2iv(location, v);","vec3<bool>":"gl.uniform3iv(location, v);","vec4<bool>":"gl.uniform4iv(location, v);"};function op(s,e){const t=[`
251
251
  var v = null;
252
252
  var cv = null;
253
253
  var cu = null;
@@ -258,14 +258,14 @@ Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!mi.noColor
258
258
  renderer.shader.bindUniformBlock(uv.${i}, "${i}");
259
259
  `):t.push(`
260
260
  renderer.shader.updateUniformGroup(uv.${i});
261
- `):s.uniforms[i]instanceof Fs&&t.push(`
261
+ `):s.uniforms[i]instanceof Gs&&t.push(`
262
262
  renderer.shader.bindBufferResource(uv.${i}, "${i}");
263
- `);continue}const r=s.uniformStructures[i];let n=!1;for(let o=0;o<ct.length;o++){const a=ct[o];if(r.type===a.type&&a.test(r)){t.push(`name = "${i}";`,ct[o].uniform),n=!0;break}}if(!n){const a=(r.size===1?sp:rp)[r.type].replace("location",`ud["${i}"].location`);t.push(`
263
+ `);continue}const r=s.uniformStructures[i];let n=!1;for(let o=0;o<ct.length;o++){const a=ct[o];if(r.type===a.type&&a.test(r)){t.push(`name = "${i}";`,ct[o].uniform),n=!0;break}}if(!n){const a=(r.size===1?rp:np)[r.type].replace("location",`ud["${i}"].location`);t.push(`
264
264
  cu = ud["${i}"];
265
265
  cv = cu.value;
266
266
  v = uv["${i}"];
267
267
  ${a};`)}}return new Function("ud","uv","renderer","syncData",t.join(`
268
- `))}class Yr{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,i){const r=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==r.uniformDirtyGroups[e.uid])&&(r.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(r.uniformData,e.uniforms,this._renderer,i))}_getUniformSyncFunction(e,t){var i;return((i=this._uniformGroupSyncHash[e._signature])==null?void 0:i[t._key])||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){const i=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),r=this._getSignature(e,t._uniformData,"u");return this._cache[r]||(this._cache[r]=this._generateUniformsSync(e,t._uniformData)),i[t._key]=this._cache[r],i[t._key]}_generateUniformsSync(e,t){return np(e,t)}_getSignature(e,t,i){const r=e.uniforms,n=[`${i}-`];for(const o in r)n.push(o),t[o]&&n.push(t[o].type);return n.join("-")}destroy(){this._renderer=null,this._cache=null}}Yr.extension={type:[A.WebGLSystem],name:"uniformGroup"};const Ki={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function op(s){const e=s.map(i=>({data:i,offset:0,size:0}));let t=0;for(let i=0;i<e.length;i++){const r=e[i];let n=Ki[r.data.type].size;const o=Ki[r.data.type].align;if(!Ki[r.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${r.data.type}`);r.data.size>1&&(n=Math.max(n,o)*r.data.size),t=Math.ceil(t/o)*o,r.size=n,r.offset=t,t+=n}return t=Math.ceil(t/16)*16,{uboElements:e,size:t}}function ap(s,e){const{size:t,align:i}=Ki[s.data.type],r=(i-t)/4,n=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
268
+ `))}class Yr{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,i){const r=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==r.uniformDirtyGroups[e.uid])&&(r.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(r.uniformData,e.uniforms,this._renderer,i))}_getUniformSyncFunction(e,t){var i;return((i=this._uniformGroupSyncHash[e._signature])==null?void 0:i[t._key])||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){const i=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),r=this._getSignature(e,t._uniformData,"u");return this._cache[r]||(this._cache[r]=this._generateUniformsSync(e,t._uniformData)),i[t._key]=this._cache[r],i[t._key]}_generateUniformsSync(e,t){return op(e,t)}_getSignature(e,t,i){const r=e.uniforms,n=[`${i}-`];for(const o in r)n.push(o),t[o]&&n.push(t[o].type);return n.join("-")}destroy(){this._renderer=null,this._cache=null}}Yr.extension={type:[A.WebGLSystem],name:"uniformGroup"};const Ki={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function ap(s){const e=s.map(i=>({data:i,offset:0,size:0}));let t=0;for(let i=0;i<e.length;i++){const r=e[i];let n=Ki[r.data.type].size;const o=Ki[r.data.type].align;if(!Ki[r.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${r.data.type}`);r.data.size>1&&(n=Math.max(n,o)*r.data.size),t=Math.ceil(t/o)*o,r.size=n,r.offset=t,t+=n}return t=Math.ceil(t/16)*16,{uboElements:e,size:t}}function lp(s,e){const{size:t,align:i}=Ki[s.data.type],r=(i-t)/4,n=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
269
269
  v = uv.${s.data.name};
270
270
  ${e!==0?`offset += ${e};`:""}
271
271
 
@@ -281,7 +281,7 @@ Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!mi.noColor
281
281
  }
282
282
  ${r!==0?`arrayOffset += ${r};`:""}
283
283
  }
284
- `}function lp(s){return ga(s,"uboWgsl",ap,Wf)}class qr extends Lr{constructor(){super({createUboElements:op,generateUboSync:lp})}}qr.extension={type:[A.WebGPUSystem],name:"ubo"};var cp={grad:.9,turn:360,rad:360/(2*Math.PI)},wt=function(s){return typeof s=="string"?s.length>0:typeof s=="number"},Ge=function(s,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*s)/t+0},ot=function(s,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),s>t?t:s>e?s:e},Ba=function(s){return(s=isFinite(s)?s%360:0)>0?s:s+360},Da=function(s){return{r:ot(s.r,0,255),g:ot(s.g,0,255),b:ot(s.b,0,255),a:ot(s.a)}},Kr=function(s){return{r:Ge(s.r),g:Ge(s.g),b:Ge(s.b),a:Ge(s.a,3)}},hp=/^#([0-9a-f]{3,8})$/i,Hs=function(s){var e=s.toString(16);return e.length<2?"0"+e:e},Na=function(s){var e=s.r,t=s.g,i=s.b,r=s.a,n=Math.max(e,t,i),o=n-Math.min(e,t,i),a=o?n===e?(t-i)/o:n===t?2+(i-e)/o:4+(e-t)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},Ua=function(s){var e=s.h,t=s.s,i=s.v,r=s.a;e=e/360*6,t/=100,i/=100;var n=Math.floor(e),o=i*(1-t),a=i*(1-(e-n)*t),l=i*(1-(1-e+n)*t),c=n%6;return{r:255*[i,a,o,o,l,i][c],g:255*[l,i,i,a,o,o][c],b:255*[o,o,l,i,i,a][c],a:r}},Fa=function(s){return{h:Ba(s.h),s:ot(s.s,0,100),l:ot(s.l,0,100),a:ot(s.a)}},Ga=function(s){return{h:Ge(s.h),s:Ge(s.s),l:Ge(s.l),a:Ge(s.a,3)}},La=function(s){return Ua((t=(e=s).s,{h:e.h,s:(t*=((i=e.l)<50?i:100-i)/100)>0?2*t/(i+t)*100:0,v:i+t,a:e.a}));var e,t,i},Zi=function(s){return{h:(e=Na(s)).h,s:(r=(200-(t=e.s))*(i=e.v)/100)>0&&r<200?t*i/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,t,i,r},up=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,dp=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,fp=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,pp=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Zr={string:[[function(s){var e=hp.exec(s);return e?(s=e[1]).length<=4?{r:parseInt(s[0]+s[0],16),g:parseInt(s[1]+s[1],16),b:parseInt(s[2]+s[2],16),a:s.length===4?Ge(parseInt(s[3]+s[3],16)/255,2):1}:s.length===6||s.length===8?{r:parseInt(s.substr(0,2),16),g:parseInt(s.substr(2,2),16),b:parseInt(s.substr(4,2),16),a:s.length===8?Ge(parseInt(s.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(s){var e=fp.exec(s)||pp.exec(s);return e?e[2]!==e[4]||e[4]!==e[6]?null:Da({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:e[7]===void 0?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(s){var e=up.exec(s)||dp.exec(s);if(!e)return null;var t,i,r=Fa({h:(t=e[1],i=e[2],i===void 0&&(i="deg"),Number(t)*(cp[i]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return La(r)},"hsl"]],object:[[function(s){var e=s.r,t=s.g,i=s.b,r=s.a,n=r===void 0?1:r;return wt(e)&&wt(t)&&wt(i)?Da({r:Number(e),g:Number(t),b:Number(i),a:Number(n)}):null},"rgb"],[function(s){var e=s.h,t=s.s,i=s.l,r=s.a,n=r===void 0?1:r;if(!wt(e)||!wt(t)||!wt(i))return null;var o=Fa({h:Number(e),s:Number(t),l:Number(i),a:Number(n)});return La(o)},"hsl"],[function(s){var e=s.h,t=s.s,i=s.v,r=s.a,n=r===void 0?1:r;if(!wt(e)||!wt(t)||!wt(i))return null;var o=(function(a){return{h:Ba(a.h),s:ot(a.s,0,100),v:ot(a.v,0,100),a:ot(a.a)}})({h:Number(e),s:Number(t),v:Number(i),a:Number(n)});return Ua(o)},"hsv"]]},Wa=function(s,e){for(var t=0;t<e.length;t++){var i=e[t][0](s);if(i)return[i,e[t][1]]}return[null,void 0]},mp=function(s){return typeof s=="string"?Wa(s.trim(),Zr.string):typeof s=="object"&&s!==null?Wa(s,Zr.object):[null,void 0]},Jr=function(s,e){var t=Zi(s);return{h:t.h,s:ot(t.s+100*e,0,100),l:t.l,a:t.a}},Qr=function(s){return(299*s.r+587*s.g+114*s.b)/1e3/255},Ha=function(s,e){var t=Zi(s);return{h:t.h,s:t.s,l:ot(t.l+100*e,0,100),a:t.a}},en=(function(){function s(e){this.parsed=mp(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return s.prototype.isValid=function(){return this.parsed!==null},s.prototype.brightness=function(){return Ge(Qr(this.rgba),2)},s.prototype.isDark=function(){return Qr(this.rgba)<.5},s.prototype.isLight=function(){return Qr(this.rgba)>=.5},s.prototype.toHex=function(){return e=Kr(this.rgba),t=e.r,i=e.g,r=e.b,o=(n=e.a)<1?Hs(Ge(255*n)):"","#"+Hs(t)+Hs(i)+Hs(r)+o;var e,t,i,r,n,o},s.prototype.toRgb=function(){return Kr(this.rgba)},s.prototype.toRgbString=function(){return e=Kr(this.rgba),t=e.r,i=e.g,r=e.b,(n=e.a)<1?"rgba("+t+", "+i+", "+r+", "+n+")":"rgb("+t+", "+i+", "+r+")";var e,t,i,r,n},s.prototype.toHsl=function(){return Ga(Zi(this.rgba))},s.prototype.toHslString=function(){return e=Ga(Zi(this.rgba)),t=e.h,i=e.s,r=e.l,(n=e.a)<1?"hsla("+t+", "+i+"%, "+r+"%, "+n+")":"hsl("+t+", "+i+"%, "+r+"%)";var e,t,i,r,n},s.prototype.toHsv=function(){return e=Na(this.rgba),{h:Ge(e.h),s:Ge(e.s),v:Ge(e.v),a:Ge(e.a,3)};var e},s.prototype.invert=function(){return _t({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},s.prototype.saturate=function(e){return e===void 0&&(e=.1),_t(Jr(this.rgba,e))},s.prototype.desaturate=function(e){return e===void 0&&(e=.1),_t(Jr(this.rgba,-e))},s.prototype.grayscale=function(){return _t(Jr(this.rgba,-1))},s.prototype.lighten=function(e){return e===void 0&&(e=.1),_t(Ha(this.rgba,e))},s.prototype.darken=function(e){return e===void 0&&(e=.1),_t(Ha(this.rgba,-e))},s.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},s.prototype.alpha=function(e){return typeof e=="number"?_t({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):Ge(this.rgba.a,3);var t},s.prototype.hue=function(e){var t=Zi(this.rgba);return typeof e=="number"?_t({h:e,s:t.s,l:t.l,a:t.a}):Ge(t.h)},s.prototype.isEqual=function(e){return this.toHex()===_t(e).toHex()},s})(),_t=function(s){return s instanceof en?s:new en(s)},Va=[],gp=function(s){s.forEach(function(e){Va.indexOf(e)<0&&(e(en,Zr),Va.push(e))})};function _p(s,e){var t={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},i={};for(var r in t)i[t[r]]=r;var n={};s.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,l,c=i[this.toHex()];if(c)return c;if(o!=null&&o.closest){var h=this.toRgb(),u=1/0,f="black";if(!n.length)for(var d in t)n[d]=new s(t[d]).toRgb();for(var g in t){var _=(a=h,l=n[g],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));_<u&&(u=_,f=g)}return f}},e.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":t[a];return l?new s(l).toRgb():null},"name"])}gp([_p]);const gi=class Ds{constructor(e=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=e}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(e){return this.value=e,this}set value(e){if(e instanceof Ds)this._value=this._cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(e===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,e))&&(this._value=this._cloneSource(e),this._normalize(this._value))}}get value(){return this._value}_cloneSource(e){return typeof e=="string"||typeof e=="number"||e instanceof Number||e===null?e:Array.isArray(e)||ArrayBuffer.isView(e)?e.slice(0):typeof e=="object"&&e!==null?{...e}:e}_isSourceEqual(e,t){const i=typeof e;if(i!==typeof t)return!1;if(i==="number"||i==="string"||e instanceof Number)return e===t;if(Array.isArray(e)&&Array.isArray(t)||ArrayBuffer.isView(e)&&ArrayBuffer.isView(t))return e.length!==t.length?!1:e.every((n,o)=>n===t[o]);if(e!==null&&t!==null){const n=Object.keys(e),o=Object.keys(t);return n.length!==o.length?!1:n.every(a=>e[a]===t[a])}return e===t}toRgba(){const[e,t,i,r]=this._components;return{r:e,g:t,b:i,a:r}}toRgb(){const[e,t,i]=this._components;return{r:e,g:t,b:i}}toRgbaString(){const[e,t,i]=this.toUint8RgbArray();return`rgba(${e},${t},${i},${this.alpha})`}toUint8RgbArray(e){const[t,i,r]=this._components;return this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb),e[0]=Math.round(t*255),e[1]=Math.round(i*255),e[2]=Math.round(r*255),e}toArray(e){this._arrayRgba||(this._arrayRgba=[]),e||(e=this._arrayRgba);const[t,i,r,n]=this._components;return e[0]=t,e[1]=i,e[2]=r,e[3]=n,e}toRgbArray(e){this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb);const[t,i,r]=this._components;return e[0]=t,e[1]=i,e[2]=r,e}toNumber(){return this._int}toBgrNumber(){const[e,t,i]=this.toUint8RgbArray();return(i<<16)+(t<<8)+e}toLittleEndianNumber(){const e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(e){const[t,i,r,n]=Ds._temp.setValue(e)._components;return this._components[0]*=t,this._components[1]*=i,this._components[2]*=r,this._components[3]*=n,this._refreshInt(),this._value=null,this}premultiply(e,t=!0){return t&&(this._components[0]*=e,this._components[1]*=e,this._components[2]*=e),this._components[3]=e,this._refreshInt(),this._value=null,this}toPremultiplied(e,t=!0){if(e===1)return(255<<24)+this._int;if(e===0)return t?0:this._int;let i=this._int>>16&255,r=this._int>>8&255,n=this._int&255;return t&&(i=i*e+.5|0,r=r*e+.5|0,n=n*e+.5|0),(e*255<<24)+(i<<16)+(r<<8)+n}toHex(){const e=this._int.toString(16);return`#${"000000".substring(0,6-e.length)+e}`}toHexa(){const t=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(e){return this._components[3]=this._clamp(e),this._value=null,this}_normalize(e){let t,i,r,n;if((typeof e=="number"||e instanceof Number)&&e>=0&&e<=16777215){const o=e;t=(o>>16&255)/255,i=(o>>8&255)/255,r=(o&255)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[t,i,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[t,i,r,n=255]=e,t/=255,i/=255,r/=255,n/=255;else if(typeof e=="string"||typeof e=="object"){if(typeof e=="string"){const a=Ds.HEX_PATTERN.exec(e);a&&(e=`#${a[2]}`)}const o=_t(e);o.isValid()&&({r:t,g:i,b:r,a:n}=o.rgba,t/=255,i/=255,r/=255)}if(t!==void 0)this._components[0]=t,this._components[1]=i,this._components[2]=r,this._components[3]=n,this._refreshInt();else throw new Error(`Unable to convert color ${e}`)}_refreshInt(){this._clamp(this._components);const[e,t,i]=this._components;this._int=(e*255<<16)+(t*255<<8)+(i*255|0)}_clamp(e,t=0,i=1){return typeof e=="number"?Math.min(Math.max(e,t),i):(e.forEach((r,n)=>{e[n]=Math.min(Math.max(r,t),i)}),e)}static isColorLike(e){return typeof e=="number"||typeof e=="string"||e instanceof Number||e instanceof Ds||Array.isArray(e)||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Float32Array||e.r!==void 0&&e.g!==void 0&&e.b!==void 0||e.r!==void 0&&e.g!==void 0&&e.b!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0&&e.a!==void 0}};gi.shared=new gi,gi._temp=new gi,gi.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let Pe=gi;const tn=[];Q.handleByNamedList(A.Environment,tn);async function yp(s){if(!s)for(let e=0;e<tn.length;e++){const t=tn[e];if(t.value.test()){await t.value.load();return}}}const bp={cullArea:null,cullable:!1,cullableChildren:!0},xp=Math.PI*2,vp=180/Math.PI,Cp=Math.PI/180;class xe{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new xe(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return sn.x=0,sn.y=0,sn}}const sn=new xe;class H{constructor(e=1,t=0,i=0,r=1,n=0,o=0){this.array=null,this.a=e,this.b=t,this.c=i,this.d=r,this.tx=n,this.ty=o}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,i,r,n,o){return this.a=e,this.b=t,this.c=i,this.d=r,this.tx=n,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const i=t||this.array;return e?(i[0]=this.a,i[1]=this.b,i[2]=0,i[3]=this.c,i[4]=this.d,i[5]=0,i[6]=this.tx,i[7]=this.ty,i[8]=1):(i[0]=this.a,i[1]=this.c,i[2]=this.tx,i[3]=this.b,i[4]=this.d,i[5]=this.ty,i[6]=0,i[7]=0,i[8]=1),i}apply(e,t){t=t||new xe;const i=e.x,r=e.y;return t.x=this.a*i+this.c*r+this.tx,t.y=this.b*i+this.d*r+this.ty,t}applyInverse(e,t){t=t||new xe;const i=this.a,r=this.b,n=this.c,o=this.d,a=this.tx,l=this.ty,c=1/(i*o+n*-r),h=e.x,u=e.y;return t.x=o*c*h+-n*c*u+(l*n-a*o)*c,t.y=i*c*u+-r*c*h+(-l*i+a*r)*c,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){const t=Math.cos(e),i=Math.sin(e),r=this.a,n=this.c,o=this.tx;return this.a=r*t-this.b*i,this.b=r*i+this.b*t,this.c=n*t-this.d*i,this.d=n*i+this.d*t,this.tx=o*t-this.ty*i,this.ty=o*i+this.ty*t,this}append(e){const t=this.a,i=this.b,r=this.c,n=this.d;return this.a=e.a*t+e.b*r,this.b=e.a*i+e.b*n,this.c=e.c*t+e.d*r,this.d=e.c*i+e.d*n,this.tx=e.tx*t+e.ty*r+this.tx,this.ty=e.tx*i+e.ty*n+this.ty,this}appendFrom(e,t){const i=e.a,r=e.b,n=e.c,o=e.d,a=e.tx,l=e.ty,c=t.a,h=t.b,u=t.c,f=t.d;return this.a=i*c+r*u,this.b=i*h+r*f,this.c=n*c+o*u,this.d=n*h+o*f,this.tx=a*c+l*u+t.tx,this.ty=a*h+l*f+t.ty,this}setTransform(e,t,i,r,n,o,a,l,c){return this.a=Math.cos(a+c)*n,this.b=Math.sin(a+c)*n,this.c=-Math.sin(a-l)*o,this.d=Math.cos(a-l)*o,this.tx=e-(i*this.a+r*this.c),this.ty=t-(i*this.b+r*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const i=this.a,r=this.c;this.a=i*e.a+this.b*e.c,this.b=i*e.b+this.b*e.d,this.c=r*e.a+this.d*e.c,this.d=r*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){const t=this.a,i=this.b,r=this.c,n=this.d,o=e.pivot,a=-Math.atan2(-r,n),l=Math.atan2(i,t),c=Math.abs(a+l);return c<1e-5||Math.abs(xp-c)<1e-5?(e.rotation=l,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=a,e.skew.y=l),e.scale.x=Math.sqrt(t*t+i*i),e.scale.y=Math.sqrt(r*r+n*n),e.position.x=this.tx+(o.x*t+o.y*r),e.position.y=this.ty+(o.x*i+o.y*n),e}invert(){const e=this.a,t=this.b,i=this.c,r=this.d,n=this.tx,o=e*r-t*i;return this.a=r/o,this.b=-t/o,this.c=-i/o,this.d=e/o,this.tx=(i*this.ty-r*n)/o,this.ty=-(e*this.ty-t*n)/o,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const e=new H;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return Ep.identity()}static get shared(){return Sp.identity()}}const Sp=new H,Ep=new H;class je{constructor(e,t,i){this._x=t||0,this._y=i||0,this._observer=e}clone(e){return new je(e??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}const _i={_registeredResources:new Set,register(s){this._registeredResources.add(s)},unregister(s){this._registeredResources.delete(s)},release(){this._registeredResources.forEach(s=>s.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(s){return this._registeredResources.has(s)},reset(){this._registeredResources.clear()}};class Tp{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){var i;let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),(i=t.init)==null||i.call(t,e),t}return(e){var t;(t=e.reset)==null||t.call(e),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let e=0;e<this._index;e++)this._pool[e].destroy();this._pool.length=0,this._count=0,this._index=0}}class Ap{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new Tp(e)),this._poolsByClass.get(e)}stats(){const e={};return this._poolsByClass.forEach(t=>{const i=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[i]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}}const Le=new Ap;_i.register(Le);const wp={get isCachedAsTexture(){var s;return!!((s=this.renderGroup)!=null&&s.isCachedAsTexture)},cacheAsTexture(s){typeof s=="boolean"&&s===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(s===!0?{}:s))},updateCacheTexture(){var s;(s=this.renderGroup)==null||s.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(s){ee("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(s)}};function za(s,e,t){const i=s.length;let r;if(e>=i||t===0)return;t=e+t>i?i-e:t;const n=i-t;for(r=e;r<n;++r)s[r]=s[r+t];s.length=n}const Ip={allowChildren:!0,removeChildren(s=0,e){var n;const t=e??this.children.length,i=t-s,r=[];if(i>0&&i<=t){for(let a=t-1;a>=s;a--){const l=this.children[a];l&&(r.push(l),l.parent=null)}za(this.children,s,t);const o=this.renderGroup||this.parentRenderGroup;o&&o.removeChildren(r);for(let a=0;a<r.length;++a){const l=r[a];(n=l.parentRenderLayer)==null||n.detach(l),this.emit("childRemoved",l,this,a),r[a].emit("removed",this)}return r.length>0&&this._didViewChangeTick++,r}else if(i===0&&this.children.length===0)return r;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(s){const e=this.getChildAt(s);return this.removeChild(e)},getChildAt(s){if(s<0||s>=this.children.length)throw new Error(`getChildAt: Index (${s}) does not exist.`);return this.children[s]},setChildIndex(s,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);this.getChildIndex(s),this.addChildAt(s,e)},getChildIndex(s){const e=this.children.indexOf(s);if(e===-1)throw new Error("The supplied Container must be a child of the caller");return e},addChildAt(s,e){this.allowChildren||ee(Be,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:t}=this;if(e<0||e>t.length)throw new Error(`${s}addChildAt: The index ${e} supplied is out of bounds ${t.length}`);const i=s.parent===this;if(s.parent){const n=s.parent.children.indexOf(s);if(i){if(n===e)return s;s.parent.children.splice(n,1)}else s.removeFromParent()}e===t.length?t.push(s):t.splice(e,0,s),s.parent=this,s.didChange=!0,s._updateFlags=15;const r=this.renderGroup||this.parentRenderGroup;return r&&r.addChild(s),this.sortableChildren&&(this.sortDirty=!0),i||(this.emit("childAdded",s,this,e),s.emit("added",this)),s},swapChildren(s,e){if(s===e)return;const t=this.getChildIndex(s),i=this.getChildIndex(e);this.children[t]=e,this.children[i]=s;const r=this.renderGroup||this.parentRenderGroup;r&&(r.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){var s;(s=this.parent)==null||s.removeChild(this)},reparentChild(...s){return s.length===1?this.reparentChildAt(s[0],this.children.length):(s.forEach(e=>this.reparentChildAt(e,this.children.length)),s[0])},reparentChildAt(s,e){if(s.parent===this)return this.setChildIndex(s,e),s;const t=s.worldTransform.clone();s.removeFromParent(),this.addChildAt(s,e);const i=this.worldTransform.clone();return i.invert(),t.prepend(i),s.setFromMatrix(t),s},replaceChild(s,e){s.updateLocalTransform(),this.addChildAt(e,this.getChildIndex(s)),e.setFromMatrix(s.localTransform),e.updateLocalTransform(),this.removeChild(s)}},Rp={collectRenderables(s,e,t){this.parentRenderLayer&&this.parentRenderLayer!==t||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(s,e,t):this.renderGroup?e.renderPipes.renderGroup.addRenderGroup(this.renderGroup,s):this.collectRenderablesWithEffects(s,e,t))},collectRenderablesSimple(s,e,t){const i=this.children,r=i.length;for(let n=0;n<r;n++)i[n].collectRenderables(s,e,t)},collectRenderablesWithEffects(s,e,t){const{renderPipes:i}=e;for(let r=0;r<this.effects.length;r++){const n=this.effects[r];i[n.pipe].push(n,this,s)}this.collectRenderablesSimple(s,e,t);for(let r=this.effects.length-1;r>=0;r--){const n=this.effects[r];i[n.pipe].pop(n,this,s)}}};class Vs{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let e=0;e<this.filters.length;e++)this.filters[e].destroy();this.filters=null,this.filterArea=null}}class Mp{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(e=>{this.add({test:e.test,maskClass:e})}))}add(e){this._tests.push(e)}getMaskEffect(e){this._initialized||this.init();for(let t=0;t<this._tests.length;t++){const i=this._tests[t];if(i.test(e))return Le.get(i.maskClass,e)}return e}returnMaskEffect(e){Le.return(e)}}const rn=new Mp;Q.handleByList(A.MaskEffect,rn._effectClasses);const Pp={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const s=this.renderGroup||this.parentRenderGroup;s&&(s.structureDidChange=!0)},addEffect(s){this.effects.indexOf(s)===-1&&(this.effects.push(s),this.effects.sort((t,i)=>t.priority-i.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(s){const e=this.effects.indexOf(s);e!==-1&&(this.effects.splice(e,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(s){const e=this._maskEffect;(e==null?void 0:e.mask)!==s&&(e&&(this.removeEffect(e),rn.returnMaskEffect(e),this._maskEffect=null),s!=null&&(this._maskEffect=rn.getMaskEffect(s),this.addEffect(this._maskEffect)))},get mask(){var s;return(s=this._maskEffect)==null?void 0:s.mask},setMask(s){this._maskOptions={...this._maskOptions,...s},s.mask&&(this.mask=s.mask),this._markStructureAsChanged()},set filters(s){var n;!Array.isArray(s)&&s&&(s=[s]);const e=this._filterEffect||(this._filterEffect=new Vs);s=s;const t=(s==null?void 0:s.length)>0,i=((n=e.filters)==null?void 0:n.length)>0,r=t!==i;s=Array.isArray(s)?s.slice(0):s,e.filters=Object.freeze(s),r&&(t?this.addEffect(e):(this.removeEffect(e),e.filters=s??null))},get filters(){var s;return(s=this._filterEffect)==null?void 0:s.filters},set filterArea(s){this._filterEffect||(this._filterEffect=new Vs),this._filterEffect.filterArea=s},get filterArea(){var s;return(s=this._filterEffect)==null?void 0:s.filterArea}},kp={label:null,get name(){return ee(Be,"Container.name property has been removed, use Container.label instead"),this.label},set name(s){ee(Be,"Container.name property has been removed, use Container.label instead"),this.label=s},getChildByName(s,e=!1){return this.getChildByLabel(s,e)},getChildByLabel(s,e=!1){const t=this.children;for(let i=0;i<t.length;i++){const r=t[i];if(r.label===s||s instanceof RegExp&&s.test(r.label))return r}if(e)for(let i=0;i<t.length;i++){const n=t[i].getChildByLabel(s,!0);if(n)return n}return null},getChildrenByLabel(s,e=!1,t=[]){const i=this.children;for(let r=0;r<i.length;r++){const n=i[r];(n.label===s||s instanceof RegExp&&s.test(n.label))&&t.push(n)}if(e)for(let r=0;r<i.length;r++)i[r].getChildrenByLabel(s,!0,t);return t}},zs=[new xe,new xe,new xe,new xe];class Se{constructor(e=0,t=0,i=0,r=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),this.width=Number(i),this.height=Number(r)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new Se(0,0,0,0)}clone(){return new Se(this.x,this.y,this.width,this.height)}copyFromBounds(e){return this.x=e.minX,this.y=e.minY,this.width=e.maxX-e.minX,this.height=e.maxY-e.minY,this}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){return this.width<=0||this.height<=0?!1:e>=this.x&&e<this.x+this.width&&t>=this.y&&t<this.y+this.height}strokeContains(e,t,i,r=.5){const{width:n,height:o}=this;if(n<=0||o<=0)return!1;const a=this.x,l=this.y,c=i*(1-r),h=i-c,u=a-c,f=a+n+c,d=l-c,g=l+o+c,_=a+h,b=a+n-h,x=l+h,C=l+o-h;return e>=u&&e<=f&&t>=d&&t<=g&&!(e>_&&e<b&&t>x&&t<C)}intersects(e,t){if(!t){const D=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=D)return!1;const k=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>k}const i=this.left,r=this.right,n=this.top,o=this.bottom;if(r<=i||o<=n)return!1;const a=zs[0].set(e.left,e.top),l=zs[1].set(e.left,e.bottom),c=zs[2].set(e.right,e.top),h=zs[3].set(e.right,e.bottom);if(c.x<=a.x||l.y<=a.y)return!1;const u=Math.sign(t.a*t.d-t.b*t.c);if(u===0||(t.apply(a,a),t.apply(l,l),t.apply(c,c),t.apply(h,h),Math.max(a.x,l.x,c.x,h.x)<=i||Math.min(a.x,l.x,c.x,h.x)>=r||Math.max(a.y,l.y,c.y,h.y)<=n||Math.min(a.y,l.y,c.y,h.y)>=o))return!1;const f=u*(l.y-a.y),d=u*(a.x-l.x),g=f*i+d*n,_=f*r+d*n,b=f*i+d*o,x=f*r+d*o;if(Math.max(g,_,b,x)<=f*a.x+d*a.y||Math.min(g,_,b,x)>=f*h.x+d*h.y)return!1;const C=u*(a.y-c.y),S=u*(c.x-a.x),E=C*i+S*n,w=C*r+S*n,R=C*i+S*o,M=C*r+S*o;return!(Math.max(E,w,R,M)<=C*a.x+S*a.y||Math.min(E,w,R,M)>=C*h.x+S*h.y)}pad(e=0,t=e){return this.x-=e,this.y-=t,this.width+=e*2,this.height+=t*2,this}fit(e){const t=Math.max(this.x,e.x),i=Math.min(this.x+this.width,e.x+e.width),r=Math.max(this.y,e.y),n=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(i-t,0),this.y=r,this.height=Math.max(n-r,0),this}ceil(e=1,t=.001){const i=Math.ceil((this.x+this.width-t)*e)/e,r=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=i-this.x,this.height=r-this.y,this}scale(e,t=e){return this.x*=e,this.y*=t,this.width*=e,this.height*=t,this}enlarge(e){const t=Math.min(this.x,e.x),i=Math.max(this.x+this.width,e.x+e.width),r=Math.min(this.y,e.y),n=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=i-t,this.y=r,this.height=n-r,this}getBounds(e){return e||(e=new Se),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,i=e.y,r=e.x+e.width,n=e.y+e.height;return t>=this.x&&t<this.x+this.width&&i>=this.y&&i<this.y+this.height&&r>=this.x&&r<this.x+this.width&&n>=this.y&&n<this.y+this.height}set(e,t,i,r){return this.x=e,this.y=t,this.width=i,this.height=r,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const $a=new H;class Ye{constructor(e=1/0,t=1/0,i=-1/0,r=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=$a,this.minX=e,this.minY=t,this.maxX=i,this.maxY=r}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new Se);const e=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(e.x=0,e.y=0,e.width=0,e.height=0):e.copyFromBounds(this),e}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=$a,this}set(e,t,i,r){this.minX=e,this.minY=t,this.maxX=i,this.maxY=r}addFrame(e,t,i,r,n){n||(n=this.matrix);const o=n.a,a=n.b,l=n.c,c=n.d,h=n.tx,u=n.ty;let f=this.minX,d=this.minY,g=this.maxX,_=this.maxY,b=o*e+l*t+h,x=a*e+c*t+u;b<f&&(f=b),x<d&&(d=x),b>g&&(g=b),x>_&&(_=x),b=o*i+l*t+h,x=a*i+c*t+u,b<f&&(f=b),x<d&&(d=x),b>g&&(g=b),x>_&&(_=x),b=o*e+l*r+h,x=a*e+c*r+u,b<f&&(f=b),x<d&&(d=x),b>g&&(g=b),x>_&&(_=x),b=o*i+l*r+h,x=a*i+c*r+u,b<f&&(f=b),x<d&&(d=x),b>g&&(g=b),x>_&&(_=x),this.minX=f,this.minY=d,this.maxX=g,this.maxY=_}addRect(e,t){this.addFrame(e.x,e.y,e.x+e.width,e.y+e.height,t)}addBounds(e,t){this.addFrame(e.minX,e.minY,e.maxX,e.maxY,t)}addBoundsMask(e){this.minX=this.minX>e.minX?this.minX:e.minX,this.minY=this.minY>e.minY?this.minY:e.minY,this.maxX=this.maxX<e.maxX?this.maxX:e.maxX,this.maxY=this.maxY<e.maxY?this.maxY:e.maxY}applyMatrix(e){const t=this.minX,i=this.minY,r=this.maxX,n=this.maxY,{a:o,b:a,c:l,d:c,tx:h,ty:u}=e;let f=o*t+l*i+h,d=a*t+c*i+u;this.minX=f,this.minY=d,this.maxX=f,this.maxY=d,f=o*r+l*i+h,d=a*r+c*i+u,this.minX=f<this.minX?f:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=f>this.maxX?f:this.maxX,this.maxY=d>this.maxY?d:this.maxY,f=o*t+l*n+h,d=a*t+c*n+u,this.minX=f<this.minX?f:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=f>this.maxX?f:this.maxX,this.maxY=d>this.maxY?d:this.maxY,f=o*r+l*n+h,d=a*r+c*n+u,this.minX=f<this.minX?f:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=f>this.maxX?f:this.maxX,this.maxY=d>this.maxY?d:this.maxY}fit(e){return this.minX<e.left&&(this.minX=e.left),this.maxX>e.right&&(this.maxX=e.right),this.minY<e.top&&(this.minY=e.top),this.maxY>e.bottom&&(this.maxY=e.bottom),this}fitBounds(e,t,i,r){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<i&&(this.minY=i),this.maxY>r&&(this.maxY=r),this}pad(e,t=e){return this.minX-=e,this.maxX+=e,this.minY-=t,this.maxY+=t,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new Ye(this.minX,this.minY,this.maxX,this.maxY)}scale(e,t=e){return this.minX*=e,this.minY*=t,this.maxX*=e,this.maxY*=t,this}get x(){return this.minX}set x(e){const t=this.maxX-this.minX;this.minX=e,this.maxX=e+t}get y(){return this.minY}set y(e){const t=this.maxY-this.minY;this.minY=e,this.maxY=e+t}get width(){return this.maxX-this.minX}set width(e){this.maxX=this.minX+e}get height(){return this.maxY-this.minY}set height(e){this.maxY=this.minY+e}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(e,t,i,r){let n=this.minX,o=this.minY,a=this.maxX,l=this.maxY;r||(r=this.matrix);const c=r.a,h=r.b,u=r.c,f=r.d,d=r.tx,g=r.ty;for(let _=t;_<i;_+=2){const b=e[_],x=e[_+1],C=c*b+u*x+d,S=h*b+f*x+g;n=C<n?C:n,o=S<o?S:o,a=C>a?C:a,l=S>l?S:l}this.minX=n,this.minY=o,this.maxX=a,this.maxY=l}containsPoint(e,t){return this.minX<=e&&this.minY<=t&&this.maxX>=e&&this.maxY>=t}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(e){return this.minX=e.minX,this.minY=e.minY,this.maxX=e.maxX,this.maxY=e.maxY,this}}const qe=Le.getPool(H),It=Le.getPool(Ye),Op=new H,Bp={getFastGlobalBounds(s,e){e||(e=new Ye),e.clear(),this._getGlobalBoundsRecursive(!!s,e,this.parentRenderLayer),e.isValid||e.set(0,0,0,0);const t=this.renderGroup||this.parentRenderGroup;return e.applyMatrix(t.worldTransform),e},_getGlobalBoundsRecursive(s,e,t){let i=e;if(s&&this.parentRenderLayer&&this.parentRenderLayer!==t||this.localDisplayStatus!==7||!this.measurable)return;const r=!!this.effects.length;if((this.renderGroup||r)&&(i=It.get().clear()),this.boundsArea)e.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;i.addFrame(o.minX,o.minY,o.maxX,o.maxY,this.groupTransform)}const n=this.children;for(let o=0;o<n.length;o++)n[o]._getGlobalBoundsRecursive(s,i,t)}if(r){let n=!1;const o=this.renderGroup||this.parentRenderGroup;for(let a=0;a<this.effects.length;a++)this.effects[a].addBounds&&(n||(n=!0,i.applyMatrix(o.worldTransform)),this.effects[a].addBounds(i,!0));n&&i.applyMatrix(o.worldTransform.copyTo(Op).invert()),e.addBounds(i),It.return(i)}else this.renderGroup&&(e.addBounds(i,this.relativeGroupTransform),It.return(i))}};function nn(s,e,t){t.clear();let i,r;return s.parent?e?i=s.parent.worldTransform:(r=qe.get().identity(),i=on(s,r)):i=H.IDENTITY,ja(s,t,i,e),r&&qe.return(r),t.isValid||t.set(0,0,0,0),t}function ja(s,e,t,i){var a,l;if(!s.visible||!s.measurable)return;let r;i?r=s.worldTransform:(s.updateLocalTransform(),r=qe.get(),r.appendFrom(s.localTransform,t));const n=e,o=!!s.effects.length;if(o&&(e=It.get().clear()),s.boundsArea)e.addRect(s.boundsArea,r);else{const c=s.bounds;c&&!c.isEmpty()&&(e.matrix=r,e.addBounds(c));for(let h=0;h<s.children.length;h++)ja(s.children[h],e,r,i)}if(o){for(let c=0;c<s.effects.length;c++)(l=(a=s.effects[c]).addBounds)==null||l.call(a,e);n.addBounds(e,H.IDENTITY),It.return(e)}i||qe.return(r)}function on(s,e){const t=s.parent;return t&&(on(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function yi(s,e){if(s===16777215||!e)return e;if(e===16777215||!s)return s;const t=s>>16&255,i=s>>8&255,r=s&255,n=e>>16&255,o=e>>8&255,a=e&255,l=t*n/255|0,c=i*o/255|0,h=r*a/255|0;return(l<<16)+(c<<8)+h}const Xa=16777215;function $s(s,e){return s===Xa?e:e===Xa?s:yi(s,e)}function bi(s){return((s&255)<<16)+(s&65280)+(s>>16&255)}const Dp={getGlobalAlpha(s){if(s)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let e=this.alpha,t=this.parent;for(;t;)e*=t.alpha,t=t.parent;return e},getGlobalTransform(s=new H,e){if(e)return s.copyFrom(this.worldTransform);this.updateLocalTransform();const t=on(this,qe.get().identity());return s.appendFrom(this.localTransform,t),qe.return(t),s},getGlobalTint(s){if(s)return this.renderGroup?bi(this.renderGroup.worldColor):this.parentRenderGroup?bi($s(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=$s(e,t.localColor),t=t.parent;return bi(e)}};function an(s,e,t){return e.clear(),t||(t=H.IDENTITY),Ya(s,e,t,s,!0),e.isValid||e.set(0,0,0,0),e}function Ya(s,e,t,i,r){var l,c;let n;if(r)n=qe.get(),n=t.copyTo(n);else{if(!s.visible||!s.measurable)return;s.updateLocalTransform();const h=s.localTransform;n=qe.get(),n.appendFrom(h,t)}const o=e,a=!!s.effects.length;if(a&&(e=It.get().clear()),s.boundsArea)e.addRect(s.boundsArea,n);else{s.renderPipeId&&(e.matrix=n,e.addBounds(s.bounds));const h=s.children;for(let u=0;u<h.length;u++)Ya(h[u],e,n,i,!1)}if(a){for(let h=0;h<s.effects.length;h++)(c=(l=s.effects[h]).addLocalBounds)==null||c.call(l,e,i);o.addBounds(e,H.IDENTITY),It.return(e)}qe.return(n)}function qa(s,e){const t=s.children;for(let i=0;i<t.length;i++){const r=t[i],n=r.uid,o=(r._didViewChangeTick&65535)<<16|r._didContainerChangeTick&65535,a=e.index;(e.data[a]!==n||e.data[a+1]!==o)&&(e.data[e.index]=n,e.data[e.index+1]=o,e.didChange=!0),e.index=a+2,r.children.length&&qa(r,e)}return e.didChange}const Np=new H,Up={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(s,e){const t=Math.sign(this.scale.x)||1;e!==0?this.scale.x=s/e*t:this.scale.x=t},_setHeight(s,e){const t=Math.sign(this.scale.y)||1;e!==0?this.scale.y=s/e*t:this.scale.y=t},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new Ye});const s=this._localBoundsCacheData;return s.index=1,s.didChange=!1,s.data[0]!==this._didViewChangeTick&&(s.didChange=!0,s.data[0]=this._didViewChangeTick),qa(this,s),s.didChange&&an(this,s.localBounds,Np),s.localBounds},getBounds(s,e){return nn(this,s,e||new Ye)}},Fp={_onRender:null,set onRender(s){const e=this.renderGroup||this.parentRenderGroup;if(!s){this._onRender&&(e==null||e.removeOnRender(this)),this._onRender=null;return}this._onRender||e==null||e.addOnRender(this),this._onRender=s},get onRender(){return this._onRender}},Gp={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(s){this._zIndex!==s&&(this._zIndex=s,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(Lp))}};function Lp(s,e){return s._zIndex-e._zIndex}const Wp={getGlobalPosition(s=new xe,e=!1){return this.parent?this.parent.toGlobal(this._position,s,e):(s.x=this._position.x,s.y=this._position.y),s},toGlobal(s,e,t=!1){const i=this.getGlobalTransform(qe.get(),t);return e=i.apply(s,e),qe.return(i),e},toLocal(s,e,t,i){e&&(s=e.toGlobal(s,t,i));const r=this.getGlobalTransform(qe.get(),i);return t=r.applyInverse(s,t),qe.return(r),t}};class ln{constructor(){this.uid=be("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(e){this.instructions[this.instructionSize++]=e}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}const ei=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],ti=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],ii=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],si=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],cn=[],Ka=[],js=Math.sign;function Hp(){for(let s=0;s<16;s++){const e=[];cn.push(e);for(let t=0;t<16;t++){const i=js(ei[s]*ei[t]+ii[s]*ti[t]),r=js(ti[s]*ei[t]+si[s]*ti[t]),n=js(ei[s]*ii[t]+ii[s]*si[t]),o=js(ti[s]*ii[t]+si[s]*si[t]);for(let a=0;a<16;a++)if(ei[a]===i&&ti[a]===r&&ii[a]===n&&si[a]===o){e.push(a);break}}}for(let s=0;s<16;s++){const e=new H;e.set(ei[s],ti[s],ii[s],si[s],0,0),Ka.push(e)}}Hp();const re={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:s=>ei[s],uY:s=>ti[s],vX:s=>ii[s],vY:s=>si[s],inv:s=>s&8?s&15:-s&7,add:(s,e)=>cn[s][e],sub:(s,e)=>cn[s][re.inv(e)],rotate180:s=>s^4,isVertical:s=>(s&3)===2,byDirection:(s,e)=>Math.abs(s)*2<=Math.abs(e)?e>=0?re.S:re.N:Math.abs(e)*2<=Math.abs(s)?s>0?re.E:re.W:e>0?s>0?re.SE:re.SW:s>0?re.NE:re.NW,matrixAppendRotationInv:(s,e,t=0,i=0,r=0,n=0)=>{const o=Ka[re.inv(e)],a=o.a,l=o.b,c=o.c,h=o.d,u=t-Math.min(0,a*r,c*n,a*r+c*n),f=i-Math.min(0,l*r,h*n,l*r+h*n),d=s.a,g=s.b,_=s.c,b=s.d;s.a=a*d+l*_,s.b=a*g+l*b,s.c=c*d+h*_,s.d=c*g+h*b,s.tx=u*d+f*_+s.tx,s.ty=u*g+f*b+s.ty},transformRectCoords:(s,e,t,i)=>{const{x:r,y:n,width:o,height:a}=s,{x:l,y:c,width:h,height:u}=e;return t===re.E?(i.set(r+l,n+c,o,a),i):t===re.S?i.set(h-n-a+l,r+c,a,o):t===re.W?i.set(h-r-o+l,u-n-a+c,o,a):t===re.N?i.set(n+l,u-r-o+c,a,o):i.set(r+l,n+c,o,a)}},Za=()=>{};class hn extends De{constructor(e){const t=e.resource||new Float32Array(e.width*e.height*4);let i=e.format;i||(t instanceof Float32Array?i="rgba32float":t instanceof Int32Array||t instanceof Uint32Array?i="rgba32uint":t instanceof Int16Array||t instanceof Uint16Array?i="rgba16uint":(t instanceof Int8Array,i="bgra8unorm")),super({...e,resource:t,format:i}),this.uploadMethodId="buffer"}static test(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array}}hn.extension=A.TextureSource;const Ja=new H;class Qa{constructor(e,t){this.mapCoord=new H,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof t>"u"?this.clampMargin=e.width<10?0:.5:this.clampMargin=t,this.isSimple=!1,this.texture=e}get texture(){return this._texture}set texture(e){var t;this.texture!==e&&((t=this._texture)==null||t.removeListener("update",this.update,this),this._texture=e,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(e,t){t===void 0&&(t=e);const i=this.mapCoord;for(let r=0;r<e.length;r+=2){const n=e[r],o=e[r+1];t[r]=n*i.a+o*i.c+i.tx,t[r+1]=n*i.b+o*i.d+i.ty}return t}update(){const e=this._texture;this._updateID++;const t=e.uvs;this.mapCoord.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0);const i=e.orig,r=e.trim;r&&(Ja.set(i.width/r.width,0,0,i.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(Ja));const n=e.source,o=this.uClampFrame,a=this.clampMargin/n._resolution,l=this.clampOffset/n._resolution;return o[0]=(e.frame.x+a+l)/n.width,o[1]=(e.frame.y+a+l)/n.height,o[2]=(e.frame.x+e.frame.width-a+l)/n.width,o[3]=(e.frame.y+e.frame.height-a+l)/n.height,this.uClampOffset[0]=this.clampOffset/n.pixelWidth,this.uClampOffset[1]=this.clampOffset/n.pixelHeight,this.isSimple=e.frame.width===n.width&&e.frame.height===n.height&&e.rotate===0,!0}}class j extends lt{constructor({source:e,label:t,frame:i,orig:r,trim:n,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:c}={}){if(super(),this.uid=be("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new Se,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=(e==null?void 0:e.source)??new De,this.noFrame=!i,i)this.frame.copyFrom(i);else{const{width:h,height:u}=this._source;this.frame.width=h,this.frame.height=u}this.orig=r||this.frame,this.trim=n,this.rotate=l??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=c||!1,this.updateUvs()}set source(e){this._source&&this._source.off("resize",this.update,this),this._source=e,e.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new Qa(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:e,frame:t}=this,{width:i,height:r}=this._source,n=t.x/i,o=t.y/r,a=t.width/i,l=t.height/r;let c=this.rotate;if(c){const h=a/2,u=l/2,f=n+h,d=o+u;c=re.add(c,re.NW),e.x0=f+h*re.uX(c),e.y0=d+u*re.uY(c),c=re.add(c,2),e.x1=f+h*re.uX(c),e.y1=d+u*re.uY(c),c=re.add(c,2),e.x2=f+h*re.uX(c),e.y2=d+u*re.uY(c),c=re.add(c,2),e.x3=f+h*re.uX(c),e.y3=d+u*re.uY(c)}else e.x0=n,e.y0=o,e.x1=n+a,e.y1=o,e.x2=n+a,e.y2=o+l,e.x3=n,e.y3=o+l}destroy(e=!1){this._source&&(this._source.off("resize",this.update,this),e&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return ee(Be,"Texture.baseTexture is now Texture.source"),this._source}}j.EMPTY=new j({label:"EMPTY",source:new De({label:"EMPTY"})}),j.EMPTY.destroy=Za,j.WHITE=new j({source:new hn({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"}),j.WHITE.destroy=Za;let Vp=0;class zp{constructor(e){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=e||{},this.enableFullScreen=!1,this.textureStyle=new zr(this.textureOptions)}createTexture(e,t,i,r){const n=new De({...this.textureOptions,width:e,height:t,resolution:1,antialias:i,autoGarbageCollect:!1,autoGenerateMipmaps:r});return new j({source:n,label:`texturePool_${Vp++}`})}getOptimalTexture(e,t,i=1,r,n=!1){let o=Math.ceil(e*i-1e-6),a=Math.ceil(t*i-1e-6);o=Gs(o),a=Gs(a);const l=r?1:0,c=n?1:0,h=(o<<17)+(a<<2)+(c<<1)+l;this._texturePool[h]||(this._texturePool[h]=[]);let u=this._texturePool[h].pop();return u||(u=this.createTexture(o,a,r,n)),u.source._resolution=i,u.source.width=o/i,u.source.height=a/i,u.source.pixelWidth=o,u.source.pixelHeight=a,u.frame.x=0,u.frame.y=0,u.frame.width=e,u.frame.height=t,u.updateUvs(),this._poolKeyHash[u.uid]=h,u}getSameSizeTexture(e,t=!1){const i=e.source;return this.getOptimalTexture(e.width,e.height,i._resolution,t)}returnTexture(e,t=!1){const i=this._poolKeyHash[e.uid];t&&(e.source.style=this.textureStyle),this._texturePool[i].push(e)}clear(e){if(e=e!==!1,e)for(const t in this._texturePool){const i=this._texturePool[t];if(i)for(let r=0;r<i.length;r++)i[r].destroy(!0)}this._texturePool={}}}const Qe=new zp;_i.register(Qe);class un{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new H,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new ln,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(e){this.root=e,e._onRender&&this.addOnRender(e),e.didChange=!0;const t=e.children;for(let i=0;i<t.length;i++){const r=t[i];r._updateFlags=15,this.addChild(r)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Qe.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const e=this._parentCacheAsTextureRenderGroup;e&&!e.textureNeedsUpdate&&e.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const e in this.childrenToUpdate){const t=this.childrenToUpdate[e];t.list.fill(null),t.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(e){e.renderGroupParent&&e.renderGroupParent._removeRenderGroupChild(e),e.renderGroupParent=this,this.renderGroupChildren.push(e)}_removeRenderGroupChild(e){const t=this.renderGroupChildren.indexOf(e);t>-1&&this.renderGroupChildren.splice(t,1),e.renderGroupParent=null}addChild(e){if(this.structureDidChange=!0,e.parentRenderGroup=this,e.updateTick=-1,e.parent===this.root?e.relativeRenderGroupDepth=1:e.relativeRenderGroupDepth=e.parent.relativeRenderGroupDepth+1,e.didChange=!0,this.onChildUpdate(e),e.renderGroup){this.addRenderGroupChild(e.renderGroup);return}e._onRender&&this.addOnRender(e);const t=e.children;for(let i=0;i<t.length;i++)this.addChild(t[i])}removeChild(e){if(this.structureDidChange=!0,e._onRender&&(e.renderGroup||this.removeOnRender(e)),e.parentRenderGroup=null,e.renderGroup){this._removeRenderGroupChild(e.renderGroup);return}const t=e.children;for(let i=0;i<t.length;i++)this.removeChild(t[i])}removeChildren(e){for(let t=0;t<e.length;t++)this.removeChild(e[t])}onChildUpdate(e){let t=this.childrenToUpdate[e.relativeRenderGroupDepth];t||(t=this.childrenToUpdate[e.relativeRenderGroupDepth]={index:0,list:[]}),t.list[t.index++]=e}updateRenderable(e){e.globalDisplayStatus<7||(this.instructionSet.renderPipes[e.renderPipeId].updateRenderable(e),e.didViewUpdate=!1)}onChildViewUpdate(e){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=e}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(e){this._onRenderContainers.push(e)}removeOnRender(e){this._onRenderContainers.splice(this._onRenderContainers.indexOf(e),1)}runOnRender(e){for(let t=0;t<this._onRenderContainers.length;t++)this._onRenderContainers[t]._onRender(e)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(e=[]){const t=this.root.children;for(let i=0;i<t.length;i++)this._getChildren(t[i],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;const i=e.children;for(let r=0;r<i.length;r++)this._getChildren(i[r],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new H),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new H),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y))}get inverseParentTextureTransform(){if((this._matrixDirty&4)===0)return this._inverseParentTextureTransform;this._matrixDirty&=-5;const e=this._parentCacheAsTextureRenderGroup;return e?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new H),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(e.inverseWorldTransform).translate(-e._textureBounds.x,-e._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function $p(s,e,t={}){for(const i in e)!t[i]&&e[i]!==void 0&&(s[i]=e[i])}const dn=new je(null),Xs=new je(null),fn=new je(null,1,1),Ys=new je(null),qs=1,pn=2,Ji=4;class Ve extends lt{constructor(e={}){var t,i;super(),this.uid=be("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new H,this.relativeGroupTransform=new H,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new je(this,0,0),this._scale=fn,this._pivot=Xs,this._origin=Ys,this._skew=dn,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],$p(this,e,{children:!0,parent:!0,effects:!0}),(t=e.children)==null||t.forEach(r=>this.addChild(r)),(i=e.parent)==null||i.addChild(this)}static mixin(e){ee("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),Q.mixin(Ve,e)}set _didChangeId(e){this._didViewChangeTick=e>>12&4095,this._didContainerChangeTick=e&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...e){if(this.allowChildren||ee(Be,"addChild: Only Containers will be allowed to add children in v8.0.0"),e.length>1){for(let r=0;r<e.length;r++)this.addChild(e[r]);return e[0]}const t=e[0],i=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),i&&(i.structureDidChange=!0),t):(t.parent&&t.parent.removeChild(t),this.children.push(t),this.sortableChildren&&(this.sortDirty=!0),t.parent=this,t.didChange=!0,t._updateFlags=15,i&&i.addChild(t),this.emit("childAdded",t,this,this.children.length-1),t.emit("added",this),this._didViewChangeTick++,t._zIndex!==0&&t.depthOfChildModified(),t)}removeChild(...e){if(e.length>1){for(let r=0;r<e.length;r++)this.removeChild(e[r]);return e[0]}const t=e[0],i=this.children.indexOf(t);return i>-1&&(this._didViewChangeTick++,this.children.splice(i,1),this.renderGroup?this.renderGroup.removeChild(t):this.parentRenderGroup&&this.parentRenderGroup.removeChild(t),t.parentRenderLayer&&t.parentRenderLayer.detach(t),t.parent=null,this.emit("childRemoved",t,this,i),t.emit("removed",this)),t}_onUpdate(e){e&&e===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(e){!!this.renderGroup!==e&&(e?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),this.renderGroup=Le.get(un,this),this.groupTransform=H.IDENTITY,e==null||e.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),Le.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e==null||e.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new H),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get position(){return this._position}set position(e){this._position.copyFrom(e)}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this._skew))}get angle(){return this.rotation*vp}set angle(e){this.rotation=e*Cp}get pivot(){return this._pivot===Xs&&(this._pivot=new je(this,0,0)),this._pivot}set pivot(e){this._pivot===Xs&&(this._pivot=new je(this,0,0),this._origin!==Ys&&se("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._pivot.set(e):this._pivot.copyFrom(e)}get skew(){return this._skew===dn&&(this._skew=new je(this,0,0)),this._skew}set skew(e){this._skew===dn&&(this._skew=new je(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===fn&&(this._scale=new je(this,1,1)),this._scale}set scale(e){this._scale===fn&&(this._scale=new je(this,0,0)),typeof e=="string"&&(e=parseFloat(e)),typeof e=="number"?this._scale.set(e):this._scale.copyFrom(e)}get origin(){return this._origin===Ys&&(this._origin=new je(this,0,0)),this._origin}set origin(e){this._origin===Ys&&(this._origin=new je(this,0,0),this._pivot!==Xs&&se("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._origin.set(e):this._origin.copyFrom(e)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(e){const t=this.getLocalBounds().width;this._setWidth(e,t)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(e){const t=this.getLocalBounds().height;this._setHeight(e,t)}getSize(e){e||(e={});const t=this.getLocalBounds();return e.width=Math.abs(this.scale.x*t.width),e.height=Math.abs(this.scale.y*t.height),e}setSize(e,t){const i=this.getLocalBounds();typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,i.width),t!==void 0&&this._setHeight(t,i.height)}_updateSkew(){const e=this._rotation,t=this._skew;this._cx=Math.cos(e+t._y),this._sx=Math.sin(e+t._y),this._cy=-Math.sin(e-t._x),this._sy=Math.cos(e-t._x)}updateTransform(e){return this.position.set(typeof e.x=="number"?e.x:this.position.x,typeof e.y=="number"?e.y:this.position.y),this.scale.set(typeof e.scaleX=="number"?e.scaleX||1:this.scale.x,typeof e.scaleY=="number"?e.scaleY||1:this.scale.y),this.rotation=typeof e.rotation=="number"?e.rotation:this.rotation,this.skew.set(typeof e.skewX=="number"?e.skewX:this.skew.x,typeof e.skewY=="number"?e.skewY:this.skew.y),this.pivot.set(typeof e.pivotX=="number"?e.pivotX:this.pivot.x,typeof e.pivotY=="number"?e.pivotY:this.pivot.y),this.origin.set(typeof e.originX=="number"?e.originX:this.origin.x,typeof e.originY=="number"?e.originY:this.origin.y),this}setFromMatrix(e){e.decompose(this)}updateLocalTransform(){const e=this._didContainerChangeTick;if(this._didLocalTransformChangeId===e)return;this._didLocalTransformChangeId=e;const t=this.localTransform,i=this._scale,r=this._pivot,n=this._origin,o=this._position,a=i._x,l=i._y,c=r._x,h=r._y,u=-n._x,f=-n._y;t.a=this._cx*a,t.b=this._sx*a,t.c=this._cy*l,t.d=this._sy*l,t.tx=o._x-(c*t.a+h*t.c)+(u*t.a+f*t.c)-u,t.ty=o._y-(c*t.b+h*t.d)+(u*t.b+f*t.d)-f}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=qs,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const i=Pe.shared.setValue(e??16777215).toBgrNumber();i!==this.localColor&&(this.localColor=i,this._updateFlags|=qs,this._onUpdate())}get tint(){return bi(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=pn,this.localBlendMode=e,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(e){const t=e?2:0;(this.localDisplayStatus&2)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=Ji,this.localDisplayStatus^=2,this._onUpdate(),this.emit("visibleChanged",e))}get culled(){return!(this.localDisplayStatus&4)}set culled(e){const t=e?0:4;(this.localDisplayStatus&4)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=Ji,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(e){const t=e?1:0;(this.localDisplayStatus&1)!==t&&(this._updateFlags|=Ji,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){var r;if(this.destroyed)return;this.destroyed=!0;let t;if(this.children.length&&(t=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof e=="boolean"?e:e==null?void 0:e.children)&&t)for(let n=0;n<t.length;++n)t[n].destroy(e);(r=this.renderGroup)==null||r.destroy(),this.renderGroup=null}}Q.mixin(Ve,Ip,Bp,Wp,Fp,Up,Pp,kp,Gp,bp,wp,Dp,Rp);function el(s,e,t=2){const i=e&&e.length,r=i?e[0]*t:s.length;let n=tl(s,0,r,t,!0);const o=[];if(!n||n.next===n.prev)return o;let a,l,c;if(i&&(n=Kp(s,e,n,t)),s.length>80*t){a=s[0],l=s[1];let h=a,u=l;for(let f=t;f<r;f+=t){const d=s[f],g=s[f+1];d<a&&(a=d),g<l&&(l=g),d>h&&(h=d),g>u&&(u=g)}c=Math.max(h-a,u-l),c=c!==0?32767/c:0}return Qi(n,o,t,a,l,c,0),o}function tl(s,e,t,i,r){let n;if(r===am(s,e,t,i)>0)for(let o=e;o<t;o+=i)n=nl(o/i|0,s[o],s[o+1],n);else for(let o=t-i;o>=e;o-=i)n=nl(o/i|0,s[o],s[o+1],n);return n&&xi(n,n.next)&&(is(n),n=n.next),n}function ri(s,e){if(!s)return s;e||(e=s);let t=s,i;do if(i=!1,!t.steiner&&(xi(t,t.next)||Ae(t.prev,t,t.next)===0)){if(is(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function Qi(s,e,t,i,r,n,o){if(!s)return;!o&&n&&tm(s,i,r,n);let a=s;for(;s.prev!==s.next;){const l=s.prev,c=s.next;if(n?Xp(s,i,r,n):jp(s)){e.push(l.i,s.i,c.i),is(s),s=c.next,a=c.next;continue}if(s=c,s===a){o?o===1?(s=Yp(ri(s),e),Qi(s,e,t,i,r,n,2)):o===2&&qp(s,e,t,i,r,n):Qi(ri(s),e,t,i,r,n,1);break}}}function jp(s){const e=s.prev,t=s,i=s.next;if(Ae(e,t,i)>=0)return!1;const r=e.x,n=t.x,o=i.x,a=e.y,l=t.y,c=i.y,h=Math.min(r,n,o),u=Math.min(a,l,c),f=Math.max(r,n,o),d=Math.max(a,l,c);let g=i.next;for(;g!==e;){if(g.x>=h&&g.x<=f&&g.y>=u&&g.y<=d&&es(r,a,n,l,o,c,g.x,g.y)&&Ae(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function Xp(s,e,t,i){const r=s.prev,n=s,o=s.next;if(Ae(r,n,o)>=0)return!1;const a=r.x,l=n.x,c=o.x,h=r.y,u=n.y,f=o.y,d=Math.min(a,l,c),g=Math.min(h,u,f),_=Math.max(a,l,c),b=Math.max(h,u,f),x=mn(d,g,e,t,i),C=mn(_,b,e,t,i);let S=s.prevZ,E=s.nextZ;for(;S&&S.z>=x&&E&&E.z<=C;){if(S.x>=d&&S.x<=_&&S.y>=g&&S.y<=b&&S!==r&&S!==o&&es(a,h,l,u,c,f,S.x,S.y)&&Ae(S.prev,S,S.next)>=0||(S=S.prevZ,E.x>=d&&E.x<=_&&E.y>=g&&E.y<=b&&E!==r&&E!==o&&es(a,h,l,u,c,f,E.x,E.y)&&Ae(E.prev,E,E.next)>=0))return!1;E=E.nextZ}for(;S&&S.z>=x;){if(S.x>=d&&S.x<=_&&S.y>=g&&S.y<=b&&S!==r&&S!==o&&es(a,h,l,u,c,f,S.x,S.y)&&Ae(S.prev,S,S.next)>=0)return!1;S=S.prevZ}for(;E&&E.z<=C;){if(E.x>=d&&E.x<=_&&E.y>=g&&E.y<=b&&E!==r&&E!==o&&es(a,h,l,u,c,f,E.x,E.y)&&Ae(E.prev,E,E.next)>=0)return!1;E=E.nextZ}return!0}function Yp(s,e){let t=s;do{const i=t.prev,r=t.next.next;!xi(i,r)&&sl(i,t,t.next,r)&&ts(i,r)&&ts(r,i)&&(e.push(i.i,t.i,r.i),is(t),is(t.next),t=s=r),t=t.next}while(t!==s);return ri(t)}function qp(s,e,t,i,r,n){let o=s;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&rm(o,a)){let l=rl(o,a);o=ri(o,o.next),l=ri(l,l.next),Qi(o,e,t,i,r,n,0),Qi(l,e,t,i,r,n,0);return}a=a.next}o=o.next}while(o!==s)}function Kp(s,e,t,i){const r=[];for(let n=0,o=e.length;n<o;n++){const a=e[n]*i,l=n<o-1?e[n+1]*i:s.length,c=tl(s,a,l,i,!1);c===c.next&&(c.steiner=!0),r.push(sm(c))}r.sort(Zp);for(let n=0;n<r.length;n++)t=Jp(r[n],t);return t}function Zp(s,e){let t=s.x-e.x;if(t===0&&(t=s.y-e.y,t===0)){const i=(s.next.y-s.y)/(s.next.x-s.x),r=(e.next.y-e.y)/(e.next.x-e.x);t=i-r}return t}function Jp(s,e){const t=Qp(s,e);if(!t)return e;const i=rl(t,s);return ri(i,i.next),ri(t,t.next)}function Qp(s,e){let t=e;const i=s.x,r=s.y;let n=-1/0,o;if(xi(s,t))return t;do{if(xi(s,t.next))return t.next;if(r<=t.y&&r>=t.next.y&&t.next.y!==t.y){const u=t.x+(r-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=i&&u>n&&(n=u,o=t.x<t.next.x?t:t.next,u===i))return o}t=t.next}while(t!==e);if(!o)return null;const a=o,l=o.x,c=o.y;let h=1/0;t=o;do{if(i>=t.x&&t.x>=l&&i!==t.x&&il(r<c?i:n,r,l,c,r<c?n:i,r,t.x,t.y)){const u=Math.abs(r-t.y)/(i-t.x);ts(t,s)&&(u<h||u===h&&(t.x>o.x||t.x===o.x&&em(o,t)))&&(o=t,h=u)}t=t.next}while(t!==a);return o}function em(s,e){return Ae(s.prev,s,e.prev)<0&&Ae(e.next,s,s.next)<0}function tm(s,e,t,i){let r=s;do r.z===0&&(r.z=mn(r.x,r.y,e,t,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==s);r.prevZ.nextZ=null,r.prevZ=null,im(r)}function im(s){let e,t=1;do{let i=s,r;s=null;let n=null;for(e=0;i;){e++;let o=i,a=0;for(let c=0;c<t&&(a++,o=o.nextZ,!!o);c++);let l=t;for(;a>0||l>0&&o;)a!==0&&(l===0||!o||i.z<=o.z)?(r=i,i=i.nextZ,a--):(r=o,o=o.nextZ,l--),n?n.nextZ=r:s=r,r.prevZ=n,n=r;i=o}n.nextZ=null,t*=2}while(e>1);return s}function mn(s,e,t,i,r){return s=(s-t)*r|0,e=(e-i)*r|0,s=(s|s<<8)&16711935,s=(s|s<<4)&252645135,s=(s|s<<2)&858993459,s=(s|s<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,s|e<<1}function sm(s){let e=s,t=s;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==s);return t}function il(s,e,t,i,r,n,o,a){return(r-o)*(e-a)>=(s-o)*(n-a)&&(s-o)*(i-a)>=(t-o)*(e-a)&&(t-o)*(n-a)>=(r-o)*(i-a)}function es(s,e,t,i,r,n,o,a){return!(s===o&&e===a)&&il(s,e,t,i,r,n,o,a)}function rm(s,e){return s.next.i!==e.i&&s.prev.i!==e.i&&!nm(s,e)&&(ts(s,e)&&ts(e,s)&&om(s,e)&&(Ae(s.prev,s,e.prev)||Ae(s,e.prev,e))||xi(s,e)&&Ae(s.prev,s,s.next)>0&&Ae(e.prev,e,e.next)>0)}function Ae(s,e,t){return(e.y-s.y)*(t.x-e.x)-(e.x-s.x)*(t.y-e.y)}function xi(s,e){return s.x===e.x&&s.y===e.y}function sl(s,e,t,i){const r=Zs(Ae(s,e,t)),n=Zs(Ae(s,e,i)),o=Zs(Ae(t,i,s)),a=Zs(Ae(t,i,e));return!!(r!==n&&o!==a||r===0&&Ks(s,t,e)||n===0&&Ks(s,i,e)||o===0&&Ks(t,s,i)||a===0&&Ks(t,e,i))}function Ks(s,e,t){return e.x<=Math.max(s.x,t.x)&&e.x>=Math.min(s.x,t.x)&&e.y<=Math.max(s.y,t.y)&&e.y>=Math.min(s.y,t.y)}function Zs(s){return s>0?1:s<0?-1:0}function nm(s,e){let t=s;do{if(t.i!==s.i&&t.next.i!==s.i&&t.i!==e.i&&t.next.i!==e.i&&sl(t,t.next,s,e))return!0;t=t.next}while(t!==s);return!1}function ts(s,e){return Ae(s.prev,s,s.next)<0?Ae(s,e,s.next)>=0&&Ae(s,s.prev,e)>=0:Ae(s,e,s.prev)<0||Ae(s,s.next,e)<0}function om(s,e){let t=s,i=!1;const r=(s.x+e.x)/2,n=(s.y+e.y)/2;do t.y>n!=t.next.y>n&&t.next.y!==t.y&&r<(t.next.x-t.x)*(n-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==s);return i}function rl(s,e){const t=gn(s.i,s.x,s.y),i=gn(e.i,e.x,e.y),r=s.next,n=e.prev;return s.next=e,e.prev=s,t.next=r,r.prev=t,i.next=t,t.prev=i,n.next=i,i.prev=n,i}function nl(s,e,t,i){const r=gn(s,e,t);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function is(s){s.next.prev=s.prev,s.prev.next=s.next,s.prevZ&&(s.prevZ.nextZ=s.nextZ),s.nextZ&&(s.nextZ.prevZ=s.prevZ)}function gn(s,e,t){return{i:s,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function am(s,e,t,i){let r=0;for(let n=e,o=t-i;n<t;n+=i)r+=(s[o]-s[n])*(s[n+1]+s[o+1]),o=n;return r}const lm=el.default||el;var it=(s=>(s[s.NONE=0]="NONE",s[s.COLOR=16384]="COLOR",s[s.STENCIL=1024]="STENCIL",s[s.DEPTH=256]="DEPTH",s[s.COLOR_DEPTH=16640]="COLOR_DEPTH",s[s.COLOR_STENCIL=17408]="COLOR_STENCIL",s[s.DEPTH_STENCIL=1280]="DEPTH_STENCIL",s[s.ALL=17664]="ALL",s))(it||{});class ol{constructor(e){this.items=[],this._name=e}emit(e,t,i,r,n,o,a,l){const{name:c,items:h}=this;for(let u=0,f=h.length;u<f;u++)h[u][c](e,t,i,r,n,o,a,l);return this}add(e){return e[this._name]&&(this.remove(e),this.items.push(e)),this}remove(e){const t=this.items.indexOf(e);return t!==-1&&this.items.splice(t,1),this}contains(e){return this.items.indexOf(e)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const cm=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],al=class pf extends lt{constructor(e){super(),this.tick=0,this.uid=be("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=e.type,this.name=e.name,this.config=e;const t=[...cm,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await yp(t),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const i in this._systemsHash)e={...this._systemsHash[i].constructor.defaultOptions,...e};e={...pf.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let i=0;i<this.runners.init.items.length;i++)await this.runners.init.items[i].init(e);this._initOptions=e}render(e,t){this.tick++;let i=e;if(i instanceof Ve&&(i={container:i},t&&(ee(Be,"passing a second argument is deprecated, please use render options instead"),i.target=t.renderTexture)),i.target||(i.target=this.view.renderTarget),i.target===this.view.renderTarget&&(this._lastObjectRendered=i.container,i.clearColor??(i.clearColor=this.background.colorRgba),i.clear??(i.clear=this.background.clearBeforeRender)),i.clearColor){const r=Array.isArray(i.clearColor)&&i.clearColor.length===4;i.clearColor=r?i.clearColor:Pe.shared.setValue(i.clearColor).toArray()}i.transform||(i.container.updateLocalTransform(),i.transform=i.container.localTransform),i.container.visible&&(i.container.enableRenderGroup(),this.runners.prerender.emit(i),this.runners.renderStart.emit(i),this.runners.render.emit(i),this.runners.renderEnd.emit(i),this.runners.postrender.emit(i))}resize(e,t,i){const r=this.view.resolution;this.view.resize(e,t,i),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),i!==void 0&&i!==r&&this.runners.resolutionChange.emit(i)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=it.ALL);const{clear:i,clearColor:r,target:n,mipLevel:o,layer:a}=e;Pe.shared.setValue(r??this.background.colorRgba),t.renderTarget.clear(n,i,Pe.shared.toArray(),o??0,a??0)}get resolution(){return this.view.resolution}set resolution(e){this.view.resolution=e,this.runners.resolutionChange.emit(e)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...e){e.forEach(t=>{this.runners[t]=new ol(t)})}_addSystems(e){let t;for(t in e){const i=e[t];this._addSystem(i.value,i.name)}}_addSystem(e,t){const i=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=i,this._systemsHash[t]=i;for(const r in this.runners)this.runners[r].add(i);return this}_addPipes(e,t){const i=t.reduce((r,n)=>(r[n.name]=n.value,r),{});e.forEach(r=>{const n=r.value,o=r.name,a=i[o];this.renderPipes[o]=new n(this,a?new a:null),this.runners.destroy.add(this.renderPipes[o])})}destroy(e=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(e),(e===!0||typeof e=="object"&&e.releaseGlobalResources)&&_i.release(),Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash=null,this.renderPipes=null,this.removeAllListeners()}generateTexture(e){return this.textureGenerator.generateTexture(e)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!fa())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};al.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let vi=al;function ll(s,e){if(!(s instanceof gt)){let t=e?ge.INDEX:ge.VERTEX;s instanceof Array&&(e?(s=new Uint32Array(s),t=ge.INDEX|ge.COPY_DST):(s=new Float32Array(s),t=ge.VERTEX|ge.COPY_DST)),s=new gt({data:s,label:e?"index-mesh-buffer":"vertex-mesh-buffer",usage:t})}return s}function hm(s,e,t){const i=s.getAttribute(e);if(!i)return t.minX=0,t.minY=0,t.maxX=0,t.maxY=0,t;const r=i.buffer.data;let n=1/0,o=1/0,a=-1/0,l=-1/0;const c=r.BYTES_PER_ELEMENT,h=(i.offset||0)/c,u=(i.stride||8)/c;for(let f=h;f<r.length;f+=u){const d=r[f],g=r[f+1];d>a&&(a=d),g>l&&(l=g),d<n&&(n=d),g<o&&(o=g)}return t.minX=n,t.minY=o,t.maxX=a,t.maxY=l,t}function um(s){return(s instanceof gt||Array.isArray(s)||s.BYTES_PER_ELEMENT)&&(s={buffer:s}),s.buffer=ll(s.buffer,!1),s}class Js extends lt{constructor(e={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=be("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new Ye,this._boundsDirty=!0;const{attributes:t,indexBuffer:i,topology:r}=e;if(this.buffers=[],this.attributes={},t)for(const n in t)this.addAttribute(n,t[n]);this.instanceCount=e.instanceCount??1,i&&this.addIndex(i),this.topology=r||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(e){return this.attributes[e]}getIndex(){return this.indexBuffer}getBuffer(e){return this.getAttribute(e).buffer}getSize(){for(const e in this.attributes){const t=this.attributes[e];return t.buffer.data.length/(t.stride/4||t.size)}return 0}addAttribute(e,t){const i=um(t);this.buffers.indexOf(i.buffer)===-1&&(this.buffers.push(i.buffer),i.buffer.on("update",this.onBufferUpdate,this),i.buffer.on("change",this.onBufferUpdate,this)),this.attributes[e]=i}addIndex(e){this.indexBuffer=ll(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,hm(this,"aPosition",this._bounds)):this._bounds}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){var t;this.emit("destroy",this),this.removeAllListeners(),e&&this.buffers.forEach(i=>i.destroy()),this.unload(),(t=this.indexBuffer)==null||t.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}class Ci{constructor(e){typeof e=="number"?this.rawBinaryData=new ArrayBuffer(e):e instanceof Uint8Array?this.rawBinaryData=e.buffer:this.rawBinaryData=e,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(e){return this[`${e}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(e){switch(e){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${e} isn't a valid view type`)}}}function cl(s,e=null){const t=s*6;if(t>65535?e||(e=new Uint32Array(t)):e||(e=new Uint16Array(t)),e.length!==t)throw new Error(`Out buffer length is incorrect, got ${e.length} and expected ${t}`);for(let i=0,r=0;i<t;i+=6,r+=4)e[i+0]=r+0,e[i+1]=r+1,e[i+2]=r+2,e[i+3]=r+0,e[i+4]=r+2,e[i+5]=r+3;return e}function dm(s){return{dynamicUpdate:hl(s,!0),staticUpdate:hl(s,!1)}}function hl(s,e){const t=[];t.push(`
284
+ `}function cp(s){return ga(s,"uboWgsl",lp,Hf)}class qr extends Lr{constructor(){super({createUboElements:ap,generateUboSync:cp})}}qr.extension={type:[A.WebGPUSystem],name:"ubo"};var hp={grad:.9,turn:360,rad:360/(2*Math.PI)},wt=function(s){return typeof s=="string"?s.length>0:typeof s=="number"},Ge=function(s,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*s)/t+0},ot=function(s,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),s>t?t:s>e?s:e},Ba=function(s){return(s=isFinite(s)?s%360:0)>0?s:s+360},Da=function(s){return{r:ot(s.r,0,255),g:ot(s.g,0,255),b:ot(s.b,0,255),a:ot(s.a)}},Kr=function(s){return{r:Ge(s.r),g:Ge(s.g),b:Ge(s.b),a:Ge(s.a,3)}},up=/^#([0-9a-f]{3,8})$/i,Vs=function(s){var e=s.toString(16);return e.length<2?"0"+e:e},Na=function(s){var e=s.r,t=s.g,i=s.b,r=s.a,n=Math.max(e,t,i),o=n-Math.min(e,t,i),a=o?n===e?(t-i)/o:n===t?2+(i-e)/o:4+(e-t)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},Ua=function(s){var e=s.h,t=s.s,i=s.v,r=s.a;e=e/360*6,t/=100,i/=100;var n=Math.floor(e),o=i*(1-t),a=i*(1-(e-n)*t),l=i*(1-(1-e+n)*t),c=n%6;return{r:255*[i,a,o,o,l,i][c],g:255*[l,i,i,a,o,o][c],b:255*[o,o,l,i,i,a][c],a:r}},Fa=function(s){return{h:Ba(s.h),s:ot(s.s,0,100),l:ot(s.l,0,100),a:ot(s.a)}},Ga=function(s){return{h:Ge(s.h),s:Ge(s.s),l:Ge(s.l),a:Ge(s.a,3)}},La=function(s){return Ua((t=(e=s).s,{h:e.h,s:(t*=((i=e.l)<50?i:100-i)/100)>0?2*t/(i+t)*100:0,v:i+t,a:e.a}));var e,t,i},Zi=function(s){return{h:(e=Na(s)).h,s:(r=(200-(t=e.s))*(i=e.v)/100)>0&&r<200?t*i/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,t,i,r},dp=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,fp=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,pp=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,mp=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Zr={string:[[function(s){var e=up.exec(s);return e?(s=e[1]).length<=4?{r:parseInt(s[0]+s[0],16),g:parseInt(s[1]+s[1],16),b:parseInt(s[2]+s[2],16),a:s.length===4?Ge(parseInt(s[3]+s[3],16)/255,2):1}:s.length===6||s.length===8?{r:parseInt(s.substr(0,2),16),g:parseInt(s.substr(2,2),16),b:parseInt(s.substr(4,2),16),a:s.length===8?Ge(parseInt(s.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(s){var e=pp.exec(s)||mp.exec(s);return e?e[2]!==e[4]||e[4]!==e[6]?null:Da({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:e[7]===void 0?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(s){var e=dp.exec(s)||fp.exec(s);if(!e)return null;var t,i,r=Fa({h:(t=e[1],i=e[2],i===void 0&&(i="deg"),Number(t)*(hp[i]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return La(r)},"hsl"]],object:[[function(s){var e=s.r,t=s.g,i=s.b,r=s.a,n=r===void 0?1:r;return wt(e)&&wt(t)&&wt(i)?Da({r:Number(e),g:Number(t),b:Number(i),a:Number(n)}):null},"rgb"],[function(s){var e=s.h,t=s.s,i=s.l,r=s.a,n=r===void 0?1:r;if(!wt(e)||!wt(t)||!wt(i))return null;var o=Fa({h:Number(e),s:Number(t),l:Number(i),a:Number(n)});return La(o)},"hsl"],[function(s){var e=s.h,t=s.s,i=s.v,r=s.a,n=r===void 0?1:r;if(!wt(e)||!wt(t)||!wt(i))return null;var o=(function(a){return{h:Ba(a.h),s:ot(a.s,0,100),v:ot(a.v,0,100),a:ot(a.a)}})({h:Number(e),s:Number(t),v:Number(i),a:Number(n)});return Ua(o)},"hsv"]]},Wa=function(s,e){for(var t=0;t<e.length;t++){var i=e[t][0](s);if(i)return[i,e[t][1]]}return[null,void 0]},gp=function(s){return typeof s=="string"?Wa(s.trim(),Zr.string):typeof s=="object"&&s!==null?Wa(s,Zr.object):[null,void 0]},Jr=function(s,e){var t=Zi(s);return{h:t.h,s:ot(t.s+100*e,0,100),l:t.l,a:t.a}},Qr=function(s){return(299*s.r+587*s.g+114*s.b)/1e3/255},Ha=function(s,e){var t=Zi(s);return{h:t.h,s:t.s,l:ot(t.l+100*e,0,100),a:t.a}},en=(function(){function s(e){this.parsed=gp(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return s.prototype.isValid=function(){return this.parsed!==null},s.prototype.brightness=function(){return Ge(Qr(this.rgba),2)},s.prototype.isDark=function(){return Qr(this.rgba)<.5},s.prototype.isLight=function(){return Qr(this.rgba)>=.5},s.prototype.toHex=function(){return e=Kr(this.rgba),t=e.r,i=e.g,r=e.b,o=(n=e.a)<1?Vs(Ge(255*n)):"","#"+Vs(t)+Vs(i)+Vs(r)+o;var e,t,i,r,n,o},s.prototype.toRgb=function(){return Kr(this.rgba)},s.prototype.toRgbString=function(){return e=Kr(this.rgba),t=e.r,i=e.g,r=e.b,(n=e.a)<1?"rgba("+t+", "+i+", "+r+", "+n+")":"rgb("+t+", "+i+", "+r+")";var e,t,i,r,n},s.prototype.toHsl=function(){return Ga(Zi(this.rgba))},s.prototype.toHslString=function(){return e=Ga(Zi(this.rgba)),t=e.h,i=e.s,r=e.l,(n=e.a)<1?"hsla("+t+", "+i+"%, "+r+"%, "+n+")":"hsl("+t+", "+i+"%, "+r+"%)";var e,t,i,r,n},s.prototype.toHsv=function(){return e=Na(this.rgba),{h:Ge(e.h),s:Ge(e.s),v:Ge(e.v),a:Ge(e.a,3)};var e},s.prototype.invert=function(){return _t({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},s.prototype.saturate=function(e){return e===void 0&&(e=.1),_t(Jr(this.rgba,e))},s.prototype.desaturate=function(e){return e===void 0&&(e=.1),_t(Jr(this.rgba,-e))},s.prototype.grayscale=function(){return _t(Jr(this.rgba,-1))},s.prototype.lighten=function(e){return e===void 0&&(e=.1),_t(Ha(this.rgba,e))},s.prototype.darken=function(e){return e===void 0&&(e=.1),_t(Ha(this.rgba,-e))},s.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},s.prototype.alpha=function(e){return typeof e=="number"?_t({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):Ge(this.rgba.a,3);var t},s.prototype.hue=function(e){var t=Zi(this.rgba);return typeof e=="number"?_t({h:e,s:t.s,l:t.l,a:t.a}):Ge(t.h)},s.prototype.isEqual=function(e){return this.toHex()===_t(e).toHex()},s})(),_t=function(s){return s instanceof en?s:new en(s)},Va=[],_p=function(s){s.forEach(function(e){Va.indexOf(e)<0&&(e(en,Zr),Va.push(e))})};function yp(s,e){var t={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},i={};for(var r in t)i[t[r]]=r;var n={};s.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,l,c=i[this.toHex()];if(c)return c;if(o!=null&&o.closest){var h=this.toRgb(),u=1/0,f="black";if(!n.length)for(var d in t)n[d]=new s(t[d]).toRgb();for(var g in t){var _=(a=h,l=n[g],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));_<u&&(u=_,f=g)}return f}},e.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":t[a];return l?new s(l).toRgb():null},"name"])}_p([yp]);const gi=class Ds{constructor(e=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=e}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(e){return this.value=e,this}set value(e){if(e instanceof Ds)this._value=this._cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(e===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,e))&&(this._value=this._cloneSource(e),this._normalize(this._value))}}get value(){return this._value}_cloneSource(e){return typeof e=="string"||typeof e=="number"||e instanceof Number||e===null?e:Array.isArray(e)||ArrayBuffer.isView(e)?e.slice(0):typeof e=="object"&&e!==null?{...e}:e}_isSourceEqual(e,t){const i=typeof e;if(i!==typeof t)return!1;if(i==="number"||i==="string"||e instanceof Number)return e===t;if(Array.isArray(e)&&Array.isArray(t)||ArrayBuffer.isView(e)&&ArrayBuffer.isView(t))return e.length!==t.length?!1:e.every((n,o)=>n===t[o]);if(e!==null&&t!==null){const n=Object.keys(e),o=Object.keys(t);return n.length!==o.length?!1:n.every(a=>e[a]===t[a])}return e===t}toRgba(){const[e,t,i,r]=this._components;return{r:e,g:t,b:i,a:r}}toRgb(){const[e,t,i]=this._components;return{r:e,g:t,b:i}}toRgbaString(){const[e,t,i]=this.toUint8RgbArray();return`rgba(${e},${t},${i},${this.alpha})`}toUint8RgbArray(e){const[t,i,r]=this._components;return this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb),e[0]=Math.round(t*255),e[1]=Math.round(i*255),e[2]=Math.round(r*255),e}toArray(e){this._arrayRgba||(this._arrayRgba=[]),e||(e=this._arrayRgba);const[t,i,r,n]=this._components;return e[0]=t,e[1]=i,e[2]=r,e[3]=n,e}toRgbArray(e){this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb);const[t,i,r]=this._components;return e[0]=t,e[1]=i,e[2]=r,e}toNumber(){return this._int}toBgrNumber(){const[e,t,i]=this.toUint8RgbArray();return(i<<16)+(t<<8)+e}toLittleEndianNumber(){const e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(e){const[t,i,r,n]=Ds._temp.setValue(e)._components;return this._components[0]*=t,this._components[1]*=i,this._components[2]*=r,this._components[3]*=n,this._refreshInt(),this._value=null,this}premultiply(e,t=!0){return t&&(this._components[0]*=e,this._components[1]*=e,this._components[2]*=e),this._components[3]=e,this._refreshInt(),this._value=null,this}toPremultiplied(e,t=!0){if(e===1)return(255<<24)+this._int;if(e===0)return t?0:this._int;let i=this._int>>16&255,r=this._int>>8&255,n=this._int&255;return t&&(i=i*e+.5|0,r=r*e+.5|0,n=n*e+.5|0),(e*255<<24)+(i<<16)+(r<<8)+n}toHex(){const e=this._int.toString(16);return`#${"000000".substring(0,6-e.length)+e}`}toHexa(){const t=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(e){return this._components[3]=this._clamp(e),this._value=null,this}_normalize(e){let t,i,r,n;if((typeof e=="number"||e instanceof Number)&&e>=0&&e<=16777215){const o=e;t=(o>>16&255)/255,i=(o>>8&255)/255,r=(o&255)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[t,i,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[t,i,r,n=255]=e,t/=255,i/=255,r/=255,n/=255;else if(typeof e=="string"||typeof e=="object"){if(typeof e=="string"){const a=Ds.HEX_PATTERN.exec(e);a&&(e=`#${a[2]}`)}const o=_t(e);o.isValid()&&({r:t,g:i,b:r,a:n}=o.rgba,t/=255,i/=255,r/=255)}if(t!==void 0)this._components[0]=t,this._components[1]=i,this._components[2]=r,this._components[3]=n,this._refreshInt();else throw new Error(`Unable to convert color ${e}`)}_refreshInt(){this._clamp(this._components);const[e,t,i]=this._components;this._int=(e*255<<16)+(t*255<<8)+(i*255|0)}_clamp(e,t=0,i=1){return typeof e=="number"?Math.min(Math.max(e,t),i):(e.forEach((r,n)=>{e[n]=Math.min(Math.max(r,t),i)}),e)}static isColorLike(e){return typeof e=="number"||typeof e=="string"||e instanceof Number||e instanceof Ds||Array.isArray(e)||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Float32Array||e.r!==void 0&&e.g!==void 0&&e.b!==void 0||e.r!==void 0&&e.g!==void 0&&e.b!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0&&e.a!==void 0}};gi.shared=new gi,gi._temp=new gi,gi.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let Pe=gi;const tn=[];Q.handleByNamedList(A.Environment,tn);async function bp(s){if(!s)for(let e=0;e<tn.length;e++){const t=tn[e];if(t.value.test()){await t.value.load();return}}}const xp={cullArea:null,cullable:!1,cullableChildren:!0},vp=Math.PI*2,Cp=180/Math.PI,Sp=Math.PI/180;class xe{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new xe(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return sn.x=0,sn.y=0,sn}}const sn=new xe;class H{constructor(e=1,t=0,i=0,r=1,n=0,o=0){this.array=null,this.a=e,this.b=t,this.c=i,this.d=r,this.tx=n,this.ty=o}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,i,r,n,o){return this.a=e,this.b=t,this.c=i,this.d=r,this.tx=n,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const i=t||this.array;return e?(i[0]=this.a,i[1]=this.b,i[2]=0,i[3]=this.c,i[4]=this.d,i[5]=0,i[6]=this.tx,i[7]=this.ty,i[8]=1):(i[0]=this.a,i[1]=this.c,i[2]=this.tx,i[3]=this.b,i[4]=this.d,i[5]=this.ty,i[6]=0,i[7]=0,i[8]=1),i}apply(e,t){t=t||new xe;const i=e.x,r=e.y;return t.x=this.a*i+this.c*r+this.tx,t.y=this.b*i+this.d*r+this.ty,t}applyInverse(e,t){t=t||new xe;const i=this.a,r=this.b,n=this.c,o=this.d,a=this.tx,l=this.ty,c=1/(i*o+n*-r),h=e.x,u=e.y;return t.x=o*c*h+-n*c*u+(l*n-a*o)*c,t.y=i*c*u+-r*c*h+(-l*i+a*r)*c,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){const t=Math.cos(e),i=Math.sin(e),r=this.a,n=this.c,o=this.tx;return this.a=r*t-this.b*i,this.b=r*i+this.b*t,this.c=n*t-this.d*i,this.d=n*i+this.d*t,this.tx=o*t-this.ty*i,this.ty=o*i+this.ty*t,this}append(e){const t=this.a,i=this.b,r=this.c,n=this.d;return this.a=e.a*t+e.b*r,this.b=e.a*i+e.b*n,this.c=e.c*t+e.d*r,this.d=e.c*i+e.d*n,this.tx=e.tx*t+e.ty*r+this.tx,this.ty=e.tx*i+e.ty*n+this.ty,this}appendFrom(e,t){const i=e.a,r=e.b,n=e.c,o=e.d,a=e.tx,l=e.ty,c=t.a,h=t.b,u=t.c,f=t.d;return this.a=i*c+r*u,this.b=i*h+r*f,this.c=n*c+o*u,this.d=n*h+o*f,this.tx=a*c+l*u+t.tx,this.ty=a*h+l*f+t.ty,this}setTransform(e,t,i,r,n,o,a,l,c){return this.a=Math.cos(a+c)*n,this.b=Math.sin(a+c)*n,this.c=-Math.sin(a-l)*o,this.d=Math.cos(a-l)*o,this.tx=e-(i*this.a+r*this.c),this.ty=t-(i*this.b+r*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const i=this.a,r=this.c;this.a=i*e.a+this.b*e.c,this.b=i*e.b+this.b*e.d,this.c=r*e.a+this.d*e.c,this.d=r*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){const t=this.a,i=this.b,r=this.c,n=this.d,o=e.pivot,a=-Math.atan2(-r,n),l=Math.atan2(i,t),c=Math.abs(a+l);return c<1e-5||Math.abs(vp-c)<1e-5?(e.rotation=l,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=a,e.skew.y=l),e.scale.x=Math.sqrt(t*t+i*i),e.scale.y=Math.sqrt(r*r+n*n),e.position.x=this.tx+(o.x*t+o.y*r),e.position.y=this.ty+(o.x*i+o.y*n),e}invert(){const e=this.a,t=this.b,i=this.c,r=this.d,n=this.tx,o=e*r-t*i;return this.a=r/o,this.b=-t/o,this.c=-i/o,this.d=e/o,this.tx=(i*this.ty-r*n)/o,this.ty=-(e*this.ty-t*n)/o,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const e=new H;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return Tp.identity()}static get shared(){return Ep.identity()}}const Ep=new H,Tp=new H;class je{constructor(e,t,i){this._x=t||0,this._y=i||0,this._observer=e}clone(e){return new je(e??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}const _i={_registeredResources:new Set,register(s){this._registeredResources.add(s)},unregister(s){this._registeredResources.delete(s)},release(){this._registeredResources.forEach(s=>s.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(s){return this._registeredResources.has(s)},reset(){this._registeredResources.clear()}};class Ap{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){var i;let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),(i=t.init)==null||i.call(t,e),t}return(e){var t;(t=e.reset)==null||t.call(e),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let e=0;e<this._index;e++)this._pool[e].destroy();this._pool.length=0,this._count=0,this._index=0}}class wp{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new Ap(e)),this._poolsByClass.get(e)}stats(){const e={};return this._poolsByClass.forEach(t=>{const i=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[i]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}}const Le=new wp;_i.register(Le);const Ip={get isCachedAsTexture(){var s;return!!((s=this.renderGroup)!=null&&s.isCachedAsTexture)},cacheAsTexture(s){typeof s=="boolean"&&s===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(s===!0?{}:s))},updateCacheTexture(){var s;(s=this.renderGroup)==null||s.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(s){ee("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(s)}};function za(s,e,t){const i=s.length;let r;if(e>=i||t===0)return;t=e+t>i?i-e:t;const n=i-t;for(r=e;r<n;++r)s[r]=s[r+t];s.length=n}const Rp={allowChildren:!0,removeChildren(s=0,e){var n;const t=e??this.children.length,i=t-s,r=[];if(i>0&&i<=t){for(let a=t-1;a>=s;a--){const l=this.children[a];l&&(r.push(l),l.parent=null)}za(this.children,s,t);const o=this.renderGroup||this.parentRenderGroup;o&&o.removeChildren(r);for(let a=0;a<r.length;++a){const l=r[a];(n=l.parentRenderLayer)==null||n.detach(l),this.emit("childRemoved",l,this,a),r[a].emit("removed",this)}return r.length>0&&this._didViewChangeTick++,r}else if(i===0&&this.children.length===0)return r;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(s){const e=this.getChildAt(s);return this.removeChild(e)},getChildAt(s){if(s<0||s>=this.children.length)throw new Error(`getChildAt: Index (${s}) does not exist.`);return this.children[s]},setChildIndex(s,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);this.getChildIndex(s),this.addChildAt(s,e)},getChildIndex(s){const e=this.children.indexOf(s);if(e===-1)throw new Error("The supplied Container must be a child of the caller");return e},addChildAt(s,e){this.allowChildren||ee(Be,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:t}=this;if(e<0||e>t.length)throw new Error(`${s}addChildAt: The index ${e} supplied is out of bounds ${t.length}`);const i=s.parent===this;if(s.parent){const n=s.parent.children.indexOf(s);if(i){if(n===e)return s;s.parent.children.splice(n,1)}else s.removeFromParent()}e===t.length?t.push(s):t.splice(e,0,s),s.parent=this,s.didChange=!0,s._updateFlags=15;const r=this.renderGroup||this.parentRenderGroup;return r&&r.addChild(s),this.sortableChildren&&(this.sortDirty=!0),i||(this.emit("childAdded",s,this,e),s.emit("added",this)),s},swapChildren(s,e){if(s===e)return;const t=this.getChildIndex(s),i=this.getChildIndex(e);this.children[t]=e,this.children[i]=s;const r=this.renderGroup||this.parentRenderGroup;r&&(r.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){var s;(s=this.parent)==null||s.removeChild(this)},reparentChild(...s){return s.length===1?this.reparentChildAt(s[0],this.children.length):(s.forEach(e=>this.reparentChildAt(e,this.children.length)),s[0])},reparentChildAt(s,e){if(s.parent===this)return this.setChildIndex(s,e),s;const t=s.worldTransform.clone();s.removeFromParent(),this.addChildAt(s,e);const i=this.worldTransform.clone();return i.invert(),t.prepend(i),s.setFromMatrix(t),s},replaceChild(s,e){s.updateLocalTransform(),this.addChildAt(e,this.getChildIndex(s)),e.setFromMatrix(s.localTransform),e.updateLocalTransform(),this.removeChild(s)}},Mp={collectRenderables(s,e,t){this.parentRenderLayer&&this.parentRenderLayer!==t||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(s,e,t):this.renderGroup?e.renderPipes.renderGroup.addRenderGroup(this.renderGroup,s):this.collectRenderablesWithEffects(s,e,t))},collectRenderablesSimple(s,e,t){const i=this.children,r=i.length;for(let n=0;n<r;n++)i[n].collectRenderables(s,e,t)},collectRenderablesWithEffects(s,e,t){const{renderPipes:i}=e;for(let r=0;r<this.effects.length;r++){const n=this.effects[r];i[n.pipe].push(n,this,s)}this.collectRenderablesSimple(s,e,t);for(let r=this.effects.length-1;r>=0;r--){const n=this.effects[r];i[n.pipe].pop(n,this,s)}}};class zs{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let e=0;e<this.filters.length;e++)this.filters[e].destroy();this.filters=null,this.filterArea=null}}class Pp{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(e=>{this.add({test:e.test,maskClass:e})}))}add(e){this._tests.push(e)}getMaskEffect(e){this._initialized||this.init();for(let t=0;t<this._tests.length;t++){const i=this._tests[t];if(i.test(e))return Le.get(i.maskClass,e)}return e}returnMaskEffect(e){Le.return(e)}}const rn=new Pp;Q.handleByList(A.MaskEffect,rn._effectClasses);const kp={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const s=this.renderGroup||this.parentRenderGroup;s&&(s.structureDidChange=!0)},addEffect(s){this.effects.indexOf(s)===-1&&(this.effects.push(s),this.effects.sort((t,i)=>t.priority-i.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(s){const e=this.effects.indexOf(s);e!==-1&&(this.effects.splice(e,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(s){const e=this._maskEffect;(e==null?void 0:e.mask)!==s&&(e&&(this.removeEffect(e),rn.returnMaskEffect(e),this._maskEffect=null),s!=null&&(this._maskEffect=rn.getMaskEffect(s),this.addEffect(this._maskEffect)))},get mask(){var s;return(s=this._maskEffect)==null?void 0:s.mask},setMask(s){this._maskOptions={...this._maskOptions,...s},s.mask&&(this.mask=s.mask),this._markStructureAsChanged()},set filters(s){var n;!Array.isArray(s)&&s&&(s=[s]);const e=this._filterEffect||(this._filterEffect=new zs);s=s;const t=(s==null?void 0:s.length)>0,i=((n=e.filters)==null?void 0:n.length)>0,r=t!==i;s=Array.isArray(s)?s.slice(0):s,e.filters=Object.freeze(s),r&&(t?this.addEffect(e):(this.removeEffect(e),e.filters=s??null))},get filters(){var s;return(s=this._filterEffect)==null?void 0:s.filters},set filterArea(s){this._filterEffect||(this._filterEffect=new zs),this._filterEffect.filterArea=s},get filterArea(){var s;return(s=this._filterEffect)==null?void 0:s.filterArea}},Op={label:null,get name(){return ee(Be,"Container.name property has been removed, use Container.label instead"),this.label},set name(s){ee(Be,"Container.name property has been removed, use Container.label instead"),this.label=s},getChildByName(s,e=!1){return this.getChildByLabel(s,e)},getChildByLabel(s,e=!1){const t=this.children;for(let i=0;i<t.length;i++){const r=t[i];if(r.label===s||s instanceof RegExp&&s.test(r.label))return r}if(e)for(let i=0;i<t.length;i++){const n=t[i].getChildByLabel(s,!0);if(n)return n}return null},getChildrenByLabel(s,e=!1,t=[]){const i=this.children;for(let r=0;r<i.length;r++){const n=i[r];(n.label===s||s instanceof RegExp&&s.test(n.label))&&t.push(n)}if(e)for(let r=0;r<i.length;r++)i[r].getChildrenByLabel(s,!0,t);return t}},$s=[new xe,new xe,new xe,new xe];class Se{constructor(e=0,t=0,i=0,r=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),this.width=Number(i),this.height=Number(r)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new Se(0,0,0,0)}clone(){return new Se(this.x,this.y,this.width,this.height)}copyFromBounds(e){return this.x=e.minX,this.y=e.minY,this.width=e.maxX-e.minX,this.height=e.maxY-e.minY,this}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){return this.width<=0||this.height<=0?!1:e>=this.x&&e<this.x+this.width&&t>=this.y&&t<this.y+this.height}strokeContains(e,t,i,r=.5){const{width:n,height:o}=this;if(n<=0||o<=0)return!1;const a=this.x,l=this.y,c=i*(1-r),h=i-c,u=a-c,f=a+n+c,d=l-c,g=l+o+c,_=a+h,y=a+n-h,x=l+h,C=l+o-h;return e>=u&&e<=f&&t>=d&&t<=g&&!(e>_&&e<y&&t>x&&t<C)}intersects(e,t){if(!t){const D=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=D)return!1;const k=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>k}const i=this.left,r=this.right,n=this.top,o=this.bottom;if(r<=i||o<=n)return!1;const a=$s[0].set(e.left,e.top),l=$s[1].set(e.left,e.bottom),c=$s[2].set(e.right,e.top),h=$s[3].set(e.right,e.bottom);if(c.x<=a.x||l.y<=a.y)return!1;const u=Math.sign(t.a*t.d-t.b*t.c);if(u===0||(t.apply(a,a),t.apply(l,l),t.apply(c,c),t.apply(h,h),Math.max(a.x,l.x,c.x,h.x)<=i||Math.min(a.x,l.x,c.x,h.x)>=r||Math.max(a.y,l.y,c.y,h.y)<=n||Math.min(a.y,l.y,c.y,h.y)>=o))return!1;const f=u*(l.y-a.y),d=u*(a.x-l.x),g=f*i+d*n,_=f*r+d*n,y=f*i+d*o,x=f*r+d*o;if(Math.max(g,_,y,x)<=f*a.x+d*a.y||Math.min(g,_,y,x)>=f*h.x+d*h.y)return!1;const C=u*(a.y-c.y),S=u*(c.x-a.x),E=C*i+S*n,w=C*r+S*n,R=C*i+S*o,M=C*r+S*o;return!(Math.max(E,w,R,M)<=C*a.x+S*a.y||Math.min(E,w,R,M)>=C*h.x+S*h.y)}pad(e=0,t=e){return this.x-=e,this.y-=t,this.width+=e*2,this.height+=t*2,this}fit(e){const t=Math.max(this.x,e.x),i=Math.min(this.x+this.width,e.x+e.width),r=Math.max(this.y,e.y),n=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(i-t,0),this.y=r,this.height=Math.max(n-r,0),this}ceil(e=1,t=.001){const i=Math.ceil((this.x+this.width-t)*e)/e,r=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=i-this.x,this.height=r-this.y,this}scale(e,t=e){return this.x*=e,this.y*=t,this.width*=e,this.height*=t,this}enlarge(e){const t=Math.min(this.x,e.x),i=Math.max(this.x+this.width,e.x+e.width),r=Math.min(this.y,e.y),n=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=i-t,this.y=r,this.height=n-r,this}getBounds(e){return e||(e=new Se),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,i=e.y,r=e.x+e.width,n=e.y+e.height;return t>=this.x&&t<this.x+this.width&&i>=this.y&&i<this.y+this.height&&r>=this.x&&r<this.x+this.width&&n>=this.y&&n<this.y+this.height}set(e,t,i,r){return this.x=e,this.y=t,this.width=i,this.height=r,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const $a=new H;class Ye{constructor(e=1/0,t=1/0,i=-1/0,r=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=$a,this.minX=e,this.minY=t,this.maxX=i,this.maxY=r}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new Se);const e=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(e.x=0,e.y=0,e.width=0,e.height=0):e.copyFromBounds(this),e}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=$a,this}set(e,t,i,r){this.minX=e,this.minY=t,this.maxX=i,this.maxY=r}addFrame(e,t,i,r,n){n||(n=this.matrix);const o=n.a,a=n.b,l=n.c,c=n.d,h=n.tx,u=n.ty;let f=this.minX,d=this.minY,g=this.maxX,_=this.maxY,y=o*e+l*t+h,x=a*e+c*t+u;y<f&&(f=y),x<d&&(d=x),y>g&&(g=y),x>_&&(_=x),y=o*i+l*t+h,x=a*i+c*t+u,y<f&&(f=y),x<d&&(d=x),y>g&&(g=y),x>_&&(_=x),y=o*e+l*r+h,x=a*e+c*r+u,y<f&&(f=y),x<d&&(d=x),y>g&&(g=y),x>_&&(_=x),y=o*i+l*r+h,x=a*i+c*r+u,y<f&&(f=y),x<d&&(d=x),y>g&&(g=y),x>_&&(_=x),this.minX=f,this.minY=d,this.maxX=g,this.maxY=_}addRect(e,t){this.addFrame(e.x,e.y,e.x+e.width,e.y+e.height,t)}addBounds(e,t){this.addFrame(e.minX,e.minY,e.maxX,e.maxY,t)}addBoundsMask(e){this.minX=this.minX>e.minX?this.minX:e.minX,this.minY=this.minY>e.minY?this.minY:e.minY,this.maxX=this.maxX<e.maxX?this.maxX:e.maxX,this.maxY=this.maxY<e.maxY?this.maxY:e.maxY}applyMatrix(e){const t=this.minX,i=this.minY,r=this.maxX,n=this.maxY,{a:o,b:a,c:l,d:c,tx:h,ty:u}=e;let f=o*t+l*i+h,d=a*t+c*i+u;this.minX=f,this.minY=d,this.maxX=f,this.maxY=d,f=o*r+l*i+h,d=a*r+c*i+u,this.minX=f<this.minX?f:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=f>this.maxX?f:this.maxX,this.maxY=d>this.maxY?d:this.maxY,f=o*t+l*n+h,d=a*t+c*n+u,this.minX=f<this.minX?f:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=f>this.maxX?f:this.maxX,this.maxY=d>this.maxY?d:this.maxY,f=o*r+l*n+h,d=a*r+c*n+u,this.minX=f<this.minX?f:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=f>this.maxX?f:this.maxX,this.maxY=d>this.maxY?d:this.maxY}fit(e){return this.minX<e.left&&(this.minX=e.left),this.maxX>e.right&&(this.maxX=e.right),this.minY<e.top&&(this.minY=e.top),this.maxY>e.bottom&&(this.maxY=e.bottom),this}fitBounds(e,t,i,r){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<i&&(this.minY=i),this.maxY>r&&(this.maxY=r),this}pad(e,t=e){return this.minX-=e,this.maxX+=e,this.minY-=t,this.maxY+=t,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new Ye(this.minX,this.minY,this.maxX,this.maxY)}scale(e,t=e){return this.minX*=e,this.minY*=t,this.maxX*=e,this.maxY*=t,this}get x(){return this.minX}set x(e){const t=this.maxX-this.minX;this.minX=e,this.maxX=e+t}get y(){return this.minY}set y(e){const t=this.maxY-this.minY;this.minY=e,this.maxY=e+t}get width(){return this.maxX-this.minX}set width(e){this.maxX=this.minX+e}get height(){return this.maxY-this.minY}set height(e){this.maxY=this.minY+e}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(e,t,i,r){let n=this.minX,o=this.minY,a=this.maxX,l=this.maxY;r||(r=this.matrix);const c=r.a,h=r.b,u=r.c,f=r.d,d=r.tx,g=r.ty;for(let _=t;_<i;_+=2){const y=e[_],x=e[_+1],C=c*y+u*x+d,S=h*y+f*x+g;n=C<n?C:n,o=S<o?S:o,a=C>a?C:a,l=S>l?S:l}this.minX=n,this.minY=o,this.maxX=a,this.maxY=l}containsPoint(e,t){return this.minX<=e&&this.minY<=t&&this.maxX>=e&&this.maxY>=t}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(e){return this.minX=e.minX,this.minY=e.minY,this.maxX=e.maxX,this.maxY=e.maxY,this}}const qe=Le.getPool(H),It=Le.getPool(Ye),Bp=new H,Dp={getFastGlobalBounds(s,e){e||(e=new Ye),e.clear(),this._getGlobalBoundsRecursive(!!s,e,this.parentRenderLayer),e.isValid||e.set(0,0,0,0);const t=this.renderGroup||this.parentRenderGroup;return e.applyMatrix(t.worldTransform),e},_getGlobalBoundsRecursive(s,e,t){let i=e;if(s&&this.parentRenderLayer&&this.parentRenderLayer!==t||this.localDisplayStatus!==7||!this.measurable)return;const r=!!this.effects.length;if((this.renderGroup||r)&&(i=It.get().clear()),this.boundsArea)e.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;i.addFrame(o.minX,o.minY,o.maxX,o.maxY,this.groupTransform)}const n=this.children;for(let o=0;o<n.length;o++)n[o]._getGlobalBoundsRecursive(s,i,t)}if(r){let n=!1;const o=this.renderGroup||this.parentRenderGroup;for(let a=0;a<this.effects.length;a++)this.effects[a].addBounds&&(n||(n=!0,i.applyMatrix(o.worldTransform)),this.effects[a].addBounds(i,!0));n&&i.applyMatrix(o.worldTransform.copyTo(Bp).invert()),e.addBounds(i),It.return(i)}else this.renderGroup&&(e.addBounds(i,this.relativeGroupTransform),It.return(i))}};function nn(s,e,t){t.clear();let i,r;return s.parent?e?i=s.parent.worldTransform:(r=qe.get().identity(),i=on(s,r)):i=H.IDENTITY,ja(s,t,i,e),r&&qe.return(r),t.isValid||t.set(0,0,0,0),t}function ja(s,e,t,i){var a,l;if(!s.visible||!s.measurable)return;let r;i?r=s.worldTransform:(s.updateLocalTransform(),r=qe.get(),r.appendFrom(s.localTransform,t));const n=e,o=!!s.effects.length;if(o&&(e=It.get().clear()),s.boundsArea)e.addRect(s.boundsArea,r);else{const c=s.bounds;c&&!c.isEmpty()&&(e.matrix=r,e.addBounds(c));for(let h=0;h<s.children.length;h++)ja(s.children[h],e,r,i)}if(o){for(let c=0;c<s.effects.length;c++)(l=(a=s.effects[c]).addBounds)==null||l.call(a,e);n.addBounds(e,H.IDENTITY),It.return(e)}i||qe.return(r)}function on(s,e){const t=s.parent;return t&&(on(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function yi(s,e){if(s===16777215||!e)return e;if(e===16777215||!s)return s;const t=s>>16&255,i=s>>8&255,r=s&255,n=e>>16&255,o=e>>8&255,a=e&255,l=t*n/255|0,c=i*o/255|0,h=r*a/255|0;return(l<<16)+(c<<8)+h}const Xa=16777215;function js(s,e){return s===Xa?e:e===Xa?s:yi(s,e)}function bi(s){return((s&255)<<16)+(s&65280)+(s>>16&255)}const Np={getGlobalAlpha(s){if(s)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let e=this.alpha,t=this.parent;for(;t;)e*=t.alpha,t=t.parent;return e},getGlobalTransform(s=new H,e){if(e)return s.copyFrom(this.worldTransform);this.updateLocalTransform();const t=on(this,qe.get().identity());return s.appendFrom(this.localTransform,t),qe.return(t),s},getGlobalTint(s){if(s)return this.renderGroup?bi(this.renderGroup.worldColor):this.parentRenderGroup?bi(js(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=js(e,t.localColor),t=t.parent;return bi(e)}};function an(s,e,t){return e.clear(),t||(t=H.IDENTITY),Ya(s,e,t,s,!0),e.isValid||e.set(0,0,0,0),e}function Ya(s,e,t,i,r){var l,c;let n;if(r)n=qe.get(),n=t.copyTo(n);else{if(!s.visible||!s.measurable)return;s.updateLocalTransform();const h=s.localTransform;n=qe.get(),n.appendFrom(h,t)}const o=e,a=!!s.effects.length;if(a&&(e=It.get().clear()),s.boundsArea)e.addRect(s.boundsArea,n);else{s.renderPipeId&&(e.matrix=n,e.addBounds(s.bounds));const h=s.children;for(let u=0;u<h.length;u++)Ya(h[u],e,n,i,!1)}if(a){for(let h=0;h<s.effects.length;h++)(c=(l=s.effects[h]).addLocalBounds)==null||c.call(l,e,i);o.addBounds(e,H.IDENTITY),It.return(e)}qe.return(n)}function qa(s,e){const t=s.children;for(let i=0;i<t.length;i++){const r=t[i],n=r.uid,o=(r._didViewChangeTick&65535)<<16|r._didContainerChangeTick&65535,a=e.index;(e.data[a]!==n||e.data[a+1]!==o)&&(e.data[e.index]=n,e.data[e.index+1]=o,e.didChange=!0),e.index=a+2,r.children.length&&qa(r,e)}return e.didChange}const Up=new H,Fp={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(s,e){const t=Math.sign(this.scale.x)||1;e!==0?this.scale.x=s/e*t:this.scale.x=t},_setHeight(s,e){const t=Math.sign(this.scale.y)||1;e!==0?this.scale.y=s/e*t:this.scale.y=t},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new Ye});const s=this._localBoundsCacheData;return s.index=1,s.didChange=!1,s.data[0]!==this._didViewChangeTick&&(s.didChange=!0,s.data[0]=this._didViewChangeTick),qa(this,s),s.didChange&&an(this,s.localBounds,Up),s.localBounds},getBounds(s,e){return nn(this,s,e||new Ye)}},Gp={_onRender:null,set onRender(s){const e=this.renderGroup||this.parentRenderGroup;if(!s){this._onRender&&(e==null||e.removeOnRender(this)),this._onRender=null;return}this._onRender||e==null||e.addOnRender(this),this._onRender=s},get onRender(){return this._onRender}},Lp={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(s){this._zIndex!==s&&(this._zIndex=s,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(Wp))}};function Wp(s,e){return s._zIndex-e._zIndex}const Hp={getGlobalPosition(s=new xe,e=!1){return this.parent?this.parent.toGlobal(this._position,s,e):(s.x=this._position.x,s.y=this._position.y),s},toGlobal(s,e,t=!1){const i=this.getGlobalTransform(qe.get(),t);return e=i.apply(s,e),qe.return(i),e},toLocal(s,e,t,i){e&&(s=e.toGlobal(s,t,i));const r=this.getGlobalTransform(qe.get(),i);return t=r.applyInverse(s,t),qe.return(r),t}};class ln{constructor(){this.uid=be("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(e){this.instructions[this.instructionSize++]=e}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}const ei=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],ti=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],ii=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],si=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],cn=[],Ka=[],Xs=Math.sign;function Vp(){for(let s=0;s<16;s++){const e=[];cn.push(e);for(let t=0;t<16;t++){const i=Xs(ei[s]*ei[t]+ii[s]*ti[t]),r=Xs(ti[s]*ei[t]+si[s]*ti[t]),n=Xs(ei[s]*ii[t]+ii[s]*si[t]),o=Xs(ti[s]*ii[t]+si[s]*si[t]);for(let a=0;a<16;a++)if(ei[a]===i&&ti[a]===r&&ii[a]===n&&si[a]===o){e.push(a);break}}}for(let s=0;s<16;s++){const e=new H;e.set(ei[s],ti[s],ii[s],si[s],0,0),Ka.push(e)}}Vp();const re={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:s=>ei[s],uY:s=>ti[s],vX:s=>ii[s],vY:s=>si[s],inv:s=>s&8?s&15:-s&7,add:(s,e)=>cn[s][e],sub:(s,e)=>cn[s][re.inv(e)],rotate180:s=>s^4,isVertical:s=>(s&3)===2,byDirection:(s,e)=>Math.abs(s)*2<=Math.abs(e)?e>=0?re.S:re.N:Math.abs(e)*2<=Math.abs(s)?s>0?re.E:re.W:e>0?s>0?re.SE:re.SW:s>0?re.NE:re.NW,matrixAppendRotationInv:(s,e,t=0,i=0,r=0,n=0)=>{const o=Ka[re.inv(e)],a=o.a,l=o.b,c=o.c,h=o.d,u=t-Math.min(0,a*r,c*n,a*r+c*n),f=i-Math.min(0,l*r,h*n,l*r+h*n),d=s.a,g=s.b,_=s.c,y=s.d;s.a=a*d+l*_,s.b=a*g+l*y,s.c=c*d+h*_,s.d=c*g+h*y,s.tx=u*d+f*_+s.tx,s.ty=u*g+f*y+s.ty},transformRectCoords:(s,e,t,i)=>{const{x:r,y:n,width:o,height:a}=s,{x:l,y:c,width:h,height:u}=e;return t===re.E?(i.set(r+l,n+c,o,a),i):t===re.S?i.set(h-n-a+l,r+c,a,o):t===re.W?i.set(h-r-o+l,u-n-a+c,o,a):t===re.N?i.set(n+l,u-r-o+c,a,o):i.set(r+l,n+c,o,a)}},Za=()=>{};class hn extends De{constructor(e){const t=e.resource||new Float32Array(e.width*e.height*4);let i=e.format;i||(t instanceof Float32Array?i="rgba32float":t instanceof Int32Array||t instanceof Uint32Array?i="rgba32uint":t instanceof Int16Array||t instanceof Uint16Array?i="rgba16uint":(t instanceof Int8Array,i="bgra8unorm")),super({...e,resource:t,format:i}),this.uploadMethodId="buffer"}static test(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array}}hn.extension=A.TextureSource;const Ja=new H;class Qa{constructor(e,t){this.mapCoord=new H,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof t>"u"?this.clampMargin=e.width<10?0:.5:this.clampMargin=t,this.isSimple=!1,this.texture=e}get texture(){return this._texture}set texture(e){var t;this.texture!==e&&((t=this._texture)==null||t.removeListener("update",this.update,this),this._texture=e,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(e,t){t===void 0&&(t=e);const i=this.mapCoord;for(let r=0;r<e.length;r+=2){const n=e[r],o=e[r+1];t[r]=n*i.a+o*i.c+i.tx,t[r+1]=n*i.b+o*i.d+i.ty}return t}update(){const e=this._texture;this._updateID++;const t=e.uvs;this.mapCoord.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0);const i=e.orig,r=e.trim;r&&(Ja.set(i.width/r.width,0,0,i.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(Ja));const n=e.source,o=this.uClampFrame,a=this.clampMargin/n._resolution,l=this.clampOffset/n._resolution;return o[0]=(e.frame.x+a+l)/n.width,o[1]=(e.frame.y+a+l)/n.height,o[2]=(e.frame.x+e.frame.width-a+l)/n.width,o[3]=(e.frame.y+e.frame.height-a+l)/n.height,this.uClampOffset[0]=this.clampOffset/n.pixelWidth,this.uClampOffset[1]=this.clampOffset/n.pixelHeight,this.isSimple=e.frame.width===n.width&&e.frame.height===n.height&&e.rotate===0,!0}}class j extends lt{constructor({source:e,label:t,frame:i,orig:r,trim:n,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:c}={}){if(super(),this.uid=be("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new Se,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=(e==null?void 0:e.source)??new De,this.noFrame=!i,i)this.frame.copyFrom(i);else{const{width:h,height:u}=this._source;this.frame.width=h,this.frame.height=u}this.orig=r||this.frame,this.trim=n,this.rotate=l??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=c||!1,this.updateUvs()}set source(e){this._source&&this._source.off("resize",this.update,this),this._source=e,e.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new Qa(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:e,frame:t}=this,{width:i,height:r}=this._source,n=t.x/i,o=t.y/r,a=t.width/i,l=t.height/r;let c=this.rotate;if(c){const h=a/2,u=l/2,f=n+h,d=o+u;c=re.add(c,re.NW),e.x0=f+h*re.uX(c),e.y0=d+u*re.uY(c),c=re.add(c,2),e.x1=f+h*re.uX(c),e.y1=d+u*re.uY(c),c=re.add(c,2),e.x2=f+h*re.uX(c),e.y2=d+u*re.uY(c),c=re.add(c,2),e.x3=f+h*re.uX(c),e.y3=d+u*re.uY(c)}else e.x0=n,e.y0=o,e.x1=n+a,e.y1=o,e.x2=n+a,e.y2=o+l,e.x3=n,e.y3=o+l}destroy(e=!1){this._source&&(this._source.off("resize",this.update,this),e&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return ee(Be,"Texture.baseTexture is now Texture.source"),this._source}}j.EMPTY=new j({label:"EMPTY",source:new De({label:"EMPTY"})}),j.EMPTY.destroy=Za,j.WHITE=new j({source:new hn({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"}),j.WHITE.destroy=Za;let zp=0;class $p{constructor(e){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=e||{},this.enableFullScreen=!1,this.textureStyle=new zr(this.textureOptions)}createTexture(e,t,i,r){const n=new De({...this.textureOptions,width:e,height:t,resolution:1,antialias:i,autoGarbageCollect:!1,autoGenerateMipmaps:r});return new j({source:n,label:`texturePool_${zp++}`})}getOptimalTexture(e,t,i=1,r,n=!1){let o=Math.ceil(e*i-1e-6),a=Math.ceil(t*i-1e-6);o=Ls(o),a=Ls(a);const l=r?1:0,c=n?1:0,h=(o<<17)+(a<<2)+(c<<1)+l;this._texturePool[h]||(this._texturePool[h]=[]);let u=this._texturePool[h].pop();return u||(u=this.createTexture(o,a,r,n)),u.source._resolution=i,u.source.width=o/i,u.source.height=a/i,u.source.pixelWidth=o,u.source.pixelHeight=a,u.frame.x=0,u.frame.y=0,u.frame.width=e,u.frame.height=t,u.updateUvs(),this._poolKeyHash[u.uid]=h,u}getSameSizeTexture(e,t=!1){const i=e.source;return this.getOptimalTexture(e.width,e.height,i._resolution,t)}returnTexture(e,t=!1){const i=this._poolKeyHash[e.uid];t&&(e.source.style=this.textureStyle),this._texturePool[i].push(e)}clear(e){if(e=e!==!1,e)for(const t in this._texturePool){const i=this._texturePool[t];if(i)for(let r=0;r<i.length;r++)i[r].destroy(!0)}this._texturePool={}}}const Qe=new $p;_i.register(Qe);class un{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new H,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new ln,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(e){this.root=e,e._onRender&&this.addOnRender(e),e.didChange=!0;const t=e.children;for(let i=0;i<t.length;i++){const r=t[i];r._updateFlags=15,this.addChild(r)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Qe.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const e=this._parentCacheAsTextureRenderGroup;e&&!e.textureNeedsUpdate&&e.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const e in this.childrenToUpdate){const t=this.childrenToUpdate[e];t.list.fill(null),t.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(e){e.renderGroupParent&&e.renderGroupParent._removeRenderGroupChild(e),e.renderGroupParent=this,this.renderGroupChildren.push(e)}_removeRenderGroupChild(e){const t=this.renderGroupChildren.indexOf(e);t>-1&&this.renderGroupChildren.splice(t,1),e.renderGroupParent=null}addChild(e){if(this.structureDidChange=!0,e.parentRenderGroup=this,e.updateTick=-1,e.parent===this.root?e.relativeRenderGroupDepth=1:e.relativeRenderGroupDepth=e.parent.relativeRenderGroupDepth+1,e.didChange=!0,this.onChildUpdate(e),e.renderGroup){this.addRenderGroupChild(e.renderGroup);return}e._onRender&&this.addOnRender(e);const t=e.children;for(let i=0;i<t.length;i++)this.addChild(t[i])}removeChild(e){if(this.structureDidChange=!0,e._onRender&&(e.renderGroup||this.removeOnRender(e)),e.parentRenderGroup=null,e.renderGroup){this._removeRenderGroupChild(e.renderGroup);return}const t=e.children;for(let i=0;i<t.length;i++)this.removeChild(t[i])}removeChildren(e){for(let t=0;t<e.length;t++)this.removeChild(e[t])}onChildUpdate(e){let t=this.childrenToUpdate[e.relativeRenderGroupDepth];t||(t=this.childrenToUpdate[e.relativeRenderGroupDepth]={index:0,list:[]}),t.list[t.index++]=e}updateRenderable(e){e.globalDisplayStatus<7||(this.instructionSet.renderPipes[e.renderPipeId].updateRenderable(e),e.didViewUpdate=!1)}onChildViewUpdate(e){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=e}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(e){this._onRenderContainers.push(e)}removeOnRender(e){this._onRenderContainers.splice(this._onRenderContainers.indexOf(e),1)}runOnRender(e){for(let t=0;t<this._onRenderContainers.length;t++)this._onRenderContainers[t]._onRender(e)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(e=[]){const t=this.root.children;for(let i=0;i<t.length;i++)this._getChildren(t[i],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;const i=e.children;for(let r=0;r<i.length;r++)this._getChildren(i[r],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new H),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new H),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y))}get inverseParentTextureTransform(){if((this._matrixDirty&4)===0)return this._inverseParentTextureTransform;this._matrixDirty&=-5;const e=this._parentCacheAsTextureRenderGroup;return e?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new H),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(e.inverseWorldTransform).translate(-e._textureBounds.x,-e._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function jp(s,e,t={}){for(const i in e)!t[i]&&e[i]!==void 0&&(s[i]=e[i])}const dn=new je(null),Ys=new je(null),fn=new je(null,1,1),qs=new je(null),Ks=1,pn=2,Ji=4;class Ve extends lt{constructor(e={}){var t,i;super(),this.uid=be("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new H,this.relativeGroupTransform=new H,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new je(this,0,0),this._scale=fn,this._pivot=Ys,this._origin=qs,this._skew=dn,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],jp(this,e,{children:!0,parent:!0,effects:!0}),(t=e.children)==null||t.forEach(r=>this.addChild(r)),(i=e.parent)==null||i.addChild(this)}static mixin(e){ee("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),Q.mixin(Ve,e)}set _didChangeId(e){this._didViewChangeTick=e>>12&4095,this._didContainerChangeTick=e&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...e){if(this.allowChildren||ee(Be,"addChild: Only Containers will be allowed to add children in v8.0.0"),e.length>1){for(let r=0;r<e.length;r++)this.addChild(e[r]);return e[0]}const t=e[0],i=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),i&&(i.structureDidChange=!0),t):(t.parent&&t.parent.removeChild(t),this.children.push(t),this.sortableChildren&&(this.sortDirty=!0),t.parent=this,t.didChange=!0,t._updateFlags=15,i&&i.addChild(t),this.emit("childAdded",t,this,this.children.length-1),t.emit("added",this),this._didViewChangeTick++,t._zIndex!==0&&t.depthOfChildModified(),t)}removeChild(...e){if(e.length>1){for(let r=0;r<e.length;r++)this.removeChild(e[r]);return e[0]}const t=e[0],i=this.children.indexOf(t);return i>-1&&(this._didViewChangeTick++,this.children.splice(i,1),this.renderGroup?this.renderGroup.removeChild(t):this.parentRenderGroup&&this.parentRenderGroup.removeChild(t),t.parentRenderLayer&&t.parentRenderLayer.detach(t),t.parent=null,this.emit("childRemoved",t,this,i),t.emit("removed",this)),t}_onUpdate(e){e&&e===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(e){!!this.renderGroup!==e&&(e?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),this.renderGroup=Le.get(un,this),this.groupTransform=H.IDENTITY,e==null||e.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),Le.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e==null||e.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new H),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get position(){return this._position}set position(e){this._position.copyFrom(e)}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this._skew))}get angle(){return this.rotation*Cp}set angle(e){this.rotation=e*Sp}get pivot(){return this._pivot===Ys&&(this._pivot=new je(this,0,0)),this._pivot}set pivot(e){this._pivot===Ys&&(this._pivot=new je(this,0,0),this._origin!==qs&&se("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._pivot.set(e):this._pivot.copyFrom(e)}get skew(){return this._skew===dn&&(this._skew=new je(this,0,0)),this._skew}set skew(e){this._skew===dn&&(this._skew=new je(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===fn&&(this._scale=new je(this,1,1)),this._scale}set scale(e){this._scale===fn&&(this._scale=new je(this,0,0)),typeof e=="string"&&(e=parseFloat(e)),typeof e=="number"?this._scale.set(e):this._scale.copyFrom(e)}get origin(){return this._origin===qs&&(this._origin=new je(this,0,0)),this._origin}set origin(e){this._origin===qs&&(this._origin=new je(this,0,0),this._pivot!==Ys&&se("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._origin.set(e):this._origin.copyFrom(e)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(e){const t=this.getLocalBounds().width;this._setWidth(e,t)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(e){const t=this.getLocalBounds().height;this._setHeight(e,t)}getSize(e){e||(e={});const t=this.getLocalBounds();return e.width=Math.abs(this.scale.x*t.width),e.height=Math.abs(this.scale.y*t.height),e}setSize(e,t){const i=this.getLocalBounds();typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,i.width),t!==void 0&&this._setHeight(t,i.height)}_updateSkew(){const e=this._rotation,t=this._skew;this._cx=Math.cos(e+t._y),this._sx=Math.sin(e+t._y),this._cy=-Math.sin(e-t._x),this._sy=Math.cos(e-t._x)}updateTransform(e){return this.position.set(typeof e.x=="number"?e.x:this.position.x,typeof e.y=="number"?e.y:this.position.y),this.scale.set(typeof e.scaleX=="number"?e.scaleX||1:this.scale.x,typeof e.scaleY=="number"?e.scaleY||1:this.scale.y),this.rotation=typeof e.rotation=="number"?e.rotation:this.rotation,this.skew.set(typeof e.skewX=="number"?e.skewX:this.skew.x,typeof e.skewY=="number"?e.skewY:this.skew.y),this.pivot.set(typeof e.pivotX=="number"?e.pivotX:this.pivot.x,typeof e.pivotY=="number"?e.pivotY:this.pivot.y),this.origin.set(typeof e.originX=="number"?e.originX:this.origin.x,typeof e.originY=="number"?e.originY:this.origin.y),this}setFromMatrix(e){e.decompose(this)}updateLocalTransform(){const e=this._didContainerChangeTick;if(this._didLocalTransformChangeId===e)return;this._didLocalTransformChangeId=e;const t=this.localTransform,i=this._scale,r=this._pivot,n=this._origin,o=this._position,a=i._x,l=i._y,c=r._x,h=r._y,u=-n._x,f=-n._y;t.a=this._cx*a,t.b=this._sx*a,t.c=this._cy*l,t.d=this._sy*l,t.tx=o._x-(c*t.a+h*t.c)+(u*t.a+f*t.c)-u,t.ty=o._y-(c*t.b+h*t.d)+(u*t.b+f*t.d)-f}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=Ks,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const i=Pe.shared.setValue(e??16777215).toBgrNumber();i!==this.localColor&&(this.localColor=i,this._updateFlags|=Ks,this._onUpdate())}get tint(){return bi(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=pn,this.localBlendMode=e,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(e){const t=e?2:0;(this.localDisplayStatus&2)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=Ji,this.localDisplayStatus^=2,this._onUpdate(),this.emit("visibleChanged",e))}get culled(){return!(this.localDisplayStatus&4)}set culled(e){const t=e?0:4;(this.localDisplayStatus&4)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=Ji,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(e){const t=e?1:0;(this.localDisplayStatus&1)!==t&&(this._updateFlags|=Ji,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){var r;if(this.destroyed)return;this.destroyed=!0;let t;if(this.children.length&&(t=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof e=="boolean"?e:e==null?void 0:e.children)&&t)for(let n=0;n<t.length;++n)t[n].destroy(e);(r=this.renderGroup)==null||r.destroy(),this.renderGroup=null}}Q.mixin(Ve,Rp,Dp,Hp,Gp,Fp,kp,Op,Lp,xp,Ip,Np,Mp);function el(s,e,t=2){const i=e&&e.length,r=i?e[0]*t:s.length;let n=tl(s,0,r,t,!0);const o=[];if(!n||n.next===n.prev)return o;let a,l,c;if(i&&(n=Zp(s,e,n,t)),s.length>80*t){a=s[0],l=s[1];let h=a,u=l;for(let f=t;f<r;f+=t){const d=s[f],g=s[f+1];d<a&&(a=d),g<l&&(l=g),d>h&&(h=d),g>u&&(u=g)}c=Math.max(h-a,u-l),c=c!==0?32767/c:0}return Qi(n,o,t,a,l,c,0),o}function tl(s,e,t,i,r){let n;if(r===lm(s,e,t,i)>0)for(let o=e;o<t;o+=i)n=nl(o/i|0,s[o],s[o+1],n);else for(let o=t-i;o>=e;o-=i)n=nl(o/i|0,s[o],s[o+1],n);return n&&xi(n,n.next)&&(is(n),n=n.next),n}function ri(s,e){if(!s)return s;e||(e=s);let t=s,i;do if(i=!1,!t.steiner&&(xi(t,t.next)||Ae(t.prev,t,t.next)===0)){if(is(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function Qi(s,e,t,i,r,n,o){if(!s)return;!o&&n&&im(s,i,r,n);let a=s;for(;s.prev!==s.next;){const l=s.prev,c=s.next;if(n?Yp(s,i,r,n):Xp(s)){e.push(l.i,s.i,c.i),is(s),s=c.next,a=c.next;continue}if(s=c,s===a){o?o===1?(s=qp(ri(s),e),Qi(s,e,t,i,r,n,2)):o===2&&Kp(s,e,t,i,r,n):Qi(ri(s),e,t,i,r,n,1);break}}}function Xp(s){const e=s.prev,t=s,i=s.next;if(Ae(e,t,i)>=0)return!1;const r=e.x,n=t.x,o=i.x,a=e.y,l=t.y,c=i.y,h=Math.min(r,n,o),u=Math.min(a,l,c),f=Math.max(r,n,o),d=Math.max(a,l,c);let g=i.next;for(;g!==e;){if(g.x>=h&&g.x<=f&&g.y>=u&&g.y<=d&&es(r,a,n,l,o,c,g.x,g.y)&&Ae(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function Yp(s,e,t,i){const r=s.prev,n=s,o=s.next;if(Ae(r,n,o)>=0)return!1;const a=r.x,l=n.x,c=o.x,h=r.y,u=n.y,f=o.y,d=Math.min(a,l,c),g=Math.min(h,u,f),_=Math.max(a,l,c),y=Math.max(h,u,f),x=mn(d,g,e,t,i),C=mn(_,y,e,t,i);let S=s.prevZ,E=s.nextZ;for(;S&&S.z>=x&&E&&E.z<=C;){if(S.x>=d&&S.x<=_&&S.y>=g&&S.y<=y&&S!==r&&S!==o&&es(a,h,l,u,c,f,S.x,S.y)&&Ae(S.prev,S,S.next)>=0||(S=S.prevZ,E.x>=d&&E.x<=_&&E.y>=g&&E.y<=y&&E!==r&&E!==o&&es(a,h,l,u,c,f,E.x,E.y)&&Ae(E.prev,E,E.next)>=0))return!1;E=E.nextZ}for(;S&&S.z>=x;){if(S.x>=d&&S.x<=_&&S.y>=g&&S.y<=y&&S!==r&&S!==o&&es(a,h,l,u,c,f,S.x,S.y)&&Ae(S.prev,S,S.next)>=0)return!1;S=S.prevZ}for(;E&&E.z<=C;){if(E.x>=d&&E.x<=_&&E.y>=g&&E.y<=y&&E!==r&&E!==o&&es(a,h,l,u,c,f,E.x,E.y)&&Ae(E.prev,E,E.next)>=0)return!1;E=E.nextZ}return!0}function qp(s,e){let t=s;do{const i=t.prev,r=t.next.next;!xi(i,r)&&sl(i,t,t.next,r)&&ts(i,r)&&ts(r,i)&&(e.push(i.i,t.i,r.i),is(t),is(t.next),t=s=r),t=t.next}while(t!==s);return ri(t)}function Kp(s,e,t,i,r,n){let o=s;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&nm(o,a)){let l=rl(o,a);o=ri(o,o.next),l=ri(l,l.next),Qi(o,e,t,i,r,n,0),Qi(l,e,t,i,r,n,0);return}a=a.next}o=o.next}while(o!==s)}function Zp(s,e,t,i){const r=[];for(let n=0,o=e.length;n<o;n++){const a=e[n]*i,l=n<o-1?e[n+1]*i:s.length,c=tl(s,a,l,i,!1);c===c.next&&(c.steiner=!0),r.push(rm(c))}r.sort(Jp);for(let n=0;n<r.length;n++)t=Qp(r[n],t);return t}function Jp(s,e){let t=s.x-e.x;if(t===0&&(t=s.y-e.y,t===0)){const i=(s.next.y-s.y)/(s.next.x-s.x),r=(e.next.y-e.y)/(e.next.x-e.x);t=i-r}return t}function Qp(s,e){const t=em(s,e);if(!t)return e;const i=rl(t,s);return ri(i,i.next),ri(t,t.next)}function em(s,e){let t=e;const i=s.x,r=s.y;let n=-1/0,o;if(xi(s,t))return t;do{if(xi(s,t.next))return t.next;if(r<=t.y&&r>=t.next.y&&t.next.y!==t.y){const u=t.x+(r-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=i&&u>n&&(n=u,o=t.x<t.next.x?t:t.next,u===i))return o}t=t.next}while(t!==e);if(!o)return null;const a=o,l=o.x,c=o.y;let h=1/0;t=o;do{if(i>=t.x&&t.x>=l&&i!==t.x&&il(r<c?i:n,r,l,c,r<c?n:i,r,t.x,t.y)){const u=Math.abs(r-t.y)/(i-t.x);ts(t,s)&&(u<h||u===h&&(t.x>o.x||t.x===o.x&&tm(o,t)))&&(o=t,h=u)}t=t.next}while(t!==a);return o}function tm(s,e){return Ae(s.prev,s,e.prev)<0&&Ae(e.next,s,s.next)<0}function im(s,e,t,i){let r=s;do r.z===0&&(r.z=mn(r.x,r.y,e,t,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==s);r.prevZ.nextZ=null,r.prevZ=null,sm(r)}function sm(s){let e,t=1;do{let i=s,r;s=null;let n=null;for(e=0;i;){e++;let o=i,a=0;for(let c=0;c<t&&(a++,o=o.nextZ,!!o);c++);let l=t;for(;a>0||l>0&&o;)a!==0&&(l===0||!o||i.z<=o.z)?(r=i,i=i.nextZ,a--):(r=o,o=o.nextZ,l--),n?n.nextZ=r:s=r,r.prevZ=n,n=r;i=o}n.nextZ=null,t*=2}while(e>1);return s}function mn(s,e,t,i,r){return s=(s-t)*r|0,e=(e-i)*r|0,s=(s|s<<8)&16711935,s=(s|s<<4)&252645135,s=(s|s<<2)&858993459,s=(s|s<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,s|e<<1}function rm(s){let e=s,t=s;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==s);return t}function il(s,e,t,i,r,n,o,a){return(r-o)*(e-a)>=(s-o)*(n-a)&&(s-o)*(i-a)>=(t-o)*(e-a)&&(t-o)*(n-a)>=(r-o)*(i-a)}function es(s,e,t,i,r,n,o,a){return!(s===o&&e===a)&&il(s,e,t,i,r,n,o,a)}function nm(s,e){return s.next.i!==e.i&&s.prev.i!==e.i&&!om(s,e)&&(ts(s,e)&&ts(e,s)&&am(s,e)&&(Ae(s.prev,s,e.prev)||Ae(s,e.prev,e))||xi(s,e)&&Ae(s.prev,s,s.next)>0&&Ae(e.prev,e,e.next)>0)}function Ae(s,e,t){return(e.y-s.y)*(t.x-e.x)-(e.x-s.x)*(t.y-e.y)}function xi(s,e){return s.x===e.x&&s.y===e.y}function sl(s,e,t,i){const r=Js(Ae(s,e,t)),n=Js(Ae(s,e,i)),o=Js(Ae(t,i,s)),a=Js(Ae(t,i,e));return!!(r!==n&&o!==a||r===0&&Zs(s,t,e)||n===0&&Zs(s,i,e)||o===0&&Zs(t,s,i)||a===0&&Zs(t,e,i))}function Zs(s,e,t){return e.x<=Math.max(s.x,t.x)&&e.x>=Math.min(s.x,t.x)&&e.y<=Math.max(s.y,t.y)&&e.y>=Math.min(s.y,t.y)}function Js(s){return s>0?1:s<0?-1:0}function om(s,e){let t=s;do{if(t.i!==s.i&&t.next.i!==s.i&&t.i!==e.i&&t.next.i!==e.i&&sl(t,t.next,s,e))return!0;t=t.next}while(t!==s);return!1}function ts(s,e){return Ae(s.prev,s,s.next)<0?Ae(s,e,s.next)>=0&&Ae(s,s.prev,e)>=0:Ae(s,e,s.prev)<0||Ae(s,s.next,e)<0}function am(s,e){let t=s,i=!1;const r=(s.x+e.x)/2,n=(s.y+e.y)/2;do t.y>n!=t.next.y>n&&t.next.y!==t.y&&r<(t.next.x-t.x)*(n-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==s);return i}function rl(s,e){const t=gn(s.i,s.x,s.y),i=gn(e.i,e.x,e.y),r=s.next,n=e.prev;return s.next=e,e.prev=s,t.next=r,r.prev=t,i.next=t,t.prev=i,n.next=i,i.prev=n,i}function nl(s,e,t,i){const r=gn(s,e,t);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function is(s){s.next.prev=s.prev,s.prev.next=s.next,s.prevZ&&(s.prevZ.nextZ=s.nextZ),s.nextZ&&(s.nextZ.prevZ=s.prevZ)}function gn(s,e,t){return{i:s,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function lm(s,e,t,i){let r=0;for(let n=e,o=t-i;n<t;n+=i)r+=(s[o]-s[n])*(s[n+1]+s[o+1]),o=n;return r}const cm=el.default||el;var it=(s=>(s[s.NONE=0]="NONE",s[s.COLOR=16384]="COLOR",s[s.STENCIL=1024]="STENCIL",s[s.DEPTH=256]="DEPTH",s[s.COLOR_DEPTH=16640]="COLOR_DEPTH",s[s.COLOR_STENCIL=17408]="COLOR_STENCIL",s[s.DEPTH_STENCIL=1280]="DEPTH_STENCIL",s[s.ALL=17664]="ALL",s))(it||{});class ol{constructor(e){this.items=[],this._name=e}emit(e,t,i,r,n,o,a,l){const{name:c,items:h}=this;for(let u=0,f=h.length;u<f;u++)h[u][c](e,t,i,r,n,o,a,l);return this}add(e){return e[this._name]&&(this.remove(e),this.items.push(e)),this}remove(e){const t=this.items.indexOf(e);return t!==-1&&this.items.splice(t,1),this}contains(e){return this.items.indexOf(e)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const hm=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],al=class pf extends lt{constructor(e){super(),this.tick=0,this.uid=be("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=e.type,this.name=e.name,this.config=e;const t=[...hm,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await bp(t),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const i in this._systemsHash)e={...this._systemsHash[i].constructor.defaultOptions,...e};e={...pf.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let i=0;i<this.runners.init.items.length;i++)await this.runners.init.items[i].init(e);this._initOptions=e}render(e,t){this.tick++;let i=e;if(i instanceof Ve&&(i={container:i},t&&(ee(Be,"passing a second argument is deprecated, please use render options instead"),i.target=t.renderTexture)),i.target||(i.target=this.view.renderTarget),i.target===this.view.renderTarget&&(this._lastObjectRendered=i.container,i.clearColor??(i.clearColor=this.background.colorRgba),i.clear??(i.clear=this.background.clearBeforeRender)),i.clearColor){const r=Array.isArray(i.clearColor)&&i.clearColor.length===4;i.clearColor=r?i.clearColor:Pe.shared.setValue(i.clearColor).toArray()}i.transform||(i.container.updateLocalTransform(),i.transform=i.container.localTransform),i.container.visible&&(i.container.enableRenderGroup(),this.runners.prerender.emit(i),this.runners.renderStart.emit(i),this.runners.render.emit(i),this.runners.renderEnd.emit(i),this.runners.postrender.emit(i))}resize(e,t,i){const r=this.view.resolution;this.view.resize(e,t,i),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),i!==void 0&&i!==r&&this.runners.resolutionChange.emit(i)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=it.ALL);const{clear:i,clearColor:r,target:n,mipLevel:o,layer:a}=e;Pe.shared.setValue(r??this.background.colorRgba),t.renderTarget.clear(n,i,Pe.shared.toArray(),o??0,a??0)}get resolution(){return this.view.resolution}set resolution(e){this.view.resolution=e,this.runners.resolutionChange.emit(e)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...e){e.forEach(t=>{this.runners[t]=new ol(t)})}_addSystems(e){let t;for(t in e){const i=e[t];this._addSystem(i.value,i.name)}}_addSystem(e,t){const i=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=i,this._systemsHash[t]=i;for(const r in this.runners)this.runners[r].add(i);return this}_addPipes(e,t){const i=t.reduce((r,n)=>(r[n.name]=n.value,r),{});e.forEach(r=>{const n=r.value,o=r.name,a=i[o];this.renderPipes[o]=new n(this,a?new a:null),this.runners.destroy.add(this.renderPipes[o])})}destroy(e=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(e),(e===!0||typeof e=="object"&&e.releaseGlobalResources)&&_i.release(),Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash=null,this.renderPipes=null,this.removeAllListeners()}generateTexture(e){return this.textureGenerator.generateTexture(e)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!fa())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};al.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let vi=al;function ll(s,e){if(!(s instanceof gt)){let t=e?ge.INDEX:ge.VERTEX;s instanceof Array&&(e?(s=new Uint32Array(s),t=ge.INDEX|ge.COPY_DST):(s=new Float32Array(s),t=ge.VERTEX|ge.COPY_DST)),s=new gt({data:s,label:e?"index-mesh-buffer":"vertex-mesh-buffer",usage:t})}return s}function um(s,e,t){const i=s.getAttribute(e);if(!i)return t.minX=0,t.minY=0,t.maxX=0,t.maxY=0,t;const r=i.buffer.data;let n=1/0,o=1/0,a=-1/0,l=-1/0;const c=r.BYTES_PER_ELEMENT,h=(i.offset||0)/c,u=(i.stride||8)/c;for(let f=h;f<r.length;f+=u){const d=r[f],g=r[f+1];d>a&&(a=d),g>l&&(l=g),d<n&&(n=d),g<o&&(o=g)}return t.minX=n,t.minY=o,t.maxX=a,t.maxY=l,t}function dm(s){return(s instanceof gt||Array.isArray(s)||s.BYTES_PER_ELEMENT)&&(s={buffer:s}),s.buffer=ll(s.buffer,!1),s}class Qs extends lt{constructor(e={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=be("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new Ye,this._boundsDirty=!0;const{attributes:t,indexBuffer:i,topology:r}=e;if(this.buffers=[],this.attributes={},t)for(const n in t)this.addAttribute(n,t[n]);this.instanceCount=e.instanceCount??1,i&&this.addIndex(i),this.topology=r||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(e){return this.attributes[e]}getIndex(){return this.indexBuffer}getBuffer(e){return this.getAttribute(e).buffer}getSize(){for(const e in this.attributes){const t=this.attributes[e];return t.buffer.data.length/(t.stride/4||t.size)}return 0}addAttribute(e,t){const i=dm(t);this.buffers.indexOf(i.buffer)===-1&&(this.buffers.push(i.buffer),i.buffer.on("update",this.onBufferUpdate,this),i.buffer.on("change",this.onBufferUpdate,this)),this.attributes[e]=i}addIndex(e){this.indexBuffer=ll(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,um(this,"aPosition",this._bounds)):this._bounds}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){var t;this.emit("destroy",this),this.removeAllListeners(),e&&this.buffers.forEach(i=>i.destroy()),this.unload(),(t=this.indexBuffer)==null||t.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}class Ci{constructor(e){typeof e=="number"?this.rawBinaryData=new ArrayBuffer(e):e instanceof Uint8Array?this.rawBinaryData=e.buffer:this.rawBinaryData=e,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(e){return this[`${e}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(e){switch(e){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${e} isn't a valid view type`)}}}function cl(s,e=null){const t=s*6;if(t>65535?e||(e=new Uint32Array(t)):e||(e=new Uint16Array(t)),e.length!==t)throw new Error(`Out buffer length is incorrect, got ${e.length} and expected ${t}`);for(let i=0,r=0;i<t;i+=6,r+=4)e[i+0]=r+0,e[i+1]=r+1,e[i+2]=r+2,e[i+3]=r+0,e[i+4]=r+2,e[i+5]=r+3;return e}function fm(s){return{dynamicUpdate:hl(s,!0),staticUpdate:hl(s,!1)}}function hl(s,e){const t=[];t.push(`
285
285
 
286
286
  var index = 0;
287
287
 
@@ -295,7 +295,7 @@ Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!mi.noColor
295
295
  `),t.unshift(`
296
296
  var stride = ${i};
297
297
  `);const r=t.join(`
298
- `);return new Function("ps","f32v","u32v",r)}class fm{constructor(e){this._size=0,this._generateParticleUpdateCache={};const t=this._size=e.size??1e3,i=e.properties;let r=0,n=0;for(const h in i){const u=i[h],f=At(u.format);u.dynamic?n+=f.stride:r+=f.stride}this._dynamicStride=n/4,this._staticStride=r/4,this.staticAttributeBuffer=new Ci(t*4*r),this.dynamicAttributeBuffer=new Ci(t*4*n),this.indexBuffer=cl(t);const o=new Js;let a=0,l=0;this._staticBuffer=new gt({data:new Float32Array(1),label:"static-particle-buffer",shrinkToFit:!1,usage:ge.VERTEX|ge.COPY_DST}),this._dynamicBuffer=new gt({data:new Float32Array(1),label:"dynamic-particle-buffer",shrinkToFit:!1,usage:ge.VERTEX|ge.COPY_DST});for(const h in i){const u=i[h],f=At(u.format);u.dynamic?(o.addAttribute(u.attributeName,{buffer:this._dynamicBuffer,stride:this._dynamicStride*4,offset:a*4,format:u.format}),a+=f.size):(o.addAttribute(u.attributeName,{buffer:this._staticBuffer,stride:this._staticStride*4,offset:l*4,format:u.format}),l+=f.size)}o.addIndex(this.indexBuffer);const c=this.getParticleUpdate(i);this._dynamicUpload=c.dynamicUpdate,this._staticUpload=c.staticUpdate,this.geometry=o}getParticleUpdate(e){const t=pm(e);return this._generateParticleUpdateCache[t]?this._generateParticleUpdateCache[t]:(this._generateParticleUpdateCache[t]=this.generateParticleUpdate(e),this._generateParticleUpdateCache[t])}generateParticleUpdate(e){return dm(e)}update(e,t){e.length>this._size&&(t=!0,this._size=Math.max(e.length,this._size*1.5|0),this.staticAttributeBuffer=new Ci(this._size*this._staticStride*4*4),this.dynamicAttributeBuffer=new Ci(this._size*this._dynamicStride*4*4),this.indexBuffer=cl(this._size),this.geometry.indexBuffer.setDataWithSize(this.indexBuffer,this.indexBuffer.byteLength,!0));const i=this.dynamicAttributeBuffer;if(this._dynamicUpload(e,i.float32View,i.uint32View),this._dynamicBuffer.setDataWithSize(this.dynamicAttributeBuffer.float32View,e.length*this._dynamicStride*4,!0),t){const r=this.staticAttributeBuffer;this._staticUpload(e,r.float32View,r.uint32View),this._staticBuffer.setDataWithSize(r.float32View,e.length*this._staticStride*4,!0)}}destroy(){this._staticBuffer.destroy(),this._dynamicBuffer.destroy(),this.geometry.destroy()}}function pm(s){const e=[];for(const t in s){const i=s[t];e.push(t,i.code,i.dynamic?"d":"s")}return e.join("_")}const mm={aVertex:(s,e,t,i,r)=>{let n=0,o=0,a=0,l=0;for(let c=0;c<s.length;++c){const h=s[c],u=h.texture,f=h.scaleX,d=h.scaleY,g=h.anchorX,_=h.anchorY,b=u.trim,x=u.orig;b?(o=b.x-g*x.width,n=o+b.width,l=b.y-_*x.height,a=l+b.height):(n=x.width*(1-g),o=x.width*-g,a=x.height*(1-_),l=x.height*-_),e[i]=o*f,e[i+1]=l*d,e[i+r]=n*f,e[i+r+1]=l*d,e[i+r*2]=n*f,e[i+r*2+1]=a*d,e[i+r*3]=o*f,e[i+r*3+1]=a*d,i+=r*4}},aPosition:(s,e,t,i,r)=>{for(let n=0;n<s.length;++n){const o=s[n],a=o.x,l=o.y;e[i]=a,e[i+1]=l,e[i+r]=a,e[i+r+1]=l,e[i+r*2]=a,e[i+r*2+1]=l,e[i+r*3]=a,e[i+r*3+1]=l,i+=r*4}},aRotation:(s,e,t,i,r)=>{for(let n=0;n<s.length;++n){const o=s[n].rotation;e[i]=o,e[i+r]=o,e[i+r*2]=o,e[i+r*3]=o,i+=r*4}},aUV:(s,e,t,i,r)=>{for(let n=0;n<s.length;++n){const o=s[n].texture.uvs;e[i]=o.x0,e[i+1]=o.y0,e[i+r]=o.x1,e[i+r+1]=o.y1,e[i+r*2]=o.x2,e[i+r*2+1]=o.y2,e[i+r*3]=o.x3,e[i+r*3+1]=o.y3,i+=r*4}},aColor:(s,e,t,i,r)=>{for(let n=0;n<s.length;++n){const o=s[n].color;t[i]=o,t[i+r]=o,t[i+r*2]=o,t[i+r*3]=o,i+=r*4}}};function gm(s){const e=Object.values(s),t=e.filter(r=>r.dynamic),i=e.filter(r=>!r.dynamic);return{dynamicUpdate:ul(t),staticUpdate:ul(i)}}function ul(s){let e=0;const t=[];for(let i=0;i<s.length;i++){const r=s[i],n=At(r.format).stride/4;e+=n,t.push({stride:n,updateFunction:r.updateFunction||mm[r.attributeName]})}return(i,r,n)=>{let o=0;for(let a=0;a<t.length;a++){const l=t[a];l.updateFunction(i,r,n,o,e),o+=l.stride}}}function _m(){return ym}function ym(s,e,t){const i=s.gl,r=s.shader,n=r._getProgramData(e.glProgram);for(const o in e.groups){const a=e.groups[o];for(const l in a.resources){const c=a.resources[l];if(c instanceof ht)c.ubo?r.bindUniformBlock(c,e._uniformBindMap[o][l],t.blockIndex++):r.updateUniformGroup(c);else if(c instanceof Fs)r.bindUniformBlock(c,e._uniformBindMap[o][l],t.blockIndex++);else if(c instanceof De){s.texture.bind(c,t.textureCount);const h=e._uniformBindMap[o][l],u=n.uniformData[h];u&&(u.value!==t.textureCount&&i.uniform1i(u.location,t.textureCount),t.textureCount++)}}}}const bm=[(s,e,t,i,r)=>{const n=i[s].toArray(!0);e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+4]=n[3],e[t+5]=n[4],e[t+6]=n[5],e[t+8]=n[6],e[t+9]=n[7],e[t+10]=n[8]},(s,e,t,i,r)=>{r=i[s],e[t]=r.x,e[t+1]=r.y,e[t+2]=r.width,e[t+3]=r.height},(s,e,t,i,r)=>{r=i[s],e[t]=r.x,e[t+1]=r.y},(s,e,t,i,r)=>{r=i[s],e[t]=r.red,e[t+1]=r.green,e[t+2]=r.blue,e[t+3]=r.alpha},(s,e,t,i,r)=>{r=i[s],e[t]=r.red,e[t+1]=r.green,e[t+2]=r.blue}],xm={f32:(s,e,t,i,r)=>{e[t]=r},i32:(s,e,t,i,r)=>{e[t]=r},"vec2<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1]},"vec3<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2]},"vec4<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3]},"mat2x2<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3]},"mat3x3<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+4]=r[3],e[t+5]=r[4],e[t+6]=r[5],e[t+8]=r[6],e[t+9]=r[7],e[t+10]=r[8]},"mat4x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<16;n++)e[t+n]=r[n]},"mat3x2<f32>":(s,e,t,i,r)=>{for(let n=0;n<6;n++)e[t+(n/3|0)*4+n%3]=r[n]},"mat4x2<f32>":(s,e,t,i,r)=>{for(let n=0;n<8;n++)e[t+(n/4|0)*4+n%4]=r[n]},"mat2x3<f32>":(s,e,t,i,r)=>{for(let n=0;n<6;n++)e[t+(n/2|0)*4+n%2]=r[n]},"mat4x3<f32>":(s,e,t,i,r)=>{for(let n=0;n<12;n++)e[t+(n/4|0)*4+n%4]=r[n]},"mat2x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<8;n++)e[t+(n/2|0)*4+n%2]=r[n]},"mat3x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<12;n++)e[t+(n/3|0)*4+n%3]=r[n]}},vm={f32:(s,e,t,i,r)=>{e[t]=r},i32:(s,e,t,i,r)=>{e[t]=r},"vec2<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1]},"vec3<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2]},"vec4<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3]},"mat2x2<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+4]=r[2],e[t+5]=r[3]},"mat3x3<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+4]=r[3],e[t+5]=r[4],e[t+6]=r[5],e[t+8]=r[6],e[t+9]=r[7],e[t+10]=r[8]},"mat4x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<16;n++)e[t+n]=r[n]},"mat3x2<f32>":(s,e,t,i,r)=>{for(let n=0;n<6;n++)e[t+(n/3|0)*4+n%3]=r[n]},"mat4x2<f32>":(s,e,t,i,r)=>{for(let n=0;n<8;n++)e[t+(n/4|0)*4+n%4]=r[n]},"mat2x3<f32>":(s,e,t,i,r)=>{for(let n=0;n<6;n++)e[t+(n/2|0)*4+n%2]=r[n]},"mat4x3<f32>":(s,e,t,i,r)=>{for(let n=0;n<12;n++)e[t+(n/4|0)*4+n%4]=r[n]},"mat2x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<8;n++)e[t+(n/2|0)*4+n%2]=r[n]},"mat3x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<12;n++)e[t+(n/3|0)*4+n%3]=r[n]}};function Cm(s){return dl(s,vm,e=>{const t=Math.max(Wr[e.data.type]/16,1),i=e.data.value.length/e.data.size,r=(4-i%4)%4;return(n,o,a,l,c)=>{let h=0;for(let u=0;u<e.data.size*t;u++){for(let f=0;f<i;f++)o[a++]=c[h++];a+=r}}})}function Sm(s){return dl(s,xm,e=>{const{size:t,align:i}=Ki[e.data.type],r=(t-i)/4;return(n,o,a,l,c)=>{let h=0;for(let u=0;u<e.data.size*(t/4);u++){for(let f=0;f<t/4;f++)o[a++]=c[h++];a+=r}}})}function dl(s,e,t){const i={};for(const r in s){const n=s[r],o=n.data;let a=!1;i[o.name]={offset:n.offset/4,func:null};for(let l=0;l<ct.length;l++){const c=ct[l];if(o.type===c.type&&c.test(o)){i[o.name].func=bm[l],a=!0;break}}a||(o.size===1?i[o.name].func=e[o.type]:i[o.name].func=t(n))}return(r,n,o)=>{for(const a in i)i[a].func(a,n,o+i[a].offset,r,r[a])}}const Em={f32(s,e,t,i,r,n,o){t!==i&&(e.value=i,o.uniform1f(r[s].location,i))},"vec2<f32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1])&&(t[0]=i[0],t[1]=i[1],o.uniform2f(r[s].location,i[0],i[1]))},"vec3<f32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],o.uniform3f(r[s].location,i[0],i[1],i[2]))},"vec4<f32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2]||t[3]!==i[3])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],o.uniform4f(r[s].location,i[0],i[1],i[2],i[3]))},i32(s,e,t,i,r,n,o){t!==i&&(e.value=i,o.uniform1i(r[s].location,i))},"vec2<i32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1])&&(t[0]=i[0],t[1]=i[1],o.uniform2i(r[s].location,i[0],i[1]))},"vec3<i32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],o.uniform3i(r[s].location,i[0],i[1],i[2]))},"vec4<i32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2]||t[3]!==i[3])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],o.uniform4i(r[s].location,i[0],i[1],i[2],i[3]))},u32(s,e,t,i,r,n,o){t!==i&&(e.value=i,o.uniform1ui(r[s].location,i))},"vec2<u32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1])&&(t[0]=i[0],t[1]=i[1],o.uniform2ui(r[s].location,i[0],i[1]))},"vec3<u32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],o.uniform3ui(r[s].location,i[0],i[1],i[2]))},"vec4<u32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2]||t[3]!==i[3])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],o.uniform4ui(r[s].location,i[0],i[1],i[2],i[3]))},bool(s,e,t,i,r,n,o){t!==i&&(e.value=i,o.uniform1i(r[s].location,i))},"vec2<bool>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1])&&(t[0]=i[0],t[1]=i[1],o.uniform2i(r[s].location,i[0],i[1]))},"vec3<bool>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],o.uniform3i(r[s].location,i[0],i[1],i[2]))},"vec4<bool>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2]||t[3]!==i[3])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],o.uniform4i(r[s].location,i[0],i[1],i[2],i[3]))},"mat2x2<f32>"(s,e,t,i,r,n,o){o.uniformMatrix2fv(r[s].location,!1,i)},"mat3x3<f32>"(s,e,t,i,r,n,o){o.uniformMatrix3fv(r[s].location,!1,i)},"mat4x4<f32>"(s,e,t,i,r,n,o){o.uniformMatrix4fv(r[s].location,!1,i)}},Tm={f32(s,e,t,i,r,n,o){o.uniform1fv(r[s].location,i)},"vec2<f32>"(s,e,t,i,r,n,o){o.uniform2fv(r[s].location,i)},"vec3<f32>"(s,e,t,i,r,n,o){o.uniform3fv(r[s].location,i)},"vec4<f32>"(s,e,t,i,r,n,o){o.uniform4fv(r[s].location,i)},"mat2x2<f32>"(s,e,t,i,r,n,o){o.uniformMatrix2fv(r[s].location,!1,i)},"mat3x3<f32>"(s,e,t,i,r,n,o){o.uniformMatrix3fv(r[s].location,!1,i)},"mat4x4<f32>"(s,e,t,i,r,n,o){o.uniformMatrix4fv(r[s].location,!1,i)},i32(s,e,t,i,r,n,o){o.uniform1iv(r[s].location,i)},"vec2<i32>"(s,e,t,i,r,n,o){o.uniform2iv(r[s].location,i)},"vec3<i32>"(s,e,t,i,r,n,o){o.uniform3iv(r[s].location,i)},"vec4<i32>"(s,e,t,i,r,n,o){o.uniform4iv(r[s].location,i)},u32(s,e,t,i,r,n,o){o.uniform1iv(r[s].location,i)},"vec2<u32>"(s,e,t,i,r,n,o){o.uniform2iv(r[s].location,i)},"vec3<u32>"(s,e,t,i,r,n,o){o.uniform3iv(r[s].location,i)},"vec4<u32>"(s,e,t,i,r,n,o){o.uniform4iv(r[s].location,i)},bool(s,e,t,i,r,n,o){o.uniform1iv(r[s].location,i)},"vec2<bool>"(s,e,t,i,r,n,o){o.uniform2iv(r[s].location,i)},"vec3<bool>"(s,e,t,i,r,n,o){o.uniform3iv(r[s].location,i)},"vec4<bool>"(s,e,t,i,r,n,o){o.uniform4iv(r[s].location,i)}},Am=[(s,e,t,i,r,n,o)=>{o.uniformMatrix3fv(r[s].location,!1,n[s].toArray(!0))},(s,e,t,i,r,n,o)=>{t=r[s].value,i=n[s],(t[0]!==i.x||t[1]!==i.y||t[2]!==i.width||t[3]!==i.height)&&(t[0]=i.x,t[1]=i.y,t[2]=i.width,t[3]=i.height,o.uniform4f(r[s].location,i.x,i.y,i.width,i.height))},(s,e,t,i,r,n,o)=>{t=r[s].value,i=n[s],(t[0]!==i.x||t[1]!==i.y)&&(t[0]=i.x,t[1]=i.y,o.uniform2f(r[s].location,i.x,i.y))},(s,e,t,i,r,n,o)=>{t=r[s].value,i=n[s],(t[0]!==i.red||t[1]!==i.green||t[2]!==i.blue||t[3]!==i.alpha)&&(t[0]=i.red,t[1]=i.green,t[2]=i.blue,t[3]=i.alpha,o.uniform4f(r[s].location,i.red,i.green,i.blue,i.alpha))},(s,e,t,i,r,n,o)=>{t=r[s].value,i=n[s],(t[0]!==i.red||t[1]!==i.green||t[2]!==i.blue)&&(t[0]=i.red,t[1]=i.green,t[2]=i.blue,o.uniform3f(r[s].location,i.red,i.green,i.blue))}];function wm(s,e){const t={};for(const i in s.uniformStructures){if(!e[i])continue;const r=s.uniformStructures[i];let n=!1;for(let o=0;o<ct.length;o++){const a=ct[o];if(r.type===a.type&&a.test(r)){t[i]=Am[o],n=!0;break}}if(!n){const o=r.size===1?Em:Tm;t[i]=o[r.type]}}return(i,r,n)=>{const o=n.gl;for(const a in t){const l=r[a],c=i[a],h=i[a].value;t[a](a,c,h,l,i,r,o)}}}function Im(){Object.assign(vi.prototype,{_unsafeEvalCheck(){}}),Object.assign(Lr.prototype,{_systemCheck(){}}),Object.assign(Yr.prototype,{_generateUniformsSync:wm}),Object.assign(Hr.prototype,{_generateUboSync:Cm}),Object.assign(qr.prototype,{_generateUboSync:Sm}),Object.assign(Xr.prototype,{_generateShaderSync:_m}),Object.assign(fm.prototype,{generateParticleUpdate:gm})}Im();const Rm={extension:{type:A.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>nS)}},Mm={extension:{type:A.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>oS)}};function Pm(s,e,t){const{width:i,height:r}=t.orig,n=t.trim;if(n){const o=n.width,a=n.height;s.minX=n.x-e._x*i,s.maxX=s.minX+o,s.minY=n.y-e._y*r,s.maxY=s.minY+a}else s.minX=-e._x*i,s.maxX=s.minX+i,s.minY=-e._y*r,s.maxY=s.minY+r}class fl extends Ve{constructor(e){super(e),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this._bounds=new Ye(0,1,0,0),this._boundsDirty=!0,this.autoGarbageCollect=e.autoGarbageCollect??!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(e){this._roundPixels=e?1:0}containsPoint(e){const t=this.bounds,{x:i,y:r}=e;return i>=t.minX&&i<=t.maxX&&r>=t.minY&&r<=t.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const e=this.renderGroup||this.parentRenderGroup;e&&e.onChildViewUpdate(this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(e){this.unload(),super.destroy(e),this._bounds=null}collectRenderablesSimple(e,t,i){const{renderPipes:r}=t;r.blendMode.pushBlendMode(this,this.groupBlendMode,e);const o=r[this.renderPipeId];o!=null&&o.addRenderable&&o.addRenderable(this,e),this.didViewUpdate=!1;const a=this.children,l=a.length;for(let c=0;c<l;c++)a[c].collectRenderables(e,t,i);r.blendMode.popBlendMode(e)}}class Ft extends fl{constructor(e=j.EMPTY){e instanceof j&&(e={texture:e});const{texture:t=j.EMPTY,anchor:i,roundPixels:r,width:n,height:o,...a}=e;super({label:"Sprite",...a}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new je({_onUpdate:()=>{this.onViewUpdate()}}),i?this.anchor=i:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=r??!1,n!==void 0&&(this.width=n),o!==void 0&&(this.height=o)}static from(e,t=!1){return e instanceof j?new Ft(e):new Ft(j.from(e,t))}set texture(e){e||(e=j.EMPTY);const t=this._texture;t!==e&&(t&&t.dynamic&&t.off("update",this.onViewUpdate,this),e.dynamic&&e.on("update",this.onViewUpdate,this),this._texture=e,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return Pm(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return ee("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const e=this._anchor,t=this._texture,i=this._bounds,{width:r,height:n}=t.orig;i.minX=-e._x*r,i.maxX=i.minX+r,i.minY=-e._y*n,i.maxY=i.minY+n}destroy(e=!1){if(super.destroy(e),typeof e=="boolean"?e:e==null?void 0:e.texture){const i=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._texture.destroy(i)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(e){this._setWidth(e,this._texture.orig.width),this._width=e}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(e){this._setHeight(e,this._texture.orig.height),this._height=e}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this._texture.orig.width,e.height=Math.abs(this.scale.y)*this._texture.orig.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this._texture.orig.width),t!==void 0&&this._setHeight(t,this._texture.orig.height)}}const km=new Ye;function pl(s,e,t){const i=km;s.measurable=!0,nn(s,t,i),e.addBoundsMask(i),s.measurable=!1}function ml(s,e,t){const i=It.get();s.measurable=!0;const r=qe.get().identity(),n=gl(s,t,r);an(s,i,n),s.measurable=!1,e.addBoundsMask(i),qe.return(r),It.return(i)}function gl(s,e,t){return s?(s!==e&&(gl(s.parent,e,t),s.updateLocalTransform(),t.append(s.localTransform)),t):(se("Mask bounds, renderable is not inside the root container"),t)}class _l{constructor(e){this.priority=0,this.inverse=!1,this.pipe="alphaMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof Ft),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(e,t){this.inverse||pl(this.mask,e,t)}addLocalBounds(e,t){ml(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof Ft}}_l.extension=A.MaskEffect;class yl{constructor(e){this.priority=0,this.pipe="colorMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e=="number"}}yl.extension=A.MaskEffect;class bl{constructor(e){this.priority=0,this.pipe="stencilMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(e,t){pl(this.mask,e,t)}addLocalBounds(e,t){ml(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof Ve}}bl.extension=A.MaskEffect;let xl={createCanvas:(s,e)=>{const t=document.createElement("canvas");return t.width=s,t.height=e,t},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(s,e)=>fetch(s,e),parseXML:s=>new DOMParser().parseFromString(s,"text/xml")};const pe={get(){return xl},set(s){xl=s}};class yt extends De{constructor(e){e.resource||(e.resource=pe.get().createCanvas()),e.width||(e.width=e.resource.width,e.autoDensity||(e.width/=e.resolution)),e.height||(e.height=e.resource.height,e.autoDensity||(e.height/=e.resolution)),super(e),this.uploadMethodId="image",this.autoDensity=e.autoDensity,this.resizeCanvas(),this.transparent=!!e.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(e=this.width,t=this.height,i=this._resolution){const r=super.resize(e,t,i);return r&&this.resizeCanvas(),r}static test(e){return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&e instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}yt.extension=A.TextureSource;class Qs extends De{constructor(e){super(e),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(e){return globalThis.HTMLImageElement&&e instanceof HTMLImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||globalThis.VideoFrame&&e instanceof VideoFrame}}Qs.extension=A.TextureSource;var Si=(s=>(s[s.INTERACTION=50]="INTERACTION",s[s.HIGH=25]="HIGH",s[s.NORMAL=0]="NORMAL",s[s.LOW=-25]="LOW",s[s.UTILITY=-50]="UTILITY",s))(Si||{});class _n{constructor(e,t=null,i=0,r=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=i,this._once=r}match(e,t=null){return this._fn===e&&this._context===t}emit(e){this._fn&&(this._context?this._fn.call(this._context,e):this._fn(e));const t=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),t}connect(e){this.previous=e,e.next&&(e.next.previous=this),this.next=e.next,e.next=this}destroy(e=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const t=this.next;return this.next=e?null:t,this.previous=null,t}}const vl=class nt{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new _n(null,null,1/0),this.deltaMS=1/nt.targetFPMS,this.elapsedMS=1/nt.targetFPMS,this._tick=e=>{this._requestId=null,this.started&&(this.update(e),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(e,t,i=Si.NORMAL){return this._addListener(new _n(e,t,i))}addOnce(e,t,i=Si.NORMAL){return this._addListener(new _n(e,t,i,!0))}_addListener(e){let t=this._head.next,i=this._head;if(!t)e.connect(i);else{for(;t;){if(e.priority>t.priority){e.connect(i);break}i=t,t=t.next}e.previous||e.connect(i)}return this._startIfPossible(),this}remove(e,t){let i=this._head.next;for(;i;)i.match(e,t)?i=i.destroy():i=i.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let e=0,t=this._head;for(;t=t.next;)e++;return e}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let e=this._head.next;for(;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let t;if(e>this.lastTime){if(t=this.elapsedMS=e-this.lastTime,t>this._maxElapsedMS&&(t=this._maxElapsedMS),t*=this.speed,this._minElapsedMS){const n=e-this._lastFrame|0;if(n<this._minElapsedMS)return;this._lastFrame=e-n%this._minElapsedMS}this.deltaMS=t,this.deltaTime=this.deltaMS*nt.targetFPMS;const i=this._head;let r=i.next;for(;r;)r=r.emit(this);i.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=e}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(e){const t=Math.min(Math.max(0,e)/1e3,nt.targetFPMS);this._maxElapsedMS=1/t,this._minElapsedMS&&e>this.maxFPS&&(this.maxFPS=e)}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(e){e===0?this._minElapsedMS=0:(e<this.minFPS&&(this.minFPS=e),this._minElapsedMS=1/(e/1e3))}static get shared(){if(!nt._shared){const e=nt._shared=new nt;e.autoStart=!0,e._protected=!0}return nt._shared}static get system(){if(!nt._system){const e=nt._system=new nt;e.autoStart=!0,e._protected=!0}return nt._system}};vl.targetFPMS=.06;let at=vl,yn;async function Om(){return yn??(yn=(async()=>{var o;const e=pe.get().createCanvas(1,1).getContext("webgl");if(!e)return"premultiply-alpha-on-upload";const t=await new Promise(a=>{const l=document.createElement("video");l.onloadeddata=()=>a(l),l.onerror=()=>a(null),l.autoplay=!1,l.crossOrigin="anonymous",l.preload="auto",l.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",l.load()});if(!t)return"premultiply-alpha-on-upload";const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t);const n=new Uint8Array(4);return e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,n),e.deleteFramebuffer(r),e.deleteTexture(i),(o=e.getExtension("WEBGL_lose_context"))==null||o.loseContext(),n[0]<=n[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),yn}const er=class mf extends De{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...mf.defaultOptions,...e},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=e.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=e.autoPlay!==!1,this.alphaMode=e.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),e.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const e=at.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-e)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const e=this.resource,t=this.options;return(e.readyState===e.HAVE_ENOUGH_DATA||e.readyState===e.HAVE_FUTURE_DATA)&&e.width&&e.height&&(e.complete=!0),e.addEventListener("play",this._onPlayStart),e.addEventListener("pause",this._onPlayStop),e.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(t.preload||e.addEventListener("canplay",this._onCanPlay),e.addEventListener("canplaythrough",this._onCanPlayThrough),e.addEventListener("error",this._onError,!0)),this.alphaMode=await Om(),this._load=new Promise((i,r)=>{this.isValid?i(this):(this._resolve=i,this._reject=r,t.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${t.preloadTimeoutMs}ms`))})),e.load())}),this._load}_onError(e){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",e),this._reject&&(this._reject(e),this._reject=null,this._resolve=null)}_isSourcePlaying(){const e=this.resource;return!e.paused&&!e.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const e=this.resource;this.isValid&&(this.isReady=!0,this.resize(e.videoWidth,e.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const e=this.resource;e&&(e.removeEventListener("play",this._onPlayStart),e.removeEventListener("pause",this._onPlayStop),e.removeEventListener("seeked",this._onSeeked),e.removeEventListener("canplay",this._onCanPlay),e.removeEventListener("canplaythrough",this._onCanPlayThrough),e.removeEventListener("error",this._onError,!0),e.pause(),e.src="",e.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(e){e!==this._updateFPS&&(this._updateFPS=e,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(at.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(at.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(at.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};er.extension=A.TextureSource,er.defaultOptions={...De.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},er.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Bm=er;const Ei=(s,e,t=!1)=>(Array.isArray(s)||(s=[s]),e?s.map(i=>typeof i=="string"||t?e(i):i):s);class Dm{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(e){return this._cache.has(e)}get(e){const t=this._cache.get(e);return t||se(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const i=Ei(e);let r;for(let l=0;l<this.parsers.length;l++){const c=this.parsers[l];if(c.test(t)){r=c.getCacheableAssets(i,t);break}}const n=new Map(Object.entries(r||{}));r||i.forEach(l=>{n.set(l,t)});const o=[...n.keys()],a={cacheKeys:o,keys:i};i.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const c=r?r[l]:t;this._cache.has(l)&&this._cache.get(l)!==c&&se("[Cache] already has key:",l),this._cache.set(l,n.get(l))})}remove(e){if(!this._cacheMap.has(e)){se(`[Assets] Asset id ${e} was not found in the Cache`);return}const t=this._cacheMap.get(e);t.cacheKeys.forEach(r=>{this._cache.delete(r)}),t.keys.forEach(r=>{this._cacheMap.delete(r)})}get parsers(){return this._parsers}}const Ti=new Dm,bn=[];Q.handleByList(A.TextureSource,bn);function Cl(s={}){const e=s&&s.resource,t=e?s.resource:s,i=e?s:{resource:s};for(let r=0;r<bn.length;r++){const n=bn[r];if(n.test(t))return new n(i)}throw new Error(`Could not find a source type for resource: ${i.resource}`)}function Nm(s={},e=!1){const t=s&&s.resource,i=t?s.resource:s,r=t?s:{resource:s};if(!e&&Ti.has(i))return Ti.get(i);const n=new j({source:Cl(r)});return n.on("destroy",()=>{Ti.has(i)&&Ti.remove(i)}),e||Ti.set(i,n),n}function Um(s,e=!1){return typeof s=="string"?Ti.get(s):s instanceof De?new j({source:s}):Nm(s,e)}j.from=Um,De.from=Cl,Q.add(_l,yl,bl,Bm,Qs,yt,hn);var Sl=(s=>(s[s.Low=0]="Low",s[s.Normal=1]="Normal",s[s.High=2]="High",s))(Sl||{});function ut(s){if(typeof s!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(s)}`)}function ss(s){return s.split("?")[0].split("#")[0]}function Fm(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gm(s,e,t){return s.replace(new RegExp(Fm(e),"g"),t)}function Lm(s,e){let t="",i=0,r=-1,n=0,o=-1;for(let a=0;a<=s.length;++a){if(a<s.length)o=s.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(r===a-1||n===1))if(r!==a-1&&n===2){if(t.length<2||i!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){const l=t.lastIndexOf("/");if(l!==t.length-1){l===-1?(t="",i=0):(t=t.slice(0,l),i=t.length-1-t.lastIndexOf("/")),r=a,n=0;continue}}else if(t.length===2||t.length===1){t="",i=0,r=a,n=0;continue}}}else t.length>0?t+=`/${s.slice(r+1,a)}`:t=s.slice(r+1,a),i=a-r-1;r=a,n=0}else o===46&&n!==-1?++n:n=-1}return t}const rs={toPosix(s){return Gm(s,"\\","/")},isUrl(s){return/^https?:/.test(this.toPosix(s))},isDataUrl(s){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(s)},isBlobUrl(s){return s.startsWith("blob:")},hasProtocol(s){return/^[^/:]+:/.test(this.toPosix(s))},getProtocol(s){ut(s),s=this.toPosix(s);const e=/^file:\/\/\//.exec(s);if(e)return e[0];const t=/^[^/:]+:\/{0,2}/.exec(s);return t?t[0]:""},toAbsolute(s,e,t){if(ut(s),this.isDataUrl(s)||this.isBlobUrl(s))return s;const i=ss(this.toPosix(e??pe.get().getBaseUrl())),r=ss(this.toPosix(t??this.rootname(i)));return s=this.toPosix(s),s.startsWith("/")?rs.join(r,s.slice(1)):this.isAbsolute(s)?s:this.join(i,s)},normalize(s){if(ut(s),s.length===0)return".";if(this.isDataUrl(s)||this.isBlobUrl(s))return s;s=this.toPosix(s);let e="";const t=s.startsWith("/");this.hasProtocol(s)&&(e=this.rootname(s),s=s.slice(e.length));const i=s.endsWith("/");return s=Lm(s),s.length>0&&i&&(s+="/"),t?`/${s}`:e+s},isAbsolute(s){return ut(s),s=this.toPosix(s),this.hasProtocol(s)?!0:s.startsWith("/")},join(...s){if(s.length===0)return".";let e;for(let t=0;t<s.length;++t){const i=s[t];if(ut(i),i.length>0)if(e===void 0)e=i;else{const r=s[t-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?e+=`/../${i}`:e+=`/${i}`}}return e===void 0?".":this.normalize(e)},dirname(s){if(ut(s),s.length===0)return".";s=this.toPosix(s);let e=s.charCodeAt(0);const t=e===47;let i=-1,r=!0;const n=this.getProtocol(s),o=s;s=s.slice(n.length);for(let a=s.length-1;a>=1;--a)if(e=s.charCodeAt(a),e===47){if(!r){i=a;break}}else r=!1;return i===-1?t?"/":this.isUrl(o)?n+s:n:t&&i===1?"//":n+s.slice(0,i)},rootname(s){ut(s),s=this.toPosix(s);let e="";if(s.startsWith("/")?e="/":e=this.getProtocol(s),this.isUrl(s)){const t=s.indexOf("/",e.length);t!==-1?e=s.slice(0,t):e=s,e.endsWith("/")||(e+="/")}return e},basename(s,e){ut(s),e&&ut(e),s=ss(this.toPosix(s));let t=0,i=-1,r=!0,n;if(e!==void 0&&e.length>0&&e.length<=s.length){if(e.length===s.length&&e===s)return"";let o=e.length-1,a=-1;for(n=s.length-1;n>=0;--n){const l=s.charCodeAt(n);if(l===47){if(!r){t=n+1;break}}else a===-1&&(r=!1,a=n+1),o>=0&&(l===e.charCodeAt(o)?--o===-1&&(i=n):(o=-1,i=a))}return t===i?i=a:i===-1&&(i=s.length),s.slice(t,i)}for(n=s.length-1;n>=0;--n)if(s.charCodeAt(n)===47){if(!r){t=n+1;break}}else i===-1&&(r=!1,i=n+1);return i===-1?"":s.slice(t,i)},extname(s){ut(s),s=ss(this.toPosix(s));let e=-1,t=0,i=-1,r=!0,n=0;for(let o=s.length-1;o>=0;--o){const a=s.charCodeAt(o);if(a===47){if(!r){t=o+1;break}continue}i===-1&&(r=!1,i=o+1),a===46?e===-1?e=o:n!==1&&(n=1):e!==-1&&(n=-1)}return e===-1||i===-1||n===0||n===1&&e===i-1&&e===t+1?"":s.slice(e,i)},parse(s){ut(s);const e={root:"",dir:"",base:"",ext:"",name:""};if(s.length===0)return e;s=ss(this.toPosix(s));let t=s.charCodeAt(0);const i=this.isAbsolute(s);let r;e.root=this.rootname(s),i||this.hasProtocol(s)?r=1:r=0;let n=-1,o=0,a=-1,l=!0,c=s.length-1,h=0;for(;c>=r;--c){if(t=s.charCodeAt(c),t===47){if(!l){o=c+1;break}continue}a===-1&&(l=!1,a=c+1),t===46?n===-1?n=c:h!==1&&(h=1):n!==-1&&(h=-1)}return n===-1||a===-1||h===0||h===1&&n===a-1&&n===o+1?a!==-1&&(o===0&&i?e.base=e.name=s.slice(1,a):e.base=e.name=s.slice(o,a)):(o===0&&i?(e.name=s.slice(1,n),e.base=s.slice(1,a)):(e.name=s.slice(o,n),e.base=s.slice(o,a)),e.ext=s.slice(n,a)),e.dir=this.dirname(s),e},sep:"/",delimiter:":",joinExtensions:[".html"]};function El(s,e,t,i,r){const n=e[t];for(let o=0;o<n.length;o++){const a=n[o];t<e.length-1?El(s.replace(i[t],a),e,t+1,i,r):r.push(s.replace(i[t],a))}}function Wm(s){const e=/\{(.*?)\}/g,t=s.match(e),i=[];if(t){const r=[];t.forEach(n=>{const o=n.substring(1,n.length-1).split(",");r.push(o)}),El(s,r,0,t,i)}else i.push(s);return i}const Tl=s=>!Array.isArray(s);class Al{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(e,t)=>`${e}${this._bundleIdConnector}${t}`,extractAssetIdFromBundle:(e,t)=>t.replace(`${e}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(e){if(this._bundleIdConnector=e.connector??this._bundleIdConnector,this._createBundleAssetId=e.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=e.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...e){e.forEach(t=>{this._preferredOrder.push(t),t.priority||(t.priority=Object.keys(t.params))}),this._resolverHash={}}set basePath(e){this._basePath=e}get basePath(){return this._basePath}set rootPath(e){this._rootPath=e}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(e){if(typeof e=="string")this._defaultSearchParams=e;else{const t=e;this._defaultSearchParams=Object.keys(t).map(i=>`${encodeURIComponent(i)}=${encodeURIComponent(t[i])}`).join("&")}}getAlias(e){const{alias:t,src:i}=e;return Ei(t||i,n=>typeof n=="string"?n:Array.isArray(n)?n.map(o=>(o==null?void 0:o.src)??o):n!=null&&n.src?n.src:n,!0)}removeAlias(e,t){this._assetMap[e]&&(t&&t!==this._resolverHash[e]||(delete this._resolverHash[e],delete this._assetMap[e]))}addManifest(e){this._manifest&&se("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=e,e.bundles.forEach(t=>{this.addBundle(t.name,t.assets)})}addBundle(e,t){const i=[];let r=t;Array.isArray(t)||(r=Object.entries(t).map(([n,o])=>typeof o=="string"||Array.isArray(o)?{alias:n,src:o}:{alias:n,...o})),r.forEach(n=>{const o=n.src,a=n.alias;let l;if(typeof a=="string"){const c=this._createBundleAssetId(e,a);i.push(c),l=[a,c]}else{const c=a.map(h=>this._createBundleAssetId(e,h));i.push(...c),l=[...a,...c]}this.add({...n,alias:l,src:o})}),this._bundles[e]=i}add(e){const t=[];Array.isArray(e)?t.push(...e):t.push(e);let i;i=n=>{this.hasKey(n)&&se(`[Resolver] already has key: ${n} overwriting`)},Ei(t).forEach(n=>{const{src:o}=n;let{data:a,format:l,loadParser:c,parser:h}=n;const u=Ei(o).map(_=>typeof _=="string"?Wm(_):Array.isArray(_)?_:[_]),f=this.getAlias(n);Array.isArray(f)?f.forEach(i):i(f);const d=[],g=_=>{const b=this._parsers.find(x=>x.test(_));return{src:_,...b==null?void 0:b.parse(_)}};u.forEach(_=>{_.forEach(b=>{let x={};if(typeof b!="object"?x=g(b):(a=b.data??a,l=b.format??l,(b.loadParser||b.parser)&&(c=b.loadParser??c,h=b.parser??h),x={...g(b.src),...b}),!f)throw new Error(`[Resolver] alias is undefined for this asset: ${x.src}`);x=this._buildResolvedAsset(x,{aliases:f,data:a,format:l,loadParser:c,parser:h,progressSize:n.progressSize}),d.push(x)})}),f.forEach(_=>{this._assetMap[_]=d})})}resolveBundle(e){const t=Tl(e);e=Ei(e);const i={};return e.forEach(r=>{const n=this._bundles[r];if(n){const o=this.resolve(n),a={};for(const l in o){const c=o[l];a[this._extractAssetIdFromBundle(r,l)]=c}i[r]=a}}),t?i[e[0]]:i}resolveUrl(e){const t=this.resolve(e);if(typeof e!="string"){const i={};for(const r in t)i[r]=t[r].src;return i}return t.src}resolve(e){const t=Tl(e);e=Ei(e);const i={};return e.forEach(r=>{if(!this._resolverHash[r])if(this._assetMap[r]){let n=this._assetMap[r];const o=this._getPreferredOrder(n);o==null||o.priority.forEach(a=>{o.params[a].forEach(l=>{const c=n.filter(h=>h[a]?h[a]===l:!1);c.length&&(n=c)})}),this._resolverHash[r]=n[0]}else this._resolverHash[r]=this._buildResolvedAsset({alias:[r],src:r},{});i[r]=this._resolverHash[r]}),t?i[e[0]]:i}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){const i=e[t],r=this._preferredOrder.find(n=>n.params.format.includes(i.format));if(r)return r}return this._preferredOrder[0]}_appendDefaultSearchParams(e){if(!this._defaultSearchParams)return e;const t=/\?/.test(e)?"&":"?";return`${e}${t}${this._defaultSearchParams}`}_buildResolvedAsset(e,t){const{aliases:i,data:r,loadParser:n,parser:o,format:a,progressSize:l}=t;return(this._basePath||this._rootPath)&&(e.src=rs.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=i??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...r||{},...e.data},e.loadParser=n??e.loadParser,e.parser=o??e.parser,e.format=a??e.format??Hm(e.src),l!==void 0&&(e.progressSize=l),e}}Al.RETINA_PREFIX=/@([0-9\.]+)x/;function Hm(s){return s.split(".").pop().split("?").shift().split("#").shift()}const wl=(s,e)=>{const t=e.split("?")[1];return t&&(s+=`?${t}`),s},Il=class Ns{constructor(e,t){this.linkedSheets=[];let i=e;(e==null?void 0:e.source)instanceof De&&(i={texture:e,data:t});const{texture:r,data:n,cachePrefix:o=""}=i;this.cachePrefix=o,this._texture=r instanceof j?r:null,this.textureSource=r.source,this.textures={},this.animations={},this.data=n;const a=parseFloat(n.meta.scale);a?(this.resolution=a,r.source.resolution=this.resolution):this.resolution=r.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(e=>{this._callback=e,this._batchIndex=0,this._frameKeys.length<=Ns.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}parseSync(){return this._processFrames(0,!0),this._processAnimations(),this.textures}_processFrames(e,t=!1){let i=e;const r=t?1/0:Ns.BATCH_SIZE;for(;i-e<r&&i<this._frameKeys.length;){const n=this._frameKeys[i],o=this._frames[n],a=o.frame;if(a){let l=null,c=null;const h=o.trimmed!==!1&&o.sourceSize?o.sourceSize:o.frame,u=new Se(0,0,Math.floor(h.w)/this.resolution,Math.floor(h.h)/this.resolution);o.rotated?l=new Se(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.h)/this.resolution,Math.floor(a.w)/this.resolution):l=new Se(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution),o.trimmed!==!1&&o.spriteSourceSize&&(c=new Se(Math.floor(o.spriteSourceSize.x)/this.resolution,Math.floor(o.spriteSourceSize.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution)),this.textures[n]=new j({source:this.textureSource,frame:l,orig:u,trim:c,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:n.toString()})}i++}}_processAnimations(){const e=this.data.animations||{};for(const t in e){this.animations[t]=[];for(let i=0;i<e[t].length;i++){const r=e[t][i];this.animations[t].push(this.textures[r])}}}_parseComplete(){const e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*Ns.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*Ns.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){var t;for(const i in this.textures)this.textures[i].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&((t=this._texture)==null||t.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};Il.BATCH_SIZE=1e3;let Rl=Il;const Vm=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Ml(s,e,t){const i={};if(s.forEach(r=>{i[r]=e}),Object.keys(e.textures).forEach(r=>{i[`${e.cachePrefix}${r}`]=e.textures[r]}),!t){const r=rs.dirname(s[0]);e.linkedSheets.forEach((n,o)=>{const a=Ml([`${r}/${e.data.meta.related_multi_packs[o]}`],n,!0);Object.assign(i,a)})}return i}const zm={extension:A.Asset,cache:{test:s=>s instanceof Rl,getCacheableAssets:(s,e)=>Ml(s,e,!1)},resolver:{extension:{type:A.ResolveParser,name:"resolveSpritesheet"},test:s=>{const t=s.split("?")[0].split("."),i=t.pop(),r=t.pop();return i==="json"&&Vm.includes(r)},parse:s=>{var t;const e=s.split(".");return{resolution:parseFloat(((t=Al.RETINA_PREFIX.exec(s))==null?void 0:t[1])??"1"),format:e[e.length-2],src:s}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:A.LoadParser,priority:Sl.Normal,name:"spritesheetLoader"},async testParse(s,e){return rs.extname(e.src).toLowerCase()===".json"&&!!s.frames},async parse(s,e,t){var u,f;const{texture:i,imageFilename:r,textureOptions:n,cachePrefix:o}=(e==null?void 0:e.data)??{};let a=rs.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(i instanceof j)l=i;else{const d=wl(a+(r??s.meta.image),e.src);l=(await t.load([{src:d,data:n}]))[d]}const c=new Rl({texture:l.source,data:s,cachePrefix:o});await c.parse();const h=(u=s==null?void 0:s.meta)==null?void 0:u.related_multi_packs;if(Array.isArray(h)){const d=[];for(const _ of h){if(typeof _!="string")continue;let b=a+_;(f=e.data)!=null&&f.ignoreMultiPack||(b=wl(b,e.src),d.push(t.load({src:b,data:{textureOptions:n,ignoreMultiPack:!0}})))}const g=await Promise.all(d);c.linkedSheets=g,g.forEach(_=>{_.linkedSheets=[c].concat(c.linkedSheets.filter(b=>b!==_))})}return c},async unload(s,e,t){await t.unload(s.textureSource._sourceOrigin),s.destroy(!1)}}};Q.add(zm);class Pl{constructor(e){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const t=this._canvas.getBoundingClientRect(),i=this._canvas.width,r=this._canvas.height,n=t.width/i*this._renderer.resolution,o=t.height/r*this._renderer.resolution,a=t.left,l=t.top,c=`translate(${a}px, ${l}px) scale(${n}, ${o})`;c!==this._lastTransform&&(this._domElement.style.transform=c,this._lastTransform=c)},this._domElement=e.domElement,this._renderer=e.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(e=>{for(const t of e){if(t.target!==this._canvas)continue;const i=this.canvas.width,r=this.canvas.height,n=t.contentRect.width/i*this._renderer.resolution,o=t.contentRect.height/r*this._renderer.resolution;(this._lastScaleX!==n||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=n,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||at.shared.add(this.updateTranslation,this,Si.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&at.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform="",this._lastScaleX=null,this._lastScaleY=null}}class ns{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=ns.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new xe,this.page=new xe,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=e}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(e,t,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,i,r,n){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var xn=/iPhone/i,kl=/iPod/i,Ol=/iPad/i,Bl=/\biOS-universal(?:.+)Mac\b/i,vn=/\bAndroid(?:.+)Mobile\b/i,Dl=/Android/i,Ai=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,tr=/Silk/i,Rt=/Windows Phone/i,Nl=/\bWindows(?:.+)ARM\b/i,Ul=/BlackBerry/i,Fl=/BB10/i,Gl=/Opera Mini/i,Ll=/\b(CriOS|Chrome)(?:.+)Mobile/i,Wl=/Mobile(?:.+)Firefox\b/i,Hl=function(s){return typeof s<"u"&&s.platform==="MacIntel"&&typeof s.maxTouchPoints=="number"&&s.maxTouchPoints>1&&typeof MSStream>"u"};function $m(s){return function(e){return e.test(s)}}function Vl(s){var e={userAgent:"",platform:"",maxTouchPoints:0};!s&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof s=="string"?e.userAgent=s:s&&s.userAgent&&(e={userAgent:s.userAgent,platform:s.platform,maxTouchPoints:s.maxTouchPoints||0});var t=e.userAgent,i=t.split("[FBAN");typeof i[1]<"u"&&(t=i[0]),i=t.split("Twitter"),typeof i[1]<"u"&&(t=i[0]);var r=$m(t),n={apple:{phone:r(xn)&&!r(Rt),ipod:r(kl),tablet:!r(xn)&&(r(Ol)||Hl(e))&&!r(Rt),universal:r(Bl),device:(r(xn)||r(kl)||r(Ol)||r(Bl)||Hl(e))&&!r(Rt)},amazon:{phone:r(Ai),tablet:!r(Ai)&&r(tr),device:r(Ai)||r(tr)},android:{phone:!r(Rt)&&r(Ai)||!r(Rt)&&r(vn),tablet:!r(Rt)&&!r(Ai)&&!r(vn)&&(r(tr)||r(Dl)),device:!r(Rt)&&(r(Ai)||r(tr)||r(vn)||r(Dl))||r(/\bokhttp\b/i)},windows:{phone:r(Rt),tablet:r(Nl),device:r(Rt)||r(Nl)},other:{blackberry:r(Ul),blackberry10:r(Fl),opera:r(Gl),firefox:r(Wl),chrome:r(Ll),device:r(Ul)||r(Fl)||r(Gl)||r(Wl)||r(Ll)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const jm=(Vl.default??Vl)(globalThis.navigator),Xm=9,zl=100,Ym=0,qm=0,$l=2,jl=1,Km=-1e3,Zm=-1e3,Jm=2,Cn=class gf{constructor(e,t=jm){this._mobileInfo=t,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(t.tablet||t.phone)&&this._createTouchHook(),this._renderer=e}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){const e=document.createElement("button");e.style.width=`${jl}px`,e.style.height=`${jl}px`,e.style.position="absolute",e.style.top=`${Km}px`,e.style.left=`${Zm}px`,e.style.zIndex=Jm.toString(),e.style.backgroundColor="#FF0000",e.title="select to enable accessibility for this content",e.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(e),this._hookDiv=e}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.position="absolute",this._div.style.top=`${Ym}px`,this._div.style.left=`${qm}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=$l.toString(),this._canvasObserver=new Pl({domElement:this._div,renderer:this._renderer})),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._deactivateOnMouseMove&&globalThis.document.addEventListener("mousemove",this._boundOnMouseMove,!0);const e=this._renderer.view.canvas;if(e.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{const t=new MutationObserver(()=>{e.parentNode&&(t.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});t.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){var e,t;if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const i of this._children)(e=i._accessibleDiv)!=null&&e.parentNode&&(i._accessibleDiv.parentNode.removeChild(i._accessibleDiv),i._accessibleDiv=null),i._accessibleActive=!1;for(const i in this._pools)this._pools[i].forEach(n=>{n.parentNode&&n.parentNode.removeChild(n)}),delete this._pools[i];(t=this._div)!=null&&t.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(e){if(!e.visible||!e.accessibleChildren)return;e.accessible&&(e._accessibleActive||this._addChild(e),e._renderId=this._renderId);const t=e.children;if(t)for(let i=0;i<t.length;i++)this._updateAccessibleObjects(t[i])}init(e){const i={accessibilityOptions:{...gf.defaultOptions,...(e==null?void 0:e.accessibilityOptions)||{}}};this.debug=i.accessibilityOptions.debug,this._activateOnTab=i.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=i.accessibilityOptions.deactivateOnMouseMove,i.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){const e=performance.now();if(this._mobileInfo.android.device&&e<this._androidUpdateCount||(this._androidUpdateCount=e+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;const t=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(const i of this._children)i._renderId===this._renderId&&t.add(this._children.indexOf(i))}for(let i=this._children.length-1;i>=0;i--){const r=this._children[i];t.has(i)||(r._accessibleDiv&&r._accessibleDiv.parentNode&&(r._accessibleDiv.parentNode.removeChild(r._accessibleDiv),this._getPool(r.accessibleType).push(r._accessibleDiv),r._accessibleDiv=null),r._accessibleActive=!1,za(this._children,i,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let i=0;i<this._children.length;i++){const r=this._children[i];if(!r._accessibleActive||!r._accessibleDiv)continue;const n=r._accessibleDiv,o=r.hitArea||r.getBounds().rectangle;if(r.hitArea){const a=r.worldTransform;n.style.left=`${a.tx+o.x*a.a}px`,n.style.top=`${a.ty+o.y*a.d}px`,n.style.width=`${o.width*a.a}px`,n.style.height=`${o.height*a.d}px`}else this._capHitArea(o),n.style.left=`${o.x}px`,n.style.top=`${o.y}px`,n.style.width=`${o.width}px`,n.style.height=`${o.height}px`}this._renderId++}_updateDebugHTML(e){e.innerHTML=`type: ${e.type}</br> title : ${e.title}</br> tabIndex: ${e.tabIndex}`}_capHitArea(e){e.x<0&&(e.width+=e.x,e.x=0),e.y<0&&(e.height+=e.y,e.y=0);const{width:t,height:i}=this._renderer;e.x+e.width>t&&(e.width=t-e.x),e.y+e.height>i&&(e.height=i-e.y)}_addChild(e){let i=this._getPool(e.accessibleType).pop();i?(i.innerHTML="",i.removeAttribute("title"),i.removeAttribute("aria-label"),i.tabIndex=0):(e.accessibleType==="button"?i=document.createElement("button"):(i=document.createElement(e.accessibleType),i.style.cssText=`
298
+ `);return new Function("ps","f32v","u32v",r)}class pm{constructor(e){this._size=0,this._generateParticleUpdateCache={};const t=this._size=e.size??1e3,i=e.properties;let r=0,n=0;for(const h in i){const u=i[h],f=At(u.format);u.dynamic?n+=f.stride:r+=f.stride}this._dynamicStride=n/4,this._staticStride=r/4,this.staticAttributeBuffer=new Ci(t*4*r),this.dynamicAttributeBuffer=new Ci(t*4*n),this.indexBuffer=cl(t);const o=new Qs;let a=0,l=0;this._staticBuffer=new gt({data:new Float32Array(1),label:"static-particle-buffer",shrinkToFit:!1,usage:ge.VERTEX|ge.COPY_DST}),this._dynamicBuffer=new gt({data:new Float32Array(1),label:"dynamic-particle-buffer",shrinkToFit:!1,usage:ge.VERTEX|ge.COPY_DST});for(const h in i){const u=i[h],f=At(u.format);u.dynamic?(o.addAttribute(u.attributeName,{buffer:this._dynamicBuffer,stride:this._dynamicStride*4,offset:a*4,format:u.format}),a+=f.size):(o.addAttribute(u.attributeName,{buffer:this._staticBuffer,stride:this._staticStride*4,offset:l*4,format:u.format}),l+=f.size)}o.addIndex(this.indexBuffer);const c=this.getParticleUpdate(i);this._dynamicUpload=c.dynamicUpdate,this._staticUpload=c.staticUpdate,this.geometry=o}getParticleUpdate(e){const t=mm(e);return this._generateParticleUpdateCache[t]?this._generateParticleUpdateCache[t]:(this._generateParticleUpdateCache[t]=this.generateParticleUpdate(e),this._generateParticleUpdateCache[t])}generateParticleUpdate(e){return fm(e)}update(e,t){e.length>this._size&&(t=!0,this._size=Math.max(e.length,this._size*1.5|0),this.staticAttributeBuffer=new Ci(this._size*this._staticStride*4*4),this.dynamicAttributeBuffer=new Ci(this._size*this._dynamicStride*4*4),this.indexBuffer=cl(this._size),this.geometry.indexBuffer.setDataWithSize(this.indexBuffer,this.indexBuffer.byteLength,!0));const i=this.dynamicAttributeBuffer;if(this._dynamicUpload(e,i.float32View,i.uint32View),this._dynamicBuffer.setDataWithSize(this.dynamicAttributeBuffer.float32View,e.length*this._dynamicStride*4,!0),t){const r=this.staticAttributeBuffer;this._staticUpload(e,r.float32View,r.uint32View),this._staticBuffer.setDataWithSize(r.float32View,e.length*this._staticStride*4,!0)}}destroy(){this._staticBuffer.destroy(),this._dynamicBuffer.destroy(),this.geometry.destroy()}}function mm(s){const e=[];for(const t in s){const i=s[t];e.push(t,i.code,i.dynamic?"d":"s")}return e.join("_")}const gm={aVertex:(s,e,t,i,r)=>{let n=0,o=0,a=0,l=0;for(let c=0;c<s.length;++c){const h=s[c],u=h.texture,f=h.scaleX,d=h.scaleY,g=h.anchorX,_=h.anchorY,y=u.trim,x=u.orig;y?(o=y.x-g*x.width,n=o+y.width,l=y.y-_*x.height,a=l+y.height):(n=x.width*(1-g),o=x.width*-g,a=x.height*(1-_),l=x.height*-_),e[i]=o*f,e[i+1]=l*d,e[i+r]=n*f,e[i+r+1]=l*d,e[i+r*2]=n*f,e[i+r*2+1]=a*d,e[i+r*3]=o*f,e[i+r*3+1]=a*d,i+=r*4}},aPosition:(s,e,t,i,r)=>{for(let n=0;n<s.length;++n){const o=s[n],a=o.x,l=o.y;e[i]=a,e[i+1]=l,e[i+r]=a,e[i+r+1]=l,e[i+r*2]=a,e[i+r*2+1]=l,e[i+r*3]=a,e[i+r*3+1]=l,i+=r*4}},aRotation:(s,e,t,i,r)=>{for(let n=0;n<s.length;++n){const o=s[n].rotation;e[i]=o,e[i+r]=o,e[i+r*2]=o,e[i+r*3]=o,i+=r*4}},aUV:(s,e,t,i,r)=>{for(let n=0;n<s.length;++n){const o=s[n].texture.uvs;e[i]=o.x0,e[i+1]=o.y0,e[i+r]=o.x1,e[i+r+1]=o.y1,e[i+r*2]=o.x2,e[i+r*2+1]=o.y2,e[i+r*3]=o.x3,e[i+r*3+1]=o.y3,i+=r*4}},aColor:(s,e,t,i,r)=>{for(let n=0;n<s.length;++n){const o=s[n].color;t[i]=o,t[i+r]=o,t[i+r*2]=o,t[i+r*3]=o,i+=r*4}}};function _m(s){const e=Object.values(s),t=e.filter(r=>r.dynamic),i=e.filter(r=>!r.dynamic);return{dynamicUpdate:ul(t),staticUpdate:ul(i)}}function ul(s){let e=0;const t=[];for(let i=0;i<s.length;i++){const r=s[i],n=At(r.format).stride/4;e+=n,t.push({stride:n,updateFunction:r.updateFunction||gm[r.attributeName]})}return(i,r,n)=>{let o=0;for(let a=0;a<t.length;a++){const l=t[a];l.updateFunction(i,r,n,o,e),o+=l.stride}}}function ym(){return bm}function bm(s,e,t){const i=s.gl,r=s.shader,n=r._getProgramData(e.glProgram);for(const o in e.groups){const a=e.groups[o];for(const l in a.resources){const c=a.resources[l];if(c instanceof ht)c.ubo?r.bindUniformBlock(c,e._uniformBindMap[o][l],t.blockIndex++):r.updateUniformGroup(c);else if(c instanceof Gs)r.bindUniformBlock(c,e._uniformBindMap[o][l],t.blockIndex++);else if(c instanceof De){s.texture.bind(c,t.textureCount);const h=e._uniformBindMap[o][l],u=n.uniformData[h];u&&(u.value!==t.textureCount&&i.uniform1i(u.location,t.textureCount),t.textureCount++)}}}}const xm=[(s,e,t,i,r)=>{const n=i[s].toArray(!0);e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+4]=n[3],e[t+5]=n[4],e[t+6]=n[5],e[t+8]=n[6],e[t+9]=n[7],e[t+10]=n[8]},(s,e,t,i,r)=>{r=i[s],e[t]=r.x,e[t+1]=r.y,e[t+2]=r.width,e[t+3]=r.height},(s,e,t,i,r)=>{r=i[s],e[t]=r.x,e[t+1]=r.y},(s,e,t,i,r)=>{r=i[s],e[t]=r.red,e[t+1]=r.green,e[t+2]=r.blue,e[t+3]=r.alpha},(s,e,t,i,r)=>{r=i[s],e[t]=r.red,e[t+1]=r.green,e[t+2]=r.blue}],vm={f32:(s,e,t,i,r)=>{e[t]=r},i32:(s,e,t,i,r)=>{e[t]=r},"vec2<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1]},"vec3<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2]},"vec4<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3]},"mat2x2<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3]},"mat3x3<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+4]=r[3],e[t+5]=r[4],e[t+6]=r[5],e[t+8]=r[6],e[t+9]=r[7],e[t+10]=r[8]},"mat4x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<16;n++)e[t+n]=r[n]},"mat3x2<f32>":(s,e,t,i,r)=>{for(let n=0;n<6;n++)e[t+(n/3|0)*4+n%3]=r[n]},"mat4x2<f32>":(s,e,t,i,r)=>{for(let n=0;n<8;n++)e[t+(n/4|0)*4+n%4]=r[n]},"mat2x3<f32>":(s,e,t,i,r)=>{for(let n=0;n<6;n++)e[t+(n/2|0)*4+n%2]=r[n]},"mat4x3<f32>":(s,e,t,i,r)=>{for(let n=0;n<12;n++)e[t+(n/4|0)*4+n%4]=r[n]},"mat2x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<8;n++)e[t+(n/2|0)*4+n%2]=r[n]},"mat3x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<12;n++)e[t+(n/3|0)*4+n%3]=r[n]}},Cm={f32:(s,e,t,i,r)=>{e[t]=r},i32:(s,e,t,i,r)=>{e[t]=r},"vec2<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1]},"vec3<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2]},"vec4<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3]},"mat2x2<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+4]=r[2],e[t+5]=r[3]},"mat3x3<f32>":(s,e,t,i,r)=>{e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+4]=r[3],e[t+5]=r[4],e[t+6]=r[5],e[t+8]=r[6],e[t+9]=r[7],e[t+10]=r[8]},"mat4x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<16;n++)e[t+n]=r[n]},"mat3x2<f32>":(s,e,t,i,r)=>{for(let n=0;n<6;n++)e[t+(n/3|0)*4+n%3]=r[n]},"mat4x2<f32>":(s,e,t,i,r)=>{for(let n=0;n<8;n++)e[t+(n/4|0)*4+n%4]=r[n]},"mat2x3<f32>":(s,e,t,i,r)=>{for(let n=0;n<6;n++)e[t+(n/2|0)*4+n%2]=r[n]},"mat4x3<f32>":(s,e,t,i,r)=>{for(let n=0;n<12;n++)e[t+(n/4|0)*4+n%4]=r[n]},"mat2x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<8;n++)e[t+(n/2|0)*4+n%2]=r[n]},"mat3x4<f32>":(s,e,t,i,r)=>{for(let n=0;n<12;n++)e[t+(n/3|0)*4+n%3]=r[n]}};function Sm(s){return dl(s,Cm,e=>{const t=Math.max(Wr[e.data.type]/16,1),i=e.data.value.length/e.data.size,r=(4-i%4)%4;return(n,o,a,l,c)=>{let h=0;for(let u=0;u<e.data.size*t;u++){for(let f=0;f<i;f++)o[a++]=c[h++];a+=r}}})}function Em(s){return dl(s,vm,e=>{const{size:t,align:i}=Ki[e.data.type],r=(t-i)/4;return(n,o,a,l,c)=>{let h=0;for(let u=0;u<e.data.size*(t/4);u++){for(let f=0;f<t/4;f++)o[a++]=c[h++];a+=r}}})}function dl(s,e,t){const i={};for(const r in s){const n=s[r],o=n.data;let a=!1;i[o.name]={offset:n.offset/4,func:null};for(let l=0;l<ct.length;l++){const c=ct[l];if(o.type===c.type&&c.test(o)){i[o.name].func=xm[l],a=!0;break}}a||(o.size===1?i[o.name].func=e[o.type]:i[o.name].func=t(n))}return(r,n,o)=>{for(const a in i)i[a].func(a,n,o+i[a].offset,r,r[a])}}const Tm={f32(s,e,t,i,r,n,o){t!==i&&(e.value=i,o.uniform1f(r[s].location,i))},"vec2<f32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1])&&(t[0]=i[0],t[1]=i[1],o.uniform2f(r[s].location,i[0],i[1]))},"vec3<f32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],o.uniform3f(r[s].location,i[0],i[1],i[2]))},"vec4<f32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2]||t[3]!==i[3])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],o.uniform4f(r[s].location,i[0],i[1],i[2],i[3]))},i32(s,e,t,i,r,n,o){t!==i&&(e.value=i,o.uniform1i(r[s].location,i))},"vec2<i32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1])&&(t[0]=i[0],t[1]=i[1],o.uniform2i(r[s].location,i[0],i[1]))},"vec3<i32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],o.uniform3i(r[s].location,i[0],i[1],i[2]))},"vec4<i32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2]||t[3]!==i[3])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],o.uniform4i(r[s].location,i[0],i[1],i[2],i[3]))},u32(s,e,t,i,r,n,o){t!==i&&(e.value=i,o.uniform1ui(r[s].location,i))},"vec2<u32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1])&&(t[0]=i[0],t[1]=i[1],o.uniform2ui(r[s].location,i[0],i[1]))},"vec3<u32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],o.uniform3ui(r[s].location,i[0],i[1],i[2]))},"vec4<u32>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2]||t[3]!==i[3])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],o.uniform4ui(r[s].location,i[0],i[1],i[2],i[3]))},bool(s,e,t,i,r,n,o){t!==i&&(e.value=i,o.uniform1i(r[s].location,i))},"vec2<bool>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1])&&(t[0]=i[0],t[1]=i[1],o.uniform2i(r[s].location,i[0],i[1]))},"vec3<bool>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],o.uniform3i(r[s].location,i[0],i[1],i[2]))},"vec4<bool>"(s,e,t,i,r,n,o){(t[0]!==i[0]||t[1]!==i[1]||t[2]!==i[2]||t[3]!==i[3])&&(t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],o.uniform4i(r[s].location,i[0],i[1],i[2],i[3]))},"mat2x2<f32>"(s,e,t,i,r,n,o){o.uniformMatrix2fv(r[s].location,!1,i)},"mat3x3<f32>"(s,e,t,i,r,n,o){o.uniformMatrix3fv(r[s].location,!1,i)},"mat4x4<f32>"(s,e,t,i,r,n,o){o.uniformMatrix4fv(r[s].location,!1,i)}},Am={f32(s,e,t,i,r,n,o){o.uniform1fv(r[s].location,i)},"vec2<f32>"(s,e,t,i,r,n,o){o.uniform2fv(r[s].location,i)},"vec3<f32>"(s,e,t,i,r,n,o){o.uniform3fv(r[s].location,i)},"vec4<f32>"(s,e,t,i,r,n,o){o.uniform4fv(r[s].location,i)},"mat2x2<f32>"(s,e,t,i,r,n,o){o.uniformMatrix2fv(r[s].location,!1,i)},"mat3x3<f32>"(s,e,t,i,r,n,o){o.uniformMatrix3fv(r[s].location,!1,i)},"mat4x4<f32>"(s,e,t,i,r,n,o){o.uniformMatrix4fv(r[s].location,!1,i)},i32(s,e,t,i,r,n,o){o.uniform1iv(r[s].location,i)},"vec2<i32>"(s,e,t,i,r,n,o){o.uniform2iv(r[s].location,i)},"vec3<i32>"(s,e,t,i,r,n,o){o.uniform3iv(r[s].location,i)},"vec4<i32>"(s,e,t,i,r,n,o){o.uniform4iv(r[s].location,i)},u32(s,e,t,i,r,n,o){o.uniform1iv(r[s].location,i)},"vec2<u32>"(s,e,t,i,r,n,o){o.uniform2iv(r[s].location,i)},"vec3<u32>"(s,e,t,i,r,n,o){o.uniform3iv(r[s].location,i)},"vec4<u32>"(s,e,t,i,r,n,o){o.uniform4iv(r[s].location,i)},bool(s,e,t,i,r,n,o){o.uniform1iv(r[s].location,i)},"vec2<bool>"(s,e,t,i,r,n,o){o.uniform2iv(r[s].location,i)},"vec3<bool>"(s,e,t,i,r,n,o){o.uniform3iv(r[s].location,i)},"vec4<bool>"(s,e,t,i,r,n,o){o.uniform4iv(r[s].location,i)}},wm=[(s,e,t,i,r,n,o)=>{o.uniformMatrix3fv(r[s].location,!1,n[s].toArray(!0))},(s,e,t,i,r,n,o)=>{t=r[s].value,i=n[s],(t[0]!==i.x||t[1]!==i.y||t[2]!==i.width||t[3]!==i.height)&&(t[0]=i.x,t[1]=i.y,t[2]=i.width,t[3]=i.height,o.uniform4f(r[s].location,i.x,i.y,i.width,i.height))},(s,e,t,i,r,n,o)=>{t=r[s].value,i=n[s],(t[0]!==i.x||t[1]!==i.y)&&(t[0]=i.x,t[1]=i.y,o.uniform2f(r[s].location,i.x,i.y))},(s,e,t,i,r,n,o)=>{t=r[s].value,i=n[s],(t[0]!==i.red||t[1]!==i.green||t[2]!==i.blue||t[3]!==i.alpha)&&(t[0]=i.red,t[1]=i.green,t[2]=i.blue,t[3]=i.alpha,o.uniform4f(r[s].location,i.red,i.green,i.blue,i.alpha))},(s,e,t,i,r,n,o)=>{t=r[s].value,i=n[s],(t[0]!==i.red||t[1]!==i.green||t[2]!==i.blue)&&(t[0]=i.red,t[1]=i.green,t[2]=i.blue,o.uniform3f(r[s].location,i.red,i.green,i.blue))}];function Im(s,e){const t={};for(const i in s.uniformStructures){if(!e[i])continue;const r=s.uniformStructures[i];let n=!1;for(let o=0;o<ct.length;o++){const a=ct[o];if(r.type===a.type&&a.test(r)){t[i]=wm[o],n=!0;break}}if(!n){const o=r.size===1?Tm:Am;t[i]=o[r.type]}}return(i,r,n)=>{const o=n.gl;for(const a in t){const l=r[a],c=i[a],h=i[a].value;t[a](a,c,h,l,i,r,o)}}}function Rm(){Object.assign(vi.prototype,{_unsafeEvalCheck(){}}),Object.assign(Lr.prototype,{_systemCheck(){}}),Object.assign(Yr.prototype,{_generateUniformsSync:Im}),Object.assign(Hr.prototype,{_generateUboSync:Sm}),Object.assign(qr.prototype,{_generateUboSync:Em}),Object.assign(Xr.prototype,{_generateShaderSync:ym}),Object.assign(pm.prototype,{generateParticleUpdate:_m})}Rm();const Mm={extension:{type:A.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>oS)}},Pm={extension:{type:A.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>aS)}};function km(s,e,t){const{width:i,height:r}=t.orig,n=t.trim;if(n){const o=n.width,a=n.height;s.minX=n.x-e._x*i,s.maxX=s.minX+o,s.minY=n.y-e._y*r,s.maxY=s.minY+a}else s.minX=-e._x*i,s.maxX=s.minX+i,s.minY=-e._y*r,s.maxY=s.minY+r}class fl extends Ve{constructor(e){super(e),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this._bounds=new Ye(0,1,0,0),this._boundsDirty=!0,this.autoGarbageCollect=e.autoGarbageCollect??!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(e){this._roundPixels=e?1:0}containsPoint(e){const t=this.bounds,{x:i,y:r}=e;return i>=t.minX&&i<=t.maxX&&r>=t.minY&&r<=t.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const e=this.renderGroup||this.parentRenderGroup;e&&e.onChildViewUpdate(this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(e){this.unload(),super.destroy(e),this._bounds=null}collectRenderablesSimple(e,t,i){const{renderPipes:r}=t;r.blendMode.pushBlendMode(this,this.groupBlendMode,e);const o=r[this.renderPipeId];o!=null&&o.addRenderable&&o.addRenderable(this,e),this.didViewUpdate=!1;const a=this.children,l=a.length;for(let c=0;c<l;c++)a[c].collectRenderables(e,t,i);r.blendMode.popBlendMode(e)}}class Ft extends fl{constructor(e=j.EMPTY){e instanceof j&&(e={texture:e});const{texture:t=j.EMPTY,anchor:i,roundPixels:r,width:n,height:o,...a}=e;super({label:"Sprite",...a}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new je({_onUpdate:()=>{this.onViewUpdate()}}),i?this.anchor=i:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=r??!1,n!==void 0&&(this.width=n),o!==void 0&&(this.height=o)}static from(e,t=!1){return e instanceof j?new Ft(e):new Ft(j.from(e,t))}set texture(e){e||(e=j.EMPTY);const t=this._texture;t!==e&&(t&&t.dynamic&&t.off("update",this.onViewUpdate,this),e.dynamic&&e.on("update",this.onViewUpdate,this),this._texture=e,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return km(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return ee("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const e=this._anchor,t=this._texture,i=this._bounds,{width:r,height:n}=t.orig;i.minX=-e._x*r,i.maxX=i.minX+r,i.minY=-e._y*n,i.maxY=i.minY+n}destroy(e=!1){if(super.destroy(e),typeof e=="boolean"?e:e==null?void 0:e.texture){const i=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._texture.destroy(i)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(e){this._setWidth(e,this._texture.orig.width),this._width=e}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(e){this._setHeight(e,this._texture.orig.height),this._height=e}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this._texture.orig.width,e.height=Math.abs(this.scale.y)*this._texture.orig.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this._texture.orig.width),t!==void 0&&this._setHeight(t,this._texture.orig.height)}}const Om=new Ye;function pl(s,e,t){const i=Om;s.measurable=!0,nn(s,t,i),e.addBoundsMask(i),s.measurable=!1}function ml(s,e,t){const i=It.get();s.measurable=!0;const r=qe.get().identity(),n=gl(s,t,r);an(s,i,n),s.measurable=!1,e.addBoundsMask(i),qe.return(r),It.return(i)}function gl(s,e,t){return s?(s!==e&&(gl(s.parent,e,t),s.updateLocalTransform(),t.append(s.localTransform)),t):(se("Mask bounds, renderable is not inside the root container"),t)}class _l{constructor(e){this.priority=0,this.inverse=!1,this.pipe="alphaMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof Ft),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(e,t){this.inverse||pl(this.mask,e,t)}addLocalBounds(e,t){ml(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof Ft}}_l.extension=A.MaskEffect;class yl{constructor(e){this.priority=0,this.pipe="colorMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e=="number"}}yl.extension=A.MaskEffect;class bl{constructor(e){this.priority=0,this.pipe="stencilMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(e,t){pl(this.mask,e,t)}addLocalBounds(e,t){ml(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof Ve}}bl.extension=A.MaskEffect;let xl={createCanvas:(s,e)=>{const t=document.createElement("canvas");return t.width=s,t.height=e,t},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(s,e)=>fetch(s,e),parseXML:s=>new DOMParser().parseFromString(s,"text/xml")};const pe={get(){return xl},set(s){xl=s}};class yt extends De{constructor(e){e.resource||(e.resource=pe.get().createCanvas()),e.width||(e.width=e.resource.width,e.autoDensity||(e.width/=e.resolution)),e.height||(e.height=e.resource.height,e.autoDensity||(e.height/=e.resolution)),super(e),this.uploadMethodId="image",this.autoDensity=e.autoDensity,this.resizeCanvas(),this.transparent=!!e.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(e=this.width,t=this.height,i=this._resolution){const r=super.resize(e,t,i);return r&&this.resizeCanvas(),r}static test(e){return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&e instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}yt.extension=A.TextureSource;class er extends De{constructor(e){super(e),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(e){return globalThis.HTMLImageElement&&e instanceof HTMLImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||globalThis.VideoFrame&&e instanceof VideoFrame}}er.extension=A.TextureSource;var Si=(s=>(s[s.INTERACTION=50]="INTERACTION",s[s.HIGH=25]="HIGH",s[s.NORMAL=0]="NORMAL",s[s.LOW=-25]="LOW",s[s.UTILITY=-50]="UTILITY",s))(Si||{});class _n{constructor(e,t=null,i=0,r=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=i,this._once=r}match(e,t=null){return this._fn===e&&this._context===t}emit(e){this._fn&&(this._context?this._fn.call(this._context,e):this._fn(e));const t=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),t}connect(e){this.previous=e,e.next&&(e.next.previous=this),this.next=e.next,e.next=this}destroy(e=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const t=this.next;return this.next=e?null:t,this.previous=null,t}}const vl=class nt{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new _n(null,null,1/0),this.deltaMS=1/nt.targetFPMS,this.elapsedMS=1/nt.targetFPMS,this._tick=e=>{this._requestId=null,this.started&&(this.update(e),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(e,t,i=Si.NORMAL){return this._addListener(new _n(e,t,i))}addOnce(e,t,i=Si.NORMAL){return this._addListener(new _n(e,t,i,!0))}_addListener(e){let t=this._head.next,i=this._head;if(!t)e.connect(i);else{for(;t;){if(e.priority>t.priority){e.connect(i);break}i=t,t=t.next}e.previous||e.connect(i)}return this._startIfPossible(),this}remove(e,t){let i=this._head.next;for(;i;)i.match(e,t)?i=i.destroy():i=i.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let e=0,t=this._head;for(;t=t.next;)e++;return e}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let e=this._head.next;for(;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let t;if(e>this.lastTime){if(t=this.elapsedMS=e-this.lastTime,t>this._maxElapsedMS&&(t=this._maxElapsedMS),t*=this.speed,this._minElapsedMS){const n=e-this._lastFrame|0;if(n<this._minElapsedMS)return;this._lastFrame=e-n%this._minElapsedMS}this.deltaMS=t,this.deltaTime=this.deltaMS*nt.targetFPMS;const i=this._head;let r=i.next;for(;r;)r=r.emit(this);i.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=e}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(e){const t=Math.min(Math.max(0,e)/1e3,nt.targetFPMS);this._maxElapsedMS=1/t,this._minElapsedMS&&e>this.maxFPS&&(this.maxFPS=e)}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(e){e===0?this._minElapsedMS=0:(e<this.minFPS&&(this.minFPS=e),this._minElapsedMS=1/(e/1e3))}static get shared(){if(!nt._shared){const e=nt._shared=new nt;e.autoStart=!0,e._protected=!0}return nt._shared}static get system(){if(!nt._system){const e=nt._system=new nt;e.autoStart=!0,e._protected=!0}return nt._system}};vl.targetFPMS=.06;let at=vl,yn;async function Bm(){return yn??(yn=(async()=>{var o;const e=pe.get().createCanvas(1,1).getContext("webgl");if(!e)return"premultiply-alpha-on-upload";const t=await new Promise(a=>{const l=document.createElement("video");l.onloadeddata=()=>a(l),l.onerror=()=>a(null),l.autoplay=!1,l.crossOrigin="anonymous",l.preload="auto",l.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",l.load()});if(!t)return"premultiply-alpha-on-upload";const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t);const n=new Uint8Array(4);return e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,n),e.deleteFramebuffer(r),e.deleteTexture(i),(o=e.getExtension("WEBGL_lose_context"))==null||o.loseContext(),n[0]<=n[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),yn}const tr=class mf extends De{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...mf.defaultOptions,...e},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=e.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=e.autoPlay!==!1,this.alphaMode=e.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),e.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const e=at.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-e)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const e=this.resource,t=this.options;return(e.readyState===e.HAVE_ENOUGH_DATA||e.readyState===e.HAVE_FUTURE_DATA)&&e.width&&e.height&&(e.complete=!0),e.addEventListener("play",this._onPlayStart),e.addEventListener("pause",this._onPlayStop),e.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(t.preload||e.addEventListener("canplay",this._onCanPlay),e.addEventListener("canplaythrough",this._onCanPlayThrough),e.addEventListener("error",this._onError,!0)),this.alphaMode=await Bm(),this._load=new Promise((i,r)=>{this.isValid?i(this):(this._resolve=i,this._reject=r,t.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${t.preloadTimeoutMs}ms`))})),e.load())}),this._load}_onError(e){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",e),this._reject&&(this._reject(e),this._reject=null,this._resolve=null)}_isSourcePlaying(){const e=this.resource;return!e.paused&&!e.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const e=this.resource;this.isValid&&(this.isReady=!0,this.resize(e.videoWidth,e.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const e=this.resource;e&&(e.removeEventListener("play",this._onPlayStart),e.removeEventListener("pause",this._onPlayStop),e.removeEventListener("seeked",this._onSeeked),e.removeEventListener("canplay",this._onCanPlay),e.removeEventListener("canplaythrough",this._onCanPlayThrough),e.removeEventListener("error",this._onError,!0),e.pause(),e.src="",e.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(e){e!==this._updateFPS&&(this._updateFPS=e,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(at.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(at.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(at.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};tr.extension=A.TextureSource,tr.defaultOptions={...De.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},tr.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Dm=tr;const Ei=(s,e,t=!1)=>(Array.isArray(s)||(s=[s]),e?s.map(i=>typeof i=="string"||t?e(i):i):s);class Nm{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(e){return this._cache.has(e)}get(e){const t=this._cache.get(e);return t||se(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const i=Ei(e);let r;for(let l=0;l<this.parsers.length;l++){const c=this.parsers[l];if(c.test(t)){r=c.getCacheableAssets(i,t);break}}const n=new Map(Object.entries(r||{}));r||i.forEach(l=>{n.set(l,t)});const o=[...n.keys()],a={cacheKeys:o,keys:i};i.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const c=r?r[l]:t;this._cache.has(l)&&this._cache.get(l)!==c&&se("[Cache] already has key:",l),this._cache.set(l,n.get(l))})}remove(e){if(!this._cacheMap.has(e)){se(`[Assets] Asset id ${e} was not found in the Cache`);return}const t=this._cacheMap.get(e);t.cacheKeys.forEach(r=>{this._cache.delete(r)}),t.keys.forEach(r=>{this._cacheMap.delete(r)})}get parsers(){return this._parsers}}const Ti=new Nm,bn=[];Q.handleByList(A.TextureSource,bn);function Cl(s={}){const e=s&&s.resource,t=e?s.resource:s,i=e?s:{resource:s};for(let r=0;r<bn.length;r++){const n=bn[r];if(n.test(t))return new n(i)}throw new Error(`Could not find a source type for resource: ${i.resource}`)}function Um(s={},e=!1){const t=s&&s.resource,i=t?s.resource:s,r=t?s:{resource:s};if(!e&&Ti.has(i))return Ti.get(i);const n=new j({source:Cl(r)});return n.on("destroy",()=>{Ti.has(i)&&Ti.remove(i)}),e||Ti.set(i,n),n}function Fm(s,e=!1){return typeof s=="string"?Ti.get(s):s instanceof De?new j({source:s}):Um(s,e)}j.from=Fm,De.from=Cl,Q.add(_l,yl,bl,Dm,er,yt,hn);var Sl=(s=>(s[s.Low=0]="Low",s[s.Normal=1]="Normal",s[s.High=2]="High",s))(Sl||{});function ut(s){if(typeof s!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(s)}`)}function ss(s){return s.split("?")[0].split("#")[0]}function Gm(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Lm(s,e,t){return s.replace(new RegExp(Gm(e),"g"),t)}function Wm(s,e){let t="",i=0,r=-1,n=0,o=-1;for(let a=0;a<=s.length;++a){if(a<s.length)o=s.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(r===a-1||n===1))if(r!==a-1&&n===2){if(t.length<2||i!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){const l=t.lastIndexOf("/");if(l!==t.length-1){l===-1?(t="",i=0):(t=t.slice(0,l),i=t.length-1-t.lastIndexOf("/")),r=a,n=0;continue}}else if(t.length===2||t.length===1){t="",i=0,r=a,n=0;continue}}}else t.length>0?t+=`/${s.slice(r+1,a)}`:t=s.slice(r+1,a),i=a-r-1;r=a,n=0}else o===46&&n!==-1?++n:n=-1}return t}const rs={toPosix(s){return Lm(s,"\\","/")},isUrl(s){return/^https?:/.test(this.toPosix(s))},isDataUrl(s){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(s)},isBlobUrl(s){return s.startsWith("blob:")},hasProtocol(s){return/^[^/:]+:/.test(this.toPosix(s))},getProtocol(s){ut(s),s=this.toPosix(s);const e=/^file:\/\/\//.exec(s);if(e)return e[0];const t=/^[^/:]+:\/{0,2}/.exec(s);return t?t[0]:""},toAbsolute(s,e,t){if(ut(s),this.isDataUrl(s)||this.isBlobUrl(s))return s;const i=ss(this.toPosix(e??pe.get().getBaseUrl())),r=ss(this.toPosix(t??this.rootname(i)));return s=this.toPosix(s),s.startsWith("/")?rs.join(r,s.slice(1)):this.isAbsolute(s)?s:this.join(i,s)},normalize(s){if(ut(s),s.length===0)return".";if(this.isDataUrl(s)||this.isBlobUrl(s))return s;s=this.toPosix(s);let e="";const t=s.startsWith("/");this.hasProtocol(s)&&(e=this.rootname(s),s=s.slice(e.length));const i=s.endsWith("/");return s=Wm(s),s.length>0&&i&&(s+="/"),t?`/${s}`:e+s},isAbsolute(s){return ut(s),s=this.toPosix(s),this.hasProtocol(s)?!0:s.startsWith("/")},join(...s){if(s.length===0)return".";let e;for(let t=0;t<s.length;++t){const i=s[t];if(ut(i),i.length>0)if(e===void 0)e=i;else{const r=s[t-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?e+=`/../${i}`:e+=`/${i}`}}return e===void 0?".":this.normalize(e)},dirname(s){if(ut(s),s.length===0)return".";s=this.toPosix(s);let e=s.charCodeAt(0);const t=e===47;let i=-1,r=!0;const n=this.getProtocol(s),o=s;s=s.slice(n.length);for(let a=s.length-1;a>=1;--a)if(e=s.charCodeAt(a),e===47){if(!r){i=a;break}}else r=!1;return i===-1?t?"/":this.isUrl(o)?n+s:n:t&&i===1?"//":n+s.slice(0,i)},rootname(s){ut(s),s=this.toPosix(s);let e="";if(s.startsWith("/")?e="/":e=this.getProtocol(s),this.isUrl(s)){const t=s.indexOf("/",e.length);t!==-1?e=s.slice(0,t):e=s,e.endsWith("/")||(e+="/")}return e},basename(s,e){ut(s),e&&ut(e),s=ss(this.toPosix(s));let t=0,i=-1,r=!0,n;if(e!==void 0&&e.length>0&&e.length<=s.length){if(e.length===s.length&&e===s)return"";let o=e.length-1,a=-1;for(n=s.length-1;n>=0;--n){const l=s.charCodeAt(n);if(l===47){if(!r){t=n+1;break}}else a===-1&&(r=!1,a=n+1),o>=0&&(l===e.charCodeAt(o)?--o===-1&&(i=n):(o=-1,i=a))}return t===i?i=a:i===-1&&(i=s.length),s.slice(t,i)}for(n=s.length-1;n>=0;--n)if(s.charCodeAt(n)===47){if(!r){t=n+1;break}}else i===-1&&(r=!1,i=n+1);return i===-1?"":s.slice(t,i)},extname(s){ut(s),s=ss(this.toPosix(s));let e=-1,t=0,i=-1,r=!0,n=0;for(let o=s.length-1;o>=0;--o){const a=s.charCodeAt(o);if(a===47){if(!r){t=o+1;break}continue}i===-1&&(r=!1,i=o+1),a===46?e===-1?e=o:n!==1&&(n=1):e!==-1&&(n=-1)}return e===-1||i===-1||n===0||n===1&&e===i-1&&e===t+1?"":s.slice(e,i)},parse(s){ut(s);const e={root:"",dir:"",base:"",ext:"",name:""};if(s.length===0)return e;s=ss(this.toPosix(s));let t=s.charCodeAt(0);const i=this.isAbsolute(s);let r;e.root=this.rootname(s),i||this.hasProtocol(s)?r=1:r=0;let n=-1,o=0,a=-1,l=!0,c=s.length-1,h=0;for(;c>=r;--c){if(t=s.charCodeAt(c),t===47){if(!l){o=c+1;break}continue}a===-1&&(l=!1,a=c+1),t===46?n===-1?n=c:h!==1&&(h=1):n!==-1&&(h=-1)}return n===-1||a===-1||h===0||h===1&&n===a-1&&n===o+1?a!==-1&&(o===0&&i?e.base=e.name=s.slice(1,a):e.base=e.name=s.slice(o,a)):(o===0&&i?(e.name=s.slice(1,n),e.base=s.slice(1,a)):(e.name=s.slice(o,n),e.base=s.slice(o,a)),e.ext=s.slice(n,a)),e.dir=this.dirname(s),e},sep:"/",delimiter:":",joinExtensions:[".html"]};function El(s,e,t,i,r){const n=e[t];for(let o=0;o<n.length;o++){const a=n[o];t<e.length-1?El(s.replace(i[t],a),e,t+1,i,r):r.push(s.replace(i[t],a))}}function Hm(s){const e=/\{(.*?)\}/g,t=s.match(e),i=[];if(t){const r=[];t.forEach(n=>{const o=n.substring(1,n.length-1).split(",");r.push(o)}),El(s,r,0,t,i)}else i.push(s);return i}const Tl=s=>!Array.isArray(s);class Al{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(e,t)=>`${e}${this._bundleIdConnector}${t}`,extractAssetIdFromBundle:(e,t)=>t.replace(`${e}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(e){if(this._bundleIdConnector=e.connector??this._bundleIdConnector,this._createBundleAssetId=e.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=e.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...e){e.forEach(t=>{this._preferredOrder.push(t),t.priority||(t.priority=Object.keys(t.params))}),this._resolverHash={}}set basePath(e){this._basePath=e}get basePath(){return this._basePath}set rootPath(e){this._rootPath=e}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(e){if(typeof e=="string")this._defaultSearchParams=e;else{const t=e;this._defaultSearchParams=Object.keys(t).map(i=>`${encodeURIComponent(i)}=${encodeURIComponent(t[i])}`).join("&")}}getAlias(e){const{alias:t,src:i}=e;return Ei(t||i,n=>typeof n=="string"?n:Array.isArray(n)?n.map(o=>(o==null?void 0:o.src)??o):n!=null&&n.src?n.src:n,!0)}removeAlias(e,t){this._assetMap[e]&&(t&&t!==this._resolverHash[e]||(delete this._resolverHash[e],delete this._assetMap[e]))}addManifest(e){this._manifest&&se("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=e,e.bundles.forEach(t=>{this.addBundle(t.name,t.assets)})}addBundle(e,t){const i=[];let r=t;Array.isArray(t)||(r=Object.entries(t).map(([n,o])=>typeof o=="string"||Array.isArray(o)?{alias:n,src:o}:{alias:n,...o})),r.forEach(n=>{const o=n.src,a=n.alias;let l;if(typeof a=="string"){const c=this._createBundleAssetId(e,a);i.push(c),l=[a,c]}else{const c=a.map(h=>this._createBundleAssetId(e,h));i.push(...c),l=[...a,...c]}this.add({...n,alias:l,src:o})}),this._bundles[e]=i}add(e){const t=[];Array.isArray(e)?t.push(...e):t.push(e);let i;i=n=>{this.hasKey(n)&&se(`[Resolver] already has key: ${n} overwriting`)},Ei(t).forEach(n=>{const{src:o}=n;let{data:a,format:l,loadParser:c,parser:h}=n;const u=Ei(o).map(_=>typeof _=="string"?Hm(_):Array.isArray(_)?_:[_]),f=this.getAlias(n);Array.isArray(f)?f.forEach(i):i(f);const d=[],g=_=>{const y=this._parsers.find(x=>x.test(_));return{src:_,...y==null?void 0:y.parse(_)}};u.forEach(_=>{_.forEach(y=>{let x={};if(typeof y!="object"?x=g(y):(a=y.data??a,l=y.format??l,(y.loadParser||y.parser)&&(c=y.loadParser??c,h=y.parser??h),x={...g(y.src),...y}),!f)throw new Error(`[Resolver] alias is undefined for this asset: ${x.src}`);x=this._buildResolvedAsset(x,{aliases:f,data:a,format:l,loadParser:c,parser:h,progressSize:n.progressSize}),d.push(x)})}),f.forEach(_=>{this._assetMap[_]=d})})}resolveBundle(e){const t=Tl(e);e=Ei(e);const i={};return e.forEach(r=>{const n=this._bundles[r];if(n){const o=this.resolve(n),a={};for(const l in o){const c=o[l];a[this._extractAssetIdFromBundle(r,l)]=c}i[r]=a}}),t?i[e[0]]:i}resolveUrl(e){const t=this.resolve(e);if(typeof e!="string"){const i={};for(const r in t)i[r]=t[r].src;return i}return t.src}resolve(e){const t=Tl(e);e=Ei(e);const i={};return e.forEach(r=>{if(!this._resolverHash[r])if(this._assetMap[r]){let n=this._assetMap[r];const o=this._getPreferredOrder(n);o==null||o.priority.forEach(a=>{o.params[a].forEach(l=>{const c=n.filter(h=>h[a]?h[a]===l:!1);c.length&&(n=c)})}),this._resolverHash[r]=n[0]}else this._resolverHash[r]=this._buildResolvedAsset({alias:[r],src:r},{});i[r]=this._resolverHash[r]}),t?i[e[0]]:i}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){const i=e[t],r=this._preferredOrder.find(n=>n.params.format.includes(i.format));if(r)return r}return this._preferredOrder[0]}_appendDefaultSearchParams(e){if(!this._defaultSearchParams)return e;const t=/\?/.test(e)?"&":"?";return`${e}${t}${this._defaultSearchParams}`}_buildResolvedAsset(e,t){const{aliases:i,data:r,loadParser:n,parser:o,format:a,progressSize:l}=t;return(this._basePath||this._rootPath)&&(e.src=rs.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=i??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...r||{},...e.data},e.loadParser=n??e.loadParser,e.parser=o??e.parser,e.format=a??e.format??Vm(e.src),l!==void 0&&(e.progressSize=l),e}}Al.RETINA_PREFIX=/@([0-9\.]+)x/;function Vm(s){return s.split(".").pop().split("?").shift().split("#").shift()}const wl=(s,e)=>{const t=e.split("?")[1];return t&&(s+=`?${t}`),s},Il=class Ns{constructor(e,t){this.linkedSheets=[];let i=e;(e==null?void 0:e.source)instanceof De&&(i={texture:e,data:t});const{texture:r,data:n,cachePrefix:o=""}=i;this.cachePrefix=o,this._texture=r instanceof j?r:null,this.textureSource=r.source,this.textures={},this.animations={},this.data=n;const a=parseFloat(n.meta.scale);a?(this.resolution=a,r.source.resolution=this.resolution):this.resolution=r.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(e=>{this._callback=e,this._batchIndex=0,this._frameKeys.length<=Ns.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}parseSync(){return this._processFrames(0,!0),this._processAnimations(),this.textures}_processFrames(e,t=!1){let i=e;const r=t?1/0:Ns.BATCH_SIZE;for(;i-e<r&&i<this._frameKeys.length;){const n=this._frameKeys[i],o=this._frames[n],a=o.frame;if(a){let l=null,c=null;const h=o.trimmed!==!1&&o.sourceSize?o.sourceSize:o.frame,u=new Se(0,0,Math.floor(h.w)/this.resolution,Math.floor(h.h)/this.resolution);o.rotated?l=new Se(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.h)/this.resolution,Math.floor(a.w)/this.resolution):l=new Se(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution),o.trimmed!==!1&&o.spriteSourceSize&&(c=new Se(Math.floor(o.spriteSourceSize.x)/this.resolution,Math.floor(o.spriteSourceSize.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution)),this.textures[n]=new j({source:this.textureSource,frame:l,orig:u,trim:c,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:n.toString()})}i++}}_processAnimations(){const e=this.data.animations||{};for(const t in e){this.animations[t]=[];for(let i=0;i<e[t].length;i++){const r=e[t][i];this.animations[t].push(this.textures[r])}}}_parseComplete(){const e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*Ns.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*Ns.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){var t;for(const i in this.textures)this.textures[i].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&((t=this._texture)==null||t.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};Il.BATCH_SIZE=1e3;let Rl=Il;const zm=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Ml(s,e,t){const i={};if(s.forEach(r=>{i[r]=e}),Object.keys(e.textures).forEach(r=>{i[`${e.cachePrefix}${r}`]=e.textures[r]}),!t){const r=rs.dirname(s[0]);e.linkedSheets.forEach((n,o)=>{const a=Ml([`${r}/${e.data.meta.related_multi_packs[o]}`],n,!0);Object.assign(i,a)})}return i}const $m={extension:A.Asset,cache:{test:s=>s instanceof Rl,getCacheableAssets:(s,e)=>Ml(s,e,!1)},resolver:{extension:{type:A.ResolveParser,name:"resolveSpritesheet"},test:s=>{const t=s.split("?")[0].split("."),i=t.pop(),r=t.pop();return i==="json"&&zm.includes(r)},parse:s=>{var t;const e=s.split(".");return{resolution:parseFloat(((t=Al.RETINA_PREFIX.exec(s))==null?void 0:t[1])??"1"),format:e[e.length-2],src:s}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:A.LoadParser,priority:Sl.Normal,name:"spritesheetLoader"},async testParse(s,e){return rs.extname(e.src).toLowerCase()===".json"&&!!s.frames},async parse(s,e,t){var u,f;const{texture:i,imageFilename:r,textureOptions:n,cachePrefix:o}=(e==null?void 0:e.data)??{};let a=rs.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(i instanceof j)l=i;else{const d=wl(a+(r??s.meta.image),e.src);l=(await t.load([{src:d,data:n}]))[d]}const c=new Rl({texture:l.source,data:s,cachePrefix:o});await c.parse();const h=(u=s==null?void 0:s.meta)==null?void 0:u.related_multi_packs;if(Array.isArray(h)){const d=[];for(const _ of h){if(typeof _!="string")continue;let y=a+_;(f=e.data)!=null&&f.ignoreMultiPack||(y=wl(y,e.src),d.push(t.load({src:y,data:{textureOptions:n,ignoreMultiPack:!0}})))}const g=await Promise.all(d);c.linkedSheets=g,g.forEach(_=>{_.linkedSheets=[c].concat(c.linkedSheets.filter(y=>y!==_))})}return c},async unload(s,e,t){await t.unload(s.textureSource._sourceOrigin),s.destroy(!1)}}};Q.add($m);class Pl{constructor(e){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const t=this._canvas.getBoundingClientRect(),i=this._canvas.width,r=this._canvas.height,n=t.width/i*this._renderer.resolution,o=t.height/r*this._renderer.resolution,a=t.left,l=t.top,c=`translate(${a}px, ${l}px) scale(${n}, ${o})`;c!==this._lastTransform&&(this._domElement.style.transform=c,this._lastTransform=c)},this._domElement=e.domElement,this._renderer=e.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(e=>{for(const t of e){if(t.target!==this._canvas)continue;const i=this.canvas.width,r=this.canvas.height,n=t.contentRect.width/i*this._renderer.resolution,o=t.contentRect.height/r*this._renderer.resolution;(this._lastScaleX!==n||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=n,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||at.shared.add(this.updateTranslation,this,Si.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&at.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform="",this._lastScaleX=null,this._lastScaleY=null}}class ns{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=ns.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new xe,this.page=new xe,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=e}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(e,t,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,i,r,n){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var xn=/iPhone/i,kl=/iPod/i,Ol=/iPad/i,Bl=/\biOS-universal(?:.+)Mac\b/i,vn=/\bAndroid(?:.+)Mobile\b/i,Dl=/Android/i,Ai=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,ir=/Silk/i,Rt=/Windows Phone/i,Nl=/\bWindows(?:.+)ARM\b/i,Ul=/BlackBerry/i,Fl=/BB10/i,Gl=/Opera Mini/i,Ll=/\b(CriOS|Chrome)(?:.+)Mobile/i,Wl=/Mobile(?:.+)Firefox\b/i,Hl=function(s){return typeof s<"u"&&s.platform==="MacIntel"&&typeof s.maxTouchPoints=="number"&&s.maxTouchPoints>1&&typeof MSStream>"u"};function jm(s){return function(e){return e.test(s)}}function Vl(s){var e={userAgent:"",platform:"",maxTouchPoints:0};!s&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof s=="string"?e.userAgent=s:s&&s.userAgent&&(e={userAgent:s.userAgent,platform:s.platform,maxTouchPoints:s.maxTouchPoints||0});var t=e.userAgent,i=t.split("[FBAN");typeof i[1]<"u"&&(t=i[0]),i=t.split("Twitter"),typeof i[1]<"u"&&(t=i[0]);var r=jm(t),n={apple:{phone:r(xn)&&!r(Rt),ipod:r(kl),tablet:!r(xn)&&(r(Ol)||Hl(e))&&!r(Rt),universal:r(Bl),device:(r(xn)||r(kl)||r(Ol)||r(Bl)||Hl(e))&&!r(Rt)},amazon:{phone:r(Ai),tablet:!r(Ai)&&r(ir),device:r(Ai)||r(ir)},android:{phone:!r(Rt)&&r(Ai)||!r(Rt)&&r(vn),tablet:!r(Rt)&&!r(Ai)&&!r(vn)&&(r(ir)||r(Dl)),device:!r(Rt)&&(r(Ai)||r(ir)||r(vn)||r(Dl))||r(/\bokhttp\b/i)},windows:{phone:r(Rt),tablet:r(Nl),device:r(Rt)||r(Nl)},other:{blackberry:r(Ul),blackberry10:r(Fl),opera:r(Gl),firefox:r(Wl),chrome:r(Ll),device:r(Ul)||r(Fl)||r(Gl)||r(Wl)||r(Ll)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const Xm=(Vl.default??Vl)(globalThis.navigator),Ym=9,zl=100,qm=0,Km=0,$l=2,jl=1,Zm=-1e3,Jm=-1e3,Qm=2,Cn=class gf{constructor(e,t=Xm){this._mobileInfo=t,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(t.tablet||t.phone)&&this._createTouchHook(),this._renderer=e}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){const e=document.createElement("button");e.style.width=`${jl}px`,e.style.height=`${jl}px`,e.style.position="absolute",e.style.top=`${Zm}px`,e.style.left=`${Jm}px`,e.style.zIndex=Qm.toString(),e.style.backgroundColor="#FF0000",e.title="select to enable accessibility for this content",e.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(e),this._hookDiv=e}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.position="absolute",this._div.style.top=`${qm}px`,this._div.style.left=`${Km}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=$l.toString(),this._canvasObserver=new Pl({domElement:this._div,renderer:this._renderer})),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._deactivateOnMouseMove&&globalThis.document.addEventListener("mousemove",this._boundOnMouseMove,!0);const e=this._renderer.view.canvas;if(e.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{const t=new MutationObserver(()=>{e.parentNode&&(t.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});t.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){var e,t;if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const i of this._children)(e=i._accessibleDiv)!=null&&e.parentNode&&(i._accessibleDiv.parentNode.removeChild(i._accessibleDiv),i._accessibleDiv=null),i._accessibleActive=!1;for(const i in this._pools)this._pools[i].forEach(n=>{n.parentNode&&n.parentNode.removeChild(n)}),delete this._pools[i];(t=this._div)!=null&&t.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(e){if(!e.visible||!e.accessibleChildren)return;e.accessible&&(e._accessibleActive||this._addChild(e),e._renderId=this._renderId);const t=e.children;if(t)for(let i=0;i<t.length;i++)this._updateAccessibleObjects(t[i])}init(e){const i={accessibilityOptions:{...gf.defaultOptions,...(e==null?void 0:e.accessibilityOptions)||{}}};this.debug=i.accessibilityOptions.debug,this._activateOnTab=i.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=i.accessibilityOptions.deactivateOnMouseMove,i.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){const e=performance.now();if(this._mobileInfo.android.device&&e<this._androidUpdateCount||(this._androidUpdateCount=e+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;const t=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(const i of this._children)i._renderId===this._renderId&&t.add(this._children.indexOf(i))}for(let i=this._children.length-1;i>=0;i--){const r=this._children[i];t.has(i)||(r._accessibleDiv&&r._accessibleDiv.parentNode&&(r._accessibleDiv.parentNode.removeChild(r._accessibleDiv),this._getPool(r.accessibleType).push(r._accessibleDiv),r._accessibleDiv=null),r._accessibleActive=!1,za(this._children,i,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let i=0;i<this._children.length;i++){const r=this._children[i];if(!r._accessibleActive||!r._accessibleDiv)continue;const n=r._accessibleDiv,o=r.hitArea||r.getBounds().rectangle;if(r.hitArea){const a=r.worldTransform;n.style.left=`${a.tx+o.x*a.a}px`,n.style.top=`${a.ty+o.y*a.d}px`,n.style.width=`${o.width*a.a}px`,n.style.height=`${o.height*a.d}px`}else this._capHitArea(o),n.style.left=`${o.x}px`,n.style.top=`${o.y}px`,n.style.width=`${o.width}px`,n.style.height=`${o.height}px`}this._renderId++}_updateDebugHTML(e){e.innerHTML=`type: ${e.type}</br> title : ${e.title}</br> tabIndex: ${e.tabIndex}`}_capHitArea(e){e.x<0&&(e.width+=e.x,e.x=0),e.y<0&&(e.height+=e.y,e.y=0);const{width:t,height:i}=this._renderer;e.x+e.width>t&&(e.width=t-e.x),e.y+e.height>i&&(e.height=i-e.y)}_addChild(e){let i=this._getPool(e.accessibleType).pop();i?(i.innerHTML="",i.removeAttribute("title"),i.removeAttribute("aria-label"),i.tabIndex=0):(e.accessibleType==="button"?i=document.createElement("button"):(i=document.createElement(e.accessibleType),i.style.cssText=`
299
299
  color: transparent;
300
300
  pointer-events: none;
301
301
  padding: 0;
@@ -308,7 +308,7 @@ Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!mi.noColor
308
308
  -webkit-user-select: none;
309
309
  -moz-user-select: none;
310
310
  -ms-user-select: none;
311
- `,e.accessibleText&&(i.innerText=e.accessibleText)),i.style.width=`${zl}px`,i.style.height=`${zl}px`,i.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",i.style.position="absolute",i.style.zIndex=$l.toString(),i.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?i.setAttribute("aria-live","off"):i.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?i.setAttribute("aria-relevant","additions"):i.setAttribute("aria-relevant","text"),i.addEventListener("click",this._onClick.bind(this)),i.addEventListener("focus",this._onFocus.bind(this)),i.addEventListener("focusout",this._onFocusOut.bind(this))),i.style.pointerEvents=e.accessiblePointerEvents,i.type=e.accessibleType,e.accessibleTitle&&e.accessibleTitle!==null?i.title=e.accessibleTitle:(!e.accessibleHint||e.accessibleHint===null)&&(i.title=`container ${e.tabIndex}`),e.accessibleHint&&e.accessibleHint!==null&&i.setAttribute("aria-label",e.accessibleHint),e.interactive?i.tabIndex=e.tabIndex:i.tabIndex=0,this.debug&&this._updateDebugHTML(i),e._accessibleActive=!0,e._accessibleDiv=i,i.container=e,this._children.push(e),this._div.appendChild(e._accessibleDiv)}_dispatchEvent(e,t){const{container:i}=e.target,r=this._renderer.events.rootBoundary,n=Object.assign(new ns(r),{target:i});r.rootTarget=this._renderer.lastObjectRendered,t.forEach(o=>r.dispatchEvent(n,o))}_onClick(e){this._dispatchEvent(e,["click","pointertap","tap"])}_onFocus(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","assertive"),this._dispatchEvent(e,["mouseover"])}_onFocusOut(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","polite"),this._dispatchEvent(e,["mouseout"])}_onKeyDown(e){e.keyCode!==Xm||!this._activateOnTab||this._activate()}_onMouseMove(e){e.movementX===0&&e.movementY===0||this._deactivate()}destroy(){var e;this._deactivate(),this._destroyTouchHook(),(e=this._canvasObserver)==null||e.destroy(),this._canvasObserver=null,this._div=null,this._pools=null,this._children=null,this._renderer=null,this._hookDiv=null,globalThis.removeEventListener("keydown",this._boundOnKeyDown),this._boundOnKeyDown=null,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._boundOnMouseMove=null}setAccessibilityEnabled(e){e?this._activate():this._deactivate()}_getPool(e){return this._pools[e]||(this._pools[e]=[]),this._pools[e]}};Cn.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"accessibility"},Cn.defaultOptions={enabledByDefault:!1,debug:!1,activateOnTab:!0,deactivateOnMouseMove:!0};let Qm=Cn;const eg={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,accessibleType:"button",accessibleText:null,accessiblePointerEvents:"auto",accessibleChildren:!0,_accessibleActive:!1,_accessibleDiv:null,_renderId:-1};let wi;function Xl(){return(!wi||wi!=null&&wi.isContextLost())&&(wi=pe.get().createCanvas().getContext("webgl",{})),wi}let ir;function tg(){if(!ir){ir="mediump";const s=Xl();s&&s.getShaderPrecisionFormat&&(ir=s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision?"highp":"mediump")}return ir}function ig(s,e,t){return e?s:t?(s=s.replace("out vec4 finalColor;",""),`
311
+ `,e.accessibleText&&(i.innerText=e.accessibleText)),i.style.width=`${zl}px`,i.style.height=`${zl}px`,i.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",i.style.position="absolute",i.style.zIndex=$l.toString(),i.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?i.setAttribute("aria-live","off"):i.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?i.setAttribute("aria-relevant","additions"):i.setAttribute("aria-relevant","text"),i.addEventListener("click",this._onClick.bind(this)),i.addEventListener("focus",this._onFocus.bind(this)),i.addEventListener("focusout",this._onFocusOut.bind(this))),i.style.pointerEvents=e.accessiblePointerEvents,i.type=e.accessibleType,e.accessibleTitle&&e.accessibleTitle!==null?i.title=e.accessibleTitle:(!e.accessibleHint||e.accessibleHint===null)&&(i.title=`container ${e.tabIndex}`),e.accessibleHint&&e.accessibleHint!==null&&i.setAttribute("aria-label",e.accessibleHint),e.interactive?i.tabIndex=e.tabIndex:i.tabIndex=0,this.debug&&this._updateDebugHTML(i),e._accessibleActive=!0,e._accessibleDiv=i,i.container=e,this._children.push(e),this._div.appendChild(e._accessibleDiv)}_dispatchEvent(e,t){const{container:i}=e.target,r=this._renderer.events.rootBoundary,n=Object.assign(new ns(r),{target:i});r.rootTarget=this._renderer.lastObjectRendered,t.forEach(o=>r.dispatchEvent(n,o))}_onClick(e){this._dispatchEvent(e,["click","pointertap","tap"])}_onFocus(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","assertive"),this._dispatchEvent(e,["mouseover"])}_onFocusOut(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","polite"),this._dispatchEvent(e,["mouseout"])}_onKeyDown(e){e.keyCode!==Ym||!this._activateOnTab||this._activate()}_onMouseMove(e){e.movementX===0&&e.movementY===0||this._deactivate()}destroy(){var e;this._deactivate(),this._destroyTouchHook(),(e=this._canvasObserver)==null||e.destroy(),this._canvasObserver=null,this._div=null,this._pools=null,this._children=null,this._renderer=null,this._hookDiv=null,globalThis.removeEventListener("keydown",this._boundOnKeyDown),this._boundOnKeyDown=null,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._boundOnMouseMove=null}setAccessibilityEnabled(e){e?this._activate():this._deactivate()}_getPool(e){return this._pools[e]||(this._pools[e]=[]),this._pools[e]}};Cn.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"accessibility"},Cn.defaultOptions={enabledByDefault:!1,debug:!1,activateOnTab:!0,deactivateOnMouseMove:!0};let eg=Cn;const tg={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,accessibleType:"button",accessibleText:null,accessiblePointerEvents:"auto",accessibleChildren:!0,_accessibleActive:!1,_accessibleDiv:null,_renderId:-1};let wi;function Xl(){return(!wi||wi!=null&&wi.isContextLost())&&(wi=pe.get().createCanvas().getContext("webgl",{})),wi}let sr;function ig(){if(!sr){sr="mediump";const s=Xl();s&&s.getShaderPrecisionFormat&&(sr=s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision?"highp":"mediump")}return sr}function sg(s,e,t){return e?s:t?(s=s.replace("out vec4 finalColor;",""),`
312
312
 
313
313
  #ifdef GL_ES // This checks if it is WebGL1
314
314
  #define in varying
@@ -323,18 +323,18 @@ Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!mi.noColor
323
323
  #define out varying
324
324
  #endif
325
325
  ${s}
326
- `}function sg(s,e,t){const i=t?e.maxSupportedFragmentPrecision:e.maxSupportedVertexPrecision;if(s.substring(0,9)!=="precision"){let r=t?e.requestedFragmentPrecision:e.requestedVertexPrecision;return r==="highp"&&i!=="highp"&&(r="mediump"),`precision ${r} float;
327
- ${s}`}else if(i!=="highp"&&s.substring(0,15)==="precision highp")return s.replace("precision highp","precision mediump");return s}function rg(s,e){return e?`#version 300 es
328
- ${s}`:s}const ng={},og={};function ag(s,{name:e="pixi-program"},t=!0){e=e.replace(/\s+/g,"-"),e+=t?"-fragment":"-vertex";const i=t?ng:og;return i[e]?(i[e]++,e+=`-${i[e]}`):i[e]=1,s.indexOf("#define SHADER_NAME")!==-1?s:`${`#define SHADER_NAME ${e}`}
329
- ${s}`}function lg(s,e){return e?s.replace("#version 300 es",""):s}const Sn={stripVersion:lg,ensurePrecision:sg,addProgramDefines:ig,setProgramName:ag,insertVersion:rg},os=Object.create(null),Yl=class na{constructor(e){e={...na.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,i={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:tg()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let r=e.fragment,n=e.vertex;Object.keys(Sn).forEach(o=>{const a=i[o];r=Sn[o](r,a,!0),n=Sn[o](n,a,!1)}),this.fragment=r,this.vertex=n,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=qi(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,os[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return os[t]||(os[t]=new na(e),os[t]._cacheKey=t),os[t]}};Yl.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let Ii=Yl;const cg={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",vec2i:"sint32x2",vec3i:"sint32x3",vec4i:"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",vec2u:"uint32x2",vec3u:"uint32x3",vec4u:"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"},ql=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function Kl(s,e){let t;for(;(t=ql.exec(s))!==null;){const i=cg[t[3]]??"float32";e[t[2]]={location:parseInt(t[1],10),format:i,stride:At(i).stride,offset:0,instance:!1,start:0}}ql.lastIndex=0}function hg(s){return s.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function ug({source:s,entryPoint:e}){const t={},i=hg(s),r=i.indexOf(`fn ${e}(`);if(r===-1)return t;const n=i.indexOf("->",r);if(n===-1)return t;const o=i.substring(r,n);if(Kl(o,t),Object.keys(t).length===0){const a=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(a){const l=a[1],c=new RegExp(`struct\\s+${l}\\s*\\{([^}]+)\\}`,"s"),h=i.match(c);h&&Kl(h[1],t)}}return t}function En(s){var u,f;const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,i=/@binding\((\d+)\)/,r=/var(<[^>]+>)? (\w+)/,n=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,c=(u=s.match(e))==null?void 0:u.map(d=>({group:parseInt(d.match(t)[1],10),binding:parseInt(d.match(i)[1],10),name:d.match(r)[2],isUniform:d.match(r)[1]==="<uniform>",type:d.match(n)[1]}));if(!c)return{groups:[],structs:[]};const h=((f=s.match(o))==null?void 0:f.map(d=>{const g=d.match(l)[1],_=d.match(a).reduce((b,x)=>{const[C,S]=x.split(":");return b[C.trim()]=S.trim(),b},{});return _?{name:g,members:_}:null}).filter(({name:d})=>c.some(g=>g.type===d||g.type.includes(`<${d}>`))))??[];return{groups:c,structs:h}}var ni=(s=>(s[s.VERTEX=1]="VERTEX",s[s.FRAGMENT=2]="FRAGMENT",s[s.COMPUTE=4]="COMPUTE",s))(ni||{});function dg({groups:s}){const e=[];for(let t=0;t<s.length;t++){const i=s[t];e[i.group]||(e[i.group]=[]),i.isUniform?e[i.group].push({binding:i.binding,visibility:ni.VERTEX|ni.FRAGMENT,buffer:{type:"uniform"}}):i.type==="sampler"?e[i.group].push({binding:i.binding,visibility:ni.FRAGMENT,sampler:{type:"filtering"}}):i.type==="texture_2d"||i.type.startsWith("texture_2d<")?e[i.group].push({binding:i.binding,visibility:ni.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}}):i.type==="texture_2d_array"||i.type.startsWith("texture_2d_array<")?e[i.group].push({binding:i.binding,visibility:ni.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array",multisampled:!1}}):(i.type==="texture_cube"||i.type.startsWith("texture_cube<"))&&e[i.group].push({binding:i.binding,visibility:ni.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let t=0;t<e.length;t++)e[t]||(e[t]=[]);return e}function fg({groups:s}){const e=[];for(let t=0;t<s.length;t++){const i=s[t];e[i.group]||(e[i.group]={}),e[i.group][i.name]=i.binding}return e}function pg(s,e){const t=new Set,i=new Set,r=[...s.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),n=[...s.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return i.has(a)?!1:(i.add(a),!0)});return{structs:r,groups:n}}const as=Object.create(null);class oi{constructor(e){var a,l;this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:i,layout:r,gpuLayout:n,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=i,t.source===i.source){const c=En(t.source);this.structsAndGroups=c}else{const c=En(i.source),h=En(t.source);this.structsAndGroups=pg(c,h)}this.layout=r??fg(this.structsAndGroups),this.gpuLayout=n??dg(this.structsAndGroups),this.autoAssignGlobalUniforms=((a=this.layout[0])==null?void 0:a.globalUniforms)!==void 0,this.autoAssignLocalUniforms=((l=this.layout[1])==null?void 0:l.localUniforms)!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,i=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=qi(i,"program")}get attributeData(){return this._attributeData??(this._attributeData=ug(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,as[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return as[t]||(as[t]=new oi(e),as[t]._cacheKey=t),as[t]}}class Gt{constructor(e){this.resources=Object.create(null),this._dirty=!0;let t=0;for(const i in e){const r=e[i];this.setResource(r,t++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const e=[];let t=0;for(const i in this.resources)e[t++]=this.resources[i]._resourceId;this._key=e.join("|")}setResource(e,t){var r,n;const i=this.resources[t];e!==i&&((r=i==null?void 0:i.off)==null||r.call(i,"change",this.onResourceChange,this),(n=e.on)==null||n.call(e,"change",this.onResourceChange,this),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e,t){const i=this.resources;for(const r in i)i[r]._gcLastUsed=e,i[r]._touched=t}destroy(){var t;const e=this.resources;for(const i in e){const r=e[i];(t=r==null?void 0:r.off)==null||t.call(r,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(e){this._dirty=!0,e.destroyed?this.destroy():this._updateKey()}}var bt=(s=>(s[s.WEBGL=1]="WEBGL",s[s.WEBGPU=2]="WEBGPU",s[s.CANVAS=4]="CANVAS",s[s.BOTH=3]="BOTH",s))(bt||{});class Mt extends lt{constructor(e){super(),this.uid=be("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:i,groups:r,resources:n,compatibleRenderers:o,groupMap:a}=e;this.gpuProgram=t,this.glProgram=i,o===void 0&&(o=0,t&&(o|=bt.WEBGPU),i&&(o|=bt.WEBGL)),this.compatibleRenderers=o;const l={};if(!n&&!r&&(n={}),n&&r)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&r&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!t&&r&&a)for(const c in a)for(const h in a[c]){const u=a[c][h];l[u]={group:c,binding:h,name:u}}else if(t&&r&&!a){const c=t.structsAndGroups.groups;a={},c.forEach(h=>{a[h.group]=a[h.group]||{},a[h.group][h.binding]=h.name,l[h.name]=h})}else if(n){r={},a={},t&&t.structsAndGroups.groups.forEach(u=>{a[u.group]=a[u.group]||{},a[u.group][u.binding]=u.name,l[u.name]=u});let c=0;for(const h in n)l[h]||(r[99]||(r[99]=new Gt,this._ownedBindGroups.push(r[99])),l[h]={group:99,binding:c,name:h},a[99]=a[99]||{},a[99][c]=h,c++);for(const h in n){const u=h;let f=n[h];!f.source&&!f._resourceType&&(f=new ht(f));const d=l[u];d&&(r[d.group]||(r[d.group]=new Gt,this._ownedBindGroups.push(r[d.group])),r[d.group].setResource(f,d.binding))}}this.groups=r,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(r,l)}addResource(e,t,i){var r,n;(r=this._uniformBindMap)[t]||(r[t]={}),(n=this._uniformBindMap[t])[i]||(n[i]=e),this.groups[t]||(this.groups[t]=new Gt,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const i={};for(const r in t){const n=t[r];Object.defineProperty(i,n.name,{get(){return e[n.group].getResource(n.binding)},set(o){e[n.group].setResource(o,n.binding)}})}return i}destroy(e=!1){var t,i;this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&((t=this.gpuProgram)==null||t.destroy(),(i=this.glProgram)==null||i.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(r=>{r.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(e){const{gpu:t,gl:i,...r}=e;let n,o;return t&&(n=oi.from(t)),i&&(o=Ii.from(i)),new Mt({gpuProgram:n,glProgram:o,...r})}}const mg={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},Tn=0,An=1,wn=2,In=3,Rn=4,Mn=5,Pn=class _f{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<Tn)}set blend(e){!!(this.data&1<<Tn)!==e&&(this.data^=1<<Tn)}get offsets(){return!!(this.data&1<<An)}set offsets(e){!!(this.data&1<<An)!==e&&(this.data^=1<<An)}set cullMode(e){if(e==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=e==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<wn)}set culling(e){!!(this.data&1<<wn)!==e&&(this.data^=1<<wn)}get depthTest(){return!!(this.data&1<<In)}set depthTest(e){!!(this.data&1<<In)!==e&&(this.data^=1<<In)}get depthMask(){return!!(this.data&1<<Mn)}set depthMask(e){!!(this.data&1<<Mn)!==e&&(this.data^=1<<Mn)}get clockwiseFrontFace(){return!!(this.data&1<<Rn)}set clockwiseFrontFace(e){!!(this.data&1<<Rn)!==e&&(this.data^=1<<Rn)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=mg[e]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(e){this.offsets=!!e,this._polygonOffset=e}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const e=new _f;return e.depthTest=!1,e.blend=!0,e}};Pn.default2d=Pn.for2d();let Pt=Pn;const Zl=class oa extends Mt{constructor(e){e={...oa.defaultOptions,...e},super(e),this.enabled=!0,this._state=Pt.for2d(),this.blendMode=e.blendMode,this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.clipToViewport=e.clipToViewport,this.addResource("uTexture",0,1),e.blendRequired&&this.addResource("uBackTexture",0,3)}apply(e,t,i,r){e.applyFilter(this,t,i,r)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:i,...r}=e;let n,o;return t&&(n=oi.from(t)),i&&(o=Ii.from(i)),new oa({gpuProgram:n,glProgram:o,...r})}};Zl.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Jl=Zl,sr;function gg(s){return sr!==void 0||(sr=(()=>{var t;const e={stencil:!0,failIfMajorPerformanceCaveat:s??vi.defaultOptions.failIfMajorPerformanceCaveat};try{if(!pe.get().getWebGLRenderingContext())return!1;let r=pe.get().createCanvas().getContext("webgl",e);const n=!!((t=r==null?void 0:r.getContextAttributes())!=null&&t.stencil);if(r){const o=r.getExtension("WEBGL_lose_context");o&&o.loseContext()}return r=null,n}catch{return!1}})()),sr}let rr;async function _g(s={}){return rr!==void 0||(rr=await(async()=>{const e=pe.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(s)).requestDevice(),!0}catch{return!1}})()),rr}const Ql=["webgl","webgpu","canvas"];async function yg(s){let e=[];s.preference?(e.push(s.preference),Ql.forEach(n=>{n!==s.preference&&e.push(n)})):e=Ql.slice();let t,i={};for(let n=0;n<e.length;n++){const o=e[n];if(o==="webgpu"&&await _g()){const{WebGPURenderer:a}=await Promise.resolve().then(()=>hx);t=a,i={...s,...s.webgpu};break}else if(o==="webgl"&&gg(s.failIfMajorPerformanceCaveat??vi.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await Promise.resolve().then(()=>$b);t=a,i={...s,...s.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await Promise.resolve().then(()=>ob);t=a,i={...s,...s.canvasOptions};break}}if(delete i.webgpu,delete i.webgl,delete i.canvasOptions,!t)throw new Error("No available renderer for the current environment");const r=new t;return await r.init(i),r}const nr="8.17.1";class ec{static init(){var e;(e=globalThis.__PIXI_APP_INIT__)==null||e.call(globalThis,this,nr)}static destroy(){}}ec.extension=A.Application;class tc{constructor(e){this._renderer=e}init(){var e;(e=globalThis.__PIXI_RENDERER_INIT__)==null||e.call(globalThis,this._renderer,nr)}destroy(){this._renderer=null}}tc.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"initHook",priority:-10};class ic{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(t){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=t,t&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let t,i;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,i=globalThis.innerHeight;else{const{clientWidth:r,clientHeight:n}=this._resizeTo;t=r,i=n}this.renderer.resize(t,i),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}ic.extension=A.Application;class sc{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,Si.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?at.shared:new at,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}sc.extension=A.Application,Q.add(ic),Q.add(sc);const rc=class aa{constructor(...e){this.stage=new Ve,e[0]!==void 0&&ee(Be,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new Ve),this.renderer=await yg(e),aa._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return ee(Be,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(e=!1,t=!1){const i=aa._plugins.slice(0);i.reverse(),i.forEach(r=>{r.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};rc._plugins=[];let nc=rc;Q.handleByList(A.Application,nc._plugins),Q.add(ec);var kn,oc;function bg(){if(oc)return kn;oc=1,kn=t;var s={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},e=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function t(n){var o=[];return n.replace(e,function(a,l,c){var h=l.toLowerCase();for(c=r(c),h=="m"&&c.length>2&&(o.push([l].concat(c.splice(0,2))),h="l",l=l=="m"?"l":"L");;){if(c.length==s[h])return c.unshift(l),o.push(c);if(c.length<s[h])throw new Error("malformed path data");o.push([l].concat(c.splice(0,s[h])))}}),o}var i=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function r(n){var o=n.match(i);return o?o.map(Number):[]}return kn}var xg=bg();const vg=pa(xg);function Cg(s,e){const t=vg(s),i=[];let r=null,n=0,o=0;for(let a=0;a<t.length;a++){const l=t[a],c=l[0],h=l;switch(c){case"M":n=h[1],o=h[2],e.moveTo(n,o);break;case"m":n+=h[1],o+=h[2],e.moveTo(n,o);break;case"H":n=h[1],e.lineTo(n,o);break;case"h":n+=h[1],e.lineTo(n,o);break;case"V":o=h[1],e.lineTo(n,o);break;case"v":o+=h[1],e.lineTo(n,o);break;case"L":n=h[1],o=h[2],e.lineTo(n,o);break;case"l":n+=h[1],o+=h[2],e.lineTo(n,o);break;case"C":n=h[5],o=h[6],e.bezierCurveTo(h[1],h[2],h[3],h[4],n,o);break;case"c":e.bezierCurveTo(n+h[1],o+h[2],n+h[3],o+h[4],n+h[5],o+h[6]),n+=h[5],o+=h[6];break;case"S":n=h[3],o=h[4],e.bezierCurveToShort(h[1],h[2],n,o);break;case"s":e.bezierCurveToShort(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"Q":n=h[3],o=h[4],e.quadraticCurveTo(h[1],h[2],n,o);break;case"q":e.quadraticCurveTo(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"T":n=h[1],o=h[2],e.quadraticCurveToShort(n,o);break;case"t":n+=h[1],o+=h[2],e.quadraticCurveToShort(n,o);break;case"A":n=h[6],o=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"a":n+=h[6],o+=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"Z":case"z":e.closePath(),i.length>0&&(r=i.pop(),r?(n=r.startX,o=r.startY):(n=0,o=0)),r=null;break;default:se(`Unknown SVG path command: ${c}`)}c!=="Z"&&c!=="z"&&r===null&&(r={startX:n,startY:o},i.push(r))}return e}class On{constructor(e=0,t=0,i=0){this.type="circle",this.x=e,this.y=t,this.radius=i}clone(){return new On(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;const i=this.radius*this.radius;let r=this.x-e,n=this.y-t;return r*=r,n*=n,r+n<=i}strokeContains(e,t,i,r=.5){if(this.radius===0)return!1;const n=this.x-e,o=this.y-t,a=this.radius,l=(1-r)*i,c=Math.sqrt(n*n+o*o);return c<=a+l&&c>a-(i-l)}getBounds(e){return e||(e=new Se),e.x=this.x-this.radius,e.y=this.y-this.radius,e.width=this.radius*2,e.height=this.radius*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.radius=e.radius,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class Bn{constructor(e=0,t=0,i=0,r=0){this.type="ellipse",this.x=e,this.y=t,this.halfWidth=i,this.halfHeight=r}clone(){return new Bn(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let i=(e-this.x)/this.halfWidth,r=(t-this.y)/this.halfHeight;return i*=i,r*=r,i+r<=1}strokeContains(e,t,i,r=.5){const{halfWidth:n,halfHeight:o}=this;if(n<=0||o<=0)return!1;const a=i*(1-r),l=i-a,c=n-l,h=o-l,u=n+a,f=o+a,d=e-this.x,g=t-this.y,_=d*d/(c*c)+g*g/(h*h),b=d*d/(u*u)+g*g/(f*f);return _>1&&b<=1}getBounds(e){return e||(e=new Se),e.x=this.x-this.halfWidth,e.y=this.y-this.halfHeight,e.width=this.halfWidth*2,e.height=this.halfHeight*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.halfWidth=e.halfWidth,this.halfHeight=e.halfHeight,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function Sg(s,e,t,i,r,n){const o=s-t,a=e-i,l=r-t,c=n-i,h=o*l+a*c,u=l*l+c*c;let f=-1;u!==0&&(f=h/u);let d,g;f<0?(d=t,g=i):f>1?(d=r,g=n):(d=t+f*l,g=i+f*c);const _=s-d,b=e-g;return _*_+b*b}let Eg,Tg;class ls{constructor(...e){this.type="polygon";let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!="number"){const i=[];for(let r=0,n=t.length;r<n;r++)i.push(t[r].x,t[r].y);t=i}this.points=t,this.closePath=!0}isClockwise(){let e=0;const t=this.points,i=t.length;for(let r=0;r<i;r+=2){const n=t[r],o=t[r+1],a=t[(r+2)%i],l=t[(r+3)%i];e+=(a-n)*(l+o)}return e<0}containsPolygon(e){const t=this.getBounds(Eg),i=e.getBounds(Tg);if(!t.containsRect(i))return!1;const r=e.points;for(let n=0;n<r.length;n+=2){const o=r[n],a=r[n+1];if(!this.contains(o,a))return!1}return!0}clone(){const e=this.points.slice(),t=new ls(e);return t.closePath=this.closePath,t}contains(e,t){let i=!1;const r=this.points.length/2;for(let n=0,o=r-1;n<r;o=n++){const a=this.points[n*2],l=this.points[n*2+1],c=this.points[o*2],h=this.points[o*2+1];l>t!=h>t&&e<(c-a)*((t-l)/(h-l))+a&&(i=!i)}return i}strokeContains(e,t,i,r=.5){const n=i*i,o=n*(1-r),a=n-o,{points:l}=this,c=l.length-(this.closePath?0:2);for(let h=0;h<c;h+=2){const u=l[h],f=l[h+1],d=l[(h+2)%l.length],g=l[(h+3)%l.length],_=Sg(e,t,u,f,d,g),b=Math.sign((d-u)*(t-f)-(g-f)*(e-u));if(_<=(b<0?a:o))return!0}return!1}getBounds(e){e||(e=new Se);const t=this.points;let i=1/0,r=-1/0,n=1/0,o=-1/0;for(let a=0,l=t.length;a<l;a+=2){const c=t[a],h=t[a+1];i=c<i?c:i,r=c>r?c:r,n=h<n?h:n,o=h>o?h:o}return e.x=i,e.width=r-i,e.y=n,e.height=o-n,e}copyFrom(e){return this.points=e.points.slice(),this.closePath=e.closePath,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((e,t)=>`${e}, ${t}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return ee("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return ee("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const or=(s,e,t,i,r,n,o)=>{const a=s-t,l=e-i,c=Math.sqrt(a*a+l*l);return c>=r-n&&c<=r+o};class Dn{constructor(e=0,t=0,i=0,r=0,n=20){this.type="roundedRectangle",this.x=e,this.y=t,this.width=i,this.height=r,this.radius=n}getBounds(e){return e||(e=new Se),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new Dn(this.x,this.y,this.width,this.height,this.radius)}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){if(this.width<=0||this.height<=0)return!1;if(e>=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){const i=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+i&&t<=this.y+this.height-i||e>=this.x+i&&e<=this.x+this.width-i)return!0;let r=e-(this.x+i),n=t-(this.y+i);const o=i*i;if(r*r+n*n<=o||(r=e-(this.x+this.width-i),r*r+n*n<=o)||(n=t-(this.y+this.height-i),r*r+n*n<=o)||(r=e-(this.x+i),r*r+n*n<=o))return!0}return!1}strokeContains(e,t,i,r=.5){const{x:n,y:o,width:a,height:l,radius:c}=this,h=i*(1-r),u=i-h,f=n+c,d=o+c,g=a-c*2,_=l-c*2,b=n+a,x=o+l;return(e>=n-h&&e<=n+u||e>=b-u&&e<=b+h)&&t>=d&&t<=d+_||(t>=o-h&&t<=o+u||t>=x-u&&t<=x+h)&&e>=f&&e<=f+g?!0:e<f&&t<d&&or(e,t,f,d,c,u,h)||e>b-c&&t<d&&or(e,t,b-c,d,c,u,h)||e>b-c&&t>x-c&&or(e,t,b-c,x-c,c,u,h)||e<f&&t>x-c&&or(e,t,f,x-c,c,u,h)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const ac={};function Nn(s,e,t){let i=2166136261;for(let r=0;r<e;r++)i^=s[r].uid,i=Math.imul(i,16777619),i>>>=0;return ac[i]||Ag(s,e,i,t)}function Ag(s,e,t,i){const r={};let n=0;for(let a=0;a<i;a++){const l=a<e?s[a]:j.EMPTY.source;r[n++]=l.source,r[n++]=l.style}const o=new Gt(r);return ac[t]=o,o}function Un(s,e,t,i){if(t??(t=0),i??(i=Math.min(s.byteLength-t,e.byteLength)),!(t&7)&&!(i&7)){const r=i/8;new Float64Array(e,0,r).set(new Float64Array(s,t,r))}else if(!(t&3)&&!(i&3)){const r=i/4;new Float32Array(e,0,r).set(new Float32Array(s,t,r))}else new Uint8Array(e).set(new Uint8Array(s,t,i))}const wg={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var ke=(s=>(s[s.DISABLED=0]="DISABLED",s[s.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",s[s.MASK_ACTIVE=2]="MASK_ACTIVE",s[s.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",s[s.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",s[s.NONE=5]="NONE",s))(ke||{});function lc(s,e){return e.alphaMode==="no-premultiply-alpha"&&wg[s]||s}const Ig=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
330
- `);function Rg(s){let e="";for(let t=0;t<s;++t)t>0&&(e+=`
331
- else `),t<s-1&&(e+=`if(test == ${t}.0){}`);return e}function cc(s,e){if(s===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const t=e.createShader(e.FRAGMENT_SHADER);try{for(;;){const i=Ig.replace(/%forloop%/gi,Rg(s));if(e.shaderSource(t,i),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))s=s/2|0;else break}}finally{e.deleteShader(t)}return s}let Ri=null;function Mg(){var e;if(Ri)return Ri;const s=Xl();return Ri=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),Ri=cc(Ri,s),(e=s.getExtension("WEBGL_lose_context"))==null||e.loseContext(),Ri}class Pg{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let e=0;e<this.count;e++){const t=this.textures[e];this.textures[e]=null,this.ids[t.uid]=null}this.count=0}}class kg{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new Pg,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null,this.elements=null}}const cs=[];let ar=0;_i.register({clear:()=>{if(cs.length>0)for(const s of cs)s&&s.destroy();cs.length=0,ar=0}});function hc(){return ar>0?cs[--ar]:new kg}function uc(s){s.elements=null,cs[ar++]=s}let hs=0;const dc=class yf{constructor(e){this.uid=be("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],e={...yf.defaultOptions,...e},e.maxTextures||(ee("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),e.maxTextures=Mg());const{maxTextures:t,attributesInitialSize:i,indicesInitialSize:r}=e;this.attributeBuffer=new Ci(i*4),this.indexBuffer=new Uint16Array(r),this.maxTextures=t}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let e=0;e<this.batchIndex;e++)uc(this.batches[e]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(e){this._elements[this.elementSize++]=e,e._indexStart=this.indexSize,e._attributeStart=this.attributeSize,e._batcher=this,this.indexSize+=e.indexSize,this.attributeSize+=e.attributeSize*this.vertexSize}checkAndUpdateTexture(e,t){const i=e._batch.textures.ids[t._source.uid];return!i&&i!==0?!1:(e._textureId=i,e.texture=t,!0)}updateElement(e){this.dirty=!0;const t=this.attributeBuffer;e.packAsQuad?this.packQuadAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId):this.packAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId)}break(e){const t=this._elements;if(!t[this.elementStart])return;let i=hc(),r=i.textures;r.clear();const n=t[this.elementStart];let o=lc(n.blendMode,n.texture._source),a=n.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const l=this.attributeBuffer.float32View,c=this.attributeBuffer.uint32View,h=this.indexBuffer;let u=this._batchIndexSize,f=this._batchIndexStart,d="startBatch",g=[];const _=this.maxTextures;for(let b=this.elementStart;b<this.elementSize;++b){const x=t[b];t[b]=null;const S=x.texture._source,E=lc(x.blendMode,S),w=o!==E||a!==x.topology;if(S._batchTick===hs&&!w){x._textureId=S._textureBindLocation,u+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,l,c,x._attributeStart,x._textureId),this.packQuadIndex(h,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,l,c,x._attributeStart,x._textureId),this.packIndex(x,h,x._indexStart,x._attributeStart/this.vertexSize)),x._batch=i,g.push(x);continue}S._batchTick=hs,(r.count>=_||w)&&(this._finishBatch(i,f,u-f,r,o,a,e,d,g),d="renderBatch",f=u,o=E,a=x.topology,i=hc(),r=i.textures,r.clear(),g=[],++hs),x._textureId=S._textureBindLocation=r.count,r.ids[S.uid]=r.count,r.textures[r.count++]=S,x._batch=i,g.push(x),u+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,l,c,x._attributeStart,x._textureId),this.packQuadIndex(h,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,l,c,x._attributeStart,x._textureId),this.packIndex(x,h,x._indexStart,x._attributeStart/this.vertexSize))}r.count>0&&(this._finishBatch(i,f,u-f,r,o,a,e,d,g),f=u,++hs),this.elementStart=this.elementSize,this._batchIndexStart=f,this._batchIndexSize=u}_finishBatch(e,t,i,r,n,o,a,l,c){e.gpuBindGroup=null,e.bindGroup=null,e.action=l,e.batcher=this,e.textures=r,e.blendMode=n,e.topology=o,e.start=t,e.size=i,e.elements=c,++hs,this.batches[this.batchIndex++]=e,a.add(e)}finish(e){this.break(e)}ensureAttributeBuffer(e){e*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(e*4)}ensureIndexBuffer(e){e<=this.indexBuffer.length||this._resizeIndexBuffer(e)}_resizeAttributeBuffer(e){const t=Math.max(e,this.attributeBuffer.size*2),i=new Ci(t);Un(this.attributeBuffer.rawBinaryData,i.rawBinaryData),this.attributeBuffer=i}_resizeIndexBuffer(e){const t=this.indexBuffer;let i=Math.max(e,t.length*1.5);i+=i%2;const r=i>65535?new Uint32Array(i):new Uint16Array(i);if(r.BYTES_PER_ELEMENT!==t.BYTES_PER_ELEMENT)for(let n=0;n<t.length;n++)r[n]=t[n];else Un(t.buffer,r.buffer);this.indexBuffer=r}packQuadIndex(e,t,i){e[t]=i+0,e[t+1]=i+1,e[t+2]=i+2,e[t+3]=i+0,e[t+4]=i+2,e[t+5]=i+3}packIndex(e,t,i,r){const n=e.indices,o=e.indexSize,a=e.indexOffset,l=e.attributeOffset;for(let c=0;c<o;c++)t[i++]=r+n[c+a]-l}destroy(e={}){var t;if(this.batches!==null){for(let i=0;i<this.batchIndex;i++)uc(this.batches[i]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,e.shader&&((t=this.shader)==null||t.destroy(),this.shader=null);for(let i=0;i<this._elements.length;i++)this._elements[i]&&(this._elements[i]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};dc.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let Og=dc;const Bg=new Float32Array(1),Dg=new Uint32Array(1);class Ng extends Js{constructor(){const t=new gt({data:Bg,label:"attribute-batch-buffer",usage:ge.VERTEX|ge.COPY_DST,shrinkToFit:!1}),i=new gt({data:Dg,label:"index-batch-buffer",usage:ge.INDEX|ge.COPY_DST,shrinkToFit:!1}),r=24;super({attributes:{aPosition:{buffer:t,format:"float32x2",stride:r,offset:0},aUV:{buffer:t,format:"float32x2",stride:r,offset:8},aColor:{buffer:t,format:"unorm8x4",stride:r,offset:16},aTextureIdAndRound:{buffer:t,format:"uint16x2",stride:r,offset:20}},indexBuffer:i})}}function fc(s,e,t){if(s)for(const i in s){const r=i.toLocaleLowerCase(),n=e[r];if(n){let o=s[i];i==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),t&&n.push(`//----${t}----//`),n.push(o)}else se(`${i} placement hook does not exist in shader`)}}const Ug=/\{\{(.*?)\}\}/g;function pc(s){var i;const e={};return(((i=s.match(Ug))==null?void 0:i.map(r=>r.replace(/[{()}]/g,"")))??[]).forEach(r=>{e[r]=[]}),e}function mc(s,e){let t;const i=/@in\s+([^;]+);/g;for(;(t=i.exec(s))!==null;)e.push(t[1])}function gc(s,e,t=!1){const i=[];mc(e,i),s.forEach(a=>{a.header&&mc(a.header,i)});const r=i;t&&r.sort();const n=r.map((a,l)=>` @location(${l}) ${a},`).join(`
326
+ `}function rg(s,e,t){const i=t?e.maxSupportedFragmentPrecision:e.maxSupportedVertexPrecision;if(s.substring(0,9)!=="precision"){let r=t?e.requestedFragmentPrecision:e.requestedVertexPrecision;return r==="highp"&&i!=="highp"&&(r="mediump"),`precision ${r} float;
327
+ ${s}`}else if(i!=="highp"&&s.substring(0,15)==="precision highp")return s.replace("precision highp","precision mediump");return s}function ng(s,e){return e?`#version 300 es
328
+ ${s}`:s}const og={},ag={};function lg(s,{name:e="pixi-program"},t=!0){e=e.replace(/\s+/g,"-"),e+=t?"-fragment":"-vertex";const i=t?og:ag;return i[e]?(i[e]++,e+=`-${i[e]}`):i[e]=1,s.indexOf("#define SHADER_NAME")!==-1?s:`${`#define SHADER_NAME ${e}`}
329
+ ${s}`}function cg(s,e){return e?s.replace("#version 300 es",""):s}const Sn={stripVersion:cg,ensurePrecision:rg,addProgramDefines:sg,setProgramName:lg,insertVersion:ng},os=Object.create(null),Yl=class na{constructor(e){e={...na.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,i={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:ig()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let r=e.fragment,n=e.vertex;Object.keys(Sn).forEach(o=>{const a=i[o];r=Sn[o](r,a,!0),n=Sn[o](n,a,!1)}),this.fragment=r,this.vertex=n,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=qi(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,os[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return os[t]||(os[t]=new na(e),os[t]._cacheKey=t),os[t]}};Yl.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let Ii=Yl;const hg={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",vec2i:"sint32x2",vec3i:"sint32x3",vec4i:"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",vec2u:"uint32x2",vec3u:"uint32x3",vec4u:"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"},ql=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function Kl(s,e){let t;for(;(t=ql.exec(s))!==null;){const i=hg[t[3]]??"float32";e[t[2]]={location:parseInt(t[1],10),format:i,stride:At(i).stride,offset:0,instance:!1,start:0}}ql.lastIndex=0}function ug(s){return s.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function dg({source:s,entryPoint:e}){const t={},i=ug(s),r=i.indexOf(`fn ${e}(`);if(r===-1)return t;const n=i.indexOf("->",r);if(n===-1)return t;const o=i.substring(r,n);if(Kl(o,t),Object.keys(t).length===0){const a=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(a){const l=a[1],c=new RegExp(`struct\\s+${l}\\s*\\{([^}]+)\\}`,"s"),h=i.match(c);h&&Kl(h[1],t)}}return t}function En(s){var u,f;const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,i=/@binding\((\d+)\)/,r=/var(<[^>]+>)? (\w+)/,n=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,c=(u=s.match(e))==null?void 0:u.map(d=>({group:parseInt(d.match(t)[1],10),binding:parseInt(d.match(i)[1],10),name:d.match(r)[2],isUniform:d.match(r)[1]==="<uniform>",type:d.match(n)[1]}));if(!c)return{groups:[],structs:[]};const h=((f=s.match(o))==null?void 0:f.map(d=>{const g=d.match(l)[1],_=d.match(a).reduce((y,x)=>{const[C,S]=x.split(":");return y[C.trim()]=S.trim(),y},{});return _?{name:g,members:_}:null}).filter(({name:d})=>c.some(g=>g.type===d||g.type.includes(`<${d}>`))))??[];return{groups:c,structs:h}}var ni=(s=>(s[s.VERTEX=1]="VERTEX",s[s.FRAGMENT=2]="FRAGMENT",s[s.COMPUTE=4]="COMPUTE",s))(ni||{});function fg({groups:s}){const e=[];for(let t=0;t<s.length;t++){const i=s[t];e[i.group]||(e[i.group]=[]),i.isUniform?e[i.group].push({binding:i.binding,visibility:ni.VERTEX|ni.FRAGMENT,buffer:{type:"uniform"}}):i.type==="sampler"?e[i.group].push({binding:i.binding,visibility:ni.FRAGMENT,sampler:{type:"filtering"}}):i.type==="texture_2d"||i.type.startsWith("texture_2d<")?e[i.group].push({binding:i.binding,visibility:ni.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}}):i.type==="texture_2d_array"||i.type.startsWith("texture_2d_array<")?e[i.group].push({binding:i.binding,visibility:ni.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array",multisampled:!1}}):(i.type==="texture_cube"||i.type.startsWith("texture_cube<"))&&e[i.group].push({binding:i.binding,visibility:ni.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let t=0;t<e.length;t++)e[t]||(e[t]=[]);return e}function pg({groups:s}){const e=[];for(let t=0;t<s.length;t++){const i=s[t];e[i.group]||(e[i.group]={}),e[i.group][i.name]=i.binding}return e}function mg(s,e){const t=new Set,i=new Set,r=[...s.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),n=[...s.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return i.has(a)?!1:(i.add(a),!0)});return{structs:r,groups:n}}const as=Object.create(null);class oi{constructor(e){var a,l;this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:i,layout:r,gpuLayout:n,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=i,t.source===i.source){const c=En(t.source);this.structsAndGroups=c}else{const c=En(i.source),h=En(t.source);this.structsAndGroups=mg(c,h)}this.layout=r??pg(this.structsAndGroups),this.gpuLayout=n??fg(this.structsAndGroups),this.autoAssignGlobalUniforms=((a=this.layout[0])==null?void 0:a.globalUniforms)!==void 0,this.autoAssignLocalUniforms=((l=this.layout[1])==null?void 0:l.localUniforms)!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,i=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=qi(i,"program")}get attributeData(){return this._attributeData??(this._attributeData=dg(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,as[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return as[t]||(as[t]=new oi(e),as[t]._cacheKey=t),as[t]}}class Gt{constructor(e){this.resources=Object.create(null),this._dirty=!0;let t=0;for(const i in e){const r=e[i];this.setResource(r,t++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const e=[];let t=0;for(const i in this.resources)e[t++]=this.resources[i]._resourceId;this._key=e.join("|")}setResource(e,t){var r,n;const i=this.resources[t];e!==i&&((r=i==null?void 0:i.off)==null||r.call(i,"change",this.onResourceChange,this),(n=e.on)==null||n.call(e,"change",this.onResourceChange,this),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e,t){const i=this.resources;for(const r in i)i[r]._gcLastUsed=e,i[r]._touched=t}destroy(){var t;const e=this.resources;for(const i in e){const r=e[i];(t=r==null?void 0:r.off)==null||t.call(r,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(e){this._dirty=!0,e.destroyed?this.destroy():this._updateKey()}}var bt=(s=>(s[s.WEBGL=1]="WEBGL",s[s.WEBGPU=2]="WEBGPU",s[s.CANVAS=4]="CANVAS",s[s.BOTH=3]="BOTH",s))(bt||{});class Mt extends lt{constructor(e){super(),this.uid=be("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:i,groups:r,resources:n,compatibleRenderers:o,groupMap:a}=e;this.gpuProgram=t,this.glProgram=i,o===void 0&&(o=0,t&&(o|=bt.WEBGPU),i&&(o|=bt.WEBGL)),this.compatibleRenderers=o;const l={};if(!n&&!r&&(n={}),n&&r)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&r&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!t&&r&&a)for(const c in a)for(const h in a[c]){const u=a[c][h];l[u]={group:c,binding:h,name:u}}else if(t&&r&&!a){const c=t.structsAndGroups.groups;a={},c.forEach(h=>{a[h.group]=a[h.group]||{},a[h.group][h.binding]=h.name,l[h.name]=h})}else if(n){r={},a={},t&&t.structsAndGroups.groups.forEach(u=>{a[u.group]=a[u.group]||{},a[u.group][u.binding]=u.name,l[u.name]=u});let c=0;for(const h in n)l[h]||(r[99]||(r[99]=new Gt,this._ownedBindGroups.push(r[99])),l[h]={group:99,binding:c,name:h},a[99]=a[99]||{},a[99][c]=h,c++);for(const h in n){const u=h;let f=n[h];!f.source&&!f._resourceType&&(f=new ht(f));const d=l[u];d&&(r[d.group]||(r[d.group]=new Gt,this._ownedBindGroups.push(r[d.group])),r[d.group].setResource(f,d.binding))}}this.groups=r,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(r,l)}addResource(e,t,i){var r,n;(r=this._uniformBindMap)[t]||(r[t]={}),(n=this._uniformBindMap[t])[i]||(n[i]=e),this.groups[t]||(this.groups[t]=new Gt,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const i={};for(const r in t){const n=t[r];Object.defineProperty(i,n.name,{get(){return e[n.group].getResource(n.binding)},set(o){e[n.group].setResource(o,n.binding)}})}return i}destroy(e=!1){var t,i;this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&((t=this.gpuProgram)==null||t.destroy(),(i=this.glProgram)==null||i.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(r=>{r.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(e){const{gpu:t,gl:i,...r}=e;let n,o;return t&&(n=oi.from(t)),i&&(o=Ii.from(i)),new Mt({gpuProgram:n,glProgram:o,...r})}}const gg={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},Tn=0,An=1,wn=2,In=3,Rn=4,Mn=5,Pn=class _f{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<Tn)}set blend(e){!!(this.data&1<<Tn)!==e&&(this.data^=1<<Tn)}get offsets(){return!!(this.data&1<<An)}set offsets(e){!!(this.data&1<<An)!==e&&(this.data^=1<<An)}set cullMode(e){if(e==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=e==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<wn)}set culling(e){!!(this.data&1<<wn)!==e&&(this.data^=1<<wn)}get depthTest(){return!!(this.data&1<<In)}set depthTest(e){!!(this.data&1<<In)!==e&&(this.data^=1<<In)}get depthMask(){return!!(this.data&1<<Mn)}set depthMask(e){!!(this.data&1<<Mn)!==e&&(this.data^=1<<Mn)}get clockwiseFrontFace(){return!!(this.data&1<<Rn)}set clockwiseFrontFace(e){!!(this.data&1<<Rn)!==e&&(this.data^=1<<Rn)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=gg[e]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(e){this.offsets=!!e,this._polygonOffset=e}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const e=new _f;return e.depthTest=!1,e.blend=!0,e}};Pn.default2d=Pn.for2d();let Pt=Pn;const Zl=class oa extends Mt{constructor(e){e={...oa.defaultOptions,...e},super(e),this.enabled=!0,this._state=Pt.for2d(),this.blendMode=e.blendMode,this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.clipToViewport=e.clipToViewport,this.addResource("uTexture",0,1),e.blendRequired&&this.addResource("uBackTexture",0,3)}apply(e,t,i,r){e.applyFilter(this,t,i,r)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:i,...r}=e;let n,o;return t&&(n=oi.from(t)),i&&(o=Ii.from(i)),new oa({gpuProgram:n,glProgram:o,...r})}};Zl.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Jl=Zl,rr;function _g(s){return rr!==void 0||(rr=(()=>{var t;const e={stencil:!0,failIfMajorPerformanceCaveat:s??vi.defaultOptions.failIfMajorPerformanceCaveat};try{if(!pe.get().getWebGLRenderingContext())return!1;let r=pe.get().createCanvas().getContext("webgl",e);const n=!!((t=r==null?void 0:r.getContextAttributes())!=null&&t.stencil);if(r){const o=r.getExtension("WEBGL_lose_context");o&&o.loseContext()}return r=null,n}catch{return!1}})()),rr}let nr;async function yg(s={}){return nr!==void 0||(nr=await(async()=>{const e=pe.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(s)).requestDevice(),!0}catch{return!1}})()),nr}const Ql=["webgl","webgpu","canvas"];async function bg(s){let e=[];s.preference?(e.push(s.preference),Ql.forEach(n=>{n!==s.preference&&e.push(n)})):e=Ql.slice();let t,i={};for(let n=0;n<e.length;n++){const o=e[n];if(o==="webgpu"&&await yg()){const{WebGPURenderer:a}=await Promise.resolve().then(()=>ux);t=a,i={...s,...s.webgpu};break}else if(o==="webgl"&&_g(s.failIfMajorPerformanceCaveat??vi.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await Promise.resolve().then(()=>jb);t=a,i={...s,...s.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await Promise.resolve().then(()=>ab);t=a,i={...s,...s.canvasOptions};break}}if(delete i.webgpu,delete i.webgl,delete i.canvasOptions,!t)throw new Error("No available renderer for the current environment");const r=new t;return await r.init(i),r}const or="8.17.1";class ec{static init(){var e;(e=globalThis.__PIXI_APP_INIT__)==null||e.call(globalThis,this,or)}static destroy(){}}ec.extension=A.Application;class tc{constructor(e){this._renderer=e}init(){var e;(e=globalThis.__PIXI_RENDERER_INIT__)==null||e.call(globalThis,this._renderer,or)}destroy(){this._renderer=null}}tc.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"initHook",priority:-10};class ic{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(t){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=t,t&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let t,i;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,i=globalThis.innerHeight;else{const{clientWidth:r,clientHeight:n}=this._resizeTo;t=r,i=n}this.renderer.resize(t,i),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}ic.extension=A.Application;class sc{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,Si.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?at.shared:new at,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}sc.extension=A.Application,Q.add(ic),Q.add(sc);const rc=class aa{constructor(...e){this.stage=new Ve,e[0]!==void 0&&ee(Be,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new Ve),this.renderer=await bg(e),aa._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return ee(Be,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(e=!1,t=!1){const i=aa._plugins.slice(0);i.reverse(),i.forEach(r=>{r.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};rc._plugins=[];let nc=rc;Q.handleByList(A.Application,nc._plugins),Q.add(ec);var kn,oc;function xg(){if(oc)return kn;oc=1,kn=t;var s={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},e=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function t(n){var o=[];return n.replace(e,function(a,l,c){var h=l.toLowerCase();for(c=r(c),h=="m"&&c.length>2&&(o.push([l].concat(c.splice(0,2))),h="l",l=l=="m"?"l":"L");;){if(c.length==s[h])return c.unshift(l),o.push(c);if(c.length<s[h])throw new Error("malformed path data");o.push([l].concat(c.splice(0,s[h])))}}),o}var i=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function r(n){var o=n.match(i);return o?o.map(Number):[]}return kn}var vg=xg();const Cg=pa(vg);function Sg(s,e){const t=Cg(s),i=[];let r=null,n=0,o=0;for(let a=0;a<t.length;a++){const l=t[a],c=l[0],h=l;switch(c){case"M":n=h[1],o=h[2],e.moveTo(n,o);break;case"m":n+=h[1],o+=h[2],e.moveTo(n,o);break;case"H":n=h[1],e.lineTo(n,o);break;case"h":n+=h[1],e.lineTo(n,o);break;case"V":o=h[1],e.lineTo(n,o);break;case"v":o+=h[1],e.lineTo(n,o);break;case"L":n=h[1],o=h[2],e.lineTo(n,o);break;case"l":n+=h[1],o+=h[2],e.lineTo(n,o);break;case"C":n=h[5],o=h[6],e.bezierCurveTo(h[1],h[2],h[3],h[4],n,o);break;case"c":e.bezierCurveTo(n+h[1],o+h[2],n+h[3],o+h[4],n+h[5],o+h[6]),n+=h[5],o+=h[6];break;case"S":n=h[3],o=h[4],e.bezierCurveToShort(h[1],h[2],n,o);break;case"s":e.bezierCurveToShort(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"Q":n=h[3],o=h[4],e.quadraticCurveTo(h[1],h[2],n,o);break;case"q":e.quadraticCurveTo(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"T":n=h[1],o=h[2],e.quadraticCurveToShort(n,o);break;case"t":n+=h[1],o+=h[2],e.quadraticCurveToShort(n,o);break;case"A":n=h[6],o=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"a":n+=h[6],o+=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"Z":case"z":e.closePath(),i.length>0&&(r=i.pop(),r?(n=r.startX,o=r.startY):(n=0,o=0)),r=null;break;default:se(`Unknown SVG path command: ${c}`)}c!=="Z"&&c!=="z"&&r===null&&(r={startX:n,startY:o},i.push(r))}return e}class On{constructor(e=0,t=0,i=0){this.type="circle",this.x=e,this.y=t,this.radius=i}clone(){return new On(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;const i=this.radius*this.radius;let r=this.x-e,n=this.y-t;return r*=r,n*=n,r+n<=i}strokeContains(e,t,i,r=.5){if(this.radius===0)return!1;const n=this.x-e,o=this.y-t,a=this.radius,l=(1-r)*i,c=Math.sqrt(n*n+o*o);return c<=a+l&&c>a-(i-l)}getBounds(e){return e||(e=new Se),e.x=this.x-this.radius,e.y=this.y-this.radius,e.width=this.radius*2,e.height=this.radius*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.radius=e.radius,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class Bn{constructor(e=0,t=0,i=0,r=0){this.type="ellipse",this.x=e,this.y=t,this.halfWidth=i,this.halfHeight=r}clone(){return new Bn(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let i=(e-this.x)/this.halfWidth,r=(t-this.y)/this.halfHeight;return i*=i,r*=r,i+r<=1}strokeContains(e,t,i,r=.5){const{halfWidth:n,halfHeight:o}=this;if(n<=0||o<=0)return!1;const a=i*(1-r),l=i-a,c=n-l,h=o-l,u=n+a,f=o+a,d=e-this.x,g=t-this.y,_=d*d/(c*c)+g*g/(h*h),y=d*d/(u*u)+g*g/(f*f);return _>1&&y<=1}getBounds(e){return e||(e=new Se),e.x=this.x-this.halfWidth,e.y=this.y-this.halfHeight,e.width=this.halfWidth*2,e.height=this.halfHeight*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.halfWidth=e.halfWidth,this.halfHeight=e.halfHeight,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function Eg(s,e,t,i,r,n){const o=s-t,a=e-i,l=r-t,c=n-i,h=o*l+a*c,u=l*l+c*c;let f=-1;u!==0&&(f=h/u);let d,g;f<0?(d=t,g=i):f>1?(d=r,g=n):(d=t+f*l,g=i+f*c);const _=s-d,y=e-g;return _*_+y*y}let Tg,Ag;class ls{constructor(...e){this.type="polygon";let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!="number"){const i=[];for(let r=0,n=t.length;r<n;r++)i.push(t[r].x,t[r].y);t=i}this.points=t,this.closePath=!0}isClockwise(){let e=0;const t=this.points,i=t.length;for(let r=0;r<i;r+=2){const n=t[r],o=t[r+1],a=t[(r+2)%i],l=t[(r+3)%i];e+=(a-n)*(l+o)}return e<0}containsPolygon(e){const t=this.getBounds(Tg),i=e.getBounds(Ag);if(!t.containsRect(i))return!1;const r=e.points;for(let n=0;n<r.length;n+=2){const o=r[n],a=r[n+1];if(!this.contains(o,a))return!1}return!0}clone(){const e=this.points.slice(),t=new ls(e);return t.closePath=this.closePath,t}contains(e,t){let i=!1;const r=this.points.length/2;for(let n=0,o=r-1;n<r;o=n++){const a=this.points[n*2],l=this.points[n*2+1],c=this.points[o*2],h=this.points[o*2+1];l>t!=h>t&&e<(c-a)*((t-l)/(h-l))+a&&(i=!i)}return i}strokeContains(e,t,i,r=.5){const n=i*i,o=n*(1-r),a=n-o,{points:l}=this,c=l.length-(this.closePath?0:2);for(let h=0;h<c;h+=2){const u=l[h],f=l[h+1],d=l[(h+2)%l.length],g=l[(h+3)%l.length],_=Eg(e,t,u,f,d,g),y=Math.sign((d-u)*(t-f)-(g-f)*(e-u));if(_<=(y<0?a:o))return!0}return!1}getBounds(e){e||(e=new Se);const t=this.points;let i=1/0,r=-1/0,n=1/0,o=-1/0;for(let a=0,l=t.length;a<l;a+=2){const c=t[a],h=t[a+1];i=c<i?c:i,r=c>r?c:r,n=h<n?h:n,o=h>o?h:o}return e.x=i,e.width=r-i,e.y=n,e.height=o-n,e}copyFrom(e){return this.points=e.points.slice(),this.closePath=e.closePath,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((e,t)=>`${e}, ${t}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return ee("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return ee("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const ar=(s,e,t,i,r,n,o)=>{const a=s-t,l=e-i,c=Math.sqrt(a*a+l*l);return c>=r-n&&c<=r+o};class Dn{constructor(e=0,t=0,i=0,r=0,n=20){this.type="roundedRectangle",this.x=e,this.y=t,this.width=i,this.height=r,this.radius=n}getBounds(e){return e||(e=new Se),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new Dn(this.x,this.y,this.width,this.height,this.radius)}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){if(this.width<=0||this.height<=0)return!1;if(e>=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){const i=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+i&&t<=this.y+this.height-i||e>=this.x+i&&e<=this.x+this.width-i)return!0;let r=e-(this.x+i),n=t-(this.y+i);const o=i*i;if(r*r+n*n<=o||(r=e-(this.x+this.width-i),r*r+n*n<=o)||(n=t-(this.y+this.height-i),r*r+n*n<=o)||(r=e-(this.x+i),r*r+n*n<=o))return!0}return!1}strokeContains(e,t,i,r=.5){const{x:n,y:o,width:a,height:l,radius:c}=this,h=i*(1-r),u=i-h,f=n+c,d=o+c,g=a-c*2,_=l-c*2,y=n+a,x=o+l;return(e>=n-h&&e<=n+u||e>=y-u&&e<=y+h)&&t>=d&&t<=d+_||(t>=o-h&&t<=o+u||t>=x-u&&t<=x+h)&&e>=f&&e<=f+g?!0:e<f&&t<d&&ar(e,t,f,d,c,u,h)||e>y-c&&t<d&&ar(e,t,y-c,d,c,u,h)||e>y-c&&t>x-c&&ar(e,t,y-c,x-c,c,u,h)||e<f&&t>x-c&&ar(e,t,f,x-c,c,u,h)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const ac={};function Nn(s,e,t){let i=2166136261;for(let r=0;r<e;r++)i^=s[r].uid,i=Math.imul(i,16777619),i>>>=0;return ac[i]||wg(s,e,i,t)}function wg(s,e,t,i){const r={};let n=0;for(let a=0;a<i;a++){const l=a<e?s[a]:j.EMPTY.source;r[n++]=l.source,r[n++]=l.style}const o=new Gt(r);return ac[t]=o,o}function Un(s,e,t,i){if(t??(t=0),i??(i=Math.min(s.byteLength-t,e.byteLength)),!(t&7)&&!(i&7)){const r=i/8;new Float64Array(e,0,r).set(new Float64Array(s,t,r))}else if(!(t&3)&&!(i&3)){const r=i/4;new Float32Array(e,0,r).set(new Float32Array(s,t,r))}else new Uint8Array(e).set(new Uint8Array(s,t,i))}const Ig={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var ke=(s=>(s[s.DISABLED=0]="DISABLED",s[s.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",s[s.MASK_ACTIVE=2]="MASK_ACTIVE",s[s.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",s[s.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",s[s.NONE=5]="NONE",s))(ke||{});function lc(s,e){return e.alphaMode==="no-premultiply-alpha"&&Ig[s]||s}const Rg=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
330
+ `);function Mg(s){let e="";for(let t=0;t<s;++t)t>0&&(e+=`
331
+ else `),t<s-1&&(e+=`if(test == ${t}.0){}`);return e}function cc(s,e){if(s===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const t=e.createShader(e.FRAGMENT_SHADER);try{for(;;){const i=Rg.replace(/%forloop%/gi,Mg(s));if(e.shaderSource(t,i),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))s=s/2|0;else break}}finally{e.deleteShader(t)}return s}let Ri=null;function Pg(){var e;if(Ri)return Ri;const s=Xl();return Ri=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),Ri=cc(Ri,s),(e=s.getExtension("WEBGL_lose_context"))==null||e.loseContext(),Ri}class kg{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let e=0;e<this.count;e++){const t=this.textures[e];this.textures[e]=null,this.ids[t.uid]=null}this.count=0}}class Og{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new kg,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null,this.elements=null}}const cs=[];let lr=0;_i.register({clear:()=>{if(cs.length>0)for(const s of cs)s&&s.destroy();cs.length=0,lr=0}});function hc(){return lr>0?cs[--lr]:new Og}function uc(s){s.elements=null,cs[lr++]=s}let hs=0;const dc=class yf{constructor(e){this.uid=be("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],e={...yf.defaultOptions,...e},e.maxTextures||(ee("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),e.maxTextures=Pg());const{maxTextures:t,attributesInitialSize:i,indicesInitialSize:r}=e;this.attributeBuffer=new Ci(i*4),this.indexBuffer=new Uint16Array(r),this.maxTextures=t}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let e=0;e<this.batchIndex;e++)uc(this.batches[e]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(e){this._elements[this.elementSize++]=e,e._indexStart=this.indexSize,e._attributeStart=this.attributeSize,e._batcher=this,this.indexSize+=e.indexSize,this.attributeSize+=e.attributeSize*this.vertexSize}checkAndUpdateTexture(e,t){const i=e._batch.textures.ids[t._source.uid];return!i&&i!==0?!1:(e._textureId=i,e.texture=t,!0)}updateElement(e){this.dirty=!0;const t=this.attributeBuffer;e.packAsQuad?this.packQuadAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId):this.packAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId)}break(e){const t=this._elements;if(!t[this.elementStart])return;let i=hc(),r=i.textures;r.clear();const n=t[this.elementStart];let o=lc(n.blendMode,n.texture._source),a=n.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const l=this.attributeBuffer.float32View,c=this.attributeBuffer.uint32View,h=this.indexBuffer;let u=this._batchIndexSize,f=this._batchIndexStart,d="startBatch",g=[];const _=this.maxTextures;for(let y=this.elementStart;y<this.elementSize;++y){const x=t[y];t[y]=null;const S=x.texture._source,E=lc(x.blendMode,S),w=o!==E||a!==x.topology;if(S._batchTick===hs&&!w){x._textureId=S._textureBindLocation,u+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,l,c,x._attributeStart,x._textureId),this.packQuadIndex(h,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,l,c,x._attributeStart,x._textureId),this.packIndex(x,h,x._indexStart,x._attributeStart/this.vertexSize)),x._batch=i,g.push(x);continue}S._batchTick=hs,(r.count>=_||w)&&(this._finishBatch(i,f,u-f,r,o,a,e,d,g),d="renderBatch",f=u,o=E,a=x.topology,i=hc(),r=i.textures,r.clear(),g=[],++hs),x._textureId=S._textureBindLocation=r.count,r.ids[S.uid]=r.count,r.textures[r.count++]=S,x._batch=i,g.push(x),u+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,l,c,x._attributeStart,x._textureId),this.packQuadIndex(h,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,l,c,x._attributeStart,x._textureId),this.packIndex(x,h,x._indexStart,x._attributeStart/this.vertexSize))}r.count>0&&(this._finishBatch(i,f,u-f,r,o,a,e,d,g),f=u,++hs),this.elementStart=this.elementSize,this._batchIndexStart=f,this._batchIndexSize=u}_finishBatch(e,t,i,r,n,o,a,l,c){e.gpuBindGroup=null,e.bindGroup=null,e.action=l,e.batcher=this,e.textures=r,e.blendMode=n,e.topology=o,e.start=t,e.size=i,e.elements=c,++hs,this.batches[this.batchIndex++]=e,a.add(e)}finish(e){this.break(e)}ensureAttributeBuffer(e){e*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(e*4)}ensureIndexBuffer(e){e<=this.indexBuffer.length||this._resizeIndexBuffer(e)}_resizeAttributeBuffer(e){const t=Math.max(e,this.attributeBuffer.size*2),i=new Ci(t);Un(this.attributeBuffer.rawBinaryData,i.rawBinaryData),this.attributeBuffer=i}_resizeIndexBuffer(e){const t=this.indexBuffer;let i=Math.max(e,t.length*1.5);i+=i%2;const r=i>65535?new Uint32Array(i):new Uint16Array(i);if(r.BYTES_PER_ELEMENT!==t.BYTES_PER_ELEMENT)for(let n=0;n<t.length;n++)r[n]=t[n];else Un(t.buffer,r.buffer);this.indexBuffer=r}packQuadIndex(e,t,i){e[t]=i+0,e[t+1]=i+1,e[t+2]=i+2,e[t+3]=i+0,e[t+4]=i+2,e[t+5]=i+3}packIndex(e,t,i,r){const n=e.indices,o=e.indexSize,a=e.indexOffset,l=e.attributeOffset;for(let c=0;c<o;c++)t[i++]=r+n[c+a]-l}destroy(e={}){var t;if(this.batches!==null){for(let i=0;i<this.batchIndex;i++)uc(this.batches[i]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,e.shader&&((t=this.shader)==null||t.destroy(),this.shader=null);for(let i=0;i<this._elements.length;i++)this._elements[i]&&(this._elements[i]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};dc.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let Bg=dc;const Dg=new Float32Array(1),Ng=new Uint32Array(1);class Ug extends Qs{constructor(){const t=new gt({data:Dg,label:"attribute-batch-buffer",usage:ge.VERTEX|ge.COPY_DST,shrinkToFit:!1}),i=new gt({data:Ng,label:"index-batch-buffer",usage:ge.INDEX|ge.COPY_DST,shrinkToFit:!1}),r=24;super({attributes:{aPosition:{buffer:t,format:"float32x2",stride:r,offset:0},aUV:{buffer:t,format:"float32x2",stride:r,offset:8},aColor:{buffer:t,format:"unorm8x4",stride:r,offset:16},aTextureIdAndRound:{buffer:t,format:"uint16x2",stride:r,offset:20}},indexBuffer:i})}}function fc(s,e,t){if(s)for(const i in s){const r=i.toLocaleLowerCase(),n=e[r];if(n){let o=s[i];i==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),t&&n.push(`//----${t}----//`),n.push(o)}else se(`${i} placement hook does not exist in shader`)}}const Fg=/\{\{(.*?)\}\}/g;function pc(s){var i;const e={};return(((i=s.match(Fg))==null?void 0:i.map(r=>r.replace(/[{()}]/g,"")))??[]).forEach(r=>{e[r]=[]}),e}function mc(s,e){let t;const i=/@in\s+([^;]+);/g;for(;(t=i.exec(s))!==null;)e.push(t[1])}function gc(s,e,t=!1){const i=[];mc(e,i),s.forEach(a=>{a.header&&mc(a.header,i)});const r=i;t&&r.sort();const n=r.map((a,l)=>` @location(${l}) ${a},`).join(`
332
332
  `);let o=e.replace(/@in\s+[^;]+;\s*/g,"");return o=o.replace("{{in}}",`
333
333
  ${n}
334
- `),o}function _c(s,e){let t;const i=/@out\s+([^;]+);/g;for(;(t=i.exec(s))!==null;)e.push(t[1])}function Fg(s){const t=/\b(\w+)\s*:/g.exec(s);return t?t[1]:""}function Gg(s){const e=/@.*?\s+/g;return s.replace(e,"")}function Lg(s,e){const t=[];_c(e,t),s.forEach(l=>{l.header&&_c(l.header,t)});let i=0;const r=t.sort().map(l=>l.indexOf("builtin")>-1?l:`@location(${i++}) ${l}`).join(`,
335
- `),n=t.sort().map(l=>` var ${Gg(l)};`).join(`
334
+ `),o}function _c(s,e){let t;const i=/@out\s+([^;]+);/g;for(;(t=i.exec(s))!==null;)e.push(t[1])}function Gg(s){const t=/\b(\w+)\s*:/g.exec(s);return t?t[1]:""}function Lg(s){const e=/@.*?\s+/g;return s.replace(e,"")}function Wg(s,e){const t=[];_c(e,t),s.forEach(l=>{l.header&&_c(l.header,t)});let i=0;const r=t.sort().map(l=>l.indexOf("builtin")>-1?l:`@location(${i++}) ${l}`).join(`,
335
+ `),n=t.sort().map(l=>` var ${Lg(l)};`).join(`
336
336
  `),o=`return VSOutput(
337
- ${t.sort().map(l=>` ${Fg(l)}`).join(`,
337
+ ${t.sort().map(l=>` ${Gg(l)}`).join(`,
338
338
  `)});`;let a=e.replace(/@out\s+[^;]+;\s*/g,"");return a=a.replace("{{struct}}",`
339
339
  ${r}
340
340
  `),a=a.replace("{{start}}",`
@@ -345,7 +345,7 @@ ${o}
345
345
  `).length?t=t.replace(`{{${i}}}`,`//-----${i} START-----//
346
346
  ${r.join(`
347
347
  `)}
348
- //----${i} FINISH----//`):t=t.replace(`{{${i}}}`,"")}return t}const Lt=Object.create(null),Fn=new Map;let Wg=0;function Hg({template:s,bits:e}){const t=bc(s,e);if(Lt[t])return Lt[t];const{vertex:i,fragment:r}=zg(s,e);return Lt[t]=xc(i,r,e),Lt[t]}function Vg({template:s,bits:e}){const t=bc(s,e);return Lt[t]||(Lt[t]=xc(s.vertex,s.fragment,e)),Lt[t]}function zg(s,e){const t=e.map(o=>o.vertex).filter(o=>!!o),i=e.map(o=>o.fragment).filter(o=>!!o);let r=gc(t,s.vertex,!0);r=Lg(t,r);const n=gc(i,s.fragment,!0);return{vertex:r,fragment:n}}function bc(s,e){return e.map(t=>(Fn.has(t)||Fn.set(t,Wg++),Fn.get(t))).sort((t,i)=>t-i).join("-")+s.vertex+s.fragment}function xc(s,e,t){const i=pc(s),r=pc(e);return t.forEach(n=>{fc(n.vertex,i,n.name),fc(n.fragment,r,n.name)}),{vertex:yc(s,i),fragment:yc(e,r)}}const $g=`
348
+ //----${i} FINISH----//`):t=t.replace(`{{${i}}}`,"")}return t}const Lt=Object.create(null),Fn=new Map;let Hg=0;function Vg({template:s,bits:e}){const t=bc(s,e);if(Lt[t])return Lt[t];const{vertex:i,fragment:r}=$g(s,e);return Lt[t]=xc(i,r,e),Lt[t]}function zg({template:s,bits:e}){const t=bc(s,e);return Lt[t]||(Lt[t]=xc(s.vertex,s.fragment,e)),Lt[t]}function $g(s,e){const t=e.map(o=>o.vertex).filter(o=>!!o),i=e.map(o=>o.fragment).filter(o=>!!o);let r=gc(t,s.vertex,!0);r=Wg(t,r);const n=gc(i,s.fragment,!0);return{vertex:r,fragment:n}}function bc(s,e){return e.map(t=>(Fn.has(t)||Fn.set(t,Hg++),Fn.get(t))).sort((t,i)=>t-i).join("-")+s.vertex+s.fragment}function xc(s,e,t){const i=pc(s),r=pc(e);return t.forEach(n=>{fc(n.vertex,i,n.name),fc(n.fragment,r,n.name)}),{vertex:yc(s,i),fragment:yc(e,r)}}const jg=`
349
349
  @in aPosition: vec2<f32>;
350
350
  @in aUV: vec2<f32>;
351
351
 
@@ -389,7 +389,7 @@ ${r.join(`
389
389
 
390
390
  {{return}}
391
391
  };
392
- `,jg=`
392
+ `,Xg=`
393
393
  @in vUV : vec2<f32>;
394
394
  @in vColor : vec4<f32>;
395
395
 
@@ -412,7 +412,7 @@ ${r.join(`
412
412
 
413
413
  return finalColor;
414
414
  };
415
- `,Xg=`
415
+ `,Yg=`
416
416
  in vec2 aPosition;
417
417
  in vec2 aUV;
418
418
 
@@ -448,7 +448,7 @@ ${r.join(`
448
448
 
449
449
  {{end}}
450
450
  }
451
- `,Yg=`
451
+ `,qg=`
452
452
 
453
453
  in vec4 vColor;
454
454
  in vec2 vUV;
@@ -469,7 +469,7 @@ ${r.join(`
469
469
 
470
470
  {{end}}
471
471
  }
472
- `,qg={name:"global-uniforms-bit",vertex:{header:`
472
+ `,Kg={name:"global-uniforms-bit",vertex:{header:`
473
473
  struct GlobalUniforms {
474
474
  uProjectionMatrix:mat3x3<f32>,
475
475
  uWorldTransformMatrix:mat3x3<f32>,
@@ -478,12 +478,12 @@ ${r.join(`
478
478
  }
479
479
 
480
480
  @group(0) @binding(0) var<uniform> globalUniforms : GlobalUniforms;
481
- `}},Kg={name:"global-uniforms-bit",vertex:{header:`
481
+ `}},Zg={name:"global-uniforms-bit",vertex:{header:`
482
482
  uniform mat3 uProjectionMatrix;
483
483
  uniform mat3 uWorldTransformMatrix;
484
484
  uniform vec4 uWorldColorAlpha;
485
485
  uniform vec2 uResolution;
486
- `}};function Gn({bits:s,name:e}){const t=Hg({template:{fragment:jg,vertex:$g},bits:[qg,...s]});return oi.from({name:e,vertex:{source:t.vertex,entryPoint:"main"},fragment:{source:t.fragment,entryPoint:"main"}})}function Ln({bits:s,name:e}){return new Ii({name:e,...Vg({template:{vertex:Xg,fragment:Yg},bits:[Kg,...s]})})}const vc={name:"color-bit",vertex:{header:`
486
+ `}};function Gn({bits:s,name:e}){const t=Vg({template:{fragment:Xg,vertex:jg},bits:[Kg,...s]});return oi.from({name:e,vertex:{source:t.vertex,entryPoint:"main"},fragment:{source:t.fragment,entryPoint:"main"}})}function Ln({bits:s,name:e}){return new Ii({name:e,...zg({template:{vertex:Yg,fragment:qg},bits:[Zg,...s]})})}const vc={name:"color-bit",vertex:{header:`
487
487
  @in aColor: vec4<f32>;
488
488
  `,main:`
489
489
  vColor *= vec4<f32>(aColor.rgb * aColor.a, aColor.a);
@@ -491,8 +491,8 @@ ${r.join(`
491
491
  in vec4 aColor;
492
492
  `,main:`
493
493
  vColor *= vec4(aColor.rgb * aColor.a, aColor.a);
494
- `}},Wn={};function Zg(s){const e=[];if(s===1)e.push("@group(1) @binding(0) var textureSource1: texture_2d<f32>;"),e.push("@group(1) @binding(1) var textureSampler1: sampler;");else{let t=0;for(let i=0;i<s;i++)e.push(`@group(1) @binding(${t++}) var textureSource${i+1}: texture_2d<f32>;`),e.push(`@group(1) @binding(${t++}) var textureSampler${i+1}: sampler;`)}return e.join(`
495
- `)}function Jg(s){const e=[];if(s===1)e.push("outColor = textureSampleGrad(textureSource1, textureSampler1, vUV, uvDx, uvDy);");else{e.push("switch vTextureId {");for(let t=0;t<s;t++)t===s-1?e.push(" default:{"):e.push(` case ${t}:{`),e.push(` outColor = textureSampleGrad(textureSource${t+1}, textureSampler${t+1}, vUV, uvDx, uvDy);`),e.push(" break;}");e.push("}")}return e.join(`
494
+ `}},Wn={};function Jg(s){const e=[];if(s===1)e.push("@group(1) @binding(0) var textureSource1: texture_2d<f32>;"),e.push("@group(1) @binding(1) var textureSampler1: sampler;");else{let t=0;for(let i=0;i<s;i++)e.push(`@group(1) @binding(${t++}) var textureSource${i+1}: texture_2d<f32>;`),e.push(`@group(1) @binding(${t++}) var textureSampler${i+1}: sampler;`)}return e.join(`
495
+ `)}function Qg(s){const e=[];if(s===1)e.push("outColor = textureSampleGrad(textureSource1, textureSampler1, vUV, uvDx, uvDy);");else{e.push("switch vTextureId {");for(let t=0;t<s;t++)t===s-1?e.push(" default:{"):e.push(` case ${t}:{`),e.push(` outColor = textureSampleGrad(textureSource${t+1}, textureSampler${t+1}, vUV, uvDx, uvDy);`),e.push(" break;}");e.push("}")}return e.join(`
496
496
  `)}function Sc(s){return Wn[s]||(Wn[s]={name:"texture-batch-bit",vertex:{header:`
497
497
  @in aTextureIdAndRound: vec2<u32>;
498
498
  @out @interpolate(flat) vTextureId : u32;
@@ -506,13 +506,13 @@ ${r.join(`
506
506
  `},fragment:{header:`
507
507
  @in @interpolate(flat) vTextureId: u32;
508
508
 
509
- ${Zg(s)}
509
+ ${Jg(s)}
510
510
  `,main:`
511
511
  var uvDx = dpdx(vUV);
512
512
  var uvDy = dpdy(vUV);
513
513
 
514
- ${Jg(s)}
515
- `}}),Wn[s]}const Hn={};function Qg(s){const e=[];for(let t=0;t<s;t++)t>0&&e.push("else"),t<s-1&&e.push(`if(vTextureId < ${t}.5)`),e.push("{"),e.push(` outColor = texture(uTextures[${t}], vUV);`),e.push("}");return e.join(`
514
+ ${Qg(s)}
515
+ `}}),Wn[s]}const Hn={};function e_(s){const e=[];for(let t=0;t<s;t++)t>0&&e.push("else"),t<s-1&&e.push(`if(vTextureId < ${t}.5)`),e.push("{"),e.push(` outColor = texture(uTextures[${t}], vUV);`),e.push("}");return e.join(`
516
516
  `)}function Ec(s){return Hn[s]||(Hn[s]={name:"texture-batch-bit",vertex:{header:`
517
517
  in vec2 aTextureIdAndRound;
518
518
  out float vTextureId;
@@ -531,7 +531,7 @@ ${r.join(`
531
531
 
532
532
  `,main:`
533
533
 
534
- ${Qg(s)}
534
+ ${e_(s)}
535
535
  `}}),Hn[s]}const Vn={name:"round-pixels-bit",vertex:{header:`
536
536
  fn roundPixels(position: vec2<f32>, targetSize: vec2<f32>) -> vec2<f32>
537
537
  {
@@ -542,7 +542,7 @@ ${r.join(`
542
542
  {
543
543
  return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
544
544
  }
545
- `}},Tc={};function Ac(s){let e=Tc[s];if(e)return e;const t=new Int32Array(s);for(let i=0;i<s;i++)t[i]=i;return e=Tc[s]=new ht({uTextures:{value:t,type:"i32",size:s}},{isStatic:!0}),e}class wc extends Mt{constructor(e){const t=Ln({name:"batch",bits:[Cc,Ec(e),zn]}),i=Gn({name:"batch",bits:[vc,Sc(e),Vn]});super({glProgram:t,gpuProgram:i,resources:{batchSamplers:Ac(e)}}),this.maxTextures=e}}let us=null;const Ic=class bf extends Og{constructor(e){super(e),this.geometry=new Ng,this.name=bf.extension.name,this.vertexSize=6,us??(us=new wc(e.maxTextures)),this.shader=us}packAttributes(e,t,i,r,n){const o=n<<16|e.roundPixels&65535,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,f=a.tx,d=a.ty,{positions:g,uvs:_}=e,b=e.color,x=e.attributeOffset,C=x+e.attributeSize;for(let S=x;S<C;S++){const E=S*2,w=g[E],R=g[E+1];t[r++]=l*w+h*R+f,t[r++]=u*R+c*w+d,t[r++]=_[E],t[r++]=_[E+1],i[r++]=b,i[r++]=o}}packQuadAttributes(e,t,i,r,n){const o=e.texture,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,f=a.tx,d=a.ty,g=e.bounds,_=g.maxX,b=g.minX,x=g.maxY,C=g.minY,S=o.uvs,E=e.color,w=n<<16|e.roundPixels&65535;t[r+0]=l*b+h*C+f,t[r+1]=u*C+c*b+d,t[r+2]=S.x0,t[r+3]=S.y0,i[r+4]=E,i[r+5]=w,t[r+6]=l*_+h*C+f,t[r+7]=u*C+c*_+d,t[r+8]=S.x1,t[r+9]=S.y1,i[r+10]=E,i[r+11]=w,t[r+12]=l*_+h*x+f,t[r+13]=u*x+c*_+d,t[r+14]=S.x2,t[r+15]=S.y2,i[r+16]=E,i[r+17]=w,t[r+18]=l*b+h*x+f,t[r+19]=u*x+c*b+d,t[r+20]=S.x3,t[r+21]=S.y3,i[r+22]=E,i[r+23]=w}_updateMaxTextures(e){this.shader.maxTextures!==e&&(us=new wc(e),this.shader=us)}destroy(){this.shader=null,super.destroy()}};Ic.extension={type:[A.Batcher],name:"default"};let $n=Ic;class kt{constructor(e){this.items=Object.create(null);const{renderer:t,type:i,onUnload:r,priority:n,name:o}=e;this._renderer=t,t.gc.addResourceHash(this,"items",i,n??0),this._onUnload=r,this.name=o}add(e){return this.items[e.uid]?!1:(this.items[e.uid]=e,e.once("unload",this.remove,this),e._gcLastUsed=this._renderer.gc.now,!0)}remove(e,...t){var r;if(!this.items[e.uid])return;const i=e._gpuData[this._renderer.uid];i&&((r=this._onUnload)==null||r.call(this,e,...t),i.destroy(),e._gpuData[this._renderer.uid]=null,this.items[e.uid]=null)}removeAll(...e){Object.values(this.items).forEach(t=>t&&this.remove(t,...e))}destroy(...e){this.removeAll(...e),this.items=Object.create(null),this._renderer=null,this._onUnload=null}}function e_(s,e,t,i,r,n,o,a=null){let l=0;t*=e,r*=n;const c=a.a,h=a.b,u=a.c,f=a.d,d=a.tx,g=a.ty;for(;l<o;){const _=s[t],b=s[t+1];i[r]=c*_+u*b+d,i[r+1]=h*_+f*b+g,r+=n,t+=e,l++}}function t_(s,e,t,i){let r=0;for(e*=t;r<i;)s[e]=0,s[e+1]=0,e+=t,r++}function Rc(s,e,t,i,r){const n=e.a,o=e.b,a=e.c,l=e.d,c=e.tx,h=e.ty;t||(t=0),i||(i=2),r||(r=s.length/i-t);let u=t*i;for(let f=0;f<r;f++){const d=s[u],g=s[u+1];s[u]=n*d+a*g+c,s[u+1]=o*d+l*g+h,u+=i}}const i_=new H;class jn{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const e=this.baseColor,t=e>>16|e&65280|(e&255)<<16,i=this.renderable;return i?yi(t,i.groupColor)+(this.alpha*i.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){var e;return((e=this.renderable)==null?void 0:e.groupTransform)||i_}copyTo(e){e.indexOffset=this.indexOffset,e.indexSize=this.indexSize,e.attributeOffset=this.attributeOffset,e.attributeSize=this.attributeSize,e.baseColor=this.baseColor,e.alpha=this.alpha,e.texture=this.texture,e.geometryData=this.geometryData,e.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const ds={extension:{type:A.ShapeBuilder,name:"circle"},build(s,e){let t,i,r,n,o,a;if(s.type==="circle"){const E=s;if(o=a=E.radius,o<=0)return!1;t=E.x,i=E.y,r=n=0}else if(s.type==="ellipse"){const E=s;if(o=E.halfWidth,a=E.halfHeight,o<=0||a<=0)return!1;t=E.x,i=E.y,r=n=0}else{const E=s,w=E.width/2,R=E.height/2;t=E.x+w,i=E.y+R,o=a=Math.max(0,Math.min(E.radius,Math.min(w,R))),r=w-o,n=R-a}if(r<0||n<0)return!1;const l=Math.ceil(2.3*Math.sqrt(o+a)),c=l*8+(r?4:0)+(n?4:0);if(c===0)return!1;if(l===0)return e[0]=e[6]=t+r,e[1]=e[3]=i+n,e[2]=e[4]=t-r,e[5]=e[7]=i-n,!0;let h=0,u=l*4+(r?2:0)+2,f=u,d=c,g=r+o,_=n,b=t+g,x=t-g,C=i+_;if(e[h++]=b,e[h++]=C,e[--u]=C,e[--u]=x,n){const E=i-_;e[f++]=x,e[f++]=E,e[--d]=E,e[--d]=b}for(let E=1;E<l;E++){const w=Math.PI/2*(E/l),R=r+Math.cos(w)*o,M=n+Math.sin(w)*a,D=t+R,F=t-R,k=i+M,O=i-M;e[h++]=D,e[h++]=k,e[--u]=k,e[--u]=F,e[f++]=F,e[f++]=O,e[--d]=O,e[--d]=D}g=r,_=n+a,b=t+g,x=t-g,C=i+_;const S=i-_;return e[h++]=b,e[h++]=C,e[--d]=S,e[--d]=b,r&&(e[h++]=x,e[h++]=C,e[--d]=S,e[--d]=x),!0},triangulate(s,e,t,i,r,n){if(s.length===0)return;let o=0,a=0;for(let h=0;h<s.length;h+=2)o+=s[h],a+=s[h+1];o/=s.length/2,a/=s.length/2;let l=i;e[l*t]=o,e[l*t+1]=a;const c=l++;for(let h=0;h<s.length;h+=2)e[l*t]=s[h],e[l*t+1]=s[h+1],h>0&&(r[n++]=l,r[n++]=c,r[n++]=l-1),l++;r[n++]=c+1,r[n++]=c,r[n++]=l-1}},s_={...ds,extension:{...ds.extension,name:"ellipse"}},r_={...ds,extension:{...ds.extension,name:"roundedRectangle"}},Mc=1e-4,Pc=1e-4;function n_(s){const e=s.length;if(e<6)return 1;let t=0;for(let i=0,r=s[e-2],n=s[e-1];i<e;i+=2){const o=s[i],a=s[i+1];t+=(o-r)*(a+n),r=o,n=a}return t<0?-1:1}function kc(s,e,t,i,r,n,o,a){const l=s-t*r,c=e-i*r,h=s+t*n,u=e+i*n;let f,d;o?(f=i,d=-t):(f=-i,d=t);const g=l+f,_=c+d,b=h+f,x=u+d;return a.push(g,_),a.push(b,x),2}function ai(s,e,t,i,r,n,o,a){const l=t-s,c=i-e;let h=Math.atan2(l,c),u=Math.atan2(r-s,n-e);a&&h<u?h+=Math.PI*2:!a&&h>u&&(u+=Math.PI*2);let f=h;const d=u-h,g=Math.abs(d),_=Math.sqrt(l*l+c*c),b=(15*g*Math.sqrt(_)/Math.PI>>0)+1,x=d/b;if(f+=x,a){o.push(s,e),o.push(t,i);for(let C=1,S=f;C<b;C++,S+=x)o.push(s,e),o.push(s+Math.sin(S)*_,e+Math.cos(S)*_);o.push(s,e),o.push(r,n)}else{o.push(t,i),o.push(s,e);for(let C=1,S=f;C<b;C++,S+=x)o.push(s+Math.sin(S)*_,e+Math.cos(S)*_),o.push(s,e);o.push(r,n),o.push(s,e)}return b*2}function Oc(s,e,t,i,r,n){const o=Mc;if(s.length===0)return;const a=e;let l=a.alignment;if(e.alignment!==.5){let N=n_(s);l=(l-.5)*N+.5}const c=new xe(s[0],s[1]),h=new xe(s[s.length-2],s[s.length-1]),u=i,f=Math.abs(c.x-h.x)<o&&Math.abs(c.y-h.y)<o;if(u){s=s.slice(),f&&(s.pop(),s.pop(),h.set(s[s.length-2],s[s.length-1]));const N=(c.x+h.x)*.5,K=(h.y+c.y)*.5;s.unshift(N,K),s.push(N,K)}const d=r,g=s.length/2;let _=s.length;const b=d.length/2,x=a.width/2,C=x*x,S=a.miterLimit*a.miterLimit;let E=s[0],w=s[1],R=s[2],M=s[3],D=0,F=0,k=-(w-M),O=E-R,V=0,X=0,z=Math.sqrt(k*k+O*O);k/=z,O/=z,k*=x,O*=x;const de=l,B=(1-de)*2,U=de*2;u||(a.cap==="round"?_+=ai(E-k*(B-U)*.5,w-O*(B-U)*.5,E-k*B,w-O*B,E+k*U,w+O*U,d,!0)+2:a.cap==="square"&&(_+=kc(E,w,k,O,B,U,!0,d))),d.push(E-k*B,w-O*B),d.push(E+k*U,w+O*U);for(let N=1;N<g-1;++N){E=s[(N-1)*2],w=s[(N-1)*2+1],R=s[N*2],M=s[N*2+1],D=s[(N+1)*2],F=s[(N+1)*2+1],k=-(w-M),O=E-R,z=Math.sqrt(k*k+O*O),k/=z,O/=z,k*=x,O*=x,V=-(M-F),X=R-D,z=Math.sqrt(V*V+X*X),V/=z,X/=z,V*=x,X*=x;const K=R-E,Z=w-M,$=R-D,ae=F-M,Ce=K*$+Z*ae,Ee=Z*$-ae*K,G=Ee<0;if(Math.abs(Ee)<.001*Math.abs(Ce)){d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),Ce>=0&&(a.join==="round"?_+=ai(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+4:_+=2,d.push(R-V*U,M-X*U),d.push(R+V*B,M+X*B));continue}const fe=(-k+E)*(-O+M)-(-k+R)*(-O+w),le=(-V+D)*(-X+M)-(-V+R)*(-X+F),L=(K*le-$*fe)/Ee,me=(ae*fe-Z*le)/Ee,Y=(L-R)*(L-R)+(me-M)*(me-M),ie=R+(L-R)*B,we=M+(me-M)*B,ce=R-(L-R)*U,He=M-(me-M)*U,Qt=Math.min(K*K+Z*Z,$*$+ae*ae),Et=G?B:U,ui=Qt+Et*Et*C;Y<=ui?a.join==="bevel"||Y/C>S?(G?(d.push(ie,we),d.push(R+k*U,M+O*U),d.push(ie,we),d.push(R+V*U,M+X*U)):(d.push(R-k*B,M-O*B),d.push(ce,He),d.push(R-V*B,M-X*B),d.push(ce,He)),_+=2):a.join==="round"?G?(d.push(ie,we),d.push(R+k*U,M+O*U),_+=ai(R,M,R+k*U,M+O*U,R+V*U,M+X*U,d,!0)+4,d.push(ie,we),d.push(R+V*U,M+X*U)):(d.push(R-k*B,M-O*B),d.push(ce,He),_+=ai(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+4,d.push(R-V*B,M-X*B),d.push(ce,He)):(d.push(ie,we),d.push(ce,He)):(d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),a.join==="round"?G?_+=ai(R,M,R+k*U,M+O*U,R+V*U,M+X*U,d,!0)+2:_+=ai(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+2:a.join==="miter"&&Y/C<=S&&(G?(d.push(ce,He),d.push(ce,He)):(d.push(ie,we),d.push(ie,we)),_+=2),d.push(R-V*B,M-X*B),d.push(R+V*U,M+X*U),_+=2)}E=s[(g-2)*2],w=s[(g-2)*2+1],R=s[(g-1)*2],M=s[(g-1)*2+1],k=-(w-M),O=E-R,z=Math.sqrt(k*k+O*O),k/=z,O/=z,k*=x,O*=x,d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),u||(a.cap==="round"?_+=ai(R-k*(B-U)*.5,M-O*(B-U)*.5,R-k*B,M-O*B,R+k*U,M+O*U,d,!1)+2:a.cap==="square"&&(_+=kc(R,M,k,O,B,U,!1,d)));const q=Pc*Pc;for(let N=b;N<_+b-2;++N)E=d[N*2],w=d[N*2+1],R=d[(N+1)*2],M=d[(N+1)*2+1],D=d[(N+2)*2],F=d[(N+2)*2+1],!(Math.abs(E*(M-F)+R*(F-w)+D*(w-M))<q)&&n.push(N,N+1,N+2)}function o_(s,e,t,i){const r=Mc;if(s.length===0)return;const n=s[0],o=s[1],a=s[s.length-2],l=s[s.length-1],c=e||Math.abs(n-a)<r&&Math.abs(o-l)<r,h=t,u=s.length/2,f=h.length/2;for(let d=0;d<u;d++)h.push(s[d*2]),h.push(s[d*2+1]);for(let d=0;d<u-1;d++)i.push(f+d,f+d+1);c&&i.push(f+u-1,f)}function Bc(s,e,t,i,r,n,o){const a=lm(s,e,2);if(!a)return;for(let c=0;c<a.length;c+=3)n[o++]=a[c]+r,n[o++]=a[c+1]+r,n[o++]=a[c+2]+r;let l=r*i;for(let c=0;c<s.length;c+=2)t[l]=s[c],t[l+1]=s[c+1],l+=i}const a_=[],l_={extension:{type:A.ShapeBuilder,name:"polygon"},build(s,e){for(let t=0;t<s.points.length;t++)e[t]=s.points[t];return!0},triangulate(s,e,t,i,r,n){Bc(s,a_,e,t,i,r,n)}},c_={extension:{type:A.ShapeBuilder,name:"rectangle"},build(s,e){const t=s,i=t.x,r=t.y,n=t.width,o=t.height;return n>0&&o>0?(e[0]=i,e[1]=r,e[2]=i+n,e[3]=r,e[4]=i+n,e[5]=r+o,e[6]=i,e[7]=r+o,!0):!1},triangulate(s,e,t,i,r,n){let o=0;i*=t,e[i+o]=s[0],e[i+o+1]=s[1],o+=t,e[i+o]=s[2],e[i+o+1]=s[3],o+=t,e[i+o]=s[6],e[i+o+1]=s[7],o+=t,e[i+o]=s[4],e[i+o+1]=s[5],o+=t;const a=i/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2,r[n++]=a+1,r[n++]=a+3,r[n++]=a+2}},h_={extension:{type:A.ShapeBuilder,name:"triangle"},build(s,e){return e[0]=s.x,e[1]=s.y,e[2]=s.x2,e[3]=s.y2,e[4]=s.x3,e[5]=s.y3,!0},triangulate(s,e,t,i,r,n){let o=0;i*=t,e[i+o]=s[0],e[i+o+1]=s[1],o+=t,e[i+o]=s[2],e[i+o+1]=s[3],o+=t,e[i+o]=s[4],e[i+o+1]=s[5];const a=i/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2}},Dc=[{offset:0,color:"white"},{offset:1,color:"black"}],Xn=class la{constructor(...e){this.uid=be("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let t=u_(e);t={...t.type==="radial"?la.defaultRadialOptions:la.defaultLinearOptions,...Ca(t)},this._textureSize=t.textureSize,this._wrapMode=t.wrapMode,t.type==="radial"?(this.center=t.center,this.outerCenter=t.outerCenter??this.center,this.innerRadius=t.innerRadius,this.outerRadius=t.outerRadius,this.scale=t.scale,this.rotation=t.rotation):(this.start=t.start,this.end=t.end),this.textureSpace=t.textureSpace,this.type=t.type,t.colorStops.forEach(r=>{this.addColorStop(r.offset,r.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:Pe.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:i,y:r}=this.end,n=i-e,o=r-t;const a=n<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(n<0){const b=e;e=i,i=b,n*=-1}if(o<0){const b=t;t=r,r=b,o*=-1}}const l=this.colorStops.length?this.colorStops:Dc,c=this._textureSize,{canvas:h,context:u}=Uc(c,1),f=a?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);Nc(f,l),u.fillStyle=f,u.fillRect(0,0,c,1),this.texture=new j({source:new Qs({resource:h,addressMode:this._wrapMode})});const d=Math.sqrt(n*n+o*o),g=Math.atan2(o,n),_=new H;_.scale(d/c,1),_.rotate(g),_.translate(e,t),this.textureSpace==="local"&&_.scale(c,c),this.transform=_}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const e=this.colorStops.length?this.colorStops:Dc,t=this._textureSize,{canvas:i,context:r}=Uc(t,t),{x:n,y:o}=this.center,{x:a,y:l}=this.outerCenter,c=this.innerRadius,h=this.outerRadius,u=a-h,f=l-h,d=t/(h*2),g=(n-u)*d,_=(o-f)*d,b=r.createRadialGradient(g,_,c*d,(a-u)*d,(l-f)*d,h*d);Nc(b,e),r.fillStyle=e[e.length-1].color,r.fillRect(0,0,t,t),r.fillStyle=b,r.translate(g,_),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-g,-_),r.fillRect(0,0,t,t),this.texture=new j({source:new Qs({resource:i,addressMode:this._wrapMode})});const x=new H;x.scale(1/d,1/d),x.translate(u,f),this.textureSpace==="local"&&x.scale(t,t),this.transform=x}destroy(){var e;(e=this.texture)==null||e.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};Xn.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"},Xn.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let Mi=Xn;function Nc(s,e){for(let t=0;t<e.length;t++){const i=e[t];s.addColorStop(i.offset,i.color)}}function Uc(s,e){const t=pe.get().createCanvas(s,e),i=t.getContext("2d");return{canvas:t,context:i}}function u_(s){let e=s[0]??{};return(typeof e=="number"||s[1])&&(ee("8.5.2","use options object instead"),e={type:"linear",start:{x:s[0],y:s[1]},end:{x:s[2],y:s[3]},textureSpace:s[4],textureSize:s[5]??Mi.defaultLinearOptions.textureSize}),e}const d_=new H,f_=new Se;function Fc(s,e,t,i){const r=e.matrix?s.copyFrom(e.matrix).invert():s.identity();if(e.textureSpace==="local"){const o=t.getBounds(f_);e.width&&o.pad(e.width);const{x:a,y:l}=o,c=1/o.width,h=1/o.height,u=-a*c,f=-l*h,d=r.a,g=r.b,_=r.c,b=r.d;r.a*=c,r.b*=c,r.c*=h,r.d*=h,r.tx=u*d+f*_+r.tx,r.ty=u*g+f*b+r.ty}else r.translate(e.texture.frame.x,e.texture.frame.y),r.scale(1/e.texture.source.width,1/e.texture.source.height);const n=e.texture.source.style;return!(e.fill instanceof Mi)&&n.addressMode==="clamp-to-edge"&&(n.addressMode="repeat",n.update()),i&&r.append(d_.copyFrom(i).invert()),r}const fs={};Q.handleByMap(A.ShapeBuilder,fs),Q.add(c_,l_,h_,ds,s_,r_);const p_=new Se,m_=new H;function g_(s,e){const{geometryData:t,batches:i}=e;i.length=0,t.indices.length=0,t.vertices.length=0,t.uvs.length=0;for(let r=0;r<s.instructions.length;r++){const n=s.instructions[r];if(n.action==="texture")__(n.data,i,t);else if(n.action==="fill"||n.action==="stroke"){const o=n.action==="stroke",a=n.data.path.shapePath,l=n.data.style,c=n.data.hole;o&&c&&Gc(c.shapePath,l,!0,i,t),c&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=c.shapePath.shapePrimitives),Gc(a,l,o,i,t)}}}function __(s,e,t){const i=[],r=fs.rectangle,n=p_;n.x=s.dx,n.y=s.dy,n.width=s.dw,n.height=s.dh;const o=s.transform;if(!r.build(n,i))return;const{vertices:a,uvs:l,indices:c}=t,h=c.length,u=a.length/2;o&&Rc(i,o),r.triangulate(i,a,2,u,c,h);const f=s.image,d=f.uvs;l.push(d.x0,d.y0,d.x1,d.y1,d.x3,d.y3,d.x2,d.y2);const g=Le.get(jn);g.indexOffset=h,g.indexSize=c.length-h,g.attributeOffset=u,g.attributeSize=a.length/2-u,g.baseColor=s.style,g.alpha=s.alpha,g.texture=f,g.geometryData=t,e.push(g)}function Gc(s,e,t,i,r){const{vertices:n,uvs:o,indices:a}=r;s.shapePrimitives.forEach(({shape:l,transform:c,holes:h})=>{const u=[],f=fs[l.type];if(!f.build(l,u))return;const d=a.length,g=n.length/2;let _="triangle-list";if(c&&Rc(u,c),t){const S=l.closePath??!0,E=e;E.pixelLine?(o_(u,S,n,a),_="line-list"):Oc(u,E,!1,S,n,a)}else if(h){const S=[],E=u.slice();y_(h).forEach(R=>{S.push(E.length/2),E.push(...R)}),Bc(E,S,n,2,g,a,d)}else f.triangulate(u,n,2,g,a,d);const b=o.length/2,x=e.texture;if(x!==j.WHITE){const S=Fc(m_,e,l,c);e_(n,2,g,o,b,2,n.length/2-g,S)}else t_(o,b,2,n.length/2-g);const C=Le.get(jn);C.indexOffset=d,C.indexSize=a.length-d,C.attributeOffset=g,C.attributeSize=n.length/2-g,C.baseColor=e.color,C.alpha=e.alpha,C.texture=x,C.geometryData=r,C.topology=_,i.push(C)})}function y_(s){const e=[];for(let t=0;t<s.length;t++){const i=s[t].shape,r=[];fs[i.type].build(i,r)&&e.push(r)}return e}class b_{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{Le.return(e)}),this.graphicsData&&Le.return(this.graphicsData),this.isBatchable=!1,this.context=null,this.batches.length=0,this.geometryData.indices.length=0,this.geometryData.vertices.length=0,this.geometryData.uvs.length=0,this.graphicsData=null}destroy(){this.reset(),this.batches=null,this.geometryData=null}}class x_{constructor(){this.instructions=new ln}init(e){const t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new $n({maxTextures:t}),this.instructions.reset()}get geometry(){return ee(jf,"GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead."),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}}const Yn=class ca{constructor(e){this._renderer=e,this._managedContexts=new kt({renderer:e,type:"resource",name:"graphicsContext"})}init(e){ca.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??ca.defaultOptions.bezierSmoothness}getContextRenderData(e){return e._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=!!e._gpuData[this._renderer.uid],i=e._gpuData[this._renderer.uid]||this._initContext(e);if(e.dirty||!t){t&&i.reset(),g_(e,i);const r=e.batchMode;e.customShader||r==="no-batch"?i.isBatchable=!1:r==="auto"?i.isBatchable=i.geometryData.vertices.length<400:i.isBatchable=!0,e.dirty=!1}return i}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=Le.get(x_,{maxTextures:this._renderer.limits.maxBatchableTextures}),i=e._gpuData[this._renderer.uid],{batches:r,geometryData:n}=i;i.graphicsData=t;const o=n.vertices.length,a=n.indices.length;for(let u=0;u<r.length;u++)r[u].applyTransform=!1;const l=t.batcher;l.ensureAttributeBuffer(o),l.ensureIndexBuffer(a),l.begin();for(let u=0;u<r.length;u++){const f=r[u];l.add(f)}l.finish(t.instructions);const c=l.geometry;c.indexBuffer.setDataWithSize(l.indexBuffer,l.indexSize,!0),c.buffers[0].setDataWithSize(l.attributeBuffer.float32View,l.attributeSize,!0);const h=l.batches;for(let u=0;u<h.length;u++){const f=h[u];f.bindGroup=Nn(f.textures.textures,f.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){const t=new b_;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Yn.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"graphicsContext"},Yn.defaultOptions={bezierSmoothness:.5};let qn=Yn;const v_=8,lr=11920929e-14,C_=1;function Lc(s,e,t,i,r,n,o,a,l,c){const u=Math.min(.99,Math.max(0,c??qn.defaultOptions.bezierSmoothness));let f=(C_-u)/1;return f*=f,S_(e,t,i,r,n,o,a,l,s,f),s}function S_(s,e,t,i,r,n,o,a,l,c){Kn(s,e,t,i,r,n,o,a,l,c,0),l.push(o,a)}function Kn(s,e,t,i,r,n,o,a,l,c,h){if(h>v_)return;const u=(s+t)/2,f=(e+i)/2,d=(t+r)/2,g=(i+n)/2,_=(r+o)/2,b=(n+a)/2,x=(u+d)/2,C=(f+g)/2,S=(d+_)/2,E=(g+b)/2,w=(x+S)/2,R=(C+E)/2;if(h>0){let M=o-s,D=a-e;const F=Math.abs((t-o)*D-(i-a)*M),k=Math.abs((r-o)*D-(n-a)*M);if(F>lr&&k>lr){if((F+k)*(F+k)<=c*(M*M+D*D)){l.push(w,R);return}}else if(F>lr){if(F*F<=c*(M*M+D*D)){l.push(w,R);return}}else if(k>lr){if(k*k<=c*(M*M+D*D)){l.push(w,R);return}}else if(M=w-(s+o)/2,D=R-(e+a)/2,M*M+D*D<=c){l.push(w,R);return}}Kn(s,e,u,f,x,C,w,R,l,c,h+1),Kn(w,R,S,E,_,b,o,a,l,c,h+1)}const E_=8,T_=11920929e-14,A_=1;function w_(s,e,t,i,r,n,o,a){const c=Math.min(.99,Math.max(0,a??qn.defaultOptions.bezierSmoothness));let h=(A_-c)/1;return h*=h,I_(e,t,i,r,n,o,s,h),s}function I_(s,e,t,i,r,n,o,a){Zn(o,s,e,t,i,r,n,a,0),o.push(r,n)}function Zn(s,e,t,i,r,n,o,a,l){if(l>E_)return;const c=(e+i)/2,h=(t+r)/2,u=(i+n)/2,f=(r+o)/2,d=(c+u)/2,g=(h+f)/2;let _=n-e,b=o-t;const x=Math.abs((i-n)*b-(r-o)*_);if(x>T_){if(x*x<=a*(_*_+b*b)){s.push(d,g);return}}else if(_=d-(e+n)/2,b=g-(t+o)/2,_*_+b*b<=a){s.push(d,g);return}Zn(s,e,t,c,h,d,g,a,l+1),Zn(s,d,g,u,f,n,o,a,l+1)}function Wc(s,e,t,i,r,n,o,a){let l=Math.abs(r-n);(!o&&r>n||o&&n>r)&&(l=2*Math.PI-l),a||(a=Math.max(6,Math.floor(6*Math.pow(i,1/3)*(l/Math.PI)))),a=Math.max(a,3);let c=l/a,h=r;c*=o?-1:1;for(let u=0;u<a+1;u++){const f=Math.cos(h),d=Math.sin(h),g=e+f*i,_=t+d*i;s.push(g,_),h+=c}}function R_(s,e,t,i,r,n){const o=s[s.length-2],l=s[s.length-1]-t,c=o-e,h=r-t,u=i-e,f=Math.abs(l*u-c*h);if(f<1e-8||n===0){(s[s.length-2]!==e||s[s.length-1]!==t)&&s.push(e,t);return}const d=l*l+c*c,g=h*h+u*u,_=l*h+c*u,b=n*Math.sqrt(d)/f,x=n*Math.sqrt(g)/f,C=b*_/d,S=x*_/g,E=b*u+x*c,w=b*h+x*l,R=c*(x+C),M=l*(x+C),D=u*(b+S),F=h*(b+S),k=Math.atan2(M-w,R-E),O=Math.atan2(F-w,D-E);Wc(s,E+e,w+t,n,k,O,c*h>u*l)}const ps=Math.PI*2,Jn={centerX:0,centerY:0,ang1:0,ang2:0},Qn=({x:s,y:e},t,i,r,n,o,a,l)=>{s*=t,e*=i;const c=r*s-n*e,h=n*s+r*e;return l.x=c+o,l.y=h+a,l};function M_(s,e){const t=e===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(e/4),i=e===1.5707963267948966?.551915024494:t,r=Math.cos(s),n=Math.sin(s),o=Math.cos(s+e),a=Math.sin(s+e);return[{x:r-n*i,y:n+r*i},{x:o+a*i,y:a-o*i},{x:o,y:a}]}const Hc=(s,e,t,i)=>{const r=s*i-e*t<0?-1:1;let n=s*t+e*i;return n>1&&(n=1),n<-1&&(n=-1),r*Math.acos(n)},P_=(s,e,t,i,r,n,o,a,l,c,h,u,f)=>{const d=Math.pow(r,2),g=Math.pow(n,2),_=Math.pow(h,2),b=Math.pow(u,2);let x=d*g-d*b-g*_;x<0&&(x=0),x/=d*b+g*_,x=Math.sqrt(x)*(o===a?-1:1);const C=x*r/n*u,S=x*-n/r*h,E=c*C-l*S+(s+t)/2,w=l*C+c*S+(e+i)/2,R=(h-C)/r,M=(u-S)/n,D=(-h-C)/r,F=(-u-S)/n,k=Hc(1,0,R,M);let O=Hc(R,M,D,F);a===0&&O>0&&(O-=ps),a===1&&O<0&&(O+=ps),f.centerX=E,f.centerY=w,f.ang1=k,f.ang2=O};function k_(s,e,t,i,r,n,o,a=0,l=0,c=0){if(n===0||o===0)return;const h=Math.sin(a*ps/360),u=Math.cos(a*ps/360),f=u*(e-i)/2+h*(t-r)/2,d=-h*(e-i)/2+u*(t-r)/2;if(f===0&&d===0)return;n=Math.abs(n),o=Math.abs(o);const g=Math.pow(f,2)/Math.pow(n,2)+Math.pow(d,2)/Math.pow(o,2);g>1&&(n*=Math.sqrt(g),o*=Math.sqrt(g)),P_(e,t,i,r,n,o,l,c,h,u,f,d,Jn);let{ang1:_,ang2:b}=Jn;const{centerX:x,centerY:C}=Jn;let S=Math.abs(b)/(ps/4);Math.abs(1-S)<1e-7&&(S=1);const E=Math.max(Math.ceil(S),1);b/=E;let w=s[s.length-2],R=s[s.length-1];const M={x:0,y:0};for(let D=0;D<E;D++){const F=M_(_,b),{x:k,y:O}=Qn(F[0],n,o,u,h,x,C,M),{x:V,y:X}=Qn(F[1],n,o,u,h,x,C,M),{x:z,y:de}=Qn(F[2],n,o,u,h,x,C,M);Lc(s,w,R,k,O,V,X,z,de),w=z,R=de,_+=b}}function O_(s,e,t){const i=(o,a)=>{const l=a.x-o.x,c=a.y-o.y,h=Math.sqrt(l*l+c*c),u=l/h,f=c/h;return{len:h,nx:u,ny:f}},r=(o,a)=>{o===0?s.moveTo(a.x,a.y):s.lineTo(a.x,a.y)};let n=e[e.length-1];for(let o=0;o<e.length;o++){const a=e[o%e.length],l=a.radius??t;if(l<=0){r(o,a),n=a;continue}const c=e[(o+1)%e.length],h=i(a,n),u=i(a,c);if(h.len<1e-4||u.len<1e-4){r(o,a),n=a;continue}let f=Math.asin(h.nx*u.ny-h.ny*u.nx),d=1,g=!1;h.nx*u.nx-h.ny*-u.ny<0?f<0?f=Math.PI+f:(f=Math.PI-f,d=-1,g=!0):f>0&&(d=-1,g=!0);const _=f/2;let b,x=Math.abs(Math.cos(_)*l/Math.sin(_));x>Math.min(h.len/2,u.len/2)?(x=Math.min(h.len/2,u.len/2),b=Math.abs(x*Math.sin(_)/Math.cos(_))):b=l;const C=a.x+u.nx*x+-u.ny*b*d,S=a.y+u.ny*x+u.nx*b*d,E=Math.atan2(h.ny,h.nx)+Math.PI/2*d,w=Math.atan2(u.ny,u.nx)-Math.PI/2*d;o===0&&s.moveTo(C+Math.cos(E)*b,S+Math.sin(E)*b),s.arc(C,S,b,E,w,g),n=a}}function B_(s,e,t,i){const r=(a,l)=>Math.sqrt((a.x-l.x)**2+(a.y-l.y)**2),n=(a,l,c)=>({x:a.x+(l.x-a.x)*c,y:a.y+(l.y-a.y)*c}),o=e.length;for(let a=0;a<o;a++){const l=e[(a+1)%o],c=l.radius??t;if(c<=0){a===0?s.moveTo(l.x,l.y):s.lineTo(l.x,l.y);continue}const h=e[a],u=e[(a+2)%o],f=r(h,l);let d;if(f<1e-4)d=l;else{const b=Math.min(f/2,c);d=n(l,h,b/f)}const g=r(u,l);let _;if(g<1e-4)_=l;else{const b=Math.min(g/2,c);_=n(l,u,b/g)}a===0?s.moveTo(d.x,d.y):s.lineTo(d.x,d.y),s.quadraticCurveTo(l.x,l.y,_.x,_.y,i)}}const D_=new Se;class N_{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Ye,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();const i=this._currentPoly.points,r=i[i.length-2],n=i[i.length-1];return(r!==e||n!==t)&&i.push(e,t),this}arc(e,t,i,r,n,o){this._ensurePoly(!1);const a=this._currentPoly.points;return Wc(a,e,t,i,r,n,o),this}arcTo(e,t,i,r,n){this._ensurePoly();const o=this._currentPoly.points;return R_(o,e,t,i,r,n),this}arcToSvg(e,t,i,r,n,o,a){const l=this._currentPoly.points;return k_(l,this._currentPoly.lastX,this._currentPoly.lastY,o,a,e,t,i,r,n),this}bezierCurveTo(e,t,i,r,n,o,a){this._ensurePoly();const l=this._currentPoly;return Lc(this._currentPoly.points,l.lastX,l.lastY,e,t,i,r,n,o,a),this}quadraticCurveTo(e,t,i,r,n){this._ensurePoly();const o=this._currentPoly;return w_(this._currentPoly.points,o.lastX,o.lastY,e,t,i,r,n),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));const i=this.shapePrimitives,r=i.length;for(let n=0;n<e.instructions.length;n++){const o=e.instructions[n];this[o.action](...o.data)}if(e.checkForHoles&&i.length-r>1){let n=null;for(let o=r;o<i.length;o++){const a=i[o];if(a.shape.type==="polygon"){const l=a.shape,c=n==null?void 0:n.shape;c&&c.containsPolygon(l)?(n.holes||(n.holes=[]),n.holes.push(a),i.copyWithin(o,o+1),i.length--,o--):n=a}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,i,r,n){return this.drawShape(new Se(e,t,i,r),n),this}circle(e,t,i,r){return this.drawShape(new On(e,t,i),r),this}poly(e,t,i){const r=new ls(e);return r.closePath=t,this.drawShape(r,i),this}regularPoly(e,t,i,r,n=0,o){r=Math.max(r|0,3);const a=-1*Math.PI/2+n,l=Math.PI*2/r,c=[];for(let h=0;h<r;h++){const u=a-h*l;c.push(e+i*Math.cos(u),t+i*Math.sin(u))}return this.poly(c,!0,o),this}roundPoly(e,t,i,r,n,o=0,a){if(r=Math.max(r|0,3),n<=0)return this.regularPoly(e,t,i,r,o);const l=i*Math.sin(Math.PI/r)-.001;n=Math.min(n,l);const c=-1*Math.PI/2+o,h=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let f=0;f<r;f++){const d=f*h+c,g=e+i*Math.cos(d),_=t+i*Math.sin(d),b=d+Math.PI+u,x=d-Math.PI-u,C=g+n*Math.cos(b),S=_+n*Math.sin(b),E=g+n*Math.cos(x),w=_+n*Math.sin(x);f===0?this.moveTo(C,S):this.lineTo(C,S),this.quadraticCurveTo(g,_,E,w,a)}return this.closePath()}roundShape(e,t,i=!1,r){return e.length<3?this:(i?B_(this,e,t,r):O_(this,e,t),this.closePath())}filletRect(e,t,i,r,n){if(n===0)return this.rect(e,t,i,r);const o=Math.min(i,r)/2,a=Math.min(o,Math.max(-o,n)),l=e+i,c=t+r,h=a<0?-a:0,u=Math.abs(a);return this.moveTo(e,t+u).arcTo(e+h,t+h,e+u,t,u).lineTo(l-u,t).arcTo(l-h,t+h,l,t+u,u).lineTo(l,c-u).arcTo(l-h,c-h,e+i-u,c,u).lineTo(e+u,c).arcTo(e+h,c-h,e,c-u,u).closePath()}chamferRect(e,t,i,r,n,o){if(n<=0)return this.rect(e,t,i,r);const a=Math.min(n,Math.min(i,r)/2),l=e+i,c=t+r,h=[e+a,t,l-a,t,l,t+a,l,c-a,l-a,c,e+a,c,e,c-a,e,t+a];for(let u=h.length-1;u>=2;u-=2)h[u]===h[u-2]&&h[u-1]===h[u-3]&&h.splice(u-1,2);return this.poly(h,!0,o)}ellipse(e,t,i,r,n){return this.drawShape(new Bn(e,t,i,r),n),this}roundRect(e,t,i,r,n,o){return this.drawShape(new Dn(e,t,i,r,n),o),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let i=this._currentPoly;return i&&this.endPoly(),i=new ls,i.points.push(e,t),this._currentPoly=i,this}endPoly(e=!1){const t=this._currentPoly;return t&&t.points.length>2&&(t.closePath=e,this.shapePrimitives.push({shape:t})),this._currentPoly=null,this}_ensurePoly(e=!0){if(!this._currentPoly&&(this._currentPoly=new ls,e)){const t=this.shapePrimitives[this.shapePrimitives.length-1];if(t){let i=t.shape.x,r=t.shape.y;if(t.transform&&!t.transform.isIdentity()){const n=t.transform,o=i;i=n.a*i+n.c*r+n.tx,r=n.b*o+n.d*r+n.ty}this._currentPoly.points.push(i,r)}else this._currentPoly.points.push(0,0)}}buildPath(){const e=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let t=0;t<e.instructions.length;t++){const i=e.instructions[t];this[i.action](...i.data)}this.finish()}get bounds(){const e=this._bounds;e.clear();const t=this.shapePrimitives;for(let i=0;i<t.length;i++){const r=t[i],n=r.shape.getBounds(D_);r.transform?e.addRect(n,r.transform):e.addRect(n)}return e}}class Ot{constructor(e,t=!1){this.instructions=[],this.uid=be("graphicsPath"),this._dirty=!0,this.checkForHoles=t,typeof e=="string"?Cg(e,this):this.instructions=(e==null?void 0:e.slice())??[]}get shapePath(){return this._shapePath||(this._shapePath=new N_(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(e,t){return e=e.clone(),this.instructions.push({action:"addPath",data:[e,t]}),this._dirty=!0,this}arc(...e){return this.instructions.push({action:"arc",data:e}),this._dirty=!0,this}arcTo(...e){return this.instructions.push({action:"arcTo",data:e}),this._dirty=!0,this}arcToSvg(...e){return this.instructions.push({action:"arcToSvg",data:e}),this._dirty=!0,this}bezierCurveTo(...e){return this.instructions.push({action:"bezierCurveTo",data:e}),this._dirty=!0,this}bezierCurveToShort(e,t,i,r,n){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(xe.shared);let l=0,c=0;if(!o||o.action!=="bezierCurveTo")l=a.x,c=a.y;else{l=o.data[2],c=o.data[3];const h=a.x,u=a.y;l=h+(h-l),c=u+(u-c)}return this.instructions.push({action:"bezierCurveTo",data:[l,c,e,t,i,r,n]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...e){return this.instructions.push({action:"ellipse",data:e}),this._dirty=!0,this}lineTo(...e){return this.instructions.push({action:"lineTo",data:e}),this._dirty=!0,this}moveTo(...e){return this.instructions.push({action:"moveTo",data:e}),this}quadraticCurveTo(...e){return this.instructions.push({action:"quadraticCurveTo",data:e}),this._dirty=!0,this}quadraticCurveToShort(e,t,i){const r=this.instructions[this.instructions.length-1],n=this.getLastPoint(xe.shared);let o=0,a=0;if(!r||r.action!=="quadraticCurveTo")o=n.x,a=n.y;else{o=r.data[0],a=r.data[1];const l=n.x,c=n.y;o=l+(l-o),a=c+(c-a)}return this.instructions.push({action:"quadraticCurveTo",data:[o,a,e,t,i]}),this._dirty=!0,this}rect(e,t,i,r,n){return this.instructions.push({action:"rect",data:[e,t,i,r,n]}),this._dirty=!0,this}circle(e,t,i,r){return this.instructions.push({action:"circle",data:[e,t,i,r]}),this._dirty=!0,this}roundRect(...e){return this.instructions.push({action:"roundRect",data:e}),this._dirty=!0,this}poly(...e){return this.instructions.push({action:"poly",data:e}),this._dirty=!0,this}regularPoly(...e){return this.instructions.push({action:"regularPoly",data:e}),this._dirty=!0,this}roundPoly(...e){return this.instructions.push({action:"roundPoly",data:e}),this._dirty=!0,this}roundShape(...e){return this.instructions.push({action:"roundShape",data:e}),this._dirty=!0,this}filletRect(...e){return this.instructions.push({action:"filletRect",data:e}),this._dirty=!0,this}chamferRect(...e){return this.instructions.push({action:"chamferRect",data:e}),this._dirty=!0,this}star(e,t,i,r,n,o,a){n||(n=r/2);const l=-1*Math.PI/2+o,c=i*2,h=Math.PI*2/c,u=[];for(let f=0;f<c;f++){const d=f%2?n:r,g=f*h+l;u.push(e+d*Math.cos(g),t+d*Math.sin(g))}return this.poly(u,!0,a),this}clone(e=!1){const t=new Ot;if(t.checkForHoles=this.checkForHoles,!e)t.instructions=this.instructions.slice();else for(let i=0;i<this.instructions.length;i++){const r=this.instructions[i];t.instructions.push({action:r.action,data:r.data.slice()})}return t}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(e){if(e.isIdentity())return this;const t=e.a,i=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty;let l=0,c=0,h=0,u=0,f=0,d=0,g=0,_=0;for(let b=0;b<this.instructions.length;b++){const x=this.instructions[b],C=x.data;switch(x.action){case"moveTo":case"lineTo":l=C[0],c=C[1],C[0]=t*l+r*c+o,C[1]=i*l+n*c+a;break;case"bezierCurveTo":h=C[0],u=C[1],f=C[2],d=C[3],l=C[4],c=C[5],C[0]=t*h+r*u+o,C[1]=i*h+n*u+a,C[2]=t*f+r*d+o,C[3]=i*f+n*d+a,C[4]=t*l+r*c+o,C[5]=i*l+n*c+a;break;case"quadraticCurveTo":h=C[0],u=C[1],l=C[2],c=C[3],C[0]=t*h+r*u+o,C[1]=i*h+n*u+a,C[2]=t*l+r*c+o,C[3]=i*l+n*c+a;break;case"arcToSvg":l=C[5],c=C[6],g=C[0],_=C[1],C[0]=t*g+r*_,C[1]=i*g+n*_,C[5]=t*l+r*c+o,C[6]=i*l+n*c+a;break;case"circle":C[4]=ms(C[3],e);break;case"rect":C[4]=ms(C[4],e);break;case"ellipse":C[8]=ms(C[8],e);break;case"roundRect":C[5]=ms(C[5],e);break;case"addPath":C[0].transform(e);break;case"poly":C[2]=ms(C[2],e);break;default:se("unknown transform action",x.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,i=this.instructions[t];if(!i)return e.x=0,e.y=0,e;for(;i.action==="closePath";){if(t--,t<0)return e.x=0,e.y=0,e;i=this.instructions[t]}switch(i.action){case"moveTo":case"lineTo":e.x=i.data[0],e.y=i.data[1];break;case"quadraticCurveTo":e.x=i.data[2],e.y=i.data[3];break;case"bezierCurveTo":e.x=i.data[4],e.y=i.data[5];break;case"arc":case"arcToSvg":e.x=i.data[5],e.y=i.data[6];break;case"addPath":i.data[0].getLastPoint(e);break}return e}}function ms(s,e){return s?s.prepend(e):e.clone()}function Ie(s,e,t){const i=s.getAttribute(e);return i?Number(i):t}function U_(s,e){const t=s.querySelectorAll("defs");for(let i=0;i<t.length;i++){const r=t[i];for(let n=0;n<r.children.length;n++){const o=r.children[n];switch(o.nodeName.toLowerCase()){case"lineargradient":e.defs[o.id]=F_(o);break;case"radialgradient":e.defs[o.id]=G_();break}}}}function F_(s){const e=Ie(s,"x1",0),t=Ie(s,"y1",0),i=Ie(s,"x2",1),r=Ie(s,"y2",0),n=s.getAttribute("gradientUnits")||"objectBoundingBox",o=new Mi(e,t,i,r,n==="objectBoundingBox"?"local":"global");for(let a=0;a<s.children.length;a++){const l=s.children[a],c=Ie(l,"offset",0),h=Pe.shared.setValue(l.getAttribute("stop-color")).toNumber();o.addColorStop(c,h)}return o}function G_(s){return se("[SVG Parser] Radial gradients are not yet supported"),new Mi(0,0,1,0)}function Vc(s){const e=s.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return e?e[1]:""}const zc={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function $c(s,e){const t=s.getAttribute("style"),i={},r={},n={strokeStyle:i,fillStyle:r,useFill:!1,useStroke:!1};for(const o in zc){const a=s.getAttribute(o);a&&jc(e,n,o,a.trim())}if(t){const o=t.split(";");for(let a=0;a<o.length;a++){const l=o[a].trim(),[c,h]=l.split(":");zc[c]&&jc(e,n,c,h.trim())}}return{strokeStyle:n.useStroke?i:null,fillStyle:n.useFill?r:null,useFill:n.useFill,useStroke:n.useStroke}}function jc(s,e,t,i){switch(t){case"stroke":if(i!=="none"){if(i.startsWith("url(")){const r=Vc(i);e.strokeStyle.fill=s.defs[r]}else e.strokeStyle.color=Pe.shared.setValue(i).toNumber();e.useStroke=!0}break;case"stroke-width":e.strokeStyle.width=Number(i);break;case"fill":if(i!=="none"){if(i.startsWith("url(")){const r=Vc(i);e.fillStyle.fill=s.defs[r]}else e.fillStyle.color=Pe.shared.setValue(i).toNumber();e.useFill=!0}break;case"fill-opacity":e.fillStyle.alpha=Number(i);break;case"stroke-opacity":e.strokeStyle.alpha=Number(i);break;case"opacity":e.fillStyle.alpha=Number(i),e.strokeStyle.alpha=Number(i);break}}function L_(s){if(s.length<=2)return!0;const e=s.map(a=>a.area).sort((a,l)=>l-a),[t,i]=e,r=e[e.length-1],n=t/i,o=i/r;return!(n>3&&o<2)}function W_(s){return s.split(/(?=[Mm])/).filter(i=>i.trim().length>0)}function H_(s){const e=s.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!e||e.length<4)return 0;const t=e.map(Number),i=[],r=[];for(let h=0;h<t.length;h+=2)h+1<t.length&&(i.push(t[h]),r.push(t[h+1]));if(i.length===0||r.length===0)return 0;const n=Math.min(...i),o=Math.max(...i),a=Math.min(...r),l=Math.max(...r);return(o-n)*(l-a)}function Xc(s,e){const t=new Ot(s,!1);for(const i of t.instructions)e.instructions.push(i)}function V_(s,e){if(typeof s=="string"){const o=document.createElement("div");o.innerHTML=s.trim(),s=o.querySelector("svg")}const t={context:e,defs:{},path:new Ot};U_(s,t);const i=s.children,{fillStyle:r,strokeStyle:n}=$c(s,t);for(let o=0;o<i.length;o++){const a=i[o];a.nodeName.toLowerCase()!=="defs"&&Yc(a,t,r,n)}return e}function Yc(s,e,t,i){const r=s.children,{fillStyle:n,strokeStyle:o}=$c(s,e);n&&t?t={...t,...n}:n&&(t=n),o&&i?i={...i,...o}:o&&(i=o);const a=!t&&!i;a&&(t={color:0});let l,c,h,u,f,d,g,_,b,x,C,S,E,w,R,M,D;switch(s.nodeName.toLowerCase()){case"path":{w=s.getAttribute("d");const F=s.getAttribute("fill-rule"),k=W_(w),O=F==="evenodd",V=k.length>1;if(O&&V){const z=k.map(B=>({path:B,area:H_(B)}));if(z.sort((B,U)=>U.area-B.area),k.length>3||!L_(z))for(let B=0;B<z.length;B++){const U=z[B],q=B===0;e.context.beginPath();const N=new Ot(void 0,!0);Xc(U.path,N),e.context.path(N),q?(t&&e.context.fill(t),i&&e.context.stroke(i)):e.context.cut()}else for(let B=0;B<z.length;B++){const U=z[B],q=B%2===1;e.context.beginPath();const N=new Ot(void 0,!0);Xc(U.path,N),e.context.path(N),q?e.context.cut():(t&&e.context.fill(t),i&&e.context.stroke(i))}}else{const z=F?F==="evenodd":!0;R=new Ot(w,z),e.context.path(R),t&&e.context.fill(t),i&&e.context.stroke(i)}break}case"circle":g=Ie(s,"cx",0),_=Ie(s,"cy",0),b=Ie(s,"r",0),e.context.ellipse(g,_,b,b),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"rect":l=Ie(s,"x",0),c=Ie(s,"y",0),M=Ie(s,"width",0),D=Ie(s,"height",0),x=Ie(s,"rx",0),C=Ie(s,"ry",0),x||C?e.context.roundRect(l,c,M,D,x||C):e.context.rect(l,c,M,D),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"ellipse":g=Ie(s,"cx",0),_=Ie(s,"cy",0),x=Ie(s,"rx",0),C=Ie(s,"ry",0),e.context.beginPath(),e.context.ellipse(g,_,x,C),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"line":h=Ie(s,"x1",0),u=Ie(s,"y1",0),f=Ie(s,"x2",0),d=Ie(s,"y2",0),e.context.beginPath(),e.context.moveTo(h,u),e.context.lineTo(f,d),i&&e.context.stroke(i);break;case"polygon":E=s.getAttribute("points"),S=E.match(/-?\d+/g).map(F=>parseInt(F,10)),e.context.poly(S,!0),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"polyline":E=s.getAttribute("points"),S=E.match(/-?\d+/g).map(F=>parseInt(F,10)),e.context.poly(S,!1),i&&e.context.stroke(i);break;case"g":case"svg":break;default:{se(`[SVG parser] <${s.nodeName}> elements unsupported`);break}}a&&(t=null);for(let F=0;F<r.length;F++)Yc(r[F],e,t,i)}const qc={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class Kc{constructor(e,t){this.uid=be("fillPattern"),this._tick=0,this.transform=new H,this.texture=e,this.transform.scale(1/e.frame.width,1/e.frame.height),t&&(e.source.style.addressModeU=qc[t].addressModeU,e.source.style.addressModeV=qc[t].addressModeV)}setTransform(e){const t=this.texture;this.transform.copyFrom(e),this.transform.invert(),this.transform.scale(1/t.frame.width,1/t.frame.height),this._tick++}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}function z_(s){return Pe.isColorLike(s)}function Zc(s){return s instanceof Kc}function Jc(s){return s instanceof Mi}function $_(s){return s instanceof j}function j_(s,e,t){const i=Pe.shared.setValue(e??0);return s.color=i.toNumber(),s.alpha=i.alpha===1?t.alpha:i.alpha,s.texture=j.WHITE,{...t,...s}}function X_(s,e,t){return s.texture=e,{...t,...s}}function Qc(s,e,t){return s.fill=e,s.color=16777215,s.texture=e.texture,s.matrix=e.transform,{...t,...s}}function eh(s,e,t){return e.buildGradient(),s.fill=e,s.color=16777215,s.texture=e.texture,s.matrix=e.transform,s.textureSpace=e.textureSpace,{...t,...s}}function Y_(s,e){const t={...e,...s},i=Pe.shared.setValue(t.color);return t.alpha*=i.alpha,t.color=i.toNumber(),t}function gs(s,e){if(s==null)return null;const t={},i=s;return z_(s)?j_(t,s,e):$_(s)?X_(t,s,e):Zc(s)?Qc(t,s,e):Jc(s)?eh(t,s,e):i.fill&&Zc(i.fill)?Qc(i,i.fill,e):i.fill&&Jc(i.fill)?eh(i,i.fill,e):Y_(i,e)}function th(s,e){const{width:t,alignment:i,miterLimit:r,cap:n,join:o,pixelLine:a,...l}=e,c=gs(s,l);return c?{width:t,alignment:i,miterLimit:r,cap:n,join:o,pixelLine:a,...c}:null}function q_(s,e){let t=1;const i=s.shapePath.shapePrimitives;for(let r=0;r<i.length;r++){const n=i[r].shape;if(n.type!=="polygon")continue;const o=n.points,a=o.length;if(a<6)continue;const l=n.closePath;for(let c=0;c<a;c+=2){if(!l&&(c===0||c===a-2))continue;const h=(c-2+a)%a,u=(c+2)%a,f=o[h],d=o[h+1],g=o[c],_=o[c+1],b=o[u],x=o[u+1],C=f-g,S=d-_,E=b-g,w=x-_,R=C*C+S*S,M=E*E+w*w;if(R<1e-12||M<1e-12)continue;let k=(C*E+S*w)/Math.sqrt(R*M);k<-1?k=-1:k>1&&(k=1);const O=Math.sqrt((1-k)*.5);if(O<1e-6)continue;const V=Math.min(1/O,e);V>t&&(t=V)}}return t}const K_=new xe,ih=new H,eo=class Tt extends lt{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=be("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new Ot,this._transform=new H,this._fillStyle={...Tt.defaultFillStyle},this._strokeStyle={...Tt.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Ye,this._boundsDirty=!0}clone(){const e=new Tt;return e.batchMode=this.batchMode,e.instructions=this.instructions.slice(),e._activePath=this._activePath.clone(),e._transform=this._transform.clone(),e._fillStyle={...this._fillStyle},e._strokeStyle={...this._strokeStyle},e._stateStack=this._stateStack.slice(),e._bounds=this._bounds.clone(),e._boundsDirty=!0,e}get fillStyle(){return this._fillStyle}set fillStyle(e){this._fillStyle=gs(e,Tt.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=th(e,Tt.defaultStrokeStyle)}setFillStyle(e){return this._fillStyle=gs(e,Tt.defaultFillStyle),this}setStrokeStyle(e){return this._strokeStyle=gs(e,Tt.defaultStrokeStyle),this}texture(e,t,i,r,n,o){return this.instructions.push({action:"texture",data:{image:e,dx:i||0,dy:r||0,dw:n||e.frame.width,dh:o||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t||t===0?Pe.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new Ot,this}fill(e,t){let i;const r=this.instructions[this.instructions.length-1];return this._tick===0&&(r==null?void 0:r.action)==="stroke"?i=r.data.path:i=this._activePath.clone(),i?(e!=null&&(t!==void 0&&typeof e=="number"&&(ee(Be,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),e={color:e,alpha:t}),this._fillStyle=gs(e,Tt.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:i}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:e,y:t}=this._activePath.getLastPoint(xe.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(e){let t;const i=this.instructions[this.instructions.length-1];return this._tick===0&&(i==null?void 0:i.action)==="fill"?t=i.data.path:t=this._activePath.clone(),t?(e!=null&&(this._strokeStyle=th(e,Tt.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:t}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let e=0;e<2;e++){const t=this.instructions[this.instructions.length-1-e],i=this._activePath.clone();if(t&&(t.action==="stroke"||t.action==="fill"))if(t.data.hole)t.data.hole.addPath(i);else{t.data.hole=i;break}}return this._initNextPathLocation(),this}arc(e,t,i,r,n,o){this._tick++;const a=this._transform;return this._activePath.arc(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,i,r,n,o),this}arcTo(e,t,i,r,n){this._tick++;const o=this._transform;return this._activePath.arcTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*i+o.c*r+o.tx,o.b*i+o.d*r+o.ty,n),this}arcToSvg(e,t,i,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.arcToSvg(e,t,i,r,n,l.a*o+l.c*a+l.tx,l.b*o+l.d*a+l.ty),this}bezierCurveTo(e,t,i,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.bezierCurveTo(l.a*e+l.c*t+l.tx,l.b*e+l.d*t+l.ty,l.a*i+l.c*r+l.tx,l.b*i+l.d*r+l.ty,l.a*n+l.c*o+l.tx,l.b*n+l.d*o+l.ty,a),this}closePath(){var e;return this._tick++,(e=this._activePath)==null||e.closePath(),this}ellipse(e,t,i,r){return this._tick++,this._activePath.ellipse(e,t,i,r,this._transform.clone()),this}circle(e,t,i){return this._tick++,this._activePath.circle(e,t,i,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;const i=this._transform;return this._activePath.lineTo(i.a*e+i.c*t+i.tx,i.b*e+i.d*t+i.ty),this}moveTo(e,t){this._tick++;const i=this._transform,r=this._activePath.instructions,n=i.a*e+i.c*t+i.tx,o=i.b*e+i.d*t+i.ty;return r.length===1&&r[0].action==="moveTo"?(r[0].data[0]=n,r[0].data[1]=o,this):(this._activePath.moveTo(n,o),this)}quadraticCurveTo(e,t,i,r,n){this._tick++;const o=this._transform;return this._activePath.quadraticCurveTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*i+o.c*r+o.tx,o.b*i+o.d*r+o.ty,n),this}rect(e,t,i,r){return this._tick++,this._activePath.rect(e,t,i,r,this._transform.clone()),this}roundRect(e,t,i,r,n){return this._tick++,this._activePath.roundRect(e,t,i,r,n,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,i,r,n=0,o){return this._tick++,this._activePath.regularPoly(e,t,i,r,n,o),this}roundPoly(e,t,i,r,n,o){return this._tick++,this._activePath.roundPoly(e,t,i,r,n,o),this}roundShape(e,t,i,r){return this._tick++,this._activePath.roundShape(e,t,i,r),this}filletRect(e,t,i,r,n){return this._tick++,this._activePath.filletRect(e,t,i,r,n),this}chamferRect(e,t,i,r,n,o){return this._tick++,this._activePath.chamferRect(e,t,i,r,n,o),this}star(e,t,i,r,n=0,o=0){return this._tick++,this._activePath.star(e,t,i,r,n,o,this._transform.clone()),this}svg(e){return this._tick++,V_(e,this),this}restore(){const e=this._stateStack.pop();return e&&(this._transform=e.transform,this._fillStyle=e.fillStyle,this._strokeStyle=e.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(e){return this._transform.rotate(e),this}scale(e,t=e){return this._transform.scale(e,t),this}setTransform(e,t,i,r,n,o){return e instanceof H?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,i,r,n,o),this)}transform(e,t,i,r,n,o){return e instanceof H?(this._transform.append(e),this):(ih.set(e,t,i,r,n,o),this._transform.append(ih),this)}translate(e,t=e){return this._transform.translate(e,t),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,this.dirty=!0,this.emit("update",this,16)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const e=this._bounds;e.clear();for(let t=0;t<this.instructions.length;t++){const i=this.instructions[t],r=i.action;if(r==="fill"){const n=i.data;e.addBounds(n.path.bounds)}else if(r==="texture"){const n=i.data;e.addFrame(n.dx,n.dy,n.dx+n.dw,n.dy+n.dh,n.transform)}if(r==="stroke"){const n=i.data,o=n.style.alignment;let a=n.style.width*(1-o);n.style.join==="miter"&&(a*=q_(n.path,n.style.miterLimit));const l=n.path.bounds;e.addFrame(l.minX-a,l.minY-a,l.maxX+a,l.maxY+a)}}return e.isValid||e.set(0,0,0,0),e}containsPoint(e){var r;if(!this.bounds.containsPoint(e.x,e.y))return!1;const t=this.instructions;let i=!1;for(let n=0;n<t.length;n++){const o=t[n],a=o.data,l=a.path;if(!o.action||!l)continue;const c=a.style,h=l.shapePath.shapePrimitives;for(let u=0;u<h.length;u++){const f=h[u].shape;if(!c||!f)continue;const d=h[u].transform,g=d?d.applyInverse(e,K_):e;if(o.action==="fill")i=f.contains(g.x,g.y);else{const b=c;i=f.strokeContains(g.x,g.y,b.width,b.alignment)}const _=a.hole;if(_){const b=(r=_.shapePath)==null?void 0:r.shapePrimitives;if(b)for(let x=0;x<b.length;x++)b[x].shape.contains(g.x,g.y)&&(i=!1)}if(i)return!0}}return i}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){if(this.destroyed)return;if(this.destroyed=!0,this._stateStack.length=0,this._transform=null,this.unload(),this.emit("destroy",this),this.removeAllListeners(),typeof e=="boolean"?e:e==null?void 0:e.texture){const i=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(i)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(i))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};eo.defaultFillStyle={color:16777215,alpha:1,texture:j.WHITE,matrix:null,fill:null,textureSpace:"local"},eo.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:j.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let _s=eo;class sh{constructor(e){this._attachedDomElements=[],this._renderer=e,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new Pl({domElement:this._domElement,renderer:this._renderer})}addRenderable(e,t){this._attachedDomElements.includes(e)||this._attachedDomElements.push(e)}updateRenderable(e){}validateRenderable(e){return!0}postrender(){const e=this._attachedDomElements;if(e.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let t=0;t<e.length;t++){const i=e[t],r=i.element;if(!i.parent||i.globalDisplayStatus<7)r==null||r.remove(),e.splice(t,1),t--;else{this._domElement.contains(r)||(r.style.position="absolute",r.style.pointerEvents="auto",this._domElement.appendChild(r));const n=i.worldTransform,o=i._anchor,a=i.width*o.x,l=i.height*o.y;r.style.transformOrigin=`${a}px ${l}px`,r.style.transform=`matrix(${n.a}, ${n.b}, ${n.c}, ${n.d}, ${n.tx-a}, ${n.ty-l})`,r.style.opacity=i.groupAlpha.toString()}}}destroy(){var e;this._renderer.runners.postrender.remove(this);for(let t=0;t<this._attachedDomElements.length;t++)(e=this._attachedDomElements[t].element)==null||e.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}sh.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"dom"};class Z_{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(e){this.removeTickerListener(),this.events=e,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(e){this._pauseUpdate=e}addTickerListener(){this._tickerAdded||!this.domElement||(at.system.add(this._tickerUpdate,this,Si.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(at.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const e=this.events._rootPointerEvent;this.events.supportsTouchEvents&&e.pointerType==="touch"||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent("pointermove",{clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,pointerId:e.pointerId}):new MouseEvent("mousemove",{clientX:e.clientX,clientY:e.clientY}))}_tickerUpdate(e){this._deltaTime+=e.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}}const Bt=new Z_;class cr extends ns{constructor(){super(...arguments),this.client=new xe,this.movement=new xe,this.offset=new xe,this.global=new xe,this.screen=new xe}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(e,t,i){return e.worldTransform.applyInverse(i||this.global,t)}getModifierState(e){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(e)}initMouseEvent(e,t,i,r,n,o,a,l,c,h,u,f,d,g,_){throw new Error("Method not implemented.")}}class dt extends cr{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class Pi extends cr{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}Pi.DOM_DELTA_PIXEL=0,Pi.DOM_DELTA_LINE=1,Pi.DOM_DELTA_PAGE=2;const J_=2048,Q_=new xe,ys=new xe;class ey{constructor(e){this.dispatch=new lt,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=e,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(e,t){this.mappingTable[e]||(this.mappingTable[e]=[]),this.mappingTable[e].push({fn:t,priority:0}),this.mappingTable[e].sort((i,r)=>i.priority-r.priority)}dispatchEvent(e,t){e.propagationStopped=!1,e.propagationImmediatelyStopped=!1,this.propagate(e,t),this.dispatch.emit(t||e.type,e)}mapEvent(e){if(!this.rootTarget)return;const t=this.mappingTable[e.type];if(t)for(let i=0,r=t.length;i<r;i++)t[i].fn(e);else se(`[EventBoundary]: Event mapping not defined for ${e.type}`)}hitTest(e,t){Bt.pauseUpdate=!0;const r=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",n=this[r](this.rootTarget,this.rootTarget.eventMode,Q_.set(e,t),this.hitTestFn,this.hitPruneFn);return n&&n[0]}propagate(e,t){if(!e.target)return;const i=e.composedPath();e.eventPhase=e.CAPTURING_PHASE;for(let r=0,n=i.length-1;r<n;r++)if(e.currentTarget=i[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return;if(e.eventPhase=e.AT_TARGET,e.currentTarget=e.target,this.notifyTarget(e,t),!(e.propagationStopped||e.propagationImmediatelyStopped)){e.eventPhase=e.BUBBLING_PHASE;for(let r=i.length-2;r>=0;r--)if(e.currentTarget=i[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return}}all(e,t,i=this._allInteractiveElements){if(i.length===0)return;e.eventPhase=e.BUBBLING_PHASE;const r=Array.isArray(t)?t:[t];for(let n=i.length-1;n>=0;n--)r.forEach(o=>{e.currentTarget=i[n],this.notifyTarget(e,o)})}propagationPath(e){const t=[e];for(let i=0;i<J_&&e!==this.rootTarget&&e.parent;i++){if(!e.parent)throw new Error("Cannot find propagation path to disconnected target");t.push(e.parent),e=e.parent}return t.reverse(),t}hitTestMoveRecursive(e,t,i,r,n,o=!1){let a=!1;if(this._interactivePrune(e))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(Bt.pauseUpdate=!1),e.interactiveChildren&&e.children){const h=e.children;for(let u=h.length-1;u>=0;u--){const f=h[u],d=this.hitTestMoveRecursive(f,this._isInteractive(t)?t:f.eventMode,i,r,n,o||n(e,i));if(d){if(d.length>0&&!d[d.length-1].parent)continue;const g=e.isInteractive();(d.length>0||g)&&(g&&this._allInteractiveElements.push(e),d.push(e)),this._hitElements.length===0&&(this._hitElements=d),a=!0}}}const l=this._isInteractive(t),c=e.isInteractive();return c&&c&&this._allInteractiveElements.push(e),o||this._hitElements.length>0?null:a?this._hitElements:l&&!n(e,i)&&r(e,i)?c?[e]:[]:null}hitTestRecursive(e,t,i,r,n){if(this._interactivePrune(e)||n(e,i))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(Bt.pauseUpdate=!1),e.interactiveChildren&&e.children){const l=e.children,c=i;for(let h=l.length-1;h>=0;h--){const u=l[h],f=this.hitTestRecursive(u,this._isInteractive(t)?t:u.eventMode,c,r,n);if(f){if(f.length>0&&!f[f.length-1].parent)continue;const d=e.isInteractive();return(f.length>0||d)&&f.push(e),f}}}const o=this._isInteractive(t),a=e.isInteractive();return o&&r(e,i)?a?[e]:[]:null}_isInteractive(e){return e==="static"||e==="dynamic"}_interactivePrune(e){return!e||!e.visible||!e.renderable||!e.measurable||e.eventMode==="none"||e.eventMode==="passive"&&!e.interactiveChildren}hitPruneFn(e,t){if(e.hitArea&&(e.worldTransform.applyInverse(t,ys),!e.hitArea.contains(ys.x,ys.y)))return!0;if(e.effects&&e.effects.length)for(let i=0;i<e.effects.length;i++){const r=e.effects[i];if(r.containsPoint&&!r.containsPoint(t,this.hitTestFn))return!0}return!1}hitTestFn(e,t){return e.hitArea?!0:e!=null&&e.containsPoint?(e.worldTransform.applyInverse(t,ys),e.containsPoint(ys)):!1}notifyTarget(e,t){var n,o;if(!e.currentTarget.isInteractive())return;t??(t=e.type);const i=`on${t}`;(o=(n=e.currentTarget)[i])==null||o.call(n,e);const r=e.eventPhase===e.CAPTURING_PHASE||e.eventPhase===e.AT_TARGET?`${t}capture`:t;this._notifyListeners(e,r),e.eventPhase===e.AT_TARGET&&this._notifyListeners(e,t)}mapPointerDown(e){if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.createPointerEvent(e);if(this.dispatchEvent(t,"pointerdown"),t.pointerType==="touch")this.dispatchEvent(t,"touchstart");else if(t.pointerType==="mouse"||t.pointerType==="pen"){const r=t.button===2;this.dispatchEvent(t,r?"rightdown":"mousedown")}const i=this.trackingData(e.pointerId);i.pressTargetsByButton[e.button]=t.composedPath(),this.freeEvent(t)}mapPointerMove(e){var l,c;if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const t=this.createPointerEvent(e);this._isPointerMoveEvent=!1;const i=t.pointerType==="mouse"||t.pointerType==="pen",r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.overTargets);if(((l=r.overTargets)==null?void 0:l.length)>0&&n!==t.target){const h=e.type==="mousemove"?"mouseout":"pointerout",u=this.createPointerEvent(e,h,n);if(this.dispatchEvent(u,"pointerout"),i&&this.dispatchEvent(u,"mouseout"),!t.composedPath().includes(n)){const f=this.createPointerEvent(e,"pointerleave",n);for(f.eventPhase=f.AT_TARGET;f.target&&!t.composedPath().includes(f.target);)f.currentTarget=f.target,this.notifyTarget(f),i&&this.notifyTarget(f,"mouseleave"),f.target=f.target.parent;this.freeEvent(f)}this.freeEvent(u)}if(n!==t.target){const h=e.type==="mousemove"?"mouseover":"pointerover",u=this.clonePointerEvent(t,h);this.dispatchEvent(u,"pointerover"),i&&this.dispatchEvent(u,"mouseover");let f=n==null?void 0:n.parent;for(;f&&f!==this.rootTarget.parent&&f!==t.target;)f=f.parent;if(!f||f===this.rootTarget.parent){const g=this.clonePointerEvent(t,"pointerenter");for(g.eventPhase=g.AT_TARGET;g.target&&g.target!==n&&g.target!==this.rootTarget.parent;)g.currentTarget=g.target,this.notifyTarget(g),i&&this.notifyTarget(g,"mouseenter"),g.target=g.target.parent;this.freeEvent(g)}this.freeEvent(u)}const o=[],a=this.enableGlobalMoveEvents??!0;this.moveOnAll?o.push("pointermove"):this.dispatchEvent(t,"pointermove"),a&&o.push("globalpointermove"),t.pointerType==="touch"&&(this.moveOnAll?o.splice(1,0,"touchmove"):this.dispatchEvent(t,"touchmove"),a&&o.push("globaltouchmove")),i&&(this.moveOnAll?o.splice(1,0,"mousemove"):this.dispatchEvent(t,"mousemove"),a&&o.push("globalmousemove"),this.cursor=(c=t.target)==null?void 0:c.cursor),o.length>0&&this.all(t,o),this._allInteractiveElements.length=0,this._hitElements.length=0,r.overTargets=t.composedPath(),this.freeEvent(t)}mapPointerOver(e){var o;if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),i=this.createPointerEvent(e),r=i.pointerType==="mouse"||i.pointerType==="pen";this.dispatchEvent(i,"pointerover"),r&&this.dispatchEvent(i,"mouseover"),i.pointerType==="mouse"&&(this.cursor=(o=i.target)==null?void 0:o.cursor);const n=this.clonePointerEvent(i,"pointerenter");for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),r&&this.notifyTarget(n,"mouseenter"),n.target=n.target.parent;t.overTargets=i.composedPath(),this.freeEvent(i),this.freeEvent(n)}mapPointerOut(e){if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId);if(t.overTargets){const i=e.pointerType==="mouse"||e.pointerType==="pen",r=this.findMountedTarget(t.overTargets),n=this.createPointerEvent(e,"pointerout",r);this.dispatchEvent(n),i&&this.dispatchEvent(n,"mouseout");const o=this.createPointerEvent(e,"pointerleave",r);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),i&&this.notifyTarget(o,"mouseleave"),o.target=o.target.parent;t.overTargets=null,this.freeEvent(n),this.freeEvent(o)}this.cursor=null}mapPointerUp(e){if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=performance.now(),i=this.createPointerEvent(e);if(this.dispatchEvent(i,"pointerup"),i.pointerType==="touch")this.dispatchEvent(i,"touchend");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const a=i.button===2;this.dispatchEvent(i,a?"rightup":"mouseup")}const r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.pressTargetsByButton[e.button]);let o=n;if(n&&!i.composedPath().includes(n)){let a=n;for(;a&&!i.composedPath().includes(a);){if(i.currentTarget=a,this.notifyTarget(i,"pointerupoutside"),i.pointerType==="touch")this.notifyTarget(i,"touchendoutside");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const l=i.button===2;this.notifyTarget(i,l?"rightupoutside":"mouseupoutside")}a=a.parent}delete r.pressTargetsByButton[e.button],o=a}if(o){const a=this.clonePointerEvent(i,"click");a.target=o,a.path=null,r.clicksByButton[e.button]||(r.clicksByButton[e.button]={clickCount:0,target:a.target,timeStamp:t});const l=r.clicksByButton[e.button];if(l.target===a.target&&t-l.timeStamp<200?++l.clickCount:l.clickCount=1,l.target=a.target,l.timeStamp=t,a.detail=l.clickCount,a.pointerType==="mouse"){const c=a.button===2;this.dispatchEvent(a,c?"rightclick":"click")}else a.pointerType==="touch"&&this.dispatchEvent(a,"tap");this.dispatchEvent(a,"pointertap"),this.freeEvent(a)}this.freeEvent(i)}mapPointerUpOutside(e){if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),i=this.findMountedTarget(t.pressTargetsByButton[e.button]),r=this.createPointerEvent(e);if(i){let n=i;for(;n;)r.currentTarget=n,this.notifyTarget(r,"pointerupoutside"),r.pointerType==="touch"?this.notifyTarget(r,"touchendoutside"):(r.pointerType==="mouse"||r.pointerType==="pen")&&this.notifyTarget(r,r.button===2?"rightupoutside":"mouseupoutside"),n=n.parent;delete t.pressTargetsByButton[e.button]}this.freeEvent(r)}mapWheel(e){if(!(e instanceof Pi)){se("EventBoundary cannot map a non-wheel event as a wheel event");return}const t=this.createWheelEvent(e);this.dispatchEvent(t),this.freeEvent(t)}findMountedTarget(e){if(!e)return null;let t=e[0];for(let i=1;i<e.length&&e[i].parent===t;i++)t=e[i];return t}createPointerEvent(e,t,i){const r=this.allocateEvent(dt);return this.copyPointerData(e,r),this.copyMouseData(e,r),this.copyData(e,r),r.nativeEvent=e.nativeEvent,r.originalEvent=e,r.target=i??this.hitTest(r.global.x,r.global.y)??this._hitElements[0],typeof t=="string"&&(r.type=t),r}createWheelEvent(e){const t=this.allocateEvent(Pi);return this.copyWheelData(e,t),this.copyMouseData(e,t),this.copyData(e,t),t.nativeEvent=e.nativeEvent,t.originalEvent=e,t.target=this.hitTest(t.global.x,t.global.y),t}clonePointerEvent(e,t){const i=this.allocateEvent(dt);return i.nativeEvent=e.nativeEvent,i.originalEvent=e.originalEvent,this.copyPointerData(e,i),this.copyMouseData(e,i),this.copyData(e,i),i.target=e.target,i.path=e.composedPath().slice(),i.type=t??i.type,i}copyWheelData(e,t){t.deltaMode=e.deltaMode,t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ}copyPointerData(e,t){e instanceof dt&&t instanceof dt&&(t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist)}copyMouseData(e,t){e instanceof cr&&t instanceof cr&&(t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.copyFrom(e.client),t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.copyFrom(e.movement),t.screen.copyFrom(e.screen),t.shiftKey=e.shiftKey,t.global.copyFrom(e.global))}copyData(e,t){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.detail=e.detail,t.view=e.view,t.which=e.which,t.layer.copyFrom(e.layer),t.page.copyFrom(e.page)}trackingData(e){return this.mappingState.trackingData[e]||(this.mappingState.trackingData[e]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[e]}allocateEvent(e){this.eventPool.has(e)||this.eventPool.set(e,[]);const t=this.eventPool.get(e).pop()||new e(this);return t.eventPhase=t.NONE,t.currentTarget=null,t.defaultPrevented=!1,t.path=null,t.target=null,t}freeEvent(e){if(e.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const t=e.constructor;this.eventPool.has(t)||this.eventPool.set(t,[]),this.eventPool.get(t).push(e)}_notifyListeners(e,t){const i=e.currentTarget._events[t];if(i)if("fn"in i)i.once&&e.currentTarget.removeListener(t,i.fn,void 0,!0),i.fn.call(i.context,e);else for(let r=0,n=i.length;r<n&&!e.propagationImmediatelyStopped;r++)i[r].once&&e.currentTarget.removeListener(t,i[r].fn,void 0,!0),i[r].fn.call(i[r].context,e)}}const ty=1,iy={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},to=class ha{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new ey(null),Bt.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new dt(null),this._rootWheelEvent=new Pi(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...ha.defaultEventFeatures},{set:(t,i,r)=>(i==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=r),t[i]=r,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{canvas:t,resolution:i}=this.renderer;this.setTargetElement(t),this.resolution=i,ha._defaultEventMode=e.eventMode??"passive",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(e){this.resolution=e}destroy(){Bt.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(e){e||(e="default");let t=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(t=!1),this._currentCursor===e)return;this._currentCursor=e;const i=this.cursorStyles[e];if(i)switch(typeof i){case"string":t&&(this.domElement.style.cursor=i);break;case"function":i(e);break;case"object":t&&Object.assign(this.domElement.style,i);break}else t&&typeof e=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,e)&&(this.domElement.style.cursor=e)}get pointer(){return this._rootPointerEvent}_onPointerDown(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);this.autoPreventDefault&&t[0].isNormalized&&(e.cancelable||!("cancelable"in e))&&e.preventDefault();for(let i=0,r=t.length;i<r;i++){const n=t[i],o=this._bootstrapEvent(this._rootPointerEvent,n);this.rootBoundary.mapEvent(o)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(e){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,Bt.pointerMoved();const t=this._normalizeToPointerData(e);for(let i=0,r=t.length;i<r;i++){const n=this._bootstrapEvent(this._rootPointerEvent,t[i]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let t=e.target;e.composedPath&&e.composedPath().length>0&&(t=e.composedPath()[0]);const i=t!==this.domElement?"outside":"",r=this._normalizeToPointerData(e);for(let n=0,o=r.length;n<o;n++){const a=this._bootstrapEvent(this._rootPointerEvent,r[n]);a.type+=i,this.rootBoundary.mapEvent(a)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);for(let i=0,r=t.length;i<r;i++){const n=this._bootstrapEvent(this._rootPointerEvent,t[i]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}onWheel(e){if(!this.features.wheel)return;const t=this.normalizeWheelEvent(e);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(t)}setTargetElement(e){this._removeEvents(),this.domElement=e,Bt.domElement=e,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;Bt.addTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="none",e.msTouchAction="none"):this.supportsPointerEvents&&(e.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this._onPointerMove,!0),this.domElement.addEventListener("pointerdown",this._onPointerDown,!0),this.domElement.addEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this._onPointerOverOut,!0),globalThis.addEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this._onPointerMove,!0),this.domElement.addEventListener("mousedown",this._onPointerDown,!0),this.domElement.addEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this._onPointerOverOut,!0),globalThis.addEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this._onPointerDown,!0),this.domElement.addEventListener("touchend",this._onPointerUp,!0),this.domElement.addEventListener("touchmove",this._onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;Bt.removeTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="",e.msTouchAction=""):this.supportsPointerEvents&&(e.touchAction="")),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this._onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this._onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this._onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this._onPointerMove,!0),this.domElement.removeEventListener("mousedown",this._onPointerDown,!0),this.domElement.removeEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this._onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this._onPointerDown,!0),this.domElement.removeEventListener("touchend",this._onPointerUp,!0),this.domElement.removeEventListener("touchmove",this._onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(e,t,i){const r=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},n=1/this.resolution;e.x=(t-r.left)*(this.domElement.width/r.width)*n,e.y=(i-r.top)*(this.domElement.height/r.height)*n}_normalizeToPointerData(e){const t=[];if(this.supportsTouchEvents&&e instanceof TouchEvent)for(let i=0,r=e.changedTouches.length;i<r;i++){const n=e.changedTouches[i];typeof n.button>"u"&&(n.button=0),typeof n.buttons>"u"&&(n.buttons=1),typeof n.isPrimary>"u"&&(n.isPrimary=e.touches.length===1&&e.type==="touchstart"),typeof n.width>"u"&&(n.width=n.radiusX||1),typeof n.height>"u"&&(n.height=n.radiusY||1),typeof n.tiltX>"u"&&(n.tiltX=0),typeof n.tiltY>"u"&&(n.tiltY=0),typeof n.pointerType>"u"&&(n.pointerType="touch"),typeof n.pointerId>"u"&&(n.pointerId=n.identifier||0),typeof n.pressure>"u"&&(n.pressure=n.force||.5),typeof n.twist>"u"&&(n.twist=0),typeof n.tangentialPressure>"u"&&(n.tangentialPressure=0),typeof n.layerX>"u"&&(n.layerX=n.offsetX=n.clientX),typeof n.layerY>"u"&&(n.layerY=n.offsetY=n.clientY),n.isNormalized=!0,n.type=e.type,n.altKey??(n.altKey=e.altKey),n.ctrlKey??(n.ctrlKey=e.ctrlKey),n.metaKey??(n.metaKey=e.metaKey),n.shiftKey??(n.shiftKey=e.shiftKey),t.push(n)}else if(!globalThis.MouseEvent||e instanceof MouseEvent&&(!this.supportsPointerEvents||!(e instanceof globalThis.PointerEvent))){const i=e;typeof i.isPrimary>"u"&&(i.isPrimary=!0),typeof i.width>"u"&&(i.width=1),typeof i.height>"u"&&(i.height=1),typeof i.tiltX>"u"&&(i.tiltX=0),typeof i.tiltY>"u"&&(i.tiltY=0),typeof i.pointerType>"u"&&(i.pointerType="mouse"),typeof i.pointerId>"u"&&(i.pointerId=ty),typeof i.pressure>"u"&&(i.pressure=.5),typeof i.twist>"u"&&(i.twist=0),typeof i.tangentialPressure>"u"&&(i.tangentialPressure=0),i.isNormalized=!0,t.push(i)}else t.push(e);return t}normalizeWheelEvent(e){const t=this._rootWheelEvent;return this._transferMouseData(t,e),t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ,t.deltaMode=e.deltaMode,this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.nativeEvent=e,t.type=e.type,t}_bootstrapEvent(e,t){return e.originalEvent=null,e.nativeEvent=t,e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist,this._transferMouseData(e,t),this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.isTrusted=t.isTrusted,e.type==="pointerleave"&&(e.type="pointerout"),e.type.startsWith("mouse")&&(e.type=e.type.replace("mouse","pointer")),e.type.startsWith("touch")&&(e.type=iy[e.type]||e.type),e}_transferMouseData(e,t){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.x=t.clientX,e.client.y=t.clientY,e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.x=t.movementX,e.movement.y=t.movementY,e.page.x=t.pageX,e.page.y=t.pageY,e.relatedTarget=null,e.shiftKey=t.shiftKey}};to.extension={name:"events",type:[A.WebGLSystem,A.CanvasSystem,A.WebGPUSystem],priority:-1},to.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let rh=to;const sy={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(s){this.eventMode=s?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??rh.defaultEventMode},set eventMode(s){this._internalEventMode=s},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(s,e,t){const i=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof t=="object"?t.signal:void 0,n=typeof t=="object"?t.once===!0:!1,o=typeof e=="function"?void 0:e;s=i?`${s}capture`:s;const a=typeof e=="function"?e:e.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(s,a,o)}),n?l.once(s,a,o):l.on(s,a,o)},removeEventListener(s,e,t){const i=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof e=="function"?void 0:e;s=i?`${s}capture`:s,e=typeof e=="function"?e:e.handleEvent,this.off(s,e,r)},dispatchEvent(s){if(!(s instanceof ns))throw new Error("Container cannot propagate events outside of the Federated Events API");return s.defaultPrevented=!1,s.path=null,s.target=this,s.manager.dispatchEvent(s),!s.defaultPrevented}};var ry=`in vec2 aPosition;
545
+ `}},Tc={};function Ac(s){let e=Tc[s];if(e)return e;const t=new Int32Array(s);for(let i=0;i<s;i++)t[i]=i;return e=Tc[s]=new ht({uTextures:{value:t,type:"i32",size:s}},{isStatic:!0}),e}class wc extends Mt{constructor(e){const t=Ln({name:"batch",bits:[Cc,Ec(e),zn]}),i=Gn({name:"batch",bits:[vc,Sc(e),Vn]});super({glProgram:t,gpuProgram:i,resources:{batchSamplers:Ac(e)}}),this.maxTextures=e}}let us=null;const Ic=class bf extends Bg{constructor(e){super(e),this.geometry=new Ug,this.name=bf.extension.name,this.vertexSize=6,us??(us=new wc(e.maxTextures)),this.shader=us}packAttributes(e,t,i,r,n){const o=n<<16|e.roundPixels&65535,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,f=a.tx,d=a.ty,{positions:g,uvs:_}=e,y=e.color,x=e.attributeOffset,C=x+e.attributeSize;for(let S=x;S<C;S++){const E=S*2,w=g[E],R=g[E+1];t[r++]=l*w+h*R+f,t[r++]=u*R+c*w+d,t[r++]=_[E],t[r++]=_[E+1],i[r++]=y,i[r++]=o}}packQuadAttributes(e,t,i,r,n){const o=e.texture,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,f=a.tx,d=a.ty,g=e.bounds,_=g.maxX,y=g.minX,x=g.maxY,C=g.minY,S=o.uvs,E=e.color,w=n<<16|e.roundPixels&65535;t[r+0]=l*y+h*C+f,t[r+1]=u*C+c*y+d,t[r+2]=S.x0,t[r+3]=S.y0,i[r+4]=E,i[r+5]=w,t[r+6]=l*_+h*C+f,t[r+7]=u*C+c*_+d,t[r+8]=S.x1,t[r+9]=S.y1,i[r+10]=E,i[r+11]=w,t[r+12]=l*_+h*x+f,t[r+13]=u*x+c*_+d,t[r+14]=S.x2,t[r+15]=S.y2,i[r+16]=E,i[r+17]=w,t[r+18]=l*y+h*x+f,t[r+19]=u*x+c*y+d,t[r+20]=S.x3,t[r+21]=S.y3,i[r+22]=E,i[r+23]=w}_updateMaxTextures(e){this.shader.maxTextures!==e&&(us=new wc(e),this.shader=us)}destroy(){this.shader=null,super.destroy()}};Ic.extension={type:[A.Batcher],name:"default"};let $n=Ic;class kt{constructor(e){this.items=Object.create(null);const{renderer:t,type:i,onUnload:r,priority:n,name:o}=e;this._renderer=t,t.gc.addResourceHash(this,"items",i,n??0),this._onUnload=r,this.name=o}add(e){return this.items[e.uid]?!1:(this.items[e.uid]=e,e.once("unload",this.remove,this),e._gcLastUsed=this._renderer.gc.now,!0)}remove(e,...t){var r;if(!this.items[e.uid])return;const i=e._gpuData[this._renderer.uid];i&&((r=this._onUnload)==null||r.call(this,e,...t),i.destroy(),e._gpuData[this._renderer.uid]=null,this.items[e.uid]=null)}removeAll(...e){Object.values(this.items).forEach(t=>t&&this.remove(t,...e))}destroy(...e){this.removeAll(...e),this.items=Object.create(null),this._renderer=null,this._onUnload=null}}function t_(s,e,t,i,r,n,o,a=null){let l=0;t*=e,r*=n;const c=a.a,h=a.b,u=a.c,f=a.d,d=a.tx,g=a.ty;for(;l<o;){const _=s[t],y=s[t+1];i[r]=c*_+u*y+d,i[r+1]=h*_+f*y+g,r+=n,t+=e,l++}}function i_(s,e,t,i){let r=0;for(e*=t;r<i;)s[e]=0,s[e+1]=0,e+=t,r++}function Rc(s,e,t,i,r){const n=e.a,o=e.b,a=e.c,l=e.d,c=e.tx,h=e.ty;t||(t=0),i||(i=2),r||(r=s.length/i-t);let u=t*i;for(let f=0;f<r;f++){const d=s[u],g=s[u+1];s[u]=n*d+a*g+c,s[u+1]=o*d+l*g+h,u+=i}}const s_=new H;class jn{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const e=this.baseColor,t=e>>16|e&65280|(e&255)<<16,i=this.renderable;return i?yi(t,i.groupColor)+(this.alpha*i.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){var e;return((e=this.renderable)==null?void 0:e.groupTransform)||s_}copyTo(e){e.indexOffset=this.indexOffset,e.indexSize=this.indexSize,e.attributeOffset=this.attributeOffset,e.attributeSize=this.attributeSize,e.baseColor=this.baseColor,e.alpha=this.alpha,e.texture=this.texture,e.geometryData=this.geometryData,e.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const ds={extension:{type:A.ShapeBuilder,name:"circle"},build(s,e){let t,i,r,n,o,a;if(s.type==="circle"){const E=s;if(o=a=E.radius,o<=0)return!1;t=E.x,i=E.y,r=n=0}else if(s.type==="ellipse"){const E=s;if(o=E.halfWidth,a=E.halfHeight,o<=0||a<=0)return!1;t=E.x,i=E.y,r=n=0}else{const E=s,w=E.width/2,R=E.height/2;t=E.x+w,i=E.y+R,o=a=Math.max(0,Math.min(E.radius,Math.min(w,R))),r=w-o,n=R-a}if(r<0||n<0)return!1;const l=Math.ceil(2.3*Math.sqrt(o+a)),c=l*8+(r?4:0)+(n?4:0);if(c===0)return!1;if(l===0)return e[0]=e[6]=t+r,e[1]=e[3]=i+n,e[2]=e[4]=t-r,e[5]=e[7]=i-n,!0;let h=0,u=l*4+(r?2:0)+2,f=u,d=c,g=r+o,_=n,y=t+g,x=t-g,C=i+_;if(e[h++]=y,e[h++]=C,e[--u]=C,e[--u]=x,n){const E=i-_;e[f++]=x,e[f++]=E,e[--d]=E,e[--d]=y}for(let E=1;E<l;E++){const w=Math.PI/2*(E/l),R=r+Math.cos(w)*o,M=n+Math.sin(w)*a,D=t+R,F=t-R,k=i+M,O=i-M;e[h++]=D,e[h++]=k,e[--u]=k,e[--u]=F,e[f++]=F,e[f++]=O,e[--d]=O,e[--d]=D}g=r,_=n+a,y=t+g,x=t-g,C=i+_;const S=i-_;return e[h++]=y,e[h++]=C,e[--d]=S,e[--d]=y,r&&(e[h++]=x,e[h++]=C,e[--d]=S,e[--d]=x),!0},triangulate(s,e,t,i,r,n){if(s.length===0)return;let o=0,a=0;for(let h=0;h<s.length;h+=2)o+=s[h],a+=s[h+1];o/=s.length/2,a/=s.length/2;let l=i;e[l*t]=o,e[l*t+1]=a;const c=l++;for(let h=0;h<s.length;h+=2)e[l*t]=s[h],e[l*t+1]=s[h+1],h>0&&(r[n++]=l,r[n++]=c,r[n++]=l-1),l++;r[n++]=c+1,r[n++]=c,r[n++]=l-1}},r_={...ds,extension:{...ds.extension,name:"ellipse"}},n_={...ds,extension:{...ds.extension,name:"roundedRectangle"}},Mc=1e-4,Pc=1e-4;function o_(s){const e=s.length;if(e<6)return 1;let t=0;for(let i=0,r=s[e-2],n=s[e-1];i<e;i+=2){const o=s[i],a=s[i+1];t+=(o-r)*(a+n),r=o,n=a}return t<0?-1:1}function kc(s,e,t,i,r,n,o,a){const l=s-t*r,c=e-i*r,h=s+t*n,u=e+i*n;let f,d;o?(f=i,d=-t):(f=-i,d=t);const g=l+f,_=c+d,y=h+f,x=u+d;return a.push(g,_),a.push(y,x),2}function ai(s,e,t,i,r,n,o,a){const l=t-s,c=i-e;let h=Math.atan2(l,c),u=Math.atan2(r-s,n-e);a&&h<u?h+=Math.PI*2:!a&&h>u&&(u+=Math.PI*2);let f=h;const d=u-h,g=Math.abs(d),_=Math.sqrt(l*l+c*c),y=(15*g*Math.sqrt(_)/Math.PI>>0)+1,x=d/y;if(f+=x,a){o.push(s,e),o.push(t,i);for(let C=1,S=f;C<y;C++,S+=x)o.push(s,e),o.push(s+Math.sin(S)*_,e+Math.cos(S)*_);o.push(s,e),o.push(r,n)}else{o.push(t,i),o.push(s,e);for(let C=1,S=f;C<y;C++,S+=x)o.push(s+Math.sin(S)*_,e+Math.cos(S)*_),o.push(s,e);o.push(r,n),o.push(s,e)}return y*2}function Oc(s,e,t,i,r,n){const o=Mc;if(s.length===0)return;const a=e;let l=a.alignment;if(e.alignment!==.5){let N=o_(s);l=(l-.5)*N+.5}const c=new xe(s[0],s[1]),h=new xe(s[s.length-2],s[s.length-1]),u=i,f=Math.abs(c.x-h.x)<o&&Math.abs(c.y-h.y)<o;if(u){s=s.slice(),f&&(s.pop(),s.pop(),h.set(s[s.length-2],s[s.length-1]));const N=(c.x+h.x)*.5,K=(h.y+c.y)*.5;s.unshift(N,K),s.push(N,K)}const d=r,g=s.length/2;let _=s.length;const y=d.length/2,x=a.width/2,C=x*x,S=a.miterLimit*a.miterLimit;let E=s[0],w=s[1],R=s[2],M=s[3],D=0,F=0,k=-(w-M),O=E-R,V=0,X=0,z=Math.sqrt(k*k+O*O);k/=z,O/=z,k*=x,O*=x;const de=l,B=(1-de)*2,U=de*2;u||(a.cap==="round"?_+=ai(E-k*(B-U)*.5,w-O*(B-U)*.5,E-k*B,w-O*B,E+k*U,w+O*U,d,!0)+2:a.cap==="square"&&(_+=kc(E,w,k,O,B,U,!0,d))),d.push(E-k*B,w-O*B),d.push(E+k*U,w+O*U);for(let N=1;N<g-1;++N){E=s[(N-1)*2],w=s[(N-1)*2+1],R=s[N*2],M=s[N*2+1],D=s[(N+1)*2],F=s[(N+1)*2+1],k=-(w-M),O=E-R,z=Math.sqrt(k*k+O*O),k/=z,O/=z,k*=x,O*=x,V=-(M-F),X=R-D,z=Math.sqrt(V*V+X*X),V/=z,X/=z,V*=x,X*=x;const K=R-E,Z=w-M,$=R-D,ae=F-M,Ce=K*$+Z*ae,Ee=Z*$-ae*K,G=Ee<0;if(Math.abs(Ee)<.001*Math.abs(Ce)){d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),Ce>=0&&(a.join==="round"?_+=ai(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+4:_+=2,d.push(R-V*U,M-X*U),d.push(R+V*B,M+X*B));continue}const fe=(-k+E)*(-O+M)-(-k+R)*(-O+w),le=(-V+D)*(-X+M)-(-V+R)*(-X+F),L=(K*le-$*fe)/Ee,me=(ae*fe-Z*le)/Ee,Y=(L-R)*(L-R)+(me-M)*(me-M),ie=R+(L-R)*B,we=M+(me-M)*B,ce=R-(L-R)*U,He=M-(me-M)*U,Qt=Math.min(K*K+Z*Z,$*$+ae*ae),Et=G?B:U,ui=Qt+Et*Et*C;Y<=ui?a.join==="bevel"||Y/C>S?(G?(d.push(ie,we),d.push(R+k*U,M+O*U),d.push(ie,we),d.push(R+V*U,M+X*U)):(d.push(R-k*B,M-O*B),d.push(ce,He),d.push(R-V*B,M-X*B),d.push(ce,He)),_+=2):a.join==="round"?G?(d.push(ie,we),d.push(R+k*U,M+O*U),_+=ai(R,M,R+k*U,M+O*U,R+V*U,M+X*U,d,!0)+4,d.push(ie,we),d.push(R+V*U,M+X*U)):(d.push(R-k*B,M-O*B),d.push(ce,He),_+=ai(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+4,d.push(R-V*B,M-X*B),d.push(ce,He)):(d.push(ie,we),d.push(ce,He)):(d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),a.join==="round"?G?_+=ai(R,M,R+k*U,M+O*U,R+V*U,M+X*U,d,!0)+2:_+=ai(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+2:a.join==="miter"&&Y/C<=S&&(G?(d.push(ce,He),d.push(ce,He)):(d.push(ie,we),d.push(ie,we)),_+=2),d.push(R-V*B,M-X*B),d.push(R+V*U,M+X*U),_+=2)}E=s[(g-2)*2],w=s[(g-2)*2+1],R=s[(g-1)*2],M=s[(g-1)*2+1],k=-(w-M),O=E-R,z=Math.sqrt(k*k+O*O),k/=z,O/=z,k*=x,O*=x,d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),u||(a.cap==="round"?_+=ai(R-k*(B-U)*.5,M-O*(B-U)*.5,R-k*B,M-O*B,R+k*U,M+O*U,d,!1)+2:a.cap==="square"&&(_+=kc(R,M,k,O,B,U,!1,d)));const q=Pc*Pc;for(let N=y;N<_+y-2;++N)E=d[N*2],w=d[N*2+1],R=d[(N+1)*2],M=d[(N+1)*2+1],D=d[(N+2)*2],F=d[(N+2)*2+1],!(Math.abs(E*(M-F)+R*(F-w)+D*(w-M))<q)&&n.push(N,N+1,N+2)}function a_(s,e,t,i){const r=Mc;if(s.length===0)return;const n=s[0],o=s[1],a=s[s.length-2],l=s[s.length-1],c=e||Math.abs(n-a)<r&&Math.abs(o-l)<r,h=t,u=s.length/2,f=h.length/2;for(let d=0;d<u;d++)h.push(s[d*2]),h.push(s[d*2+1]);for(let d=0;d<u-1;d++)i.push(f+d,f+d+1);c&&i.push(f+u-1,f)}function Bc(s,e,t,i,r,n,o){const a=cm(s,e,2);if(!a)return;for(let c=0;c<a.length;c+=3)n[o++]=a[c]+r,n[o++]=a[c+1]+r,n[o++]=a[c+2]+r;let l=r*i;for(let c=0;c<s.length;c+=2)t[l]=s[c],t[l+1]=s[c+1],l+=i}const l_=[],c_={extension:{type:A.ShapeBuilder,name:"polygon"},build(s,e){for(let t=0;t<s.points.length;t++)e[t]=s.points[t];return!0},triangulate(s,e,t,i,r,n){Bc(s,l_,e,t,i,r,n)}},h_={extension:{type:A.ShapeBuilder,name:"rectangle"},build(s,e){const t=s,i=t.x,r=t.y,n=t.width,o=t.height;return n>0&&o>0?(e[0]=i,e[1]=r,e[2]=i+n,e[3]=r,e[4]=i+n,e[5]=r+o,e[6]=i,e[7]=r+o,!0):!1},triangulate(s,e,t,i,r,n){let o=0;i*=t,e[i+o]=s[0],e[i+o+1]=s[1],o+=t,e[i+o]=s[2],e[i+o+1]=s[3],o+=t,e[i+o]=s[6],e[i+o+1]=s[7],o+=t,e[i+o]=s[4],e[i+o+1]=s[5],o+=t;const a=i/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2,r[n++]=a+1,r[n++]=a+3,r[n++]=a+2}},u_={extension:{type:A.ShapeBuilder,name:"triangle"},build(s,e){return e[0]=s.x,e[1]=s.y,e[2]=s.x2,e[3]=s.y2,e[4]=s.x3,e[5]=s.y3,!0},triangulate(s,e,t,i,r,n){let o=0;i*=t,e[i+o]=s[0],e[i+o+1]=s[1],o+=t,e[i+o]=s[2],e[i+o+1]=s[3],o+=t,e[i+o]=s[4],e[i+o+1]=s[5];const a=i/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2}},Dc=[{offset:0,color:"white"},{offset:1,color:"black"}],Xn=class la{constructor(...e){this.uid=be("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let t=d_(e);t={...t.type==="radial"?la.defaultRadialOptions:la.defaultLinearOptions,...Ca(t)},this._textureSize=t.textureSize,this._wrapMode=t.wrapMode,t.type==="radial"?(this.center=t.center,this.outerCenter=t.outerCenter??this.center,this.innerRadius=t.innerRadius,this.outerRadius=t.outerRadius,this.scale=t.scale,this.rotation=t.rotation):(this.start=t.start,this.end=t.end),this.textureSpace=t.textureSpace,this.type=t.type,t.colorStops.forEach(r=>{this.addColorStop(r.offset,r.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:Pe.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:i,y:r}=this.end,n=i-e,o=r-t;const a=n<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(n<0){const y=e;e=i,i=y,n*=-1}if(o<0){const y=t;t=r,r=y,o*=-1}}const l=this.colorStops.length?this.colorStops:Dc,c=this._textureSize,{canvas:h,context:u}=Uc(c,1),f=a?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);Nc(f,l),u.fillStyle=f,u.fillRect(0,0,c,1),this.texture=new j({source:new er({resource:h,addressMode:this._wrapMode})});const d=Math.sqrt(n*n+o*o),g=Math.atan2(o,n),_=new H;_.scale(d/c,1),_.rotate(g),_.translate(e,t),this.textureSpace==="local"&&_.scale(c,c),this.transform=_}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const e=this.colorStops.length?this.colorStops:Dc,t=this._textureSize,{canvas:i,context:r}=Uc(t,t),{x:n,y:o}=this.center,{x:a,y:l}=this.outerCenter,c=this.innerRadius,h=this.outerRadius,u=a-h,f=l-h,d=t/(h*2),g=(n-u)*d,_=(o-f)*d,y=r.createRadialGradient(g,_,c*d,(a-u)*d,(l-f)*d,h*d);Nc(y,e),r.fillStyle=e[e.length-1].color,r.fillRect(0,0,t,t),r.fillStyle=y,r.translate(g,_),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-g,-_),r.fillRect(0,0,t,t),this.texture=new j({source:new er({resource:i,addressMode:this._wrapMode})});const x=new H;x.scale(1/d,1/d),x.translate(u,f),this.textureSpace==="local"&&x.scale(t,t),this.transform=x}destroy(){var e;(e=this.texture)==null||e.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};Xn.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"},Xn.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let Mi=Xn;function Nc(s,e){for(let t=0;t<e.length;t++){const i=e[t];s.addColorStop(i.offset,i.color)}}function Uc(s,e){const t=pe.get().createCanvas(s,e),i=t.getContext("2d");return{canvas:t,context:i}}function d_(s){let e=s[0]??{};return(typeof e=="number"||s[1])&&(ee("8.5.2","use options object instead"),e={type:"linear",start:{x:s[0],y:s[1]},end:{x:s[2],y:s[3]},textureSpace:s[4],textureSize:s[5]??Mi.defaultLinearOptions.textureSize}),e}const f_=new H,p_=new Se;function Fc(s,e,t,i){const r=e.matrix?s.copyFrom(e.matrix).invert():s.identity();if(e.textureSpace==="local"){const o=t.getBounds(p_);e.width&&o.pad(e.width);const{x:a,y:l}=o,c=1/o.width,h=1/o.height,u=-a*c,f=-l*h,d=r.a,g=r.b,_=r.c,y=r.d;r.a*=c,r.b*=c,r.c*=h,r.d*=h,r.tx=u*d+f*_+r.tx,r.ty=u*g+f*y+r.ty}else r.translate(e.texture.frame.x,e.texture.frame.y),r.scale(1/e.texture.source.width,1/e.texture.source.height);const n=e.texture.source.style;return!(e.fill instanceof Mi)&&n.addressMode==="clamp-to-edge"&&(n.addressMode="repeat",n.update()),i&&r.append(f_.copyFrom(i).invert()),r}const fs={};Q.handleByMap(A.ShapeBuilder,fs),Q.add(h_,c_,u_,ds,r_,n_);const m_=new Se,g_=new H;function __(s,e){const{geometryData:t,batches:i}=e;i.length=0,t.indices.length=0,t.vertices.length=0,t.uvs.length=0;for(let r=0;r<s.instructions.length;r++){const n=s.instructions[r];if(n.action==="texture")y_(n.data,i,t);else if(n.action==="fill"||n.action==="stroke"){const o=n.action==="stroke",a=n.data.path.shapePath,l=n.data.style,c=n.data.hole;o&&c&&Gc(c.shapePath,l,!0,i,t),c&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=c.shapePath.shapePrimitives),Gc(a,l,o,i,t)}}}function y_(s,e,t){const i=[],r=fs.rectangle,n=m_;n.x=s.dx,n.y=s.dy,n.width=s.dw,n.height=s.dh;const o=s.transform;if(!r.build(n,i))return;const{vertices:a,uvs:l,indices:c}=t,h=c.length,u=a.length/2;o&&Rc(i,o),r.triangulate(i,a,2,u,c,h);const f=s.image,d=f.uvs;l.push(d.x0,d.y0,d.x1,d.y1,d.x3,d.y3,d.x2,d.y2);const g=Le.get(jn);g.indexOffset=h,g.indexSize=c.length-h,g.attributeOffset=u,g.attributeSize=a.length/2-u,g.baseColor=s.style,g.alpha=s.alpha,g.texture=f,g.geometryData=t,e.push(g)}function Gc(s,e,t,i,r){const{vertices:n,uvs:o,indices:a}=r;s.shapePrimitives.forEach(({shape:l,transform:c,holes:h})=>{const u=[],f=fs[l.type];if(!f.build(l,u))return;const d=a.length,g=n.length/2;let _="triangle-list";if(c&&Rc(u,c),t){const S=l.closePath??!0,E=e;E.pixelLine?(a_(u,S,n,a),_="line-list"):Oc(u,E,!1,S,n,a)}else if(h){const S=[],E=u.slice();b_(h).forEach(R=>{S.push(E.length/2),E.push(...R)}),Bc(E,S,n,2,g,a,d)}else f.triangulate(u,n,2,g,a,d);const y=o.length/2,x=e.texture;if(x!==j.WHITE){const S=Fc(g_,e,l,c);t_(n,2,g,o,y,2,n.length/2-g,S)}else i_(o,y,2,n.length/2-g);const C=Le.get(jn);C.indexOffset=d,C.indexSize=a.length-d,C.attributeOffset=g,C.attributeSize=n.length/2-g,C.baseColor=e.color,C.alpha=e.alpha,C.texture=x,C.geometryData=r,C.topology=_,i.push(C)})}function b_(s){const e=[];for(let t=0;t<s.length;t++){const i=s[t].shape,r=[];fs[i.type].build(i,r)&&e.push(r)}return e}class x_{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{Le.return(e)}),this.graphicsData&&Le.return(this.graphicsData),this.isBatchable=!1,this.context=null,this.batches.length=0,this.geometryData.indices.length=0,this.geometryData.vertices.length=0,this.geometryData.uvs.length=0,this.graphicsData=null}destroy(){this.reset(),this.batches=null,this.geometryData=null}}class v_{constructor(){this.instructions=new ln}init(e){const t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new $n({maxTextures:t}),this.instructions.reset()}get geometry(){return ee(Xf,"GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead."),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}}const Yn=class ca{constructor(e){this._renderer=e,this._managedContexts=new kt({renderer:e,type:"resource",name:"graphicsContext"})}init(e){ca.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??ca.defaultOptions.bezierSmoothness}getContextRenderData(e){return e._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=!!e._gpuData[this._renderer.uid],i=e._gpuData[this._renderer.uid]||this._initContext(e);if(e.dirty||!t){t&&i.reset(),__(e,i);const r=e.batchMode;e.customShader||r==="no-batch"?i.isBatchable=!1:r==="auto"?i.isBatchable=i.geometryData.vertices.length<400:i.isBatchable=!0,e.dirty=!1}return i}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=Le.get(v_,{maxTextures:this._renderer.limits.maxBatchableTextures}),i=e._gpuData[this._renderer.uid],{batches:r,geometryData:n}=i;i.graphicsData=t;const o=n.vertices.length,a=n.indices.length;for(let u=0;u<r.length;u++)r[u].applyTransform=!1;const l=t.batcher;l.ensureAttributeBuffer(o),l.ensureIndexBuffer(a),l.begin();for(let u=0;u<r.length;u++){const f=r[u];l.add(f)}l.finish(t.instructions);const c=l.geometry;c.indexBuffer.setDataWithSize(l.indexBuffer,l.indexSize,!0),c.buffers[0].setDataWithSize(l.attributeBuffer.float32View,l.attributeSize,!0);const h=l.batches;for(let u=0;u<h.length;u++){const f=h[u];f.bindGroup=Nn(f.textures.textures,f.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){const t=new x_;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Yn.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"graphicsContext"},Yn.defaultOptions={bezierSmoothness:.5};let qn=Yn;const C_=8,cr=11920929e-14,S_=1;function Lc(s,e,t,i,r,n,o,a,l,c){const u=Math.min(.99,Math.max(0,c??qn.defaultOptions.bezierSmoothness));let f=(S_-u)/1;return f*=f,E_(e,t,i,r,n,o,a,l,s,f),s}function E_(s,e,t,i,r,n,o,a,l,c){Kn(s,e,t,i,r,n,o,a,l,c,0),l.push(o,a)}function Kn(s,e,t,i,r,n,o,a,l,c,h){if(h>C_)return;const u=(s+t)/2,f=(e+i)/2,d=(t+r)/2,g=(i+n)/2,_=(r+o)/2,y=(n+a)/2,x=(u+d)/2,C=(f+g)/2,S=(d+_)/2,E=(g+y)/2,w=(x+S)/2,R=(C+E)/2;if(h>0){let M=o-s,D=a-e;const F=Math.abs((t-o)*D-(i-a)*M),k=Math.abs((r-o)*D-(n-a)*M);if(F>cr&&k>cr){if((F+k)*(F+k)<=c*(M*M+D*D)){l.push(w,R);return}}else if(F>cr){if(F*F<=c*(M*M+D*D)){l.push(w,R);return}}else if(k>cr){if(k*k<=c*(M*M+D*D)){l.push(w,R);return}}else if(M=w-(s+o)/2,D=R-(e+a)/2,M*M+D*D<=c){l.push(w,R);return}}Kn(s,e,u,f,x,C,w,R,l,c,h+1),Kn(w,R,S,E,_,y,o,a,l,c,h+1)}const T_=8,A_=11920929e-14,w_=1;function I_(s,e,t,i,r,n,o,a){const c=Math.min(.99,Math.max(0,a??qn.defaultOptions.bezierSmoothness));let h=(w_-c)/1;return h*=h,R_(e,t,i,r,n,o,s,h),s}function R_(s,e,t,i,r,n,o,a){Zn(o,s,e,t,i,r,n,a,0),o.push(r,n)}function Zn(s,e,t,i,r,n,o,a,l){if(l>T_)return;const c=(e+i)/2,h=(t+r)/2,u=(i+n)/2,f=(r+o)/2,d=(c+u)/2,g=(h+f)/2;let _=n-e,y=o-t;const x=Math.abs((i-n)*y-(r-o)*_);if(x>A_){if(x*x<=a*(_*_+y*y)){s.push(d,g);return}}else if(_=d-(e+n)/2,y=g-(t+o)/2,_*_+y*y<=a){s.push(d,g);return}Zn(s,e,t,c,h,d,g,a,l+1),Zn(s,d,g,u,f,n,o,a,l+1)}function Wc(s,e,t,i,r,n,o,a){let l=Math.abs(r-n);(!o&&r>n||o&&n>r)&&(l=2*Math.PI-l),a||(a=Math.max(6,Math.floor(6*Math.pow(i,1/3)*(l/Math.PI)))),a=Math.max(a,3);let c=l/a,h=r;c*=o?-1:1;for(let u=0;u<a+1;u++){const f=Math.cos(h),d=Math.sin(h),g=e+f*i,_=t+d*i;s.push(g,_),h+=c}}function M_(s,e,t,i,r,n){const o=s[s.length-2],l=s[s.length-1]-t,c=o-e,h=r-t,u=i-e,f=Math.abs(l*u-c*h);if(f<1e-8||n===0){(s[s.length-2]!==e||s[s.length-1]!==t)&&s.push(e,t);return}const d=l*l+c*c,g=h*h+u*u,_=l*h+c*u,y=n*Math.sqrt(d)/f,x=n*Math.sqrt(g)/f,C=y*_/d,S=x*_/g,E=y*u+x*c,w=y*h+x*l,R=c*(x+C),M=l*(x+C),D=u*(y+S),F=h*(y+S),k=Math.atan2(M-w,R-E),O=Math.atan2(F-w,D-E);Wc(s,E+e,w+t,n,k,O,c*h>u*l)}const ps=Math.PI*2,Jn={centerX:0,centerY:0,ang1:0,ang2:0},Qn=({x:s,y:e},t,i,r,n,o,a,l)=>{s*=t,e*=i;const c=r*s-n*e,h=n*s+r*e;return l.x=c+o,l.y=h+a,l};function P_(s,e){const t=e===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(e/4),i=e===1.5707963267948966?.551915024494:t,r=Math.cos(s),n=Math.sin(s),o=Math.cos(s+e),a=Math.sin(s+e);return[{x:r-n*i,y:n+r*i},{x:o+a*i,y:a-o*i},{x:o,y:a}]}const Hc=(s,e,t,i)=>{const r=s*i-e*t<0?-1:1;let n=s*t+e*i;return n>1&&(n=1),n<-1&&(n=-1),r*Math.acos(n)},k_=(s,e,t,i,r,n,o,a,l,c,h,u,f)=>{const d=Math.pow(r,2),g=Math.pow(n,2),_=Math.pow(h,2),y=Math.pow(u,2);let x=d*g-d*y-g*_;x<0&&(x=0),x/=d*y+g*_,x=Math.sqrt(x)*(o===a?-1:1);const C=x*r/n*u,S=x*-n/r*h,E=c*C-l*S+(s+t)/2,w=l*C+c*S+(e+i)/2,R=(h-C)/r,M=(u-S)/n,D=(-h-C)/r,F=(-u-S)/n,k=Hc(1,0,R,M);let O=Hc(R,M,D,F);a===0&&O>0&&(O-=ps),a===1&&O<0&&(O+=ps),f.centerX=E,f.centerY=w,f.ang1=k,f.ang2=O};function O_(s,e,t,i,r,n,o,a=0,l=0,c=0){if(n===0||o===0)return;const h=Math.sin(a*ps/360),u=Math.cos(a*ps/360),f=u*(e-i)/2+h*(t-r)/2,d=-h*(e-i)/2+u*(t-r)/2;if(f===0&&d===0)return;n=Math.abs(n),o=Math.abs(o);const g=Math.pow(f,2)/Math.pow(n,2)+Math.pow(d,2)/Math.pow(o,2);g>1&&(n*=Math.sqrt(g),o*=Math.sqrt(g)),k_(e,t,i,r,n,o,l,c,h,u,f,d,Jn);let{ang1:_,ang2:y}=Jn;const{centerX:x,centerY:C}=Jn;let S=Math.abs(y)/(ps/4);Math.abs(1-S)<1e-7&&(S=1);const E=Math.max(Math.ceil(S),1);y/=E;let w=s[s.length-2],R=s[s.length-1];const M={x:0,y:0};for(let D=0;D<E;D++){const F=P_(_,y),{x:k,y:O}=Qn(F[0],n,o,u,h,x,C,M),{x:V,y:X}=Qn(F[1],n,o,u,h,x,C,M),{x:z,y:de}=Qn(F[2],n,o,u,h,x,C,M);Lc(s,w,R,k,O,V,X,z,de),w=z,R=de,_+=y}}function B_(s,e,t){const i=(o,a)=>{const l=a.x-o.x,c=a.y-o.y,h=Math.sqrt(l*l+c*c),u=l/h,f=c/h;return{len:h,nx:u,ny:f}},r=(o,a)=>{o===0?s.moveTo(a.x,a.y):s.lineTo(a.x,a.y)};let n=e[e.length-1];for(let o=0;o<e.length;o++){const a=e[o%e.length],l=a.radius??t;if(l<=0){r(o,a),n=a;continue}const c=e[(o+1)%e.length],h=i(a,n),u=i(a,c);if(h.len<1e-4||u.len<1e-4){r(o,a),n=a;continue}let f=Math.asin(h.nx*u.ny-h.ny*u.nx),d=1,g=!1;h.nx*u.nx-h.ny*-u.ny<0?f<0?f=Math.PI+f:(f=Math.PI-f,d=-1,g=!0):f>0&&(d=-1,g=!0);const _=f/2;let y,x=Math.abs(Math.cos(_)*l/Math.sin(_));x>Math.min(h.len/2,u.len/2)?(x=Math.min(h.len/2,u.len/2),y=Math.abs(x*Math.sin(_)/Math.cos(_))):y=l;const C=a.x+u.nx*x+-u.ny*y*d,S=a.y+u.ny*x+u.nx*y*d,E=Math.atan2(h.ny,h.nx)+Math.PI/2*d,w=Math.atan2(u.ny,u.nx)-Math.PI/2*d;o===0&&s.moveTo(C+Math.cos(E)*y,S+Math.sin(E)*y),s.arc(C,S,y,E,w,g),n=a}}function D_(s,e,t,i){const r=(a,l)=>Math.sqrt((a.x-l.x)**2+(a.y-l.y)**2),n=(a,l,c)=>({x:a.x+(l.x-a.x)*c,y:a.y+(l.y-a.y)*c}),o=e.length;for(let a=0;a<o;a++){const l=e[(a+1)%o],c=l.radius??t;if(c<=0){a===0?s.moveTo(l.x,l.y):s.lineTo(l.x,l.y);continue}const h=e[a],u=e[(a+2)%o],f=r(h,l);let d;if(f<1e-4)d=l;else{const y=Math.min(f/2,c);d=n(l,h,y/f)}const g=r(u,l);let _;if(g<1e-4)_=l;else{const y=Math.min(g/2,c);_=n(l,u,y/g)}a===0?s.moveTo(d.x,d.y):s.lineTo(d.x,d.y),s.quadraticCurveTo(l.x,l.y,_.x,_.y,i)}}const N_=new Se;class U_{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Ye,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();const i=this._currentPoly.points,r=i[i.length-2],n=i[i.length-1];return(r!==e||n!==t)&&i.push(e,t),this}arc(e,t,i,r,n,o){this._ensurePoly(!1);const a=this._currentPoly.points;return Wc(a,e,t,i,r,n,o),this}arcTo(e,t,i,r,n){this._ensurePoly();const o=this._currentPoly.points;return M_(o,e,t,i,r,n),this}arcToSvg(e,t,i,r,n,o,a){const l=this._currentPoly.points;return O_(l,this._currentPoly.lastX,this._currentPoly.lastY,o,a,e,t,i,r,n),this}bezierCurveTo(e,t,i,r,n,o,a){this._ensurePoly();const l=this._currentPoly;return Lc(this._currentPoly.points,l.lastX,l.lastY,e,t,i,r,n,o,a),this}quadraticCurveTo(e,t,i,r,n){this._ensurePoly();const o=this._currentPoly;return I_(this._currentPoly.points,o.lastX,o.lastY,e,t,i,r,n),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));const i=this.shapePrimitives,r=i.length;for(let n=0;n<e.instructions.length;n++){const o=e.instructions[n];this[o.action](...o.data)}if(e.checkForHoles&&i.length-r>1){let n=null;for(let o=r;o<i.length;o++){const a=i[o];if(a.shape.type==="polygon"){const l=a.shape,c=n==null?void 0:n.shape;c&&c.containsPolygon(l)?(n.holes||(n.holes=[]),n.holes.push(a),i.copyWithin(o,o+1),i.length--,o--):n=a}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,i,r,n){return this.drawShape(new Se(e,t,i,r),n),this}circle(e,t,i,r){return this.drawShape(new On(e,t,i),r),this}poly(e,t,i){const r=new ls(e);return r.closePath=t,this.drawShape(r,i),this}regularPoly(e,t,i,r,n=0,o){r=Math.max(r|0,3);const a=-1*Math.PI/2+n,l=Math.PI*2/r,c=[];for(let h=0;h<r;h++){const u=a-h*l;c.push(e+i*Math.cos(u),t+i*Math.sin(u))}return this.poly(c,!0,o),this}roundPoly(e,t,i,r,n,o=0,a){if(r=Math.max(r|0,3),n<=0)return this.regularPoly(e,t,i,r,o);const l=i*Math.sin(Math.PI/r)-.001;n=Math.min(n,l);const c=-1*Math.PI/2+o,h=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let f=0;f<r;f++){const d=f*h+c,g=e+i*Math.cos(d),_=t+i*Math.sin(d),y=d+Math.PI+u,x=d-Math.PI-u,C=g+n*Math.cos(y),S=_+n*Math.sin(y),E=g+n*Math.cos(x),w=_+n*Math.sin(x);f===0?this.moveTo(C,S):this.lineTo(C,S),this.quadraticCurveTo(g,_,E,w,a)}return this.closePath()}roundShape(e,t,i=!1,r){return e.length<3?this:(i?D_(this,e,t,r):B_(this,e,t),this.closePath())}filletRect(e,t,i,r,n){if(n===0)return this.rect(e,t,i,r);const o=Math.min(i,r)/2,a=Math.min(o,Math.max(-o,n)),l=e+i,c=t+r,h=a<0?-a:0,u=Math.abs(a);return this.moveTo(e,t+u).arcTo(e+h,t+h,e+u,t,u).lineTo(l-u,t).arcTo(l-h,t+h,l,t+u,u).lineTo(l,c-u).arcTo(l-h,c-h,e+i-u,c,u).lineTo(e+u,c).arcTo(e+h,c-h,e,c-u,u).closePath()}chamferRect(e,t,i,r,n,o){if(n<=0)return this.rect(e,t,i,r);const a=Math.min(n,Math.min(i,r)/2),l=e+i,c=t+r,h=[e+a,t,l-a,t,l,t+a,l,c-a,l-a,c,e+a,c,e,c-a,e,t+a];for(let u=h.length-1;u>=2;u-=2)h[u]===h[u-2]&&h[u-1]===h[u-3]&&h.splice(u-1,2);return this.poly(h,!0,o)}ellipse(e,t,i,r,n){return this.drawShape(new Bn(e,t,i,r),n),this}roundRect(e,t,i,r,n,o){return this.drawShape(new Dn(e,t,i,r,n),o),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let i=this._currentPoly;return i&&this.endPoly(),i=new ls,i.points.push(e,t),this._currentPoly=i,this}endPoly(e=!1){const t=this._currentPoly;return t&&t.points.length>2&&(t.closePath=e,this.shapePrimitives.push({shape:t})),this._currentPoly=null,this}_ensurePoly(e=!0){if(!this._currentPoly&&(this._currentPoly=new ls,e)){const t=this.shapePrimitives[this.shapePrimitives.length-1];if(t){let i=t.shape.x,r=t.shape.y;if(t.transform&&!t.transform.isIdentity()){const n=t.transform,o=i;i=n.a*i+n.c*r+n.tx,r=n.b*o+n.d*r+n.ty}this._currentPoly.points.push(i,r)}else this._currentPoly.points.push(0,0)}}buildPath(){const e=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let t=0;t<e.instructions.length;t++){const i=e.instructions[t];this[i.action](...i.data)}this.finish()}get bounds(){const e=this._bounds;e.clear();const t=this.shapePrimitives;for(let i=0;i<t.length;i++){const r=t[i],n=r.shape.getBounds(N_);r.transform?e.addRect(n,r.transform):e.addRect(n)}return e}}class Ot{constructor(e,t=!1){this.instructions=[],this.uid=be("graphicsPath"),this._dirty=!0,this.checkForHoles=t,typeof e=="string"?Sg(e,this):this.instructions=(e==null?void 0:e.slice())??[]}get shapePath(){return this._shapePath||(this._shapePath=new U_(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(e,t){return e=e.clone(),this.instructions.push({action:"addPath",data:[e,t]}),this._dirty=!0,this}arc(...e){return this.instructions.push({action:"arc",data:e}),this._dirty=!0,this}arcTo(...e){return this.instructions.push({action:"arcTo",data:e}),this._dirty=!0,this}arcToSvg(...e){return this.instructions.push({action:"arcToSvg",data:e}),this._dirty=!0,this}bezierCurveTo(...e){return this.instructions.push({action:"bezierCurveTo",data:e}),this._dirty=!0,this}bezierCurveToShort(e,t,i,r,n){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(xe.shared);let l=0,c=0;if(!o||o.action!=="bezierCurveTo")l=a.x,c=a.y;else{l=o.data[2],c=o.data[3];const h=a.x,u=a.y;l=h+(h-l),c=u+(u-c)}return this.instructions.push({action:"bezierCurveTo",data:[l,c,e,t,i,r,n]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...e){return this.instructions.push({action:"ellipse",data:e}),this._dirty=!0,this}lineTo(...e){return this.instructions.push({action:"lineTo",data:e}),this._dirty=!0,this}moveTo(...e){return this.instructions.push({action:"moveTo",data:e}),this}quadraticCurveTo(...e){return this.instructions.push({action:"quadraticCurveTo",data:e}),this._dirty=!0,this}quadraticCurveToShort(e,t,i){const r=this.instructions[this.instructions.length-1],n=this.getLastPoint(xe.shared);let o=0,a=0;if(!r||r.action!=="quadraticCurveTo")o=n.x,a=n.y;else{o=r.data[0],a=r.data[1];const l=n.x,c=n.y;o=l+(l-o),a=c+(c-a)}return this.instructions.push({action:"quadraticCurveTo",data:[o,a,e,t,i]}),this._dirty=!0,this}rect(e,t,i,r,n){return this.instructions.push({action:"rect",data:[e,t,i,r,n]}),this._dirty=!0,this}circle(e,t,i,r){return this.instructions.push({action:"circle",data:[e,t,i,r]}),this._dirty=!0,this}roundRect(...e){return this.instructions.push({action:"roundRect",data:e}),this._dirty=!0,this}poly(...e){return this.instructions.push({action:"poly",data:e}),this._dirty=!0,this}regularPoly(...e){return this.instructions.push({action:"regularPoly",data:e}),this._dirty=!0,this}roundPoly(...e){return this.instructions.push({action:"roundPoly",data:e}),this._dirty=!0,this}roundShape(...e){return this.instructions.push({action:"roundShape",data:e}),this._dirty=!0,this}filletRect(...e){return this.instructions.push({action:"filletRect",data:e}),this._dirty=!0,this}chamferRect(...e){return this.instructions.push({action:"chamferRect",data:e}),this._dirty=!0,this}star(e,t,i,r,n,o,a){n||(n=r/2);const l=-1*Math.PI/2+o,c=i*2,h=Math.PI*2/c,u=[];for(let f=0;f<c;f++){const d=f%2?n:r,g=f*h+l;u.push(e+d*Math.cos(g),t+d*Math.sin(g))}return this.poly(u,!0,a),this}clone(e=!1){const t=new Ot;if(t.checkForHoles=this.checkForHoles,!e)t.instructions=this.instructions.slice();else for(let i=0;i<this.instructions.length;i++){const r=this.instructions[i];t.instructions.push({action:r.action,data:r.data.slice()})}return t}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(e){if(e.isIdentity())return this;const t=e.a,i=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty;let l=0,c=0,h=0,u=0,f=0,d=0,g=0,_=0;for(let y=0;y<this.instructions.length;y++){const x=this.instructions[y],C=x.data;switch(x.action){case"moveTo":case"lineTo":l=C[0],c=C[1],C[0]=t*l+r*c+o,C[1]=i*l+n*c+a;break;case"bezierCurveTo":h=C[0],u=C[1],f=C[2],d=C[3],l=C[4],c=C[5],C[0]=t*h+r*u+o,C[1]=i*h+n*u+a,C[2]=t*f+r*d+o,C[3]=i*f+n*d+a,C[4]=t*l+r*c+o,C[5]=i*l+n*c+a;break;case"quadraticCurveTo":h=C[0],u=C[1],l=C[2],c=C[3],C[0]=t*h+r*u+o,C[1]=i*h+n*u+a,C[2]=t*l+r*c+o,C[3]=i*l+n*c+a;break;case"arcToSvg":l=C[5],c=C[6],g=C[0],_=C[1],C[0]=t*g+r*_,C[1]=i*g+n*_,C[5]=t*l+r*c+o,C[6]=i*l+n*c+a;break;case"circle":C[4]=ms(C[3],e);break;case"rect":C[4]=ms(C[4],e);break;case"ellipse":C[8]=ms(C[8],e);break;case"roundRect":C[5]=ms(C[5],e);break;case"addPath":C[0].transform(e);break;case"poly":C[2]=ms(C[2],e);break;default:se("unknown transform action",x.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,i=this.instructions[t];if(!i)return e.x=0,e.y=0,e;for(;i.action==="closePath";){if(t--,t<0)return e.x=0,e.y=0,e;i=this.instructions[t]}switch(i.action){case"moveTo":case"lineTo":e.x=i.data[0],e.y=i.data[1];break;case"quadraticCurveTo":e.x=i.data[2],e.y=i.data[3];break;case"bezierCurveTo":e.x=i.data[4],e.y=i.data[5];break;case"arc":case"arcToSvg":e.x=i.data[5],e.y=i.data[6];break;case"addPath":i.data[0].getLastPoint(e);break}return e}}function ms(s,e){return s?s.prepend(e):e.clone()}function Ie(s,e,t){const i=s.getAttribute(e);return i?Number(i):t}function F_(s,e){const t=s.querySelectorAll("defs");for(let i=0;i<t.length;i++){const r=t[i];for(let n=0;n<r.children.length;n++){const o=r.children[n];switch(o.nodeName.toLowerCase()){case"lineargradient":e.defs[o.id]=G_(o);break;case"radialgradient":e.defs[o.id]=L_();break}}}}function G_(s){const e=Ie(s,"x1",0),t=Ie(s,"y1",0),i=Ie(s,"x2",1),r=Ie(s,"y2",0),n=s.getAttribute("gradientUnits")||"objectBoundingBox",o=new Mi(e,t,i,r,n==="objectBoundingBox"?"local":"global");for(let a=0;a<s.children.length;a++){const l=s.children[a],c=Ie(l,"offset",0),h=Pe.shared.setValue(l.getAttribute("stop-color")).toNumber();o.addColorStop(c,h)}return o}function L_(s){return se("[SVG Parser] Radial gradients are not yet supported"),new Mi(0,0,1,0)}function Vc(s){const e=s.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return e?e[1]:""}const zc={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function $c(s,e){const t=s.getAttribute("style"),i={},r={},n={strokeStyle:i,fillStyle:r,useFill:!1,useStroke:!1};for(const o in zc){const a=s.getAttribute(o);a&&jc(e,n,o,a.trim())}if(t){const o=t.split(";");for(let a=0;a<o.length;a++){const l=o[a].trim(),[c,h]=l.split(":");zc[c]&&jc(e,n,c,h.trim())}}return{strokeStyle:n.useStroke?i:null,fillStyle:n.useFill?r:null,useFill:n.useFill,useStroke:n.useStroke}}function jc(s,e,t,i){switch(t){case"stroke":if(i!=="none"){if(i.startsWith("url(")){const r=Vc(i);e.strokeStyle.fill=s.defs[r]}else e.strokeStyle.color=Pe.shared.setValue(i).toNumber();e.useStroke=!0}break;case"stroke-width":e.strokeStyle.width=Number(i);break;case"fill":if(i!=="none"){if(i.startsWith("url(")){const r=Vc(i);e.fillStyle.fill=s.defs[r]}else e.fillStyle.color=Pe.shared.setValue(i).toNumber();e.useFill=!0}break;case"fill-opacity":e.fillStyle.alpha=Number(i);break;case"stroke-opacity":e.strokeStyle.alpha=Number(i);break;case"opacity":e.fillStyle.alpha=Number(i),e.strokeStyle.alpha=Number(i);break}}function W_(s){if(s.length<=2)return!0;const e=s.map(a=>a.area).sort((a,l)=>l-a),[t,i]=e,r=e[e.length-1],n=t/i,o=i/r;return!(n>3&&o<2)}function H_(s){return s.split(/(?=[Mm])/).filter(i=>i.trim().length>0)}function V_(s){const e=s.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!e||e.length<4)return 0;const t=e.map(Number),i=[],r=[];for(let h=0;h<t.length;h+=2)h+1<t.length&&(i.push(t[h]),r.push(t[h+1]));if(i.length===0||r.length===0)return 0;const n=Math.min(...i),o=Math.max(...i),a=Math.min(...r),l=Math.max(...r);return(o-n)*(l-a)}function Xc(s,e){const t=new Ot(s,!1);for(const i of t.instructions)e.instructions.push(i)}function z_(s,e){if(typeof s=="string"){const o=document.createElement("div");o.innerHTML=s.trim(),s=o.querySelector("svg")}const t={context:e,defs:{},path:new Ot};F_(s,t);const i=s.children,{fillStyle:r,strokeStyle:n}=$c(s,t);for(let o=0;o<i.length;o++){const a=i[o];a.nodeName.toLowerCase()!=="defs"&&Yc(a,t,r,n)}return e}function Yc(s,e,t,i){const r=s.children,{fillStyle:n,strokeStyle:o}=$c(s,e);n&&t?t={...t,...n}:n&&(t=n),o&&i?i={...i,...o}:o&&(i=o);const a=!t&&!i;a&&(t={color:0});let l,c,h,u,f,d,g,_,y,x,C,S,E,w,R,M,D;switch(s.nodeName.toLowerCase()){case"path":{w=s.getAttribute("d");const F=s.getAttribute("fill-rule"),k=H_(w),O=F==="evenodd",V=k.length>1;if(O&&V){const z=k.map(B=>({path:B,area:V_(B)}));if(z.sort((B,U)=>U.area-B.area),k.length>3||!W_(z))for(let B=0;B<z.length;B++){const U=z[B],q=B===0;e.context.beginPath();const N=new Ot(void 0,!0);Xc(U.path,N),e.context.path(N),q?(t&&e.context.fill(t),i&&e.context.stroke(i)):e.context.cut()}else for(let B=0;B<z.length;B++){const U=z[B],q=B%2===1;e.context.beginPath();const N=new Ot(void 0,!0);Xc(U.path,N),e.context.path(N),q?e.context.cut():(t&&e.context.fill(t),i&&e.context.stroke(i))}}else{const z=F?F==="evenodd":!0;R=new Ot(w,z),e.context.path(R),t&&e.context.fill(t),i&&e.context.stroke(i)}break}case"circle":g=Ie(s,"cx",0),_=Ie(s,"cy",0),y=Ie(s,"r",0),e.context.ellipse(g,_,y,y),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"rect":l=Ie(s,"x",0),c=Ie(s,"y",0),M=Ie(s,"width",0),D=Ie(s,"height",0),x=Ie(s,"rx",0),C=Ie(s,"ry",0),x||C?e.context.roundRect(l,c,M,D,x||C):e.context.rect(l,c,M,D),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"ellipse":g=Ie(s,"cx",0),_=Ie(s,"cy",0),x=Ie(s,"rx",0),C=Ie(s,"ry",0),e.context.beginPath(),e.context.ellipse(g,_,x,C),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"line":h=Ie(s,"x1",0),u=Ie(s,"y1",0),f=Ie(s,"x2",0),d=Ie(s,"y2",0),e.context.beginPath(),e.context.moveTo(h,u),e.context.lineTo(f,d),i&&e.context.stroke(i);break;case"polygon":E=s.getAttribute("points"),S=E.match(/-?\d+/g).map(F=>parseInt(F,10)),e.context.poly(S,!0),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"polyline":E=s.getAttribute("points"),S=E.match(/-?\d+/g).map(F=>parseInt(F,10)),e.context.poly(S,!1),i&&e.context.stroke(i);break;case"g":case"svg":break;default:{se(`[SVG parser] <${s.nodeName}> elements unsupported`);break}}a&&(t=null);for(let F=0;F<r.length;F++)Yc(r[F],e,t,i)}const qc={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class Kc{constructor(e,t){this.uid=be("fillPattern"),this._tick=0,this.transform=new H,this.texture=e,this.transform.scale(1/e.frame.width,1/e.frame.height),t&&(e.source.style.addressModeU=qc[t].addressModeU,e.source.style.addressModeV=qc[t].addressModeV)}setTransform(e){const t=this.texture;this.transform.copyFrom(e),this.transform.invert(),this.transform.scale(1/t.frame.width,1/t.frame.height),this._tick++}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}function $_(s){return Pe.isColorLike(s)}function Zc(s){return s instanceof Kc}function Jc(s){return s instanceof Mi}function j_(s){return s instanceof j}function X_(s,e,t){const i=Pe.shared.setValue(e??0);return s.color=i.toNumber(),s.alpha=i.alpha===1?t.alpha:i.alpha,s.texture=j.WHITE,{...t,...s}}function Y_(s,e,t){return s.texture=e,{...t,...s}}function Qc(s,e,t){return s.fill=e,s.color=16777215,s.texture=e.texture,s.matrix=e.transform,{...t,...s}}function eh(s,e,t){return e.buildGradient(),s.fill=e,s.color=16777215,s.texture=e.texture,s.matrix=e.transform,s.textureSpace=e.textureSpace,{...t,...s}}function q_(s,e){const t={...e,...s},i=Pe.shared.setValue(t.color);return t.alpha*=i.alpha,t.color=i.toNumber(),t}function gs(s,e){if(s==null)return null;const t={},i=s;return $_(s)?X_(t,s,e):j_(s)?Y_(t,s,e):Zc(s)?Qc(t,s,e):Jc(s)?eh(t,s,e):i.fill&&Zc(i.fill)?Qc(i,i.fill,e):i.fill&&Jc(i.fill)?eh(i,i.fill,e):q_(i,e)}function th(s,e){const{width:t,alignment:i,miterLimit:r,cap:n,join:o,pixelLine:a,...l}=e,c=gs(s,l);return c?{width:t,alignment:i,miterLimit:r,cap:n,join:o,pixelLine:a,...c}:null}function K_(s,e){let t=1;const i=s.shapePath.shapePrimitives;for(let r=0;r<i.length;r++){const n=i[r].shape;if(n.type!=="polygon")continue;const o=n.points,a=o.length;if(a<6)continue;const l=n.closePath;for(let c=0;c<a;c+=2){if(!l&&(c===0||c===a-2))continue;const h=(c-2+a)%a,u=(c+2)%a,f=o[h],d=o[h+1],g=o[c],_=o[c+1],y=o[u],x=o[u+1],C=f-g,S=d-_,E=y-g,w=x-_,R=C*C+S*S,M=E*E+w*w;if(R<1e-12||M<1e-12)continue;let k=(C*E+S*w)/Math.sqrt(R*M);k<-1?k=-1:k>1&&(k=1);const O=Math.sqrt((1-k)*.5);if(O<1e-6)continue;const V=Math.min(1/O,e);V>t&&(t=V)}}return t}const Z_=new xe,ih=new H,eo=class Tt extends lt{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=be("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new Ot,this._transform=new H,this._fillStyle={...Tt.defaultFillStyle},this._strokeStyle={...Tt.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Ye,this._boundsDirty=!0}clone(){const e=new Tt;return e.batchMode=this.batchMode,e.instructions=this.instructions.slice(),e._activePath=this._activePath.clone(),e._transform=this._transform.clone(),e._fillStyle={...this._fillStyle},e._strokeStyle={...this._strokeStyle},e._stateStack=this._stateStack.slice(),e._bounds=this._bounds.clone(),e._boundsDirty=!0,e}get fillStyle(){return this._fillStyle}set fillStyle(e){this._fillStyle=gs(e,Tt.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=th(e,Tt.defaultStrokeStyle)}setFillStyle(e){return this._fillStyle=gs(e,Tt.defaultFillStyle),this}setStrokeStyle(e){return this._strokeStyle=gs(e,Tt.defaultStrokeStyle),this}texture(e,t,i,r,n,o){return this.instructions.push({action:"texture",data:{image:e,dx:i||0,dy:r||0,dw:n||e.frame.width,dh:o||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t||t===0?Pe.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new Ot,this}fill(e,t){let i;const r=this.instructions[this.instructions.length-1];return this._tick===0&&(r==null?void 0:r.action)==="stroke"?i=r.data.path:i=this._activePath.clone(),i?(e!=null&&(t!==void 0&&typeof e=="number"&&(ee(Be,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),e={color:e,alpha:t}),this._fillStyle=gs(e,Tt.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:i}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:e,y:t}=this._activePath.getLastPoint(xe.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(e){let t;const i=this.instructions[this.instructions.length-1];return this._tick===0&&(i==null?void 0:i.action)==="fill"?t=i.data.path:t=this._activePath.clone(),t?(e!=null&&(this._strokeStyle=th(e,Tt.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:t}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let e=0;e<2;e++){const t=this.instructions[this.instructions.length-1-e],i=this._activePath.clone();if(t&&(t.action==="stroke"||t.action==="fill"))if(t.data.hole)t.data.hole.addPath(i);else{t.data.hole=i;break}}return this._initNextPathLocation(),this}arc(e,t,i,r,n,o){this._tick++;const a=this._transform;return this._activePath.arc(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,i,r,n,o),this}arcTo(e,t,i,r,n){this._tick++;const o=this._transform;return this._activePath.arcTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*i+o.c*r+o.tx,o.b*i+o.d*r+o.ty,n),this}arcToSvg(e,t,i,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.arcToSvg(e,t,i,r,n,l.a*o+l.c*a+l.tx,l.b*o+l.d*a+l.ty),this}bezierCurveTo(e,t,i,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.bezierCurveTo(l.a*e+l.c*t+l.tx,l.b*e+l.d*t+l.ty,l.a*i+l.c*r+l.tx,l.b*i+l.d*r+l.ty,l.a*n+l.c*o+l.tx,l.b*n+l.d*o+l.ty,a),this}closePath(){var e;return this._tick++,(e=this._activePath)==null||e.closePath(),this}ellipse(e,t,i,r){return this._tick++,this._activePath.ellipse(e,t,i,r,this._transform.clone()),this}circle(e,t,i){return this._tick++,this._activePath.circle(e,t,i,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;const i=this._transform;return this._activePath.lineTo(i.a*e+i.c*t+i.tx,i.b*e+i.d*t+i.ty),this}moveTo(e,t){this._tick++;const i=this._transform,r=this._activePath.instructions,n=i.a*e+i.c*t+i.tx,o=i.b*e+i.d*t+i.ty;return r.length===1&&r[0].action==="moveTo"?(r[0].data[0]=n,r[0].data[1]=o,this):(this._activePath.moveTo(n,o),this)}quadraticCurveTo(e,t,i,r,n){this._tick++;const o=this._transform;return this._activePath.quadraticCurveTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*i+o.c*r+o.tx,o.b*i+o.d*r+o.ty,n),this}rect(e,t,i,r){return this._tick++,this._activePath.rect(e,t,i,r,this._transform.clone()),this}roundRect(e,t,i,r,n){return this._tick++,this._activePath.roundRect(e,t,i,r,n,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,i,r,n=0,o){return this._tick++,this._activePath.regularPoly(e,t,i,r,n,o),this}roundPoly(e,t,i,r,n,o){return this._tick++,this._activePath.roundPoly(e,t,i,r,n,o),this}roundShape(e,t,i,r){return this._tick++,this._activePath.roundShape(e,t,i,r),this}filletRect(e,t,i,r,n){return this._tick++,this._activePath.filletRect(e,t,i,r,n),this}chamferRect(e,t,i,r,n,o){return this._tick++,this._activePath.chamferRect(e,t,i,r,n,o),this}star(e,t,i,r,n=0,o=0){return this._tick++,this._activePath.star(e,t,i,r,n,o,this._transform.clone()),this}svg(e){return this._tick++,z_(e,this),this}restore(){const e=this._stateStack.pop();return e&&(this._transform=e.transform,this._fillStyle=e.fillStyle,this._strokeStyle=e.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(e){return this._transform.rotate(e),this}scale(e,t=e){return this._transform.scale(e,t),this}setTransform(e,t,i,r,n,o){return e instanceof H?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,i,r,n,o),this)}transform(e,t,i,r,n,o){return e instanceof H?(this._transform.append(e),this):(ih.set(e,t,i,r,n,o),this._transform.append(ih),this)}translate(e,t=e){return this._transform.translate(e,t),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,this.dirty=!0,this.emit("update",this,16)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const e=this._bounds;e.clear();for(let t=0;t<this.instructions.length;t++){const i=this.instructions[t],r=i.action;if(r==="fill"){const n=i.data;e.addBounds(n.path.bounds)}else if(r==="texture"){const n=i.data;e.addFrame(n.dx,n.dy,n.dx+n.dw,n.dy+n.dh,n.transform)}if(r==="stroke"){const n=i.data,o=n.style.alignment;let a=n.style.width*(1-o);n.style.join==="miter"&&(a*=K_(n.path,n.style.miterLimit));const l=n.path.bounds;e.addFrame(l.minX-a,l.minY-a,l.maxX+a,l.maxY+a)}}return e.isValid||e.set(0,0,0,0),e}containsPoint(e){var r;if(!this.bounds.containsPoint(e.x,e.y))return!1;const t=this.instructions;let i=!1;for(let n=0;n<t.length;n++){const o=t[n],a=o.data,l=a.path;if(!o.action||!l)continue;const c=a.style,h=l.shapePath.shapePrimitives;for(let u=0;u<h.length;u++){const f=h[u].shape;if(!c||!f)continue;const d=h[u].transform,g=d?d.applyInverse(e,Z_):e;if(o.action==="fill")i=f.contains(g.x,g.y);else{const y=c;i=f.strokeContains(g.x,g.y,y.width,y.alignment)}const _=a.hole;if(_){const y=(r=_.shapePath)==null?void 0:r.shapePrimitives;if(y)for(let x=0;x<y.length;x++)y[x].shape.contains(g.x,g.y)&&(i=!1)}if(i)return!0}}return i}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){if(this.destroyed)return;if(this.destroyed=!0,this._stateStack.length=0,this._transform=null,this.unload(),this.emit("destroy",this),this.removeAllListeners(),typeof e=="boolean"?e:e==null?void 0:e.texture){const i=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(i)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(i))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};eo.defaultFillStyle={color:16777215,alpha:1,texture:j.WHITE,matrix:null,fill:null,textureSpace:"local"},eo.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:j.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let _s=eo;class sh{constructor(e){this._attachedDomElements=[],this._renderer=e,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new Pl({domElement:this._domElement,renderer:this._renderer})}addRenderable(e,t){this._attachedDomElements.includes(e)||this._attachedDomElements.push(e)}updateRenderable(e){}validateRenderable(e){return!0}postrender(){const e=this._attachedDomElements;if(e.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let t=0;t<e.length;t++){const i=e[t],r=i.element;if(!i.parent||i.globalDisplayStatus<7)r==null||r.remove(),e.splice(t,1),t--;else{this._domElement.contains(r)||(r.style.position="absolute",r.style.pointerEvents="auto",this._domElement.appendChild(r));const n=i.worldTransform,o=i._anchor,a=i.width*o.x,l=i.height*o.y;r.style.transformOrigin=`${a}px ${l}px`,r.style.transform=`matrix(${n.a}, ${n.b}, ${n.c}, ${n.d}, ${n.tx-a}, ${n.ty-l})`,r.style.opacity=i.groupAlpha.toString()}}}destroy(){var e;this._renderer.runners.postrender.remove(this);for(let t=0;t<this._attachedDomElements.length;t++)(e=this._attachedDomElements[t].element)==null||e.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}sh.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"dom"};class J_{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(e){this.removeTickerListener(),this.events=e,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(e){this._pauseUpdate=e}addTickerListener(){this._tickerAdded||!this.domElement||(at.system.add(this._tickerUpdate,this,Si.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(at.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const e=this.events._rootPointerEvent;this.events.supportsTouchEvents&&e.pointerType==="touch"||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent("pointermove",{clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,pointerId:e.pointerId}):new MouseEvent("mousemove",{clientX:e.clientX,clientY:e.clientY}))}_tickerUpdate(e){this._deltaTime+=e.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}}const Bt=new J_;class hr extends ns{constructor(){super(...arguments),this.client=new xe,this.movement=new xe,this.offset=new xe,this.global=new xe,this.screen=new xe}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(e,t,i){return e.worldTransform.applyInverse(i||this.global,t)}getModifierState(e){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(e)}initMouseEvent(e,t,i,r,n,o,a,l,c,h,u,f,d,g,_){throw new Error("Method not implemented.")}}class dt extends hr{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class Pi extends hr{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}Pi.DOM_DELTA_PIXEL=0,Pi.DOM_DELTA_LINE=1,Pi.DOM_DELTA_PAGE=2;const Q_=2048,ey=new xe,ys=new xe;class ty{constructor(e){this.dispatch=new lt,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=e,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(e,t){this.mappingTable[e]||(this.mappingTable[e]=[]),this.mappingTable[e].push({fn:t,priority:0}),this.mappingTable[e].sort((i,r)=>i.priority-r.priority)}dispatchEvent(e,t){e.propagationStopped=!1,e.propagationImmediatelyStopped=!1,this.propagate(e,t),this.dispatch.emit(t||e.type,e)}mapEvent(e){if(!this.rootTarget)return;const t=this.mappingTable[e.type];if(t)for(let i=0,r=t.length;i<r;i++)t[i].fn(e);else se(`[EventBoundary]: Event mapping not defined for ${e.type}`)}hitTest(e,t){Bt.pauseUpdate=!0;const r=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",n=this[r](this.rootTarget,this.rootTarget.eventMode,ey.set(e,t),this.hitTestFn,this.hitPruneFn);return n&&n[0]}propagate(e,t){if(!e.target)return;const i=e.composedPath();e.eventPhase=e.CAPTURING_PHASE;for(let r=0,n=i.length-1;r<n;r++)if(e.currentTarget=i[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return;if(e.eventPhase=e.AT_TARGET,e.currentTarget=e.target,this.notifyTarget(e,t),!(e.propagationStopped||e.propagationImmediatelyStopped)){e.eventPhase=e.BUBBLING_PHASE;for(let r=i.length-2;r>=0;r--)if(e.currentTarget=i[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return}}all(e,t,i=this._allInteractiveElements){if(i.length===0)return;e.eventPhase=e.BUBBLING_PHASE;const r=Array.isArray(t)?t:[t];for(let n=i.length-1;n>=0;n--)r.forEach(o=>{e.currentTarget=i[n],this.notifyTarget(e,o)})}propagationPath(e){const t=[e];for(let i=0;i<Q_&&e!==this.rootTarget&&e.parent;i++){if(!e.parent)throw new Error("Cannot find propagation path to disconnected target");t.push(e.parent),e=e.parent}return t.reverse(),t}hitTestMoveRecursive(e,t,i,r,n,o=!1){let a=!1;if(this._interactivePrune(e))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(Bt.pauseUpdate=!1),e.interactiveChildren&&e.children){const h=e.children;for(let u=h.length-1;u>=0;u--){const f=h[u],d=this.hitTestMoveRecursive(f,this._isInteractive(t)?t:f.eventMode,i,r,n,o||n(e,i));if(d){if(d.length>0&&!d[d.length-1].parent)continue;const g=e.isInteractive();(d.length>0||g)&&(g&&this._allInteractiveElements.push(e),d.push(e)),this._hitElements.length===0&&(this._hitElements=d),a=!0}}}const l=this._isInteractive(t),c=e.isInteractive();return c&&c&&this._allInteractiveElements.push(e),o||this._hitElements.length>0?null:a?this._hitElements:l&&!n(e,i)&&r(e,i)?c?[e]:[]:null}hitTestRecursive(e,t,i,r,n){if(this._interactivePrune(e)||n(e,i))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(Bt.pauseUpdate=!1),e.interactiveChildren&&e.children){const l=e.children,c=i;for(let h=l.length-1;h>=0;h--){const u=l[h],f=this.hitTestRecursive(u,this._isInteractive(t)?t:u.eventMode,c,r,n);if(f){if(f.length>0&&!f[f.length-1].parent)continue;const d=e.isInteractive();return(f.length>0||d)&&f.push(e),f}}}const o=this._isInteractive(t),a=e.isInteractive();return o&&r(e,i)?a?[e]:[]:null}_isInteractive(e){return e==="static"||e==="dynamic"}_interactivePrune(e){return!e||!e.visible||!e.renderable||!e.measurable||e.eventMode==="none"||e.eventMode==="passive"&&!e.interactiveChildren}hitPruneFn(e,t){if(e.hitArea&&(e.worldTransform.applyInverse(t,ys),!e.hitArea.contains(ys.x,ys.y)))return!0;if(e.effects&&e.effects.length)for(let i=0;i<e.effects.length;i++){const r=e.effects[i];if(r.containsPoint&&!r.containsPoint(t,this.hitTestFn))return!0}return!1}hitTestFn(e,t){return e.hitArea?!0:e!=null&&e.containsPoint?(e.worldTransform.applyInverse(t,ys),e.containsPoint(ys)):!1}notifyTarget(e,t){var n,o;if(!e.currentTarget.isInteractive())return;t??(t=e.type);const i=`on${t}`;(o=(n=e.currentTarget)[i])==null||o.call(n,e);const r=e.eventPhase===e.CAPTURING_PHASE||e.eventPhase===e.AT_TARGET?`${t}capture`:t;this._notifyListeners(e,r),e.eventPhase===e.AT_TARGET&&this._notifyListeners(e,t)}mapPointerDown(e){if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.createPointerEvent(e);if(this.dispatchEvent(t,"pointerdown"),t.pointerType==="touch")this.dispatchEvent(t,"touchstart");else if(t.pointerType==="mouse"||t.pointerType==="pen"){const r=t.button===2;this.dispatchEvent(t,r?"rightdown":"mousedown")}const i=this.trackingData(e.pointerId);i.pressTargetsByButton[e.button]=t.composedPath(),this.freeEvent(t)}mapPointerMove(e){var l,c;if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const t=this.createPointerEvent(e);this._isPointerMoveEvent=!1;const i=t.pointerType==="mouse"||t.pointerType==="pen",r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.overTargets);if(((l=r.overTargets)==null?void 0:l.length)>0&&n!==t.target){const h=e.type==="mousemove"?"mouseout":"pointerout",u=this.createPointerEvent(e,h,n);if(this.dispatchEvent(u,"pointerout"),i&&this.dispatchEvent(u,"mouseout"),!t.composedPath().includes(n)){const f=this.createPointerEvent(e,"pointerleave",n);for(f.eventPhase=f.AT_TARGET;f.target&&!t.composedPath().includes(f.target);)f.currentTarget=f.target,this.notifyTarget(f),i&&this.notifyTarget(f,"mouseleave"),f.target=f.target.parent;this.freeEvent(f)}this.freeEvent(u)}if(n!==t.target){const h=e.type==="mousemove"?"mouseover":"pointerover",u=this.clonePointerEvent(t,h);this.dispatchEvent(u,"pointerover"),i&&this.dispatchEvent(u,"mouseover");let f=n==null?void 0:n.parent;for(;f&&f!==this.rootTarget.parent&&f!==t.target;)f=f.parent;if(!f||f===this.rootTarget.parent){const g=this.clonePointerEvent(t,"pointerenter");for(g.eventPhase=g.AT_TARGET;g.target&&g.target!==n&&g.target!==this.rootTarget.parent;)g.currentTarget=g.target,this.notifyTarget(g),i&&this.notifyTarget(g,"mouseenter"),g.target=g.target.parent;this.freeEvent(g)}this.freeEvent(u)}const o=[],a=this.enableGlobalMoveEvents??!0;this.moveOnAll?o.push("pointermove"):this.dispatchEvent(t,"pointermove"),a&&o.push("globalpointermove"),t.pointerType==="touch"&&(this.moveOnAll?o.splice(1,0,"touchmove"):this.dispatchEvent(t,"touchmove"),a&&o.push("globaltouchmove")),i&&(this.moveOnAll?o.splice(1,0,"mousemove"):this.dispatchEvent(t,"mousemove"),a&&o.push("globalmousemove"),this.cursor=(c=t.target)==null?void 0:c.cursor),o.length>0&&this.all(t,o),this._allInteractiveElements.length=0,this._hitElements.length=0,r.overTargets=t.composedPath(),this.freeEvent(t)}mapPointerOver(e){var o;if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),i=this.createPointerEvent(e),r=i.pointerType==="mouse"||i.pointerType==="pen";this.dispatchEvent(i,"pointerover"),r&&this.dispatchEvent(i,"mouseover"),i.pointerType==="mouse"&&(this.cursor=(o=i.target)==null?void 0:o.cursor);const n=this.clonePointerEvent(i,"pointerenter");for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),r&&this.notifyTarget(n,"mouseenter"),n.target=n.target.parent;t.overTargets=i.composedPath(),this.freeEvent(i),this.freeEvent(n)}mapPointerOut(e){if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId);if(t.overTargets){const i=e.pointerType==="mouse"||e.pointerType==="pen",r=this.findMountedTarget(t.overTargets),n=this.createPointerEvent(e,"pointerout",r);this.dispatchEvent(n),i&&this.dispatchEvent(n,"mouseout");const o=this.createPointerEvent(e,"pointerleave",r);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),i&&this.notifyTarget(o,"mouseleave"),o.target=o.target.parent;t.overTargets=null,this.freeEvent(n),this.freeEvent(o)}this.cursor=null}mapPointerUp(e){if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=performance.now(),i=this.createPointerEvent(e);if(this.dispatchEvent(i,"pointerup"),i.pointerType==="touch")this.dispatchEvent(i,"touchend");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const a=i.button===2;this.dispatchEvent(i,a?"rightup":"mouseup")}const r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.pressTargetsByButton[e.button]);let o=n;if(n&&!i.composedPath().includes(n)){let a=n;for(;a&&!i.composedPath().includes(a);){if(i.currentTarget=a,this.notifyTarget(i,"pointerupoutside"),i.pointerType==="touch")this.notifyTarget(i,"touchendoutside");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const l=i.button===2;this.notifyTarget(i,l?"rightupoutside":"mouseupoutside")}a=a.parent}delete r.pressTargetsByButton[e.button],o=a}if(o){const a=this.clonePointerEvent(i,"click");a.target=o,a.path=null,r.clicksByButton[e.button]||(r.clicksByButton[e.button]={clickCount:0,target:a.target,timeStamp:t});const l=r.clicksByButton[e.button];if(l.target===a.target&&t-l.timeStamp<200?++l.clickCount:l.clickCount=1,l.target=a.target,l.timeStamp=t,a.detail=l.clickCount,a.pointerType==="mouse"){const c=a.button===2;this.dispatchEvent(a,c?"rightclick":"click")}else a.pointerType==="touch"&&this.dispatchEvent(a,"tap");this.dispatchEvent(a,"pointertap"),this.freeEvent(a)}this.freeEvent(i)}mapPointerUpOutside(e){if(!(e instanceof dt)){se("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),i=this.findMountedTarget(t.pressTargetsByButton[e.button]),r=this.createPointerEvent(e);if(i){let n=i;for(;n;)r.currentTarget=n,this.notifyTarget(r,"pointerupoutside"),r.pointerType==="touch"?this.notifyTarget(r,"touchendoutside"):(r.pointerType==="mouse"||r.pointerType==="pen")&&this.notifyTarget(r,r.button===2?"rightupoutside":"mouseupoutside"),n=n.parent;delete t.pressTargetsByButton[e.button]}this.freeEvent(r)}mapWheel(e){if(!(e instanceof Pi)){se("EventBoundary cannot map a non-wheel event as a wheel event");return}const t=this.createWheelEvent(e);this.dispatchEvent(t),this.freeEvent(t)}findMountedTarget(e){if(!e)return null;let t=e[0];for(let i=1;i<e.length&&e[i].parent===t;i++)t=e[i];return t}createPointerEvent(e,t,i){const r=this.allocateEvent(dt);return this.copyPointerData(e,r),this.copyMouseData(e,r),this.copyData(e,r),r.nativeEvent=e.nativeEvent,r.originalEvent=e,r.target=i??this.hitTest(r.global.x,r.global.y)??this._hitElements[0],typeof t=="string"&&(r.type=t),r}createWheelEvent(e){const t=this.allocateEvent(Pi);return this.copyWheelData(e,t),this.copyMouseData(e,t),this.copyData(e,t),t.nativeEvent=e.nativeEvent,t.originalEvent=e,t.target=this.hitTest(t.global.x,t.global.y),t}clonePointerEvent(e,t){const i=this.allocateEvent(dt);return i.nativeEvent=e.nativeEvent,i.originalEvent=e.originalEvent,this.copyPointerData(e,i),this.copyMouseData(e,i),this.copyData(e,i),i.target=e.target,i.path=e.composedPath().slice(),i.type=t??i.type,i}copyWheelData(e,t){t.deltaMode=e.deltaMode,t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ}copyPointerData(e,t){e instanceof dt&&t instanceof dt&&(t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist)}copyMouseData(e,t){e instanceof hr&&t instanceof hr&&(t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.copyFrom(e.client),t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.copyFrom(e.movement),t.screen.copyFrom(e.screen),t.shiftKey=e.shiftKey,t.global.copyFrom(e.global))}copyData(e,t){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.detail=e.detail,t.view=e.view,t.which=e.which,t.layer.copyFrom(e.layer),t.page.copyFrom(e.page)}trackingData(e){return this.mappingState.trackingData[e]||(this.mappingState.trackingData[e]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[e]}allocateEvent(e){this.eventPool.has(e)||this.eventPool.set(e,[]);const t=this.eventPool.get(e).pop()||new e(this);return t.eventPhase=t.NONE,t.currentTarget=null,t.defaultPrevented=!1,t.path=null,t.target=null,t}freeEvent(e){if(e.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const t=e.constructor;this.eventPool.has(t)||this.eventPool.set(t,[]),this.eventPool.get(t).push(e)}_notifyListeners(e,t){const i=e.currentTarget._events[t];if(i)if("fn"in i)i.once&&e.currentTarget.removeListener(t,i.fn,void 0,!0),i.fn.call(i.context,e);else for(let r=0,n=i.length;r<n&&!e.propagationImmediatelyStopped;r++)i[r].once&&e.currentTarget.removeListener(t,i[r].fn,void 0,!0),i[r].fn.call(i[r].context,e)}}const iy=1,sy={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},to=class ha{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new ty(null),Bt.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new dt(null),this._rootWheelEvent=new Pi(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...ha.defaultEventFeatures},{set:(t,i,r)=>(i==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=r),t[i]=r,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{canvas:t,resolution:i}=this.renderer;this.setTargetElement(t),this.resolution=i,ha._defaultEventMode=e.eventMode??"passive",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(e){this.resolution=e}destroy(){Bt.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(e){e||(e="default");let t=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(t=!1),this._currentCursor===e)return;this._currentCursor=e;const i=this.cursorStyles[e];if(i)switch(typeof i){case"string":t&&(this.domElement.style.cursor=i);break;case"function":i(e);break;case"object":t&&Object.assign(this.domElement.style,i);break}else t&&typeof e=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,e)&&(this.domElement.style.cursor=e)}get pointer(){return this._rootPointerEvent}_onPointerDown(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);this.autoPreventDefault&&t[0].isNormalized&&(e.cancelable||!("cancelable"in e))&&e.preventDefault();for(let i=0,r=t.length;i<r;i++){const n=t[i],o=this._bootstrapEvent(this._rootPointerEvent,n);this.rootBoundary.mapEvent(o)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(e){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,Bt.pointerMoved();const t=this._normalizeToPointerData(e);for(let i=0,r=t.length;i<r;i++){const n=this._bootstrapEvent(this._rootPointerEvent,t[i]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let t=e.target;e.composedPath&&e.composedPath().length>0&&(t=e.composedPath()[0]);const i=t!==this.domElement?"outside":"",r=this._normalizeToPointerData(e);for(let n=0,o=r.length;n<o;n++){const a=this._bootstrapEvent(this._rootPointerEvent,r[n]);a.type+=i,this.rootBoundary.mapEvent(a)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);for(let i=0,r=t.length;i<r;i++){const n=this._bootstrapEvent(this._rootPointerEvent,t[i]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}onWheel(e){if(!this.features.wheel)return;const t=this.normalizeWheelEvent(e);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(t)}setTargetElement(e){this._removeEvents(),this.domElement=e,Bt.domElement=e,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;Bt.addTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="none",e.msTouchAction="none"):this.supportsPointerEvents&&(e.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this._onPointerMove,!0),this.domElement.addEventListener("pointerdown",this._onPointerDown,!0),this.domElement.addEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this._onPointerOverOut,!0),globalThis.addEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this._onPointerMove,!0),this.domElement.addEventListener("mousedown",this._onPointerDown,!0),this.domElement.addEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this._onPointerOverOut,!0),globalThis.addEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this._onPointerDown,!0),this.domElement.addEventListener("touchend",this._onPointerUp,!0),this.domElement.addEventListener("touchmove",this._onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;Bt.removeTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="",e.msTouchAction=""):this.supportsPointerEvents&&(e.touchAction="")),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this._onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this._onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this._onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this._onPointerMove,!0),this.domElement.removeEventListener("mousedown",this._onPointerDown,!0),this.domElement.removeEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this._onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this._onPointerDown,!0),this.domElement.removeEventListener("touchend",this._onPointerUp,!0),this.domElement.removeEventListener("touchmove",this._onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(e,t,i){const r=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},n=1/this.resolution;e.x=(t-r.left)*(this.domElement.width/r.width)*n,e.y=(i-r.top)*(this.domElement.height/r.height)*n}_normalizeToPointerData(e){const t=[];if(this.supportsTouchEvents&&e instanceof TouchEvent)for(let i=0,r=e.changedTouches.length;i<r;i++){const n=e.changedTouches[i];typeof n.button>"u"&&(n.button=0),typeof n.buttons>"u"&&(n.buttons=1),typeof n.isPrimary>"u"&&(n.isPrimary=e.touches.length===1&&e.type==="touchstart"),typeof n.width>"u"&&(n.width=n.radiusX||1),typeof n.height>"u"&&(n.height=n.radiusY||1),typeof n.tiltX>"u"&&(n.tiltX=0),typeof n.tiltY>"u"&&(n.tiltY=0),typeof n.pointerType>"u"&&(n.pointerType="touch"),typeof n.pointerId>"u"&&(n.pointerId=n.identifier||0),typeof n.pressure>"u"&&(n.pressure=n.force||.5),typeof n.twist>"u"&&(n.twist=0),typeof n.tangentialPressure>"u"&&(n.tangentialPressure=0),typeof n.layerX>"u"&&(n.layerX=n.offsetX=n.clientX),typeof n.layerY>"u"&&(n.layerY=n.offsetY=n.clientY),n.isNormalized=!0,n.type=e.type,n.altKey??(n.altKey=e.altKey),n.ctrlKey??(n.ctrlKey=e.ctrlKey),n.metaKey??(n.metaKey=e.metaKey),n.shiftKey??(n.shiftKey=e.shiftKey),t.push(n)}else if(!globalThis.MouseEvent||e instanceof MouseEvent&&(!this.supportsPointerEvents||!(e instanceof globalThis.PointerEvent))){const i=e;typeof i.isPrimary>"u"&&(i.isPrimary=!0),typeof i.width>"u"&&(i.width=1),typeof i.height>"u"&&(i.height=1),typeof i.tiltX>"u"&&(i.tiltX=0),typeof i.tiltY>"u"&&(i.tiltY=0),typeof i.pointerType>"u"&&(i.pointerType="mouse"),typeof i.pointerId>"u"&&(i.pointerId=iy),typeof i.pressure>"u"&&(i.pressure=.5),typeof i.twist>"u"&&(i.twist=0),typeof i.tangentialPressure>"u"&&(i.tangentialPressure=0),i.isNormalized=!0,t.push(i)}else t.push(e);return t}normalizeWheelEvent(e){const t=this._rootWheelEvent;return this._transferMouseData(t,e),t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ,t.deltaMode=e.deltaMode,this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.nativeEvent=e,t.type=e.type,t}_bootstrapEvent(e,t){return e.originalEvent=null,e.nativeEvent=t,e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist,this._transferMouseData(e,t),this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.isTrusted=t.isTrusted,e.type==="pointerleave"&&(e.type="pointerout"),e.type.startsWith("mouse")&&(e.type=e.type.replace("mouse","pointer")),e.type.startsWith("touch")&&(e.type=sy[e.type]||e.type),e}_transferMouseData(e,t){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.x=t.clientX,e.client.y=t.clientY,e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.x=t.movementX,e.movement.y=t.movementY,e.page.x=t.pageX,e.page.y=t.pageY,e.relatedTarget=null,e.shiftKey=t.shiftKey}};to.extension={name:"events",type:[A.WebGLSystem,A.CanvasSystem,A.WebGPUSystem],priority:-1},to.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let rh=to;const ry={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(s){this.eventMode=s?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??rh.defaultEventMode},set eventMode(s){this._internalEventMode=s},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(s,e,t){const i=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof t=="object"?t.signal:void 0,n=typeof t=="object"?t.once===!0:!1,o=typeof e=="function"?void 0:e;s=i?`${s}capture`:s;const a=typeof e=="function"?e:e.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(s,a,o)}),n?l.once(s,a,o):l.on(s,a,o)},removeEventListener(s,e,t){const i=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof e=="function"?void 0:e;s=i?`${s}capture`:s,e=typeof e=="function"?e:e.handleEvent,this.off(s,e,r)},dispatchEvent(s){if(!(s instanceof ns))throw new Error("Container cannot propagate events outside of the Federated Events API");return s.defaultPrevented=!1,s.path=null,s.target=this,s.manager.dispatchEvent(s),!s.defaultPrevented}};var ny=`in vec2 aPosition;
546
546
  out vec2 vTextureCoord;
547
547
 
548
548
  uniform vec4 uInputSize;
@@ -569,7 +569,7 @@ void main(void)
569
569
  gl_Position = filterVertexPosition();
570
570
  vTextureCoord = filterTextureCoord();
571
571
  }
572
- `,ny=`in vec2 vTextureCoord;
572
+ `,oy=`in vec2 vTextureCoord;
573
573
  out vec4 finalColor;
574
574
  uniform sampler2D uTexture;
575
575
  void main() {
@@ -624,7 +624,7 @@ fn mainFragment(
624
624
  ) -> @location(0) vec4<f32> {
625
625
  return textureSample(uTexture, uSampler, uv);
626
626
  }
627
- `;class oy extends Jl{constructor(){const e=oi.from({vertex:{source:nh,entryPoint:"mainVertex"},fragment:{source:nh,entryPoint:"mainFragment"},name:"passthrough-filter"}),t=Ii.from({vertex:ry,fragment:ny,name:"passthrough-filter"});super({gpuProgram:e,glProgram:t})}}class oh{constructor(e){this._renderer=e}push(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:t,filterEffect:e})}pop(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}execute(e){e.action==="pushFilter"?this._renderer.filter.push(e):e.action==="popFilter"&&this._renderer.filter.pop()}destroy(){this._renderer=null}}oh.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"filter"};const ah=new H;function ay(s,e){e.clear();const t=e.matrix;for(let i=0;i<s.length;i++){const r=s[i];if(r.globalDisplayStatus<7)continue;const n=r.renderGroup??r.parentRenderGroup;n!=null&&n.isCachedAsTexture?e.matrix=ah.copyFrom(n.textureOffsetInverseTransform).append(r.worldTransform):n!=null&&n._parentCacheAsTextureRenderGroup?e.matrix=ah.copyFrom(n._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(r.groupTransform):e.matrix=r.worldTransform,e.addBounds(r.bounds)}return e.matrix=t,e}const ly=new Js({attributes:{aPosition:{buffer:new Float32Array([0,0,1,0,1,1,0,1]),format:"float32x2",stride:8,offset:0}},indexBuffer:new Uint32Array([0,1,2,0,2,3])});class cy{constructor(){this.skip=!1,this.inputTexture=null,this.backTexture=null,this.filters=null,this.bounds=new Ye,this.container=null,this.blendRequired=!1,this.outputRenderSurface=null,this.globalFrame={x:0,y:0,width:0,height:0},this.firstEnabledIndex=-1,this.lastEnabledIndex=-1}}class lh{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new ht({uInputSize:{value:new Float32Array(4),type:"vec4<f32>"},uInputPixel:{value:new Float32Array(4),type:"vec4<f32>"},uInputClamp:{value:new Float32Array(4),type:"vec4<f32>"},uOutputFrame:{value:new Float32Array(4),type:"vec4<f32>"},uGlobalFrame:{value:new Float32Array(4),type:"vec4<f32>"},uOutputTexture:{value:new Float32Array(4),type:"vec4<f32>"}}),this._globalFilterBindGroup=new Gt({}),this.renderer=e}get activeBackTexture(){var e;return(e=this._activeFilterData)==null?void 0:e.backTexture}push(e){const t=this.renderer,i=e.filterEffect.filters,r=this._pushFilterData();r.skip=!1,r.filters=i,r.container=e.container,r.outputRenderSurface=t.renderTarget.renderSurface;const n=t.renderTarget.renderTarget.colorTexture.source,o=n.resolution,a=n.antialias;if(i.every(d=>!d.enabled)){r.skip=!0;return}const l=r.bounds;if(this._calculateFilterArea(e,l),this._calculateFilterBounds(r,t.renderTarget.rootViewPort,a,o,1),r.skip)return;const c=this._getPreviousFilterData(),h=this._findFilterResolution(o);let u=0,f=0;c&&(u=c.bounds.minX,f=c.bounds.minY),this._calculateGlobalFrame(r,u,f,h,n.width,n.height),this._setupFilterTextures(r,l,t,c)}generateFilteredTexture({texture:e,filters:t}){const i=this._pushFilterData();this._activeFilterData=i,i.skip=!1,i.filters=t;const r=e.source,n=r.resolution,o=r.antialias;if(t.every(d=>!d.enabled))return i.skip=!0,e;const a=i.bounds;if(a.addRect(e.frame),this._calculateFilterBounds(i,a.rectangle,o,n,0),i.skip)return e;const l=n;this._calculateGlobalFrame(i,0,0,l,r.width,r.height),i.outputRenderSurface=Qe.getOptimalTexture(a.width,a.height,i.resolution,i.antialias),i.backTexture=j.EMPTY,i.inputTexture=e,this.renderer.renderTarget.finishRenderPass(),this._applyFiltersToTexture(i,!0);const f=i.outputRenderSurface;return f.source.alphaMode="premultiplied-alpha",f}pop(){const e=this.renderer,t=this._popFilterData();t.skip||(e.globalUniforms.pop(),e.renderTarget.finishRenderPass(),this._activeFilterData=t,this._applyFiltersToTexture(t,!1),t.blendRequired&&Qe.returnTexture(t.backTexture),Qe.returnTexture(t.inputTexture))}getBackTexture(e,t,i){const r=e.colorTexture.source._resolution,n=Qe.getOptimalTexture(t.width,t.height,r,!1);let o=t.minX,a=t.minY;i&&(o-=i.minX,a-=i.minY),o=Math.floor(o*r),a=Math.floor(a*r);const l=Math.ceil(t.width*r),c=Math.ceil(t.height*r);return this.renderer.renderTarget.copyToTexture(e,n,{x:o,y:a},{width:l,height:c},{x:0,y:0}),n}applyFilter(e,t,i,r){const n=this.renderer,o=this._activeFilterData,l=o.outputRenderSurface===i,c=n.renderTarget.rootRenderTarget.colorTexture.source._resolution,h=this._findFilterResolution(c);let u=0,f=0;if(l){const g=this._findPreviousFilterOffset();u=g.x,f=g.y}this._updateFilterUniforms(t,i,o,u,f,h,l,r);const d=e.enabled?e:this._getPassthroughFilter();this._setupBindGroupsAndRender(d,t,n)}calculateSpriteMatrix(e,t){const i=this._activeFilterData,r=e.set(i.inputTexture._source.width,0,0,i.inputTexture._source.height,i.bounds.minX,i.bounds.minY),n=t.worldTransform.copyTo(H.shared),o=t.renderGroup||t.parentRenderGroup;return o&&o.cacheToLocalTransform&&n.prepend(o.cacheToLocalTransform),n.invert(),r.prepend(n),r.scale(1/t.texture.orig.width,1/t.texture.orig.height),r.translate(t.anchor.x,t.anchor.y),r}destroy(){var e;(e=this._passthroughFilter)==null||e.destroy(!0),this._passthroughFilter=null}_getPassthroughFilter(){return this._passthroughFilter??(this._passthroughFilter=new oy),this._passthroughFilter}_setupBindGroupsAndRender(e,t,i){if(i.renderPipes.uniformBatch){const r=i.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);this._globalFilterBindGroup.setResource(r,0)}else this._globalFilterBindGroup.setResource(this._filterGlobalUniforms,0);this._globalFilterBindGroup.setResource(t.source,1),this._globalFilterBindGroup.setResource(t.source.style,2),e.groups[0]=this._globalFilterBindGroup,i.encoder.draw({geometry:ly,shader:e,state:e._state,topology:"triangle-list"}),i.type===bt.WEBGL&&i.renderTarget.finishRenderPass()}_setupFilterTextures(e,t,i,r){if(e.backTexture=j.EMPTY,e.inputTexture=Qe.getOptimalTexture(t.width,t.height,e.resolution,e.antialias),e.blendRequired){i.renderTarget.finishRenderPass();const n=i.renderTarget.getRenderTarget(e.outputRenderSurface);e.backTexture=this.getBackTexture(n,t,r==null?void 0:r.bounds)}i.renderTarget.bind(e.inputTexture,!0),i.globalUniforms.push({offset:t})}_calculateGlobalFrame(e,t,i,r,n,o){const a=e.globalFrame;a.x=t*r,a.y=i*r,a.width=n*r,a.height=o*r}_updateFilterUniforms(e,t,i,r,n,o,a,l){const c=this._filterGlobalUniforms.uniforms,h=c.uOutputFrame,u=c.uInputSize,f=c.uInputPixel,d=c.uInputClamp,g=c.uGlobalFrame,_=c.uOutputTexture;a?(h[0]=i.bounds.minX-r,h[1]=i.bounds.minY-n):(h[0]=0,h[1]=0),h[2]=e.frame.width,h[3]=e.frame.height,u[0]=e.source.width,u[1]=e.source.height,u[2]=1/u[0],u[3]=1/u[1],f[0]=e.source.pixelWidth,f[1]=e.source.pixelHeight,f[2]=1/f[0],f[3]=1/f[1],d[0]=.5*f[2],d[1]=.5*f[3],d[2]=e.frame.width*u[2]-.5*f[2],d[3]=e.frame.height*u[3]-.5*f[3];const b=this.renderer.renderTarget.rootRenderTarget.colorTexture;g[0]=r*o,g[1]=n*o,g[2]=b.source.width*o,g[3]=b.source.height*o,t instanceof j&&(t.source.resource=null);const x=this.renderer.renderTarget.getRenderTarget(t);this.renderer.renderTarget.bind(t,!!l),t instanceof j?(_[0]=t.frame.width,_[1]=t.frame.height):(_[0]=x.width,_[1]=x.height),_[2]=x.isRoot?-1:1,this._filterGlobalUniforms.update()}_findFilterResolution(e){let t=this._filterStackIndex-1;for(;t>0&&this._filterStack[t].skip;)--t;return t>0&&this._filterStack[t].inputTexture?this._filterStack[t].inputTexture.source._resolution:e}_findPreviousFilterOffset(){let e=0,t=0,i=this._filterStackIndex;for(;i>0;){i--;const r=this._filterStack[i];if(!r.skip){e=r.bounds.minX,t=r.bounds.minY;break}}return{x:e,y:t}}_calculateFilterArea(e,t){if(e.renderables?ay(e.renderables,t):e.filterEffect.filterArea?(t.clear(),t.addRect(e.filterEffect.filterArea),t.applyMatrix(e.container.worldTransform)):e.container.getFastGlobalBounds(!0,t),e.container){const r=(e.container.renderGroup||e.container.parentRenderGroup).cacheToLocalTransform;r&&t.applyMatrix(r)}}_applyFiltersToTexture(e,t){const i=e.inputTexture,r=e.bounds,n=e.filters,o=e.firstEnabledIndex,a=e.lastEnabledIndex;if(this._globalFilterBindGroup.setResource(i.source.style,2),this._globalFilterBindGroup.setResource(e.backTexture.source,3),o===a)n[o].apply(this,i,e.outputRenderSurface,t);else{let l=e.inputTexture;const c=Qe.getOptimalTexture(r.width,r.height,l.source._resolution,!1);let h=c;for(let u=o;u<a;u++){const f=n[u];if(!f.enabled)continue;f.apply(this,l,h,!0);const d=l;l=h,h=d}n[a].apply(this,l,e.outputRenderSurface,t),Qe.returnTexture(c)}}_calculateFilterBounds(e,t,i,r,n){var x;const o=this.renderer,a=e.bounds,l=e.filters;let c=1/0,h=0,u=!0,f=!1,d=!1,g=!0,_=-1,b=-1;for(let C=0;C<l.length;C++){const S=l[C];if(!S.enabled)continue;if(_===-1&&(_=C),b=C,c=Math.min(c,S.resolution==="inherit"?r:S.resolution),h+=S.padding,S.antialias==="off"?u=!1:S.antialias==="inherit"&&u&&(u=i),S.clipToViewport||(g=!1),!!!(S.compatibleRenderers&o.type)){d=!1;break}if(S.blendRequired&&!(((x=o.backBuffer)==null?void 0:x.useBackBuffer)??!0)){se("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),d=!1;break}d=!0,f||(f=S.blendRequired)}if(!d){e.skip=!0;return}if(g&&a.fitBounds(0,t.width/r,0,t.height/r),a.scale(c).ceil().scale(1/c).pad((h|0)*n),!a.isPositive){e.skip=!0;return}e.antialias=u,e.resolution=c,e.blendRequired=f,e.firstEnabledIndex=_,e.lastEnabledIndex=b}_popFilterData(){return this._filterStackIndex--,this._filterStack[this._filterStackIndex]}_getPreviousFilterData(){let e,t=this._filterStackIndex-1;for(;t>0&&(t--,e=this._filterStack[t],!!e.skip););return e}_pushFilterData(){let e=this._filterStack[this._filterStackIndex];return e||(e=this._filterStack[this._filterStackIndex]=new cy),this._filterStackIndex++,e}}lh.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"filter"};var hy=`in vec2 vMaskCoord;
627
+ `;class ay extends Jl{constructor(){const e=oi.from({vertex:{source:nh,entryPoint:"mainVertex"},fragment:{source:nh,entryPoint:"mainFragment"},name:"passthrough-filter"}),t=Ii.from({vertex:ny,fragment:oy,name:"passthrough-filter"});super({gpuProgram:e,glProgram:t})}}class oh{constructor(e){this._renderer=e}push(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:t,filterEffect:e})}pop(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}execute(e){e.action==="pushFilter"?this._renderer.filter.push(e):e.action==="popFilter"&&this._renderer.filter.pop()}destroy(){this._renderer=null}}oh.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"filter"};const ah=new H;function ly(s,e){e.clear();const t=e.matrix;for(let i=0;i<s.length;i++){const r=s[i];if(r.globalDisplayStatus<7)continue;const n=r.renderGroup??r.parentRenderGroup;n!=null&&n.isCachedAsTexture?e.matrix=ah.copyFrom(n.textureOffsetInverseTransform).append(r.worldTransform):n!=null&&n._parentCacheAsTextureRenderGroup?e.matrix=ah.copyFrom(n._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(r.groupTransform):e.matrix=r.worldTransform,e.addBounds(r.bounds)}return e.matrix=t,e}const cy=new Qs({attributes:{aPosition:{buffer:new Float32Array([0,0,1,0,1,1,0,1]),format:"float32x2",stride:8,offset:0}},indexBuffer:new Uint32Array([0,1,2,0,2,3])});class hy{constructor(){this.skip=!1,this.inputTexture=null,this.backTexture=null,this.filters=null,this.bounds=new Ye,this.container=null,this.blendRequired=!1,this.outputRenderSurface=null,this.globalFrame={x:0,y:0,width:0,height:0},this.firstEnabledIndex=-1,this.lastEnabledIndex=-1}}class lh{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new ht({uInputSize:{value:new Float32Array(4),type:"vec4<f32>"},uInputPixel:{value:new Float32Array(4),type:"vec4<f32>"},uInputClamp:{value:new Float32Array(4),type:"vec4<f32>"},uOutputFrame:{value:new Float32Array(4),type:"vec4<f32>"},uGlobalFrame:{value:new Float32Array(4),type:"vec4<f32>"},uOutputTexture:{value:new Float32Array(4),type:"vec4<f32>"}}),this._globalFilterBindGroup=new Gt({}),this.renderer=e}get activeBackTexture(){var e;return(e=this._activeFilterData)==null?void 0:e.backTexture}push(e){const t=this.renderer,i=e.filterEffect.filters,r=this._pushFilterData();r.skip=!1,r.filters=i,r.container=e.container,r.outputRenderSurface=t.renderTarget.renderSurface;const n=t.renderTarget.renderTarget.colorTexture.source,o=n.resolution,a=n.antialias;if(i.every(d=>!d.enabled)){r.skip=!0;return}const l=r.bounds;if(this._calculateFilterArea(e,l),this._calculateFilterBounds(r,t.renderTarget.rootViewPort,a,o,1),r.skip)return;const c=this._getPreviousFilterData(),h=this._findFilterResolution(o);let u=0,f=0;c&&(u=c.bounds.minX,f=c.bounds.minY),this._calculateGlobalFrame(r,u,f,h,n.width,n.height),this._setupFilterTextures(r,l,t,c)}generateFilteredTexture({texture:e,filters:t}){const i=this._pushFilterData();this._activeFilterData=i,i.skip=!1,i.filters=t;const r=e.source,n=r.resolution,o=r.antialias;if(t.every(d=>!d.enabled))return i.skip=!0,e;const a=i.bounds;if(a.addRect(e.frame),this._calculateFilterBounds(i,a.rectangle,o,n,0),i.skip)return e;const l=n;this._calculateGlobalFrame(i,0,0,l,r.width,r.height),i.outputRenderSurface=Qe.getOptimalTexture(a.width,a.height,i.resolution,i.antialias),i.backTexture=j.EMPTY,i.inputTexture=e,this.renderer.renderTarget.finishRenderPass(),this._applyFiltersToTexture(i,!0);const f=i.outputRenderSurface;return f.source.alphaMode="premultiplied-alpha",f}pop(){const e=this.renderer,t=this._popFilterData();t.skip||(e.globalUniforms.pop(),e.renderTarget.finishRenderPass(),this._activeFilterData=t,this._applyFiltersToTexture(t,!1),t.blendRequired&&Qe.returnTexture(t.backTexture),Qe.returnTexture(t.inputTexture))}getBackTexture(e,t,i){const r=e.colorTexture.source._resolution,n=Qe.getOptimalTexture(t.width,t.height,r,!1);let o=t.minX,a=t.minY;i&&(o-=i.minX,a-=i.minY),o=Math.floor(o*r),a=Math.floor(a*r);const l=Math.ceil(t.width*r),c=Math.ceil(t.height*r);return this.renderer.renderTarget.copyToTexture(e,n,{x:o,y:a},{width:l,height:c},{x:0,y:0}),n}applyFilter(e,t,i,r){const n=this.renderer,o=this._activeFilterData,l=o.outputRenderSurface===i,c=n.renderTarget.rootRenderTarget.colorTexture.source._resolution,h=this._findFilterResolution(c);let u=0,f=0;if(l){const g=this._findPreviousFilterOffset();u=g.x,f=g.y}this._updateFilterUniforms(t,i,o,u,f,h,l,r);const d=e.enabled?e:this._getPassthroughFilter();this._setupBindGroupsAndRender(d,t,n)}calculateSpriteMatrix(e,t){const i=this._activeFilterData,r=e.set(i.inputTexture._source.width,0,0,i.inputTexture._source.height,i.bounds.minX,i.bounds.minY),n=t.worldTransform.copyTo(H.shared),o=t.renderGroup||t.parentRenderGroup;return o&&o.cacheToLocalTransform&&n.prepend(o.cacheToLocalTransform),n.invert(),r.prepend(n),r.scale(1/t.texture.orig.width,1/t.texture.orig.height),r.translate(t.anchor.x,t.anchor.y),r}destroy(){var e;(e=this._passthroughFilter)==null||e.destroy(!0),this._passthroughFilter=null}_getPassthroughFilter(){return this._passthroughFilter??(this._passthroughFilter=new ay),this._passthroughFilter}_setupBindGroupsAndRender(e,t,i){if(i.renderPipes.uniformBatch){const r=i.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);this._globalFilterBindGroup.setResource(r,0)}else this._globalFilterBindGroup.setResource(this._filterGlobalUniforms,0);this._globalFilterBindGroup.setResource(t.source,1),this._globalFilterBindGroup.setResource(t.source.style,2),e.groups[0]=this._globalFilterBindGroup,i.encoder.draw({geometry:cy,shader:e,state:e._state,topology:"triangle-list"}),i.type===bt.WEBGL&&i.renderTarget.finishRenderPass()}_setupFilterTextures(e,t,i,r){if(e.backTexture=j.EMPTY,e.inputTexture=Qe.getOptimalTexture(t.width,t.height,e.resolution,e.antialias),e.blendRequired){i.renderTarget.finishRenderPass();const n=i.renderTarget.getRenderTarget(e.outputRenderSurface);e.backTexture=this.getBackTexture(n,t,r==null?void 0:r.bounds)}i.renderTarget.bind(e.inputTexture,!0),i.globalUniforms.push({offset:t})}_calculateGlobalFrame(e,t,i,r,n,o){const a=e.globalFrame;a.x=t*r,a.y=i*r,a.width=n*r,a.height=o*r}_updateFilterUniforms(e,t,i,r,n,o,a,l){const c=this._filterGlobalUniforms.uniforms,h=c.uOutputFrame,u=c.uInputSize,f=c.uInputPixel,d=c.uInputClamp,g=c.uGlobalFrame,_=c.uOutputTexture;a?(h[0]=i.bounds.minX-r,h[1]=i.bounds.minY-n):(h[0]=0,h[1]=0),h[2]=e.frame.width,h[3]=e.frame.height,u[0]=e.source.width,u[1]=e.source.height,u[2]=1/u[0],u[3]=1/u[1],f[0]=e.source.pixelWidth,f[1]=e.source.pixelHeight,f[2]=1/f[0],f[3]=1/f[1],d[0]=.5*f[2],d[1]=.5*f[3],d[2]=e.frame.width*u[2]-.5*f[2],d[3]=e.frame.height*u[3]-.5*f[3];const y=this.renderer.renderTarget.rootRenderTarget.colorTexture;g[0]=r*o,g[1]=n*o,g[2]=y.source.width*o,g[3]=y.source.height*o,t instanceof j&&(t.source.resource=null);const x=this.renderer.renderTarget.getRenderTarget(t);this.renderer.renderTarget.bind(t,!!l),t instanceof j?(_[0]=t.frame.width,_[1]=t.frame.height):(_[0]=x.width,_[1]=x.height),_[2]=x.isRoot?-1:1,this._filterGlobalUniforms.update()}_findFilterResolution(e){let t=this._filterStackIndex-1;for(;t>0&&this._filterStack[t].skip;)--t;return t>0&&this._filterStack[t].inputTexture?this._filterStack[t].inputTexture.source._resolution:e}_findPreviousFilterOffset(){let e=0,t=0,i=this._filterStackIndex;for(;i>0;){i--;const r=this._filterStack[i];if(!r.skip){e=r.bounds.minX,t=r.bounds.minY;break}}return{x:e,y:t}}_calculateFilterArea(e,t){if(e.renderables?ly(e.renderables,t):e.filterEffect.filterArea?(t.clear(),t.addRect(e.filterEffect.filterArea),t.applyMatrix(e.container.worldTransform)):e.container.getFastGlobalBounds(!0,t),e.container){const r=(e.container.renderGroup||e.container.parentRenderGroup).cacheToLocalTransform;r&&t.applyMatrix(r)}}_applyFiltersToTexture(e,t){const i=e.inputTexture,r=e.bounds,n=e.filters,o=e.firstEnabledIndex,a=e.lastEnabledIndex;if(this._globalFilterBindGroup.setResource(i.source.style,2),this._globalFilterBindGroup.setResource(e.backTexture.source,3),o===a)n[o].apply(this,i,e.outputRenderSurface,t);else{let l=e.inputTexture;const c=Qe.getOptimalTexture(r.width,r.height,l.source._resolution,!1);let h=c;for(let u=o;u<a;u++){const f=n[u];if(!f.enabled)continue;f.apply(this,l,h,!0);const d=l;l=h,h=d}n[a].apply(this,l,e.outputRenderSurface,t),Qe.returnTexture(c)}}_calculateFilterBounds(e,t,i,r,n){var x;const o=this.renderer,a=e.bounds,l=e.filters;let c=1/0,h=0,u=!0,f=!1,d=!1,g=!0,_=-1,y=-1;for(let C=0;C<l.length;C++){const S=l[C];if(!S.enabled)continue;if(_===-1&&(_=C),y=C,c=Math.min(c,S.resolution==="inherit"?r:S.resolution),h+=S.padding,S.antialias==="off"?u=!1:S.antialias==="inherit"&&u&&(u=i),S.clipToViewport||(g=!1),!!!(S.compatibleRenderers&o.type)){d=!1;break}if(S.blendRequired&&!(((x=o.backBuffer)==null?void 0:x.useBackBuffer)??!0)){se("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),d=!1;break}d=!0,f||(f=S.blendRequired)}if(!d){e.skip=!0;return}if(g&&a.fitBounds(0,t.width/r,0,t.height/r),a.scale(c).ceil().scale(1/c).pad((h|0)*n),!a.isPositive){e.skip=!0;return}e.antialias=u,e.resolution=c,e.blendRequired=f,e.firstEnabledIndex=_,e.lastEnabledIndex=y}_popFilterData(){return this._filterStackIndex--,this._filterStack[this._filterStackIndex]}_getPreviousFilterData(){let e,t=this._filterStackIndex-1;for(;t>0&&(t--,e=this._filterStack[t],!!e.skip););return e}_pushFilterData(){let e=this._filterStack[this._filterStackIndex];return e||(e=this._filterStack[this._filterStackIndex]=new hy),this._filterStackIndex++,e}}lh.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"filter"};var uy=`in vec2 vMaskCoord;
628
628
  in vec2 vTextureCoord;
629
629
 
630
630
  uniform sampler2D uTexture;
@@ -658,7 +658,7 @@ void main(void)
658
658
 
659
659
  finalColor = original * a;
660
660
  }
661
- `,uy=`in vec2 aPosition;
661
+ `,dy=`in vec2 aPosition;
662
662
 
663
663
  out vec2 vTextureCoord;
664
664
  out vec2 vMaskCoord;
@@ -793,7 +793,7 @@ fn mainFragment(
793
793
 
794
794
  return source * a;
795
795
  }
796
- `;class dy extends Jl{constructor(e){const{sprite:t,...i}=e,r=new Qa(t.texture),n=new ht({uFilterMatrix:{value:new H,type:"mat3x3<f32>"},uMaskClamp:{value:r.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:e.inverse?1:0,type:"f32"}}),o=oi.from({vertex:{source:ch,entryPoint:"mainVertex"},fragment:{source:ch,entryPoint:"mainFragment"}}),a=Ii.from({vertex:uy,fragment:hy,name:"mask-filter"});super({...i,gpuProgram:o,glProgram:a,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=r}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=e?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}apply(e,t,i,r){this._textureMatrix.texture=this.sprite.texture,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,e.applyFilter(this,t,i,r)}}class fy{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class py{constructor(){this.instructions=new ln}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const io=class ua{constructor(e){this._renderer=e,this._managedContexts=new kt({renderer:e,type:"resource",name:"graphicsContext"})}init(e){ua.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??ua.defaultOptions.bezierSmoothness}getContextRenderData(e){return this.getGpuContext(e).graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=e._gpuData,i=!!t[this._renderer.uid],r=t[this._renderer.uid]||this._initContext(e);return(e.dirty||!i)&&(i&&r.reset(),r.isBatchable=!1,e.dirty=!1),r}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=new py,i=this.getGpuContext(e);return i.graphicsData=t,t.init(),t}_initContext(e){const t=new fy;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};io.extension={type:[A.CanvasSystem],name:"graphicsContext"},io.defaultOptions={bezierSmoothness:.5};let my=io;class hh{constructor(e,t){this.state=Pt.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new kt({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){return!1}addRenderable(e,t){this._managedGraphics.add(e),this.renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){e.isRenderable&&this._adaptor.execute(this,e)}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null}}hh.extension={type:[A.CanvasPipes],name:"graphics"};function uh(s,e,t){const i=(s>>24&255)/255;e[t++]=(s&255)/255*i,e[t++]=(s>>8&255)/255*i,e[t++]=(s>>16&255)/255*i,e[t++]=i}class gy{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{Le.return(e)}),this.batches.length=0}}class dh{constructor(e,t){this.state=Pt.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new kt({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){const t=e.context,i=!!e._gpuData,n=this.renderer.graphicsContext.updateGpuContext(t);return!!(n.isBatchable||i!==n.isBatchable)}addRenderable(e,t){const r=this.renderer.graphicsContext.updateGpuContext(e.context);e.didViewUpdate&&this._rebuild(e),r.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){const i=this._getGpuDataForRenderable(e).batches;for(let r=0;r<i.length;r++){const n=i[r];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;const t=this.renderer,i=e.context;if(!t.graphicsContext.getGpuContext(i).batches.length)return;const n=i.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;const o=n.resources.localUniforms.uniforms;o.uTransformMatrix=e.groupTransform,o.uRound=t._roundPixels|e._roundPixels,uh(e.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){const t=this._getGpuDataForRenderable(e),r=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),r.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){const i=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(e).batches;for(let n=0;n<r.length;n++){const o=r[n];i.addToBatch(o,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){const t=new gy;return e._gpuData[this.renderer.uid]=t,this._managedGraphics.add(e),t}_updateBatchesForRenderable(e,t){const i=e.context,n=this.renderer.graphicsContext.getGpuContext(i),o=this.renderer._roundPixels|e._roundPixels;t.batches=n.batches.map(a=>{const l=Le.get(jn);return a.copyTo(l),l.renderable=e,l.roundPixels=o,l})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}dh.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"graphics"},Q.add(hh),Q.add(dh),Q.add(my),Q.add(qn);class hr extends fl{constructor(e){e instanceof _s&&(e={context:e});const{context:t,roundPixels:i,...r}=e||{};super({label:"Graphics",...r}),this.renderPipeId="graphics",t?this.context=t:(this.context=this._ownedContext=new _s,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=i??!1}set context(e){e!==this._context&&(this._context&&(this._context.off("update",this.onViewUpdate,this),this._context.off("unload",this.unload,this)),this._context=e,this._context.on("update",this.onViewUpdate,this),this._context.on("unload",this.unload,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||(e==null?void 0:e.context)===!0)&&this._context.destroy(e),this._ownedContext=null,this._context=null,super.destroy(e)}_onTouch(e){this._gcLastUsed=e,this._context._gcLastUsed=e}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod("setFillStyle",e)}setStrokeStyle(...e){return this._callContextMethod("setStrokeStyle",e)}fill(...e){return this._callContextMethod("fill",e)}stroke(...e){return this._callContextMethod("stroke",e)}texture(...e){return this._callContextMethod("texture",e)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...e){return this._callContextMethod("arc",e)}arcTo(...e){return this._callContextMethod("arcTo",e)}arcToSvg(...e){return this._callContextMethod("arcToSvg",e)}bezierCurveTo(...e){return this._callContextMethod("bezierCurveTo",e)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...e){return this._callContextMethod("ellipse",e)}circle(...e){return this._callContextMethod("circle",e)}path(...e){return this._callContextMethod("path",e)}lineTo(...e){return this._callContextMethod("lineTo",e)}moveTo(...e){return this._callContextMethod("moveTo",e)}quadraticCurveTo(...e){return this._callContextMethod("quadraticCurveTo",e)}rect(...e){return this._callContextMethod("rect",e)}roundRect(...e){return this._callContextMethod("roundRect",e)}poly(...e){return this._callContextMethod("poly",e)}regularPoly(...e){return this._callContextMethod("regularPoly",e)}roundPoly(...e){return this._callContextMethod("roundPoly",e)}roundShape(...e){return this._callContextMethod("roundShape",e)}filletRect(...e){return this._callContextMethod("filletRect",e)}chamferRect(...e){return this._callContextMethod("chamferRect",e)}star(...e){return this._callContextMethod("star",e)}svg(...e){return this._callContextMethod("svg",e)}restore(...e){return this._callContextMethod("restore",e)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...e){return this._callContextMethod("rotate",e)}scaleTransform(...e){return this._callContextMethod("scale",e)}setTransform(...e){return this._callContextMethod("setTransform",e)}transform(...e){return this._callContextMethod("transform",e)}translateTransform(...e){return this._callContextMethod("translate",e)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(e=!1){return e?new hr(this._context.clone()):(this._ownedContext=null,new hr(this._context))}lineStyle(e,t,i){ee(Be,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const r={};return e&&(r.width=e),t&&(r.color=t),i&&(r.alpha=i),this.context.strokeStyle=r,this}beginFill(e,t){ee(Be,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const i={};return e!==void 0&&(i.color=e),t!==void 0&&(i.alpha=t),this.context.fillStyle=i,this}endFill(){ee(Be,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const e=this.context.strokeStyle;return(e.width!==_s.defaultStrokeStyle.width||e.color!==_s.defaultStrokeStyle.color||e.alpha!==_s.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return ee(Be,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return ee(Be,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return ee(Be,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return ee(Be,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return ee(Be,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return ee(Be,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}let ki;function fh(s){const e=pe.get().createCanvas(6,1),t=e.getContext("2d");return t.fillStyle=s,t.fillRect(0,0,6,1),e}function ph(){if(ki!==void 0)return ki;try{const s=fh("#ff00ff"),e=fh("#ffff00"),i=pe.get().createCanvas(6,1).getContext("2d");i.globalCompositeOperation="multiply",i.drawImage(s,0,0),i.drawImage(e,2,0);const r=i.getImageData(2,0,1,1);if(!r)ki=!1;else{const n=r.data;ki=n[0]===255&&n[1]===0&&n[2]===0}}catch{ki=!1}return ki}const ne={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:ph(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:s=>{const e=s.source,t=e==null?void 0:e.resource;if(!t)return null;const i=e.alphaMode==="premultiplied-alpha",r=e.resourceWidth??e.pixelWidth,n=e.resourceHeight??e.pixelHeight,o=r!==e.pixelWidth||n!==e.pixelHeight;if(i){if((t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)&&!o)return t;const a=ne._unpremultipliedCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas}if(t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||t instanceof Uint16Array||t instanceof Int16Array||t instanceof Uint32Array||t instanceof Int32Array||t instanceof Float32Array||t instanceof ArrayBuffer){const a=ne._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const l=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),c=l.getContext("2d"),h=c.createImageData(e.pixelWidth,e.pixelHeight),u=h.data,f=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(e.format==="bgra8unorm")for(let d=0;d<u.length&&d+3<f.length;d+=4)u[d]=f[d+2],u[d+1]=f[d+1],u[d+2]=f[d],u[d+3]=f[d+3];else u.set(f.subarray(0,u.length));return c.putImageData(h,0,0),ne._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}if(i){const a=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),l=a.getContext("2d",{willReadFrequently:!0});a.width=e.pixelWidth,a.height=e.pixelHeight,l.drawImage(t,0,0);const c=l.getImageData(0,0,a.width,a.height),h=c.data;for(let u=0;u<h.length;u+=4){const f=h[u+3];if(f>0){const d=255/f;h[u]=Math.min(255,h[u]*d+.5),h[u+1]=Math.min(255,h[u+1]*d+.5),h[u+2]=Math.min(255,h[u+2]*d+.5)}}return l.putImageData(c,0,0),ne._unpremultipliedCache.set(e,{canvas:a,resourceId:e._resourceId}),a}if(o){const a=ne._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const l=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),c=l.getContext("2d");return l.width=e.pixelWidth,l.height=e.pixelHeight,c.drawImage(t,0,0),ne._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}return t},getTintedCanvas:(s,e)=>{const t=s.texture,i=Pe.shared.setValue(e).toHex(),r=t.tintCache||(t.tintCache={}),n=r[i],o=t.source._resourceId;if((n==null?void 0:n.tintId)===o)return n;const a=n&&"getContext"in n?n:pe.get().createCanvas();return ne.tintMethod(t,e,a),a.tintId=o,r[i]=a,r[i]},getTintedPattern:(s,e)=>{const t=Pe.shared.setValue(e).toHex(),i=s.patternCache||(s.patternCache={}),r=s.source._resourceId;let n=i[t];return(n==null?void 0:n.tintId)===r||(ne.canvas||(ne.canvas=pe.get().createCanvas()),ne.tintMethod(s,e,ne.canvas),n=ne.canvas.getContext("2d").createPattern(ne.canvas,"repeat"),n.tintId=r,i[t]=n),n},applyPatternTransform:(s,e,t=!0)=>{if(!e)return;const i=s;if(!i.setTransform)return;const r=globalThis.DOMMatrix;if(!r)return;const n=new r([e.a,e.b,e.c,e.d,e.tx,e.ty]);i.setTransform(t?n.inverse():n)},tintWithMultiply:(s,e,t)=>{const i=t.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),i.save(),i.fillStyle=Pe.shared.setValue(e).toHex(),i.fillRect(0,0,l,c),i.globalCompositeOperation="multiply";const h=ne.getCanvasSource(s);if(!h){i.restore();return}o&&ne._applyInverseRotation(i,o,r.width,r.height),i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.globalCompositeOperation="destination-atop",i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore()},tintWithOverlay:(s,e,t)=>{const i=t.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),i.save(),i.globalCompositeOperation="copy",i.fillStyle=Pe.shared.setValue(e).toHex(),i.fillRect(0,0,l,c),i.globalCompositeOperation="destination-atop";const h=ne.getCanvasSource(s);if(!h){i.restore();return}o&&ne._applyInverseRotation(i,o,r.width,r.height),i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore()},tintWithPerPixel:(s,e,t)=>{const i=t.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),i.save(),i.globalCompositeOperation="copy";const h=ne.getCanvasSource(s);if(!h){i.restore();return}o&&ne._applyInverseRotation(i,o,r.width,r.height),i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore();const u=e>>16&255,f=e>>8&255,d=e&255,g=i.getImageData(0,0,l,c),_=g.data;for(let b=0;b<_.length;b+=4)_[b]=_[b]*u/255,_[b+1]=_[b+1]*f/255,_[b+2]=_[b+2]*d/255;i.putImageData(g,0,0)},_applyInverseRotation:(s,e,t,i)=>{const r=re.inv(e),n=re.uX(r),o=re.uY(r),a=re.vX(r),l=re.vY(r),c=-Math.min(0,n*t,a*i,n*t+a*i),h=-Math.min(0,o*t,l*i,o*t+l*i);s.transform(n,o,a,l,c,h)}};ne.tintMethod=ne.canUseMultiply?ne.tintWithMultiply:ne.tintWithPerPixel;const ur={name:"local-uniform-bit",vertex:{header:`
796
+ `;class fy extends Jl{constructor(e){const{sprite:t,...i}=e,r=new Qa(t.texture),n=new ht({uFilterMatrix:{value:new H,type:"mat3x3<f32>"},uMaskClamp:{value:r.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:e.inverse?1:0,type:"f32"}}),o=oi.from({vertex:{source:ch,entryPoint:"mainVertex"},fragment:{source:ch,entryPoint:"mainFragment"}}),a=Ii.from({vertex:dy,fragment:uy,name:"mask-filter"});super({...i,gpuProgram:o,glProgram:a,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=r}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=e?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}apply(e,t,i,r){this._textureMatrix.texture=this.sprite.texture,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,e.applyFilter(this,t,i,r)}}class py{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class my{constructor(){this.instructions=new ln}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const io=class ua{constructor(e){this._renderer=e,this._managedContexts=new kt({renderer:e,type:"resource",name:"graphicsContext"})}init(e){ua.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??ua.defaultOptions.bezierSmoothness}getContextRenderData(e){return this.getGpuContext(e).graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=e._gpuData,i=!!t[this._renderer.uid],r=t[this._renderer.uid]||this._initContext(e);return(e.dirty||!i)&&(i&&r.reset(),r.isBatchable=!1,e.dirty=!1),r}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=new my,i=this.getGpuContext(e);return i.graphicsData=t,t.init(),t}_initContext(e){const t=new py;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};io.extension={type:[A.CanvasSystem],name:"graphicsContext"},io.defaultOptions={bezierSmoothness:.5};let gy=io;class hh{constructor(e,t){this.state=Pt.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new kt({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){return!1}addRenderable(e,t){this._managedGraphics.add(e),this.renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){e.isRenderable&&this._adaptor.execute(this,e)}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null}}hh.extension={type:[A.CanvasPipes],name:"graphics"};function uh(s,e,t){const i=(s>>24&255)/255;e[t++]=(s&255)/255*i,e[t++]=(s>>8&255)/255*i,e[t++]=(s>>16&255)/255*i,e[t++]=i}class _y{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{Le.return(e)}),this.batches.length=0}}class dh{constructor(e,t){this.state=Pt.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new kt({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){const t=e.context,i=!!e._gpuData,n=this.renderer.graphicsContext.updateGpuContext(t);return!!(n.isBatchable||i!==n.isBatchable)}addRenderable(e,t){const r=this.renderer.graphicsContext.updateGpuContext(e.context);e.didViewUpdate&&this._rebuild(e),r.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){const i=this._getGpuDataForRenderable(e).batches;for(let r=0;r<i.length;r++){const n=i[r];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;const t=this.renderer,i=e.context;if(!t.graphicsContext.getGpuContext(i).batches.length)return;const n=i.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;const o=n.resources.localUniforms.uniforms;o.uTransformMatrix=e.groupTransform,o.uRound=t._roundPixels|e._roundPixels,uh(e.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){const t=this._getGpuDataForRenderable(e),r=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),r.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){const i=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(e).batches;for(let n=0;n<r.length;n++){const o=r[n];i.addToBatch(o,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){const t=new _y;return e._gpuData[this.renderer.uid]=t,this._managedGraphics.add(e),t}_updateBatchesForRenderable(e,t){const i=e.context,n=this.renderer.graphicsContext.getGpuContext(i),o=this.renderer._roundPixels|e._roundPixels;t.batches=n.batches.map(a=>{const l=Le.get(jn);return a.copyTo(l),l.renderable=e,l.roundPixels=o,l})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}dh.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"graphics"},Q.add(hh),Q.add(dh),Q.add(gy),Q.add(qn);class ur extends fl{constructor(e){e instanceof _s&&(e={context:e});const{context:t,roundPixels:i,...r}=e||{};super({label:"Graphics",...r}),this.renderPipeId="graphics",t?this.context=t:(this.context=this._ownedContext=new _s,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=i??!1}set context(e){e!==this._context&&(this._context&&(this._context.off("update",this.onViewUpdate,this),this._context.off("unload",this.unload,this)),this._context=e,this._context.on("update",this.onViewUpdate,this),this._context.on("unload",this.unload,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||(e==null?void 0:e.context)===!0)&&this._context.destroy(e),this._ownedContext=null,this._context=null,super.destroy(e)}_onTouch(e){this._gcLastUsed=e,this._context._gcLastUsed=e}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod("setFillStyle",e)}setStrokeStyle(...e){return this._callContextMethod("setStrokeStyle",e)}fill(...e){return this._callContextMethod("fill",e)}stroke(...e){return this._callContextMethod("stroke",e)}texture(...e){return this._callContextMethod("texture",e)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...e){return this._callContextMethod("arc",e)}arcTo(...e){return this._callContextMethod("arcTo",e)}arcToSvg(...e){return this._callContextMethod("arcToSvg",e)}bezierCurveTo(...e){return this._callContextMethod("bezierCurveTo",e)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...e){return this._callContextMethod("ellipse",e)}circle(...e){return this._callContextMethod("circle",e)}path(...e){return this._callContextMethod("path",e)}lineTo(...e){return this._callContextMethod("lineTo",e)}moveTo(...e){return this._callContextMethod("moveTo",e)}quadraticCurveTo(...e){return this._callContextMethod("quadraticCurveTo",e)}rect(...e){return this._callContextMethod("rect",e)}roundRect(...e){return this._callContextMethod("roundRect",e)}poly(...e){return this._callContextMethod("poly",e)}regularPoly(...e){return this._callContextMethod("regularPoly",e)}roundPoly(...e){return this._callContextMethod("roundPoly",e)}roundShape(...e){return this._callContextMethod("roundShape",e)}filletRect(...e){return this._callContextMethod("filletRect",e)}chamferRect(...e){return this._callContextMethod("chamferRect",e)}star(...e){return this._callContextMethod("star",e)}svg(...e){return this._callContextMethod("svg",e)}restore(...e){return this._callContextMethod("restore",e)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...e){return this._callContextMethod("rotate",e)}scaleTransform(...e){return this._callContextMethod("scale",e)}setTransform(...e){return this._callContextMethod("setTransform",e)}transform(...e){return this._callContextMethod("transform",e)}translateTransform(...e){return this._callContextMethod("translate",e)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(e=!1){return e?new ur(this._context.clone()):(this._ownedContext=null,new ur(this._context))}lineStyle(e,t,i){ee(Be,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const r={};return e&&(r.width=e),t&&(r.color=t),i&&(r.alpha=i),this.context.strokeStyle=r,this}beginFill(e,t){ee(Be,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const i={};return e!==void 0&&(i.color=e),t!==void 0&&(i.alpha=t),this.context.fillStyle=i,this}endFill(){ee(Be,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const e=this.context.strokeStyle;return(e.width!==_s.defaultStrokeStyle.width||e.color!==_s.defaultStrokeStyle.color||e.alpha!==_s.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return ee(Be,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return ee(Be,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return ee(Be,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return ee(Be,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return ee(Be,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return ee(Be,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}let ki;function fh(s){const e=pe.get().createCanvas(6,1),t=e.getContext("2d");return t.fillStyle=s,t.fillRect(0,0,6,1),e}function ph(){if(ki!==void 0)return ki;try{const s=fh("#ff00ff"),e=fh("#ffff00"),i=pe.get().createCanvas(6,1).getContext("2d");i.globalCompositeOperation="multiply",i.drawImage(s,0,0),i.drawImage(e,2,0);const r=i.getImageData(2,0,1,1);if(!r)ki=!1;else{const n=r.data;ki=n[0]===255&&n[1]===0&&n[2]===0}}catch{ki=!1}return ki}const ne={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:ph(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:s=>{const e=s.source,t=e==null?void 0:e.resource;if(!t)return null;const i=e.alphaMode==="premultiplied-alpha",r=e.resourceWidth??e.pixelWidth,n=e.resourceHeight??e.pixelHeight,o=r!==e.pixelWidth||n!==e.pixelHeight;if(i){if((t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)&&!o)return t;const a=ne._unpremultipliedCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas}if(t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||t instanceof Uint16Array||t instanceof Int16Array||t instanceof Uint32Array||t instanceof Int32Array||t instanceof Float32Array||t instanceof ArrayBuffer){const a=ne._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const l=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),c=l.getContext("2d"),h=c.createImageData(e.pixelWidth,e.pixelHeight),u=h.data,f=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(e.format==="bgra8unorm")for(let d=0;d<u.length&&d+3<f.length;d+=4)u[d]=f[d+2],u[d+1]=f[d+1],u[d+2]=f[d],u[d+3]=f[d+3];else u.set(f.subarray(0,u.length));return c.putImageData(h,0,0),ne._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}if(i){const a=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),l=a.getContext("2d",{willReadFrequently:!0});a.width=e.pixelWidth,a.height=e.pixelHeight,l.drawImage(t,0,0);const c=l.getImageData(0,0,a.width,a.height),h=c.data;for(let u=0;u<h.length;u+=4){const f=h[u+3];if(f>0){const d=255/f;h[u]=Math.min(255,h[u]*d+.5),h[u+1]=Math.min(255,h[u+1]*d+.5),h[u+2]=Math.min(255,h[u+2]*d+.5)}}return l.putImageData(c,0,0),ne._unpremultipliedCache.set(e,{canvas:a,resourceId:e._resourceId}),a}if(o){const a=ne._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const l=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),c=l.getContext("2d");return l.width=e.pixelWidth,l.height=e.pixelHeight,c.drawImage(t,0,0),ne._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}return t},getTintedCanvas:(s,e)=>{const t=s.texture,i=Pe.shared.setValue(e).toHex(),r=t.tintCache||(t.tintCache={}),n=r[i],o=t.source._resourceId;if((n==null?void 0:n.tintId)===o)return n;const a=n&&"getContext"in n?n:pe.get().createCanvas();return ne.tintMethod(t,e,a),a.tintId=o,r[i]=a,r[i]},getTintedPattern:(s,e)=>{const t=Pe.shared.setValue(e).toHex(),i=s.patternCache||(s.patternCache={}),r=s.source._resourceId;let n=i[t];return(n==null?void 0:n.tintId)===r||(ne.canvas||(ne.canvas=pe.get().createCanvas()),ne.tintMethod(s,e,ne.canvas),n=ne.canvas.getContext("2d").createPattern(ne.canvas,"repeat"),n.tintId=r,i[t]=n),n},applyPatternTransform:(s,e,t=!0)=>{if(!e)return;const i=s;if(!i.setTransform)return;const r=globalThis.DOMMatrix;if(!r)return;const n=new r([e.a,e.b,e.c,e.d,e.tx,e.ty]);i.setTransform(t?n.inverse():n)},tintWithMultiply:(s,e,t)=>{const i=t.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),i.save(),i.fillStyle=Pe.shared.setValue(e).toHex(),i.fillRect(0,0,l,c),i.globalCompositeOperation="multiply";const h=ne.getCanvasSource(s);if(!h){i.restore();return}o&&ne._applyInverseRotation(i,o,r.width,r.height),i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.globalCompositeOperation="destination-atop",i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore()},tintWithOverlay:(s,e,t)=>{const i=t.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),i.save(),i.globalCompositeOperation="copy",i.fillStyle=Pe.shared.setValue(e).toHex(),i.fillRect(0,0,l,c),i.globalCompositeOperation="destination-atop";const h=ne.getCanvasSource(s);if(!h){i.restore();return}o&&ne._applyInverseRotation(i,o,r.width,r.height),i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore()},tintWithPerPixel:(s,e,t)=>{const i=t.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),i.save(),i.globalCompositeOperation="copy";const h=ne.getCanvasSource(s);if(!h){i.restore();return}o&&ne._applyInverseRotation(i,o,r.width,r.height),i.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore();const u=e>>16&255,f=e>>8&255,d=e&255,g=i.getImageData(0,0,l,c),_=g.data;for(let y=0;y<_.length;y+=4)_[y]=_[y]*u/255,_[y+1]=_[y+1]*f/255,_[y+2]=_[y+2]*d/255;i.putImageData(g,0,0)},_applyInverseRotation:(s,e,t,i)=>{const r=re.inv(e),n=re.uX(r),o=re.uY(r),a=re.vX(r),l=re.vY(r),c=-Math.min(0,n*t,a*i,n*t+a*i),h=-Math.min(0,o*t,l*i,o*t+l*i);s.transform(n,o,a,l,c,h)}};ne.tintMethod=ne.canUseMultiply?ne.tintWithMultiply:ne.tintWithPerPixel;const dr={name:"local-uniform-bit",vertex:{header:`
797
797
 
798
798
  struct LocalUniforms {
799
799
  uTransformMatrix:mat3x3<f32>,
@@ -810,7 +810,7 @@ fn mainFragment(
810
810
  {
811
811
  vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
812
812
  }
813
- `}},_y={...ur,vertex:{...ur.vertex,header:ur.vertex.header.replace("group(1)","group(2)")}},mh={name:"local-uniform-bit",vertex:{header:`
813
+ `}},yy={...dr,vertex:{...dr.vertex,header:dr.vertex.header.replace("group(1)","group(2)")}},mh={name:"local-uniform-bit",vertex:{header:`
814
814
 
815
815
  uniform mat3 uTransformMatrix;
816
816
  uniform vec4 uColor;
@@ -823,7 +823,7 @@ fn mainFragment(
823
823
  {
824
824
  gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
825
825
  }
826
- `}};class yy{constructor(e){this._canvasPool=Object.create(null),this.canvasOptions=e||{},this.enableFullScreen=!1}_createCanvasAndContext(e,t){const i=pe.get().createCanvas();i.width=e,i.height=t;const r=i.getContext("2d");return{canvas:i,context:r}}getOptimalCanvasAndContext(e,t,i=1){e=Math.ceil(e*i-1e-6),t=Math.ceil(t*i-1e-6),e=Gs(e),t=Gs(t);const r=(e<<17)+(t<<1);this._canvasPool[r]||(this._canvasPool[r]=[]);let n=this._canvasPool[r].pop();return n||(n=this._createCanvasAndContext(e,t)),n}returnCanvasAndContext(e){const t=e.canvas,{width:i,height:r}=t,n=(i<<17)+(r<<1);e.context.resetTransform(),e.context.clearRect(0,0,i,r),this._canvasPool[n].push(e)}clear(){this._canvasPool={}}}const so=new yy;_i.register(so);class gh{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){this.reset()}}function by(){const{userAgent:s}=pe.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(s)}const ro=class di{static _getPatternRepeat(e,t){const i=e&&e!=="clamp-to-edge",r=t&&t!=="clamp-to-edge";return i&&r?"repeat":i?"repeat-x":r?"repeat-y":"no-repeat"}start(e,t,i){}execute(e,t){var a,l,c,h;const i=t.elements;if(!i||!i.length)return;const r=e.renderer,n=r.canvasContext,o=n.activeContext;for(let u=0;u<i.length;u++){const f=i[u];if(!f.packAsQuad)continue;const d=f,g=d.texture,_=g?ne.getCanvasSource(g):null;if(!_)continue;const b=g.source.style,x=n.smoothProperty,C=b.scaleMode!=="nearest";o[x]!==C&&(o[x]=C),n.setBlendMode(t.blendMode);const S=((a=r.globalUniforms.globalUniformData)==null?void 0:a.worldColor)??4294967295,E=d.color,w=(S>>>24&255)/255,R=(E>>>24&255)/255,M=((l=r.filter)==null?void 0:l.alphaMultiplier)??1,D=w*R*M;if(D<=0)continue;o.globalAlpha=D;const F=S&16777215,k=E&16777215,O=bi(yi(k,F)),V=g.frame,X=b.addressModeU??b.addressMode,z=b.addressModeV??b.addressMode,de=di._getPatternRepeat(X,z),B=g.source._resolution??g.source.resolution??1,U=(h=(c=d.renderable)==null?void 0:c.renderGroup)==null?void 0:h.isCachedAsTexture,q=V.x*B,N=V.y*B,K=V.width*B,Z=V.height*B,$=d.bounds,ae=r.renderTarget.renderTarget.isRoot,Ce=$.minX,Ee=$.minY,G=$.maxX-$.minX,fe=$.maxY-$.minY,le=g.rotate,L=g.uvs,me=Math.min(L.x0,L.x1,L.x2,L.x3,L.y0,L.y1,L.y2,L.y3),Y=Math.max(L.x0,L.x1,L.x2,L.x3,L.y0,L.y1,L.y2,L.y3),ie=de!=="no-repeat"&&(me<0||Y>1),ce=le&&!(!ie&&(O!==16777215||le));ce?(di._tempPatternMatrix.copyFrom(d.transform),re.matrixAppendRotationInv(di._tempPatternMatrix,le,Ce,Ee,G,fe),n.setContextTransform(di._tempPatternMatrix,d.roundPixels===1,void 0,U&&ae)):n.setContextTransform(d.transform,d.roundPixels===1,void 0,U&&ae);const He=ce?0:Ce,Qt=ce?0:Ee,Et=G,ui=fe;if(ie){let ji=_;const Ut=O!==16777215&&!le,pt=V.width<=g.source.width&&V.height<=g.source.height;Ut&&pt&&(ji=ne.getTintedCanvas({texture:g},O));const tt=o.createPattern(ji,de);if(!tt)continue;const Xi=Et,Or=ui;if(Xi===0||Or===0)continue;const mt=1/Xi,Br=1/Or,y=(L.x1-L.x0)*mt,p=(L.y1-L.y0)*mt,m=(L.x3-L.x0)*Br,v=(L.y3-L.y0)*Br,T=L.x0-y*He-m*Qt,I=L.y0-p*He-v*Qt,P=g.source.pixelWidth,J=g.source.pixelHeight;di._tempPatternMatrix.set(y*P,p*J,m*P,v*J,T*P,I*J),ne.applyPatternTransform(tt,di._tempPatternMatrix),o.fillStyle=tt,o.fillRect(He,Qt,Et,ui)}else{const Ut=O!==16777215||le?ne.getTintedCanvas({texture:g},O):_,pt=Ut!==_;o.drawImage(Ut,pt?0:q,pt?0:N,pt?Ut.width:K,pt?Ut.height:Z,He,Qt,Et,ui)}}}};ro._tempPatternMatrix=new H,ro.extension={type:[A.CanvasPipesAdaptor],name:"batch"};let xy=ro;class _h{constructor(){this._tempState=Pt.for2d(),this._didUploadHash={}}init(e){e.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(e,t,i){const r=e.renderer,n=this._didUploadHash[i.uid];r.shader.bind(i,n),n||(this._didUploadHash[i.uid]=!0),r.shader.updateUniformGroup(r.globalUniforms.uniformGroup),r.geometry.bind(t,i.glProgram)}execute(e,t){const i=e.renderer;this._tempState.blendMode=t.blendMode,i.state.set(this._tempState);const r=t.textures.textures;for(let n=0;n<t.textures.count;n++)i.texture.bind(r[n],n);i.geometry.draw(t.topology,t.size,t.start)}}_h.extension={type:[A.WebGLPipesAdaptor],name:"batch"};const dr=Pt.for2d();class yh{start(e,t,i){const r=e.renderer,n=r.encoder,o=i.gpuProgram;this._shader=i,this._geometry=t,n.setGeometry(t,o),dr.blendMode="normal",r.pipeline.getPipeline(t,o,dr);const a=r.globalUniforms.bindGroup;n.resetBindGroup(1),n.setBindGroup(0,a,o)}execute(e,t){const i=this._shader.gpuProgram,r=e.renderer,n=r.encoder;if(!t.bindGroup){const l=t.textures;t.bindGroup=Nn(l.textures,l.count,r.limits.maxBatchableTextures)}dr.blendMode=t.blendMode;const o=r.bindGroup.getBindGroup(t.bindGroup,i,1),a=r.pipeline.getPipeline(this._geometry,i,dr,t.topology);t.bindGroup._touch(r.gc.now,r.tick),n.setPipeline(a),n.renderPassEncoder.setBindGroup(1,o),n.renderPassEncoder.drawIndexed(t.size,1,t.start)}}yh.extension={type:[A.WebGPUPipesAdaptor],name:"batch"};const no=class xf{constructor(e,t){var i,r;this.state=Pt.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=e,this._adaptor=t,(r=(i=this._adaptor).init)==null||r.call(i,this)}static getBatcher(e){return new this._availableBatchers[e]}buildStart(e){let t=this._batchersByInstructionSet[e.uid];t||(t=this._batchersByInstructionSet[e.uid]=Object.create(null),t.default||(t.default=new $n({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=t,this._activeBatch=this._activeBatches.default;for(const i in this._activeBatches)this._activeBatches[i].begin()}addToBatch(e,t){if(this._activeBatch.name!==e.batcherName){this._activeBatch.break(t);let i=this._activeBatches[e.batcherName];i||(i=this._activeBatches[e.batcherName]=xf.getBatcher(e.batcherName),i.begin()),this._activeBatch=i}this._activeBatch.add(e)}break(e){this._activeBatch.break(e)}buildEnd(e){this._activeBatch.break(e);const t=this._activeBatches;for(const i in t){const r=t[i],n=r.geometry;n.indexBuffer.setDataWithSize(r.indexBuffer,r.indexSize,!0),n.buffers[0].setDataWithSize(r.attributeBuffer.float32View,r.attributeSize,!1)}}upload(e){const t=this._batchersByInstructionSet[e.uid];for(const i in t){const r=t[i],n=r.geometry;r.dirty&&(r.dirty=!1,n.buffers[0].update(r.attributeSize*4))}}execute(e){if(e.action==="startBatch"){const t=e.batcher,i=t.geometry,r=t.shader;this._adaptor.start(this,i,r)}this._adaptor.execute(this,e)}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const e in this._activeBatches)this._activeBatches[e].destroy();this._activeBatches=null}};no.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"batch"},no._availableBatchers=Object.create(null);let oo=no;Q.handleByMap(A.Batcher,oo._availableBatchers),Q.add($n);const vy={name:"texture-bit",vertex:{header:`
826
+ `}};class by{constructor(e){this._canvasPool=Object.create(null),this.canvasOptions=e||{},this.enableFullScreen=!1}_createCanvasAndContext(e,t){const i=pe.get().createCanvas();i.width=e,i.height=t;const r=i.getContext("2d");return{canvas:i,context:r}}getOptimalCanvasAndContext(e,t,i=1){e=Math.ceil(e*i-1e-6),t=Math.ceil(t*i-1e-6),e=Ls(e),t=Ls(t);const r=(e<<17)+(t<<1);this._canvasPool[r]||(this._canvasPool[r]=[]);let n=this._canvasPool[r].pop();return n||(n=this._createCanvasAndContext(e,t)),n}returnCanvasAndContext(e){const t=e.canvas,{width:i,height:r}=t,n=(i<<17)+(r<<1);e.context.resetTransform(),e.context.clearRect(0,0,i,r),this._canvasPool[n].push(e)}clear(){this._canvasPool={}}}const so=new by;_i.register(so);class gh{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){this.reset()}}function xy(){const{userAgent:s}=pe.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(s)}const ro=class di{static _getPatternRepeat(e,t){const i=e&&e!=="clamp-to-edge",r=t&&t!=="clamp-to-edge";return i&&r?"repeat":i?"repeat-x":r?"repeat-y":"no-repeat"}start(e,t,i){}execute(e,t){var a,l,c,h;const i=t.elements;if(!i||!i.length)return;const r=e.renderer,n=r.canvasContext,o=n.activeContext;for(let u=0;u<i.length;u++){const f=i[u];if(!f.packAsQuad)continue;const d=f,g=d.texture,_=g?ne.getCanvasSource(g):null;if(!_)continue;const y=g.source.style,x=n.smoothProperty,C=y.scaleMode!=="nearest";o[x]!==C&&(o[x]=C),n.setBlendMode(t.blendMode);const S=((a=r.globalUniforms.globalUniformData)==null?void 0:a.worldColor)??4294967295,E=d.color,w=(S>>>24&255)/255,R=(E>>>24&255)/255,M=((l=r.filter)==null?void 0:l.alphaMultiplier)??1,D=w*R*M;if(D<=0)continue;o.globalAlpha=D;const F=S&16777215,k=E&16777215,O=bi(yi(k,F)),V=g.frame,X=y.addressModeU??y.addressMode,z=y.addressModeV??y.addressMode,de=di._getPatternRepeat(X,z),B=g.source._resolution??g.source.resolution??1,U=(h=(c=d.renderable)==null?void 0:c.renderGroup)==null?void 0:h.isCachedAsTexture,q=V.x*B,N=V.y*B,K=V.width*B,Z=V.height*B,$=d.bounds,ae=r.renderTarget.renderTarget.isRoot,Ce=$.minX,Ee=$.minY,G=$.maxX-$.minX,fe=$.maxY-$.minY,le=g.rotate,L=g.uvs,me=Math.min(L.x0,L.x1,L.x2,L.x3,L.y0,L.y1,L.y2,L.y3),Y=Math.max(L.x0,L.x1,L.x2,L.x3,L.y0,L.y1,L.y2,L.y3),ie=de!=="no-repeat"&&(me<0||Y>1),ce=le&&!(!ie&&(O!==16777215||le));ce?(di._tempPatternMatrix.copyFrom(d.transform),re.matrixAppendRotationInv(di._tempPatternMatrix,le,Ce,Ee,G,fe),n.setContextTransform(di._tempPatternMatrix,d.roundPixels===1,void 0,U&&ae)):n.setContextTransform(d.transform,d.roundPixels===1,void 0,U&&ae);const He=ce?0:Ce,Qt=ce?0:Ee,Et=G,ui=fe;if(ie){let ji=_;const Ut=O!==16777215&&!le,pt=V.width<=g.source.width&&V.height<=g.source.height;Ut&&pt&&(ji=ne.getTintedCanvas({texture:g},O));const tt=o.createPattern(ji,de);if(!tt)continue;const Xi=Et,Br=ui;if(Xi===0||Br===0)continue;const mt=1/Xi,Dr=1/Br,b=(L.x1-L.x0)*mt,p=(L.y1-L.y0)*mt,m=(L.x3-L.x0)*Dr,v=(L.y3-L.y0)*Dr,T=L.x0-b*He-m*Qt,I=L.y0-p*He-v*Qt,P=g.source.pixelWidth,J=g.source.pixelHeight;di._tempPatternMatrix.set(b*P,p*J,m*P,v*J,T*P,I*J),ne.applyPatternTransform(tt,di._tempPatternMatrix),o.fillStyle=tt,o.fillRect(He,Qt,Et,ui)}else{const Ut=O!==16777215||le?ne.getTintedCanvas({texture:g},O):_,pt=Ut!==_;o.drawImage(Ut,pt?0:q,pt?0:N,pt?Ut.width:K,pt?Ut.height:Z,He,Qt,Et,ui)}}}};ro._tempPatternMatrix=new H,ro.extension={type:[A.CanvasPipesAdaptor],name:"batch"};let vy=ro;class _h{constructor(){this._tempState=Pt.for2d(),this._didUploadHash={}}init(e){e.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(e,t,i){const r=e.renderer,n=this._didUploadHash[i.uid];r.shader.bind(i,n),n||(this._didUploadHash[i.uid]=!0),r.shader.updateUniformGroup(r.globalUniforms.uniformGroup),r.geometry.bind(t,i.glProgram)}execute(e,t){const i=e.renderer;this._tempState.blendMode=t.blendMode,i.state.set(this._tempState);const r=t.textures.textures;for(let n=0;n<t.textures.count;n++)i.texture.bind(r[n],n);i.geometry.draw(t.topology,t.size,t.start)}}_h.extension={type:[A.WebGLPipesAdaptor],name:"batch"};const fr=Pt.for2d();class yh{start(e,t,i){const r=e.renderer,n=r.encoder,o=i.gpuProgram;this._shader=i,this._geometry=t,n.setGeometry(t,o),fr.blendMode="normal",r.pipeline.getPipeline(t,o,fr);const a=r.globalUniforms.bindGroup;n.resetBindGroup(1),n.setBindGroup(0,a,o)}execute(e,t){const i=this._shader.gpuProgram,r=e.renderer,n=r.encoder;if(!t.bindGroup){const l=t.textures;t.bindGroup=Nn(l.textures,l.count,r.limits.maxBatchableTextures)}fr.blendMode=t.blendMode;const o=r.bindGroup.getBindGroup(t.bindGroup,i,1),a=r.pipeline.getPipeline(this._geometry,i,fr,t.topology);t.bindGroup._touch(r.gc.now,r.tick),n.setPipeline(a),n.renderPassEncoder.setBindGroup(1,o),n.renderPassEncoder.drawIndexed(t.size,1,t.start)}}yh.extension={type:[A.WebGPUPipesAdaptor],name:"batch"};const no=class xf{constructor(e,t){var i,r;this.state=Pt.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=e,this._adaptor=t,(r=(i=this._adaptor).init)==null||r.call(i,this)}static getBatcher(e){return new this._availableBatchers[e]}buildStart(e){let t=this._batchersByInstructionSet[e.uid];t||(t=this._batchersByInstructionSet[e.uid]=Object.create(null),t.default||(t.default=new $n({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=t,this._activeBatch=this._activeBatches.default;for(const i in this._activeBatches)this._activeBatches[i].begin()}addToBatch(e,t){if(this._activeBatch.name!==e.batcherName){this._activeBatch.break(t);let i=this._activeBatches[e.batcherName];i||(i=this._activeBatches[e.batcherName]=xf.getBatcher(e.batcherName),i.begin()),this._activeBatch=i}this._activeBatch.add(e)}break(e){this._activeBatch.break(e)}buildEnd(e){this._activeBatch.break(e);const t=this._activeBatches;for(const i in t){const r=t[i],n=r.geometry;n.indexBuffer.setDataWithSize(r.indexBuffer,r.indexSize,!0),n.buffers[0].setDataWithSize(r.attributeBuffer.float32View,r.attributeSize,!1)}}upload(e){const t=this._batchersByInstructionSet[e.uid];for(const i in t){const r=t[i],n=r.geometry;r.dirty&&(r.dirty=!1,n.buffers[0].update(r.attributeSize*4))}}execute(e){if(e.action==="startBatch"){const t=e.batcher,i=t.geometry,r=t.shader;this._adaptor.start(this,i,r)}this._adaptor.execute(this,e)}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const e in this._activeBatches)this._activeBatches[e].destroy();this._activeBatches=null}};no.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"batch"},no._availableBatchers=Object.create(null);let oo=no;Q.handleByMap(A.Batcher,oo._availableBatchers),Q.add($n);const Cy={name:"texture-bit",vertex:{header:`
827
827
 
828
828
  struct TextureUniforms {
829
829
  uTextureMatrix:mat3x3<f32>,
@@ -839,7 +839,7 @@ fn mainFragment(
839
839
 
840
840
  `,main:`
841
841
  outColor = textureSample(uTexture, uSampler, vUV);
842
- `}},Cy={name:"texture-bit",vertex:{header:`
842
+ `}},Sy={name:"texture-bit",vertex:{header:`
843
843
  uniform mat3 uTextureMatrix;
844
844
  `,main:`
845
845
  uv = (uTextureMatrix * vec3(uv, 1.0)).xy;
@@ -849,9 +849,9 @@ fn mainFragment(
849
849
 
850
850
  `,main:`
851
851
  outColor = texture(uTexture, vUV);
852
- `}},Sy=new Ye;class Ey extends Vs{constructor(){super(),this.filters=[new dy({sprite:new Ft(j.EMPTY),inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(e){this.filters[0].sprite=e}get inverse(){return this.filters[0].inverse}set inverse(e){this.filters[0].inverse=e}}class ao{constructor(e){this._activeMaskStage=[],this._renderer=e}push(e,t,i){const r=this._renderer;if(r.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1,maskedContainer:t}),e.inverse=t._maskOptions.inverse,e.renderMaskToTexture){const n=e.mask;n.includeInBuild=!0,n.collectRenderables(i,r,null),n.includeInBuild=!1}r.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:e,maskedContainer:t,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){const t=this._renderer,i=e.mask.renderMaskToTexture;if(e.action==="pushMaskBegin"){const r=Le.get(Ey);if(r.inverse=e.inverse,i){e.mask.mask.measurable=!0;const n=nn(e.mask.mask,!0,Sy);e.mask.mask.measurable=!1,n.ceil();const o=t.renderTarget.renderTarget.colorTexture.source,a=Qe.getOptimalTexture(n.width,n.height,o._resolution,o.antialias);t.renderTarget.push(a,!0),t.globalUniforms.push({offset:n,worldColor:4294967295});const l=r.sprite;l.texture=a,l.worldTransform.tx=n.minX,l.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer,filterTexture:a})}else r.sprite=e.mask.mask,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer})}else if(e.action==="pushMaskEnd"){const r=this._activeMaskStage[this._activeMaskStage.length-1];i&&(t.type===bt.WEBGL&&t.renderTarget.finishRenderPass(),t.renderTarget.pop(),t.globalUniforms.pop()),t.filter.push({renderPipeId:"filter",action:"pushFilter",container:r.maskedContainer,filterEffect:r.filterEffect,canBundle:!1})}else if(e.action==="popMaskEnd"){t.filter.pop();const r=this._activeMaskStage.pop();i&&Qe.returnTexture(r.filterTexture),Le.return(r.filterEffect)}}destroy(){this._renderer=null,this._activeMaskStage=null}}ao.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"alphaMask"};class bh{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,i){this._renderer.renderPipes.batch.break(i);const r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&e.mask;const n=this._colorStack[this._colorStackIndex];n!==this._currentColor&&(this._currentColor=n,i.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1})),this._colorStackIndex++}pop(e,t,i){this._renderer.renderPipes.batch.break(i);const r=this._colorStack;this._colorStackIndex--;const n=r[this._colorStackIndex-1];n!==this._currentColor&&(this._currentColor=n,i.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}}bh.extension={type:[A.CanvasPipes],name:"colorMask"};class xh{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,i){this._renderer.renderPipes.batch.break(i);const n=this._colorStack;n[this._colorStackIndex]=n[this._colorStackIndex-1]&e.mask;const o=this._colorStack[this._colorStackIndex];o!==this._currentColor&&(this._currentColor=o,i.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1})),this._colorStackIndex++}pop(e,t,i){this._renderer.renderPipes.batch.break(i);const n=this._colorStack;this._colorStackIndex--;const o=n[this._colorStackIndex-1];o!==this._currentColor&&(this._currentColor=o,i.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1}))}execute(e){this._renderer.colorMask.setMask(e.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}xh.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"colorMask"};function Ty(s,e,t,i,r,n){n=Math.max(0,Math.min(n,Math.min(i,r)/2)),s.moveTo(e+n,t),s.lineTo(e+i-n,t),s.quadraticCurveTo(e+i,t,e+i,t+n),s.lineTo(e+i,t+r-n),s.quadraticCurveTo(e+i,t+r,e+i-n,t+r),s.lineTo(e+n,t+r),s.quadraticCurveTo(e,t+r,e,t+r-n),s.lineTo(e,t+n),s.quadraticCurveTo(e,t,e+n,t)}function vh(s,e){switch(e.type){case"rectangle":{const t=e;s.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;Ty(s,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;s.moveTo(t.x+t.radius,t.y),s.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;s.ellipse?(s.moveTo(t.x+t.halfWidth,t.y),s.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2)):(s.save(),s.translate(t.x,t.y),s.scale(t.halfWidth,t.halfHeight),s.moveTo(1,0),s.arc(0,0,1,0,Math.PI*2),s.restore());break}case"triangle":{const t=e;s.moveTo(t.x,t.y),s.lineTo(t.x2,t.y2),s.lineTo(t.x3,t.y3),s.closePath();break}case"polygon":default:{const t=e,i=t.points;if(!(i!=null&&i.length))break;s.moveTo(i[0],i[1]);for(let r=2;r<i.length;r+=2)s.lineTo(i[r],i[r+1]);t.closePath&&s.closePath();break}}}function Ay(s,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const i=e[t];if(!(i!=null&&i.shape))continue;const r=i.transform,n=r&&!r.isIdentity();n&&(s.save(),s.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),vh(s,i.shape),n&&s.restore()}return!0}class Ch{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){var h,u,f;if(e.action!=="pushMaskBegin"&&e.action!=="popMaskEnd")return;const t=this._renderer,i=t.canvasContext,r=i==null?void 0:i.activeContext;if(!r)return;if(e.action==="popMaskEnd"){this._canvasMaskStack.pop()&&r.restore();return}e.inverse&&this._warnOnce("inverse","CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.");const n=e.mask.mask;if(!(n instanceof hr)){this._warnOnce("nonGraphics","CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask."),this._canvasMaskStack.push(!1);return}const o=n,a=(h=o.context)==null?void 0:h.instructions;if(!(a!=null&&a.length)){this._canvasMaskStack.push(!1);return}r.save(),i.setContextTransform(o.groupTransform,(t._roundPixels|o._roundPixels)===1),r.beginPath();let l=!1,c=!1;for(let d=0;d<a.length;d++){const g=a[d],_=g.action;if(_!=="fill"&&_!=="stroke")continue;const b=g.data,x=(u=b==null?void 0:b.path)==null?void 0:u.shapePath;if(!((f=x==null?void 0:x.shapePrimitives)!=null&&f.length))continue;const C=x.shapePrimitives;for(let S=0;S<C.length;S++){const E=C[S];if(!(E!=null&&E.shape))continue;const w=E.transform,R=w&&!w.isIdentity();R&&(r.save(),r.transform(w.a,w.b,w.c,w.d,w.tx,w.ty)),vh(r,E.shape),c=Ay(r,E.holes)||c,l=!0,R&&r.restore()}}if(!l){r.restore(),this._canvasMaskStack.push(!1);return}c?r.clip("evenodd"):r.clip(),this._canvasMaskStack.push(!0)}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(e,t){this._warnedMaskTypes.has(e)||(this._warnedMaskTypes.add(e),se(t))}}Ch.extension={type:[A.CanvasPipes],name:"stencilMask"};class Sh{constructor(e){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=e}push(e,t,i){var r;const n=e,o=this._renderer;o.renderPipes.batch.break(i),o.renderPipes.blendMode.setBlendMode(n.mask,"none",i),i.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const a=n.mask;a.includeInBuild=!0,this._maskHash.has(n)||this._maskHash.set(n,{instructionsStart:0,instructionsLength:0});const l=this._maskHash.get(n);l.instructionsStart=i.instructionSize,a.collectRenderables(i,o,null),a.includeInBuild=!1,o.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const c=i.instructionSize-l.instructionsStart-1;l.instructionsLength=c;const h=o.renderTarget.renderTarget.uid;(r=this._maskStackHash)[h]??(r[h]=0)}pop(e,t,i){const r=e,n=this._renderer;n.renderPipes.batch.break(i),n.renderPipes.blendMode.setBlendMode(r.mask,"none",i),i.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:t._maskOptions.inverse,canBundle:!1});const o=this._maskHash.get(e);for(let a=0;a<o.instructionsLength;a++)i.instructions[i.instructionSize++]=i.instructions[o.instructionsStart++];i.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(e){var t;const i=this._renderer,r=i,n=i.renderTarget.renderTarget.uid;let o=(t=this._maskStackHash)[n]??(t[n]=0);e.action==="pushMaskBegin"?(r.renderTarget.ensureDepthStencil(),r.stencil.setStencilMode(ke.RENDERING_MASK_ADD,o),o++,r.colorMask.setMask(0)):e.action==="pushMaskEnd"?(e.inverse?r.stencil.setStencilMode(ke.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(ke.MASK_ACTIVE,o),r.colorMask.setMask(15)):e.action==="popMaskBegin"?(r.colorMask.setMask(0),o!==0?r.stencil.setStencilMode(ke.RENDERING_MASK_REMOVE,o):(r.renderTarget.clear(null,it.STENCIL),r.stencil.setStencilMode(ke.DISABLED,o)),o--):e.action==="popMaskEnd"&&(e.inverse?r.stencil.setStencilMode(ke.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(ke.MASK_ACTIVE,o),r.colorMask.setMask(15)),this._maskStackHash[n]=o}destroy(){this._renderer=null,this._maskStackHash=null,this._maskHash=null}}Sh.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"stencilMask"};const _e="source-over";function wy(){const s=ph(),e=Object.create(null);return e.inherit=_e,e.none=_e,e.normal="source-over",e.add="lighter",e.multiply=s?"multiply":_e,e.screen=s?"screen":_e,e.overlay=s?"overlay":_e,e.darken=s?"darken":_e,e.lighten=s?"lighten":_e,e["color-dodge"]=s?"color-dodge":_e,e["color-burn"]=s?"color-burn":_e,e["hard-light"]=s?"hard-light":_e,e["soft-light"]=s?"soft-light":_e,e.difference=s?"difference":_e,e.exclusion=s?"exclusion":_e,e.saturation=s?"saturation":_e,e.color=s?"color":_e,e.luminosity=s?"luminosity":_e,e["linear-burn"]=s?"color-burn":_e,e["linear-dodge"]=s?"color-dodge":_e,e["linear-light"]=s?"hard-light":_e,e["pin-light"]=s?"hard-light":_e,e["vivid-light"]=s?"hard-light":_e,e["hard-mix"]=_e,e.negation=s?"difference":_e,e["normal-npm"]=e.normal,e["add-npm"]=e.add,e["screen-npm"]=e.screen,e.erase="destination-out",e.subtract=_e,e.divide=_e,e.min=_e,e.max=_e,e}const Iy=new H;class Eh{constructor(e){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=wy(),this._activeBlendMode="normal",this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=e}resolutionChange(e){this.activeResolution=e}init(){const e=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext("2d",{alpha:e}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){const t=this.rootContext;t.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":t.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":t.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":t.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(e,t,i,r){var c;const n=r?H.IDENTITY:((c=this._renderer.globalUniforms.globalUniformData)==null?void 0:c.worldTransformMatrix)||H.IDENTITY;let o=Iy;o.copyFrom(n),o.append(e);const a=this._projTransform,l=this.activeResolution;if(i=i||l,a){const h=H.shared;h.copyFrom(o),h.prepend(a),o=h}t?this.activeContext.setTransform(o.a*i,o.b*i,o.c*i,o.d*i,o.tx*l|0,o.ty*l|0):this.activeContext.setTransform(o.a*i,o.b*i,o.c*i,o.d*i,o.tx*l,o.ty*l)}clear(e,t){const i=this.activeContext,r=this._renderer;if(i.clearRect(0,0,r.width,r.height),e){const n=Pe.shared.setValue(e);i.globalAlpha=t??n.alpha,i.fillStyle=n.toHex(),i.fillRect(0,0,r.width,r.height),i.globalAlpha=1}}setBlendMode(e){if(this._activeBlendMode===e)return;this._activeBlendMode=e,this._outerBlend=!1;const t=this.blendModes[e];if(!t){this._warnedBlendModes.has(e)||(console.warn(`CanvasRenderer: blend mode "${e}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(e)),this.activeContext.globalCompositeOperation="source-over";return}this.activeContext.globalCompositeOperation=t}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}}Eh.extension={type:[A.CanvasSystem],name:"canvasContext"};class Th{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}}Th.extension={type:[A.CanvasSystem],name:"limits"};class lo{constructor(e){this._renderer=e}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}execute(e){e.isRenderable&&e.render(this._renderer)}destroy(){this._renderer=null}}lo.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"customRender"};function co(s,e){const t=s.instructionSet,i=t.instructions;for(let r=0;r<t.instructionSize;r++){const n=i[r];e[n.renderPipeId].execute(n)}}class ho{constructor(e){this._renderer=e}addRenderGroup(e,t){e.isCachedAsTexture?this._addRenderableCacheAsTexture(e,t):this._addRenderableDirect(e,t)}execute(e){e.isRenderable&&(e.isCachedAsTexture?this._executeCacheAsTexture(e):this._executeDirect(e))}destroy(){this._renderer=null}_addRenderableDirect(e,t){this._renderer.renderPipes.batch.break(t),e._batchableRenderGroup&&(Le.return(e._batchableRenderGroup),e._batchableRenderGroup=null),t.add(e)}_addRenderableCacheAsTexture(e,t){const i=e._batchableRenderGroup??(e._batchableRenderGroup=Le.get(gh));i.renderable=e.root,i.transform=e.root.relativeGroupTransform,i.texture=e.texture,i.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(i,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;const t=new H().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push(e.texture,!0,null,e.texture.frame),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),co(e,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}e._batchableRenderGroup._batcher.updateElement(e._batchableRenderGroup),e._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(e){this._renderer.globalUniforms.push({worldTransformMatrix:e.inverseParentTextureTransform,worldColor:e.worldColorAlpha}),co(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}ho.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"renderGroup"};const Ry="#808080",fr=new H,My=new H,Py=new H,uo=new H;function ky(s,e,t){s.beginPath();for(let i=0;i<t.length;i+=3){const r=t[i]*2,n=t[i+1]*2,o=t[i+2]*2;s.moveTo(e[r],e[r+1]),s.lineTo(e[n],e[n+1]),s.lineTo(e[o],e[o+1]),s.closePath()}s.fill()}function Oy(s){return`#${(s&16777215).toString(16).padStart(6,"0")}`}function By(s,e,t,i,r,n){n=Math.max(0,Math.min(n,Math.min(i,r)/2)),s.moveTo(e+n,t),s.lineTo(e+i-n,t),s.quadraticCurveTo(e+i,t,e+i,t+n),s.lineTo(e+i,t+r-n),s.quadraticCurveTo(e+i,t+r,e+i-n,t+r),s.lineTo(e+n,t+r),s.quadraticCurveTo(e,t+r,e,t+r-n),s.lineTo(e,t+n),s.quadraticCurveTo(e,t,e+n,t)}function pr(s,e){switch(e.type){case"rectangle":{const t=e;s.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;By(s,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;s.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;s.ellipse?s.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2):(s.save(),s.translate(t.x,t.y),s.scale(t.halfWidth,t.halfHeight),s.arc(0,0,1,0,Math.PI*2),s.restore());break}case"triangle":{const t=e;s.moveTo(t.x,t.y),s.lineTo(t.x2,t.y2),s.lineTo(t.x3,t.y3),s.closePath();break}case"polygon":default:{const t=e,i=t.points;if(!(i!=null&&i.length))break;s.moveTo(i[0],i[1]);for(let r=2;r<i.length;r+=2)s.lineTo(i[r],i[r+1]);t.closePath&&s.closePath();break}}}function Dy(s,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const i=e[t];if(!(i!=null&&i.shape))continue;const r=i.transform,n=r&&!r.isIdentity();n&&(s.save(),s.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),pr(s,i.shape),n&&s.restore()}return!0}function Ny(s,e,t,i){const r=s.fill;if(r instanceof Mi){r.buildGradient();const o=r.texture;if(o){const a=ne.getTintedPattern(o,e),l=t?uo.copyFrom(t).scale(o.source.pixelWidth,o.source.pixelHeight):uo.copyFrom(r.transform);return i&&!s.textureSpace&&l.append(i),ne.applyPatternTransform(a,l),a}}if(r instanceof Kc){const o=ne.getTintedPattern(r.texture,e);return ne.applyPatternTransform(o,r.transform),o}const n=s.texture;if(n&&n!==j.WHITE){if(!n.source.resource)return Ry;const o=ne.getTintedPattern(n,e),a=t?uo.copyFrom(t).scale(n.source.pixelWidth,n.source.pixelHeight):s.matrix;return ne.applyPatternTransform(o,a),o}return Oy(e)}class Ah{constructor(){this.shader=null}contextChange(e){}execute(e,t){var C,S,E,w,R,M,D;const i=e.renderer,r=i.canvasContext,n=r.activeContext,o=t.groupTransform,a=((C=i.globalUniforms.globalUniformData)==null?void 0:C.worldColor)??4294967295,l=t.groupColorAlpha,c=(a>>>24&255)/255,h=(l>>>24&255)/255,u=((S=i.filter)==null?void 0:S.alphaMultiplier)??1,f=c*h*u;if(f<=0)return;const d=a&16777215,g=l&16777215,_=bi(yi(g,d)),b=i._roundPixels|t._roundPixels;n.save(),r.setContextTransform(o,b===1),r.setBlendMode(t.groupBlendMode);const x=t.context.instructions;for(let F=0;F<x.length;F++){const k=x[F];if(k.action==="texture"){const q=k.data,N=q.image,K=N?ne.getCanvasSource(N):null;if(!K)continue;const Z=q.alpha*f;if(Z<=0)continue;const $=yi(q.style,_);n.globalAlpha=Z;let ae=K;$!==16777215&&(ae=ne.getTintedCanvas({texture:N},$));const Ce=N.frame,Ee=N.source._resolution??N.source.resolution??1;let G=Ce.x*Ee,fe=Ce.y*Ee;const le=Ce.width*Ee,L=Ce.height*Ee;ae!==K&&(G=0,fe=0);const me=q.transform,Y=me&&!me.isIdentity(),ie=N.rotate;Y||ie?(fr.copyFrom(o),Y&&fr.append(me),ie&&re.matrixAppendRotationInv(fr,ie,q.dx,q.dy,q.dw,q.dh),r.setContextTransform(fr,b===1)):r.setContextTransform(o,b===1),n.drawImage(ae,G,fe,ae===K?le:ae.width,ae===K?L:ae.height,ie?0:q.dx,ie?0:q.dy,q.dw,q.dh),(Y||ie)&&r.setContextTransform(o,b===1);continue}const O=k.data,V=(E=O==null?void 0:O.path)==null?void 0:E.shapePath;if(!((w=V==null?void 0:V.shapePrimitives)!=null&&w.length))continue;const X=O.style,z=yi(X.color,_),de=X.alpha*f;if(de<=0)continue;const B=k.action==="stroke";if(n.globalAlpha=de,B){const q=X;n.lineWidth=q.width,n.lineCap=q.cap,n.lineJoin=q.join,n.miterLimit=q.miterLimit}const U=V.shapePrimitives;if(!B&&((D=(M=(R=O.hole)==null?void 0:R.shapePath)==null?void 0:M.shapePrimitives)!=null&&D.length)){const q=U[U.length-1];q.holes=O.hole.shapePath.shapePrimitives}for(let q=0;q<U.length;q++){const N=U[q];if(!(N!=null&&N.shape))continue;const K=N.transform,Z=K&&!K.isIdentity(),$=X.texture&&X.texture!==j.WHITE,ae=X.textureSpace==="global"?K:null,Ce=$?Fc(My,X,N.shape,ae):null,Ee=Z?Py.copyFrom(o).append(K):o,G=Ny(X,z,Ce,Ee);if(Z&&(n.save(),n.transform(K.a,K.b,K.c,K.d,K.tx,K.ty)),B){const fe=X;if(fe.alignment!==.5&&!fe.pixelLine){const L=[],me=[],Y=[],ie=fs[N.shape.type];if(ie!=null&&ie.build(N.shape,L)){const we=N.shape.closePath??!0;Oc(L,fe,!1,we,me,Y),n.fillStyle=G,ky(n,me,Y)}else n.strokeStyle=G,n.beginPath(),pr(n,N.shape),n.stroke()}else n.strokeStyle=G,n.beginPath(),pr(n,N.shape),n.stroke()}else n.fillStyle=G,n.beginPath(),pr(n,N.shape),Dy(n,N.holes)?n.fill("evenodd"):n.fill();Z&&n.restore()}}n.restore()}destroy(){this.shader=null}}Ah.extension={type:[A.CanvasPipesAdaptor],name:"graphics"};class fo{constructor(e){this._renderer=e}addRenderable(e,t){const i=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,i),this._renderer.renderPipes.batch.addToBatch(i,t)}updateRenderable(e){const t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){const t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.bounds=e.visualBounds,t.texture=e._texture}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){const t=new gh;return t.renderable=e,t.transform=e.groupTransform,t.texture=e._texture,t.bounds=e.visualBounds,t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}fo.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"sprite"};const bs={};Q.handle(A.BlendMode,s=>{if(!s.name)throw new Error("BlendMode extension must have a name property");bs[s.name]=s.ref},s=>{delete bs[s.name]});class po{constructor(e){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=e,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(e,t,i){this._blendModeStack.push(t),this.setBlendMode(e,t,i)}popBlendMode(e){this._blendModeStack.pop();const t=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,t,e)}setBlendMode(e,t,i){var n;const r=e instanceof un;if(this._activeBlendMode===t){this._isAdvanced&&e&&!r&&((n=this._renderableList)==null||n.push(e));return}this._isAdvanced&&this._endAdvancedBlendMode(i),this._activeBlendMode=t,e&&(this._isAdvanced=!!bs[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,i))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);const i=this._activeBlendMode;if(!bs[i]){se(`Unable to assign BlendMode: '${i}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const r=this._ensureFilterEffect(i),n=e instanceof un,o={renderPipeId:"filter",action:"pushFilter",filterEffect:r,renderables:n?null:[e],container:n?e.root:null,canBundle:!1};this._renderableList=o.renderables,t.add(o)}_ensureFilterEffect(e){let t=this._filterHash[e];return t||(t=this._filterHash[e]=new Vs,t.filters=[new bs[e]]),t}_endAdvancedBlendMode(e){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(e),e.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(e){this._isAdvanced&&this._endAdvancedBlendMode(e)}destroy(){this._renderer=null,this._renderableList=null;for(const e in this._filterHash)this._filterHash[e].destroy();this._filterHash=null}}po.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"blendMode"};function mo(s,e){e||(e=0);for(let t=e;t<s.length&&s[t];t++)s[t]=null}const Uy=new Ve,wh=Ji|qs|pn;function Ih(s,e=!1){Fy(s);const t=s.childrenToUpdate,i=s.updateTick++;for(const r in t){const n=Number(r),o=t[r],a=o.list,l=o.index;for(let c=0;c<l;c++){const h=a[c];h.parentRenderGroup===s&&h.relativeRenderGroupDepth===n&&Rh(h,i,0)}mo(a,l),o.index=0}if(e)for(let r=0;r<s.renderGroupChildren.length;r++)Ih(s.renderGroupChildren[r],e)}function Fy(s){const e=s.root;let t;if(s.renderGroupParent){const i=s.renderGroupParent;s.worldTransform.appendFrom(e.relativeGroupTransform,i.worldTransform),s.worldColor=$s(e.groupColor,i.worldColor),t=e.groupAlpha*i.worldAlpha}else s.worldTransform.copyFrom(e.localTransform),s.worldColor=e.localColor,t=e.localAlpha;t=t<0?0:t>1?1:t,s.worldAlpha=t,s.worldColorAlpha=s.worldColor+((t*255|0)<<24)}function Rh(s,e,t){if(e===s.updateTick)return;s.updateTick=e,s.didChange=!1;const i=s.localTransform;s.updateLocalTransform();const r=s.parent;if(r&&!r.renderGroup?(t|=s._updateFlags,s.relativeGroupTransform.appendFrom(i,r.relativeGroupTransform),t&wh&&Mh(s,r,t)):(t=s._updateFlags,s.relativeGroupTransform.copyFrom(i),t&wh&&Mh(s,Uy,t)),!s.renderGroup){const n=s.children,o=n.length;for(let c=0;c<o;c++)Rh(n[c],e,t);const a=s.parentRenderGroup,l=s;l.renderPipeId&&!a.structureDidChange&&a.updateRenderable(l)}}function Mh(s,e,t){if(t&qs){s.groupColor=$s(s.localColor,e.groupColor);let i=s.localAlpha*e.groupAlpha;i=i<0?0:i>1?1:i,s.groupAlpha=i,s.groupColorAlpha=s.groupColor+((i*255|0)<<24)}t&pn&&(s.groupBlendMode=s.localBlendMode==="inherit"?e.groupBlendMode:s.localBlendMode),t&Ji&&(s.globalDisplayStatus=s.localDisplayStatus&e.globalDisplayStatus),s._updateFlags=0}function Gy(s,e){const{list:t}=s.childrenRenderablesToUpdate;let i=!1;for(let r=0;r<s.childrenRenderablesToUpdate.index;r++){const n=t[r];if(i=e[n.renderPipeId].validateRenderable(n),i)break}return s.structureDidChange=i,i}const Ly=new H;class Ph{constructor(e){this._renderer=e}render({container:e,transform:t}){const i=e.parent,r=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;const n=this._renderer,o=Ly;t&&(o.copyFrom(e.renderGroup.localTransform),e.renderGroup.localTransform.copyFrom(t));const a=n.renderPipes;this._updateCachedRenderGroups(e.renderGroup,null),this._updateRenderGroups(e.renderGroup),n.globalUniforms.start({worldTransformMatrix:t?e.renderGroup.localTransform:e.renderGroup.worldTransform,worldColor:e.renderGroup.worldColorAlpha}),co(e.renderGroup,a),a.uniformBatch&&a.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(o),e.parent=i,e.renderGroup.renderGroupParent=r}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let i=e.renderGroupChildren.length-1;i>=0;i--)this._updateCachedRenderGroups(e.renderGroupChildren[i],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){const i=e.root.getLocalBounds(),r=this._renderer,n=e.textureOptions.resolution||r.view.resolution,o=e.textureOptions.antialias??r.view.antialias,a=e.textureOptions.scaleMode??"linear",l=e.texture;i.ceil(),e.texture&&Qe.returnTexture(e.texture,!0);const c=Qe.getOptimalTexture(i.width,i.height,n,o);c._source.style=new zr({scaleMode:a}),e.texture=c,e._textureBounds||(e._textureBounds=new Ye),e._textureBounds.copyFrom(i),l!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&(Qe.returnTexture(e.texture,!0),e.texture=null)}_updateRenderGroups(e){const t=this._renderer,i=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=i,e.structureDidChange?mo(e.childrenRenderablesToUpdate.list,0):Gy(e,i),Ih(e),e.structureDidChange?(e.structureDidChange=!1,this._buildInstructions(e,t)):this._updateRenderables(e),e.childrenRenderablesToUpdate.index=0,t.renderPipes.batch.upload(e.instructionSet),!(e.isCachedAsTexture&&!e.textureNeedsUpdate))for(let r=0;r<e.renderGroupChildren.length;r++)this._updateRenderGroups(e.renderGroupChildren[r])}_updateRenderables(e){const{list:t,index:i}=e.childrenRenderablesToUpdate;for(let r=0;r<i;r++){const n=t[r];n.didViewUpdate&&e.updateRenderable(n)}mo(t,i)}_buildInstructions(e,t){const i=e.root,r=e.instructionSet;r.reset();const n=t.renderPipes?t:t.batch.renderer,o=n.renderPipes;o.batch.buildStart(r),o.blendMode.buildStart(),o.colorMask.buildStart(),i.sortableChildren&&i.sortChildren(),i.collectRenderablesWithEffects(r,n,null),o.batch.buildEnd(r),o.blendMode.buildEnd(r)}}Ph.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"renderGroup"};const go=class vf{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new Pe(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={...vf.defaultOptions,...e},this.clearBeforeRender=e.clearBeforeRender,this.color=e.background||e.backgroundColor||this._backgroundColor,this.alpha=e.backgroundAlpha,this._backgroundColor.setAlpha(e.backgroundAlpha)}get color(){return this._backgroundColor}set color(e){Pe.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&se("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(e)}get alpha(){return this._backgroundColor.alpha}set alpha(e){this._backgroundColor.setAlpha(e)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};go.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"background",priority:0},go.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let Wy=go;const _o={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},yo=class Cf{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof Ve||e instanceof j?{target:e,...t}:{...t,...e}}async image(e){const t=pe.get().createImage();return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,Cf.defaultImageOptions);const{format:t,quality:i}=e,r=this.canvas(e);if(r.toBlob!==void 0)return new Promise((n,o)=>{r.toBlob(a=>{if(!a){o(new Error("ICanvas.toBlob failed!"));return}const l=new FileReader;l.onload=()=>n(l.result),l.onerror=o,l.readAsDataURL(a)},_o[t],i)});if(r.toDataURL!==void 0)return r.toDataURL(_o[t],i);if(r.convertToBlob!==void 0){const n=await r.convertToBlob({type:_o[t],quality:i});return new Promise((o,a)=>{const l=new FileReader;l.onload=()=>o(l.result),l.onerror=a,l.readAsDataURL(n)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(e){e=this._normalizeOptions(e);const t=e.target,i=this._renderer;if(t instanceof j)return i.texture.generateCanvas(t);const r=i.textureGenerator.generateTexture(e),n=i.texture.generateCanvas(r);return r.destroy(!0),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,i=this._renderer,r=t instanceof j?t:i.textureGenerator.generateTexture(e),n=i.texture.getPixels(r);return t instanceof Ve&&r.destroy(!0),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof j?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),i=document.createElement("a");i.download=e.filename??"image.png",i.href=t.toDataURL("image/png"),document.body.appendChild(i),i.click(),document.body.removeChild(i)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const i=this.canvas(e),r=i.toDataURL();console.log(`[Pixi Texture] ${i.width}px ${i.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${r}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};yo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"extract"},yo.defaultImageOptions={format:"png",quality:1};let Hy=yo;class bo extends j{static create(e){const{dynamic:t,...i}=e;return new bo({source:new De(i),dynamic:t??!1})}resize(e,t,i){return this.source.resize(e,t,i),this}}const Vy=new Se,zy=new Ye,$y=[0,0,0,0];class kh{constructor(e){this._renderer=e}generateTexture(e){var c;e instanceof Ve&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,i=e.antialias||this._renderer.view.antialias,r=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:Pe.shared.setValue(n).toArray():n=$y;const o=((c=e.frame)==null?void 0:c.copyTo(Vy))||an(r,zy).rectangle;o.width=Math.max(o.width,1/t)|0,o.height=Math.max(o.height,1/t)|0;const a=bo.create({...e.textureSourceOptions,width:o.width,height:o.height,resolution:t,antialias:i}),l=H.shared.translate(-o.x,-o.y);return this._renderer.render({container:r,transform:l,target:a,clearColor:n}),a.source.updateMipmaps(),a}destroy(){this._renderer=null}}kh.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"textureGenerator"};function jy(s){let e=!1;for(const i in s)if(s[i]==null){e=!0;break}if(!e)return s;const t=Object.create(null);for(const i in s){const r=s[i];r&&(t[i]=r)}return t}function Xy(s){let e=0;for(let t=0;t<s.length;t++)s[t]==null?e++:s[t-e]=s[t];return s.length-=e,s}const xo=class Sf{constructor(e){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._renderer=e}init(e){e={...Sf.defaultOptions,...e},this.maxUnusedTime=e.gcMaxUnusedTime,this._frequency=e.gcFrequency,this.enabled=e.gcActive,this.now=performance.now()}get enabled(){return!!this._handler}set enabled(e){this.enabled!==e&&(e?(this._handler=this._renderer.scheduler.repeat(()=>{this._ready=!0},this._frequency,!1),this._collectionsHandler=this._renderer.scheduler.repeat(()=>{for(const t of this._managedCollections){const{context:i,collection:r,type:n}=t;n==="hash"?i[r]=jy(i[r]):i[r]=Xy(i[r])}},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._collectionsHandler),this._handler=0,this._collectionsHandler=0))}prerender({container:e}){this.now=performance.now(),e.renderGroup.gcTick=this._renderer.tick++,this._updateInstructionGCTick(e.renderGroup,e.renderGroup.gcTick)}postrender(){!this._ready||!this.enabled||(this.run(),this._ready=!1)}_updateInstructionGCTick(e,t){e.instructionSet.gcTick=t,e.gcTick=t;for(const i of e.renderGroupChildren)this._updateInstructionGCTick(i,t)}addCollection(e,t,i){this._managedCollections.push({context:e,collection:t,type:i})}addResource(e,t){var r,n;if(e._gcLastUsed!==-1){e._gcLastUsed=this.now,(r=e._onTouch)==null||r.call(e,this.now);return}const i=this._managedResources.length;e._gcData={index:i,type:t},e._gcLastUsed=this.now,(n=e._onTouch)==null||n.call(e,this.now),e.once("unload",this.removeResource,this),this._managedResources.push(e)}removeResource(e){const t=e._gcData;if(!t)return;const i=t.index,r=this._managedResources.length-1;if(i!==r){const n=this._managedResources[r];this._managedResources[i]=n,n._gcData.index=i}this._managedResources.length--,e._gcData=null,e._gcLastUsed=-1}addResourceHash(e,t,i,r=0){this._managedResourceHashes.push({context:e,hash:t,type:i,priority:r}),this._managedResourceHashes.sort((n,o)=>n.priority-o.priority)}run(){const e=performance.now(),t=this._managedResourceHashes;for(const r of t)this.runOnHash(r,e);let i=0;for(let r=0;r<this._managedResources.length;r++){const n=this._managedResources[r];i=this.runOnResource(n,e,i)}this._managedResources.length=i}updateRenderableGCTick(e,t){var n,o;const i=e.renderGroup??e.parentRenderGroup,r=((n=i==null?void 0:i.instructionSet)==null?void 0:n.gcTick)??-1;((i==null?void 0:i.gcTick)??0)===r&&(e._gcLastUsed=t,(o=e._onTouch)==null||o.call(e,t))}runOnResource(e,t,i){const r=e._gcData;return r.type==="renderable"&&this.updateRenderableGCTick(e,t),t-e._gcLastUsed<this.maxUnusedTime||!e.autoGarbageCollect?(this._managedResources[i]=e,r.index=i,i++):(e.unload(),e._gcData=null,e._gcLastUsed=-1,e.off("unload",this.removeResource,this)),i}_createHashClone(e,t){const i=Object.create(null);for(const r in e){if(r===t)break;e[r]!==null&&(i[r]=e[r])}return i}runOnHash(e,t){var c;const{context:i,hash:r,type:n}=e,o=i[r];let a=null,l=0;for(const h in o){const u=o[h];if(u===null){l++,l===1e4&&!a&&(a=this._createHashClone(o,h));continue}if(u._gcLastUsed===-1){u._gcLastUsed=t,(c=u._onTouch)==null||c.call(u,t),a&&(a[h]=u);continue}if(n==="renderable"&&this.updateRenderableGCTick(u,t),!(t-u._gcLastUsed<this.maxUnusedTime)&&u.autoGarbageCollect){if(a||(l+1!==1e4?(o[h]=null,l++):a=this._createHashClone(o,h)),n==="renderable"){const d=u,g=d.renderGroup??d.parentRenderGroup;g&&(g.structureDidChange=!0)}u.unload(),u._gcData=null,u._gcLastUsed=-1}else a&&(a[h]=u)}a&&(i[r]=a)}destroy(){this.enabled=!1,this._managedResources.forEach(e=>{e.off("unload",this.removeResource,this)}),this._managedResources.length=0,this._managedResourceHashes.length=0,this._managedCollections.length=0,this._renderer=null}};xo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"gc",priority:0},xo.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4};let Yy=xo;class Oh{constructor(e){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=e}reset(){this._stackIndex=0;for(let e=0;e<this._activeUniforms.length;e++)this._uniformsPool.push(this._activeUniforms[e]);for(let e=0;e<this._activeBindGroups.length;e++)this._bindGroupPool.push(this._activeBindGroups[e]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(e){this.reset(),this.push(e)}bind({size:e,projectionMatrix:t,worldTransformMatrix:i,worldColor:r,offset:n}){const o=this._renderer.renderTarget.renderTarget,a=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new H,worldColor:4294967295,offset:new xe},l={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||o.size,worldTransformMatrix:i||a.worldTransformMatrix,worldColor:r||a.worldColor,offset:n||a.offset,bindGroup:null},c=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(c);const h=c.uniforms;h.uProjectionMatrix=l.projectionMatrix,h.uResolution=l.resolution,h.uWorldTransformMatrix.copyFrom(l.worldTransformMatrix),h.uWorldTransformMatrix.tx-=l.offset.x,h.uWorldTransformMatrix.ty-=l.offset.y,uh(l.worldColor,h.uWorldColorAlpha,0),c.update();let u;this._renderer.renderPipes.uniformBatch?u=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(c,!1):(u=this._bindGroupPool.pop()||new Gt,this._activeBindGroups.push(u),u.setResource(c,0)),l.bindGroup=u,this._currentGlobalUniformData=l}push(e){this.bind(e),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===bt.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new ht({uProjectionMatrix:{value:new H,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new H,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}Oh.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"globalUniforms"};let qy=1;class Bh{constructor(){this._tasks=[],this._offset=0}init(){at.system.add(this._update,this)}repeat(e,t,i=!0){const r=qy++;let n=0;return i&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:r}),r}cancel(e){for(let t=0;t<this._tasks.length;t++)if(this._tasks[t].id===e){this._tasks.splice(t,1);return}}_update(){const e=performance.now();for(let t=0;t<this._tasks.length;t++){const i=this._tasks[t];if(e-i.offset-i.last>=i.duration){const r=e-i.start;i.func(r),i.last=e}}}destroy(){at.system.remove(this._update,this),this._tasks.length=0}}Bh.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"scheduler",priority:0};let Dh=!1;function Ky(s){if(!Dh){if(pe.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c %c %c %c %c PixiJS %c v${nr} (${s}) http://www.pixijs.com/
852
+ `}},Ey=new Ye;class Ty extends zs{constructor(){super(),this.filters=[new fy({sprite:new Ft(j.EMPTY),inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(e){this.filters[0].sprite=e}get inverse(){return this.filters[0].inverse}set inverse(e){this.filters[0].inverse=e}}class ao{constructor(e){this._activeMaskStage=[],this._renderer=e}push(e,t,i){const r=this._renderer;if(r.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1,maskedContainer:t}),e.inverse=t._maskOptions.inverse,e.renderMaskToTexture){const n=e.mask;n.includeInBuild=!0,n.collectRenderables(i,r,null),n.includeInBuild=!1}r.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:e,maskedContainer:t,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){const t=this._renderer,i=e.mask.renderMaskToTexture;if(e.action==="pushMaskBegin"){const r=Le.get(Ty);if(r.inverse=e.inverse,i){e.mask.mask.measurable=!0;const n=nn(e.mask.mask,!0,Ey);e.mask.mask.measurable=!1,n.ceil();const o=t.renderTarget.renderTarget.colorTexture.source,a=Qe.getOptimalTexture(n.width,n.height,o._resolution,o.antialias);t.renderTarget.push(a,!0),t.globalUniforms.push({offset:n,worldColor:4294967295});const l=r.sprite;l.texture=a,l.worldTransform.tx=n.minX,l.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer,filterTexture:a})}else r.sprite=e.mask.mask,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer})}else if(e.action==="pushMaskEnd"){const r=this._activeMaskStage[this._activeMaskStage.length-1];i&&(t.type===bt.WEBGL&&t.renderTarget.finishRenderPass(),t.renderTarget.pop(),t.globalUniforms.pop()),t.filter.push({renderPipeId:"filter",action:"pushFilter",container:r.maskedContainer,filterEffect:r.filterEffect,canBundle:!1})}else if(e.action==="popMaskEnd"){t.filter.pop();const r=this._activeMaskStage.pop();i&&Qe.returnTexture(r.filterTexture),Le.return(r.filterEffect)}}destroy(){this._renderer=null,this._activeMaskStage=null}}ao.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"alphaMask"};class bh{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,i){this._renderer.renderPipes.batch.break(i);const r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&e.mask;const n=this._colorStack[this._colorStackIndex];n!==this._currentColor&&(this._currentColor=n,i.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1})),this._colorStackIndex++}pop(e,t,i){this._renderer.renderPipes.batch.break(i);const r=this._colorStack;this._colorStackIndex--;const n=r[this._colorStackIndex-1];n!==this._currentColor&&(this._currentColor=n,i.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}}bh.extension={type:[A.CanvasPipes],name:"colorMask"};class xh{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,i){this._renderer.renderPipes.batch.break(i);const n=this._colorStack;n[this._colorStackIndex]=n[this._colorStackIndex-1]&e.mask;const o=this._colorStack[this._colorStackIndex];o!==this._currentColor&&(this._currentColor=o,i.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1})),this._colorStackIndex++}pop(e,t,i){this._renderer.renderPipes.batch.break(i);const n=this._colorStack;this._colorStackIndex--;const o=n[this._colorStackIndex-1];o!==this._currentColor&&(this._currentColor=o,i.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1}))}execute(e){this._renderer.colorMask.setMask(e.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}xh.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"colorMask"};function Ay(s,e,t,i,r,n){n=Math.max(0,Math.min(n,Math.min(i,r)/2)),s.moveTo(e+n,t),s.lineTo(e+i-n,t),s.quadraticCurveTo(e+i,t,e+i,t+n),s.lineTo(e+i,t+r-n),s.quadraticCurveTo(e+i,t+r,e+i-n,t+r),s.lineTo(e+n,t+r),s.quadraticCurveTo(e,t+r,e,t+r-n),s.lineTo(e,t+n),s.quadraticCurveTo(e,t,e+n,t)}function vh(s,e){switch(e.type){case"rectangle":{const t=e;s.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;Ay(s,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;s.moveTo(t.x+t.radius,t.y),s.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;s.ellipse?(s.moveTo(t.x+t.halfWidth,t.y),s.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2)):(s.save(),s.translate(t.x,t.y),s.scale(t.halfWidth,t.halfHeight),s.moveTo(1,0),s.arc(0,0,1,0,Math.PI*2),s.restore());break}case"triangle":{const t=e;s.moveTo(t.x,t.y),s.lineTo(t.x2,t.y2),s.lineTo(t.x3,t.y3),s.closePath();break}case"polygon":default:{const t=e,i=t.points;if(!(i!=null&&i.length))break;s.moveTo(i[0],i[1]);for(let r=2;r<i.length;r+=2)s.lineTo(i[r],i[r+1]);t.closePath&&s.closePath();break}}}function wy(s,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const i=e[t];if(!(i!=null&&i.shape))continue;const r=i.transform,n=r&&!r.isIdentity();n&&(s.save(),s.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),vh(s,i.shape),n&&s.restore()}return!0}class Ch{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){var h,u,f;if(e.action!=="pushMaskBegin"&&e.action!=="popMaskEnd")return;const t=this._renderer,i=t.canvasContext,r=i==null?void 0:i.activeContext;if(!r)return;if(e.action==="popMaskEnd"){this._canvasMaskStack.pop()&&r.restore();return}e.inverse&&this._warnOnce("inverse","CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.");const n=e.mask.mask;if(!(n instanceof ur)){this._warnOnce("nonGraphics","CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask."),this._canvasMaskStack.push(!1);return}const o=n,a=(h=o.context)==null?void 0:h.instructions;if(!(a!=null&&a.length)){this._canvasMaskStack.push(!1);return}r.save(),i.setContextTransform(o.groupTransform,(t._roundPixels|o._roundPixels)===1),r.beginPath();let l=!1,c=!1;for(let d=0;d<a.length;d++){const g=a[d],_=g.action;if(_!=="fill"&&_!=="stroke")continue;const y=g.data,x=(u=y==null?void 0:y.path)==null?void 0:u.shapePath;if(!((f=x==null?void 0:x.shapePrimitives)!=null&&f.length))continue;const C=x.shapePrimitives;for(let S=0;S<C.length;S++){const E=C[S];if(!(E!=null&&E.shape))continue;const w=E.transform,R=w&&!w.isIdentity();R&&(r.save(),r.transform(w.a,w.b,w.c,w.d,w.tx,w.ty)),vh(r,E.shape),c=wy(r,E.holes)||c,l=!0,R&&r.restore()}}if(!l){r.restore(),this._canvasMaskStack.push(!1);return}c?r.clip("evenodd"):r.clip(),this._canvasMaskStack.push(!0)}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(e,t){this._warnedMaskTypes.has(e)||(this._warnedMaskTypes.add(e),se(t))}}Ch.extension={type:[A.CanvasPipes],name:"stencilMask"};class Sh{constructor(e){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=e}push(e,t,i){var r;const n=e,o=this._renderer;o.renderPipes.batch.break(i),o.renderPipes.blendMode.setBlendMode(n.mask,"none",i),i.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const a=n.mask;a.includeInBuild=!0,this._maskHash.has(n)||this._maskHash.set(n,{instructionsStart:0,instructionsLength:0});const l=this._maskHash.get(n);l.instructionsStart=i.instructionSize,a.collectRenderables(i,o,null),a.includeInBuild=!1,o.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const c=i.instructionSize-l.instructionsStart-1;l.instructionsLength=c;const h=o.renderTarget.renderTarget.uid;(r=this._maskStackHash)[h]??(r[h]=0)}pop(e,t,i){const r=e,n=this._renderer;n.renderPipes.batch.break(i),n.renderPipes.blendMode.setBlendMode(r.mask,"none",i),i.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:t._maskOptions.inverse,canBundle:!1});const o=this._maskHash.get(e);for(let a=0;a<o.instructionsLength;a++)i.instructions[i.instructionSize++]=i.instructions[o.instructionsStart++];i.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(e){var t;const i=this._renderer,r=i,n=i.renderTarget.renderTarget.uid;let o=(t=this._maskStackHash)[n]??(t[n]=0);e.action==="pushMaskBegin"?(r.renderTarget.ensureDepthStencil(),r.stencil.setStencilMode(ke.RENDERING_MASK_ADD,o),o++,r.colorMask.setMask(0)):e.action==="pushMaskEnd"?(e.inverse?r.stencil.setStencilMode(ke.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(ke.MASK_ACTIVE,o),r.colorMask.setMask(15)):e.action==="popMaskBegin"?(r.colorMask.setMask(0),o!==0?r.stencil.setStencilMode(ke.RENDERING_MASK_REMOVE,o):(r.renderTarget.clear(null,it.STENCIL),r.stencil.setStencilMode(ke.DISABLED,o)),o--):e.action==="popMaskEnd"&&(e.inverse?r.stencil.setStencilMode(ke.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(ke.MASK_ACTIVE,o),r.colorMask.setMask(15)),this._maskStackHash[n]=o}destroy(){this._renderer=null,this._maskStackHash=null,this._maskHash=null}}Sh.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"stencilMask"};const _e="source-over";function Iy(){const s=ph(),e=Object.create(null);return e.inherit=_e,e.none=_e,e.normal="source-over",e.add="lighter",e.multiply=s?"multiply":_e,e.screen=s?"screen":_e,e.overlay=s?"overlay":_e,e.darken=s?"darken":_e,e.lighten=s?"lighten":_e,e["color-dodge"]=s?"color-dodge":_e,e["color-burn"]=s?"color-burn":_e,e["hard-light"]=s?"hard-light":_e,e["soft-light"]=s?"soft-light":_e,e.difference=s?"difference":_e,e.exclusion=s?"exclusion":_e,e.saturation=s?"saturation":_e,e.color=s?"color":_e,e.luminosity=s?"luminosity":_e,e["linear-burn"]=s?"color-burn":_e,e["linear-dodge"]=s?"color-dodge":_e,e["linear-light"]=s?"hard-light":_e,e["pin-light"]=s?"hard-light":_e,e["vivid-light"]=s?"hard-light":_e,e["hard-mix"]=_e,e.negation=s?"difference":_e,e["normal-npm"]=e.normal,e["add-npm"]=e.add,e["screen-npm"]=e.screen,e.erase="destination-out",e.subtract=_e,e.divide=_e,e.min=_e,e.max=_e,e}const Ry=new H;class Eh{constructor(e){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=Iy(),this._activeBlendMode="normal",this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=e}resolutionChange(e){this.activeResolution=e}init(){const e=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext("2d",{alpha:e}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){const t=this.rootContext;t.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":t.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":t.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":t.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(e,t,i,r){var c;const n=r?H.IDENTITY:((c=this._renderer.globalUniforms.globalUniformData)==null?void 0:c.worldTransformMatrix)||H.IDENTITY;let o=Ry;o.copyFrom(n),o.append(e);const a=this._projTransform,l=this.activeResolution;if(i=i||l,a){const h=H.shared;h.copyFrom(o),h.prepend(a),o=h}t?this.activeContext.setTransform(o.a*i,o.b*i,o.c*i,o.d*i,o.tx*l|0,o.ty*l|0):this.activeContext.setTransform(o.a*i,o.b*i,o.c*i,o.d*i,o.tx*l,o.ty*l)}clear(e,t){const i=this.activeContext,r=this._renderer;if(i.clearRect(0,0,r.width,r.height),e){const n=Pe.shared.setValue(e);i.globalAlpha=t??n.alpha,i.fillStyle=n.toHex(),i.fillRect(0,0,r.width,r.height),i.globalAlpha=1}}setBlendMode(e){if(this._activeBlendMode===e)return;this._activeBlendMode=e,this._outerBlend=!1;const t=this.blendModes[e];if(!t){this._warnedBlendModes.has(e)||(console.warn(`CanvasRenderer: blend mode "${e}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(e)),this.activeContext.globalCompositeOperation="source-over";return}this.activeContext.globalCompositeOperation=t}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}}Eh.extension={type:[A.CanvasSystem],name:"canvasContext"};class Th{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}}Th.extension={type:[A.CanvasSystem],name:"limits"};class lo{constructor(e){this._renderer=e}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}execute(e){e.isRenderable&&e.render(this._renderer)}destroy(){this._renderer=null}}lo.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"customRender"};function co(s,e){const t=s.instructionSet,i=t.instructions;for(let r=0;r<t.instructionSize;r++){const n=i[r];e[n.renderPipeId].execute(n)}}class ho{constructor(e){this._renderer=e}addRenderGroup(e,t){e.isCachedAsTexture?this._addRenderableCacheAsTexture(e,t):this._addRenderableDirect(e,t)}execute(e){e.isRenderable&&(e.isCachedAsTexture?this._executeCacheAsTexture(e):this._executeDirect(e))}destroy(){this._renderer=null}_addRenderableDirect(e,t){this._renderer.renderPipes.batch.break(t),e._batchableRenderGroup&&(Le.return(e._batchableRenderGroup),e._batchableRenderGroup=null),t.add(e)}_addRenderableCacheAsTexture(e,t){const i=e._batchableRenderGroup??(e._batchableRenderGroup=Le.get(gh));i.renderable=e.root,i.transform=e.root.relativeGroupTransform,i.texture=e.texture,i.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(i,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;const t=new H().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push(e.texture,!0,null,e.texture.frame),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),co(e,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}e._batchableRenderGroup._batcher.updateElement(e._batchableRenderGroup),e._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(e){this._renderer.globalUniforms.push({worldTransformMatrix:e.inverseParentTextureTransform,worldColor:e.worldColorAlpha}),co(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}ho.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"renderGroup"};const My="#808080",pr=new H,Py=new H,ky=new H,uo=new H;function Oy(s,e,t){s.beginPath();for(let i=0;i<t.length;i+=3){const r=t[i]*2,n=t[i+1]*2,o=t[i+2]*2;s.moveTo(e[r],e[r+1]),s.lineTo(e[n],e[n+1]),s.lineTo(e[o],e[o+1]),s.closePath()}s.fill()}function By(s){return`#${(s&16777215).toString(16).padStart(6,"0")}`}function Dy(s,e,t,i,r,n){n=Math.max(0,Math.min(n,Math.min(i,r)/2)),s.moveTo(e+n,t),s.lineTo(e+i-n,t),s.quadraticCurveTo(e+i,t,e+i,t+n),s.lineTo(e+i,t+r-n),s.quadraticCurveTo(e+i,t+r,e+i-n,t+r),s.lineTo(e+n,t+r),s.quadraticCurveTo(e,t+r,e,t+r-n),s.lineTo(e,t+n),s.quadraticCurveTo(e,t,e+n,t)}function mr(s,e){switch(e.type){case"rectangle":{const t=e;s.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;Dy(s,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;s.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;s.ellipse?s.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2):(s.save(),s.translate(t.x,t.y),s.scale(t.halfWidth,t.halfHeight),s.arc(0,0,1,0,Math.PI*2),s.restore());break}case"triangle":{const t=e;s.moveTo(t.x,t.y),s.lineTo(t.x2,t.y2),s.lineTo(t.x3,t.y3),s.closePath();break}case"polygon":default:{const t=e,i=t.points;if(!(i!=null&&i.length))break;s.moveTo(i[0],i[1]);for(let r=2;r<i.length;r+=2)s.lineTo(i[r],i[r+1]);t.closePath&&s.closePath();break}}}function Ny(s,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const i=e[t];if(!(i!=null&&i.shape))continue;const r=i.transform,n=r&&!r.isIdentity();n&&(s.save(),s.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),mr(s,i.shape),n&&s.restore()}return!0}function Uy(s,e,t,i){const r=s.fill;if(r instanceof Mi){r.buildGradient();const o=r.texture;if(o){const a=ne.getTintedPattern(o,e),l=t?uo.copyFrom(t).scale(o.source.pixelWidth,o.source.pixelHeight):uo.copyFrom(r.transform);return i&&!s.textureSpace&&l.append(i),ne.applyPatternTransform(a,l),a}}if(r instanceof Kc){const o=ne.getTintedPattern(r.texture,e);return ne.applyPatternTransform(o,r.transform),o}const n=s.texture;if(n&&n!==j.WHITE){if(!n.source.resource)return My;const o=ne.getTintedPattern(n,e),a=t?uo.copyFrom(t).scale(n.source.pixelWidth,n.source.pixelHeight):s.matrix;return ne.applyPatternTransform(o,a),o}return By(e)}class Ah{constructor(){this.shader=null}contextChange(e){}execute(e,t){var C,S,E,w,R,M,D;const i=e.renderer,r=i.canvasContext,n=r.activeContext,o=t.groupTransform,a=((C=i.globalUniforms.globalUniformData)==null?void 0:C.worldColor)??4294967295,l=t.groupColorAlpha,c=(a>>>24&255)/255,h=(l>>>24&255)/255,u=((S=i.filter)==null?void 0:S.alphaMultiplier)??1,f=c*h*u;if(f<=0)return;const d=a&16777215,g=l&16777215,_=bi(yi(g,d)),y=i._roundPixels|t._roundPixels;n.save(),r.setContextTransform(o,y===1),r.setBlendMode(t.groupBlendMode);const x=t.context.instructions;for(let F=0;F<x.length;F++){const k=x[F];if(k.action==="texture"){const q=k.data,N=q.image,K=N?ne.getCanvasSource(N):null;if(!K)continue;const Z=q.alpha*f;if(Z<=0)continue;const $=yi(q.style,_);n.globalAlpha=Z;let ae=K;$!==16777215&&(ae=ne.getTintedCanvas({texture:N},$));const Ce=N.frame,Ee=N.source._resolution??N.source.resolution??1;let G=Ce.x*Ee,fe=Ce.y*Ee;const le=Ce.width*Ee,L=Ce.height*Ee;ae!==K&&(G=0,fe=0);const me=q.transform,Y=me&&!me.isIdentity(),ie=N.rotate;Y||ie?(pr.copyFrom(o),Y&&pr.append(me),ie&&re.matrixAppendRotationInv(pr,ie,q.dx,q.dy,q.dw,q.dh),r.setContextTransform(pr,y===1)):r.setContextTransform(o,y===1),n.drawImage(ae,G,fe,ae===K?le:ae.width,ae===K?L:ae.height,ie?0:q.dx,ie?0:q.dy,q.dw,q.dh),(Y||ie)&&r.setContextTransform(o,y===1);continue}const O=k.data,V=(E=O==null?void 0:O.path)==null?void 0:E.shapePath;if(!((w=V==null?void 0:V.shapePrimitives)!=null&&w.length))continue;const X=O.style,z=yi(X.color,_),de=X.alpha*f;if(de<=0)continue;const B=k.action==="stroke";if(n.globalAlpha=de,B){const q=X;n.lineWidth=q.width,n.lineCap=q.cap,n.lineJoin=q.join,n.miterLimit=q.miterLimit}const U=V.shapePrimitives;if(!B&&((D=(M=(R=O.hole)==null?void 0:R.shapePath)==null?void 0:M.shapePrimitives)!=null&&D.length)){const q=U[U.length-1];q.holes=O.hole.shapePath.shapePrimitives}for(let q=0;q<U.length;q++){const N=U[q];if(!(N!=null&&N.shape))continue;const K=N.transform,Z=K&&!K.isIdentity(),$=X.texture&&X.texture!==j.WHITE,ae=X.textureSpace==="global"?K:null,Ce=$?Fc(Py,X,N.shape,ae):null,Ee=Z?ky.copyFrom(o).append(K):o,G=Uy(X,z,Ce,Ee);if(Z&&(n.save(),n.transform(K.a,K.b,K.c,K.d,K.tx,K.ty)),B){const fe=X;if(fe.alignment!==.5&&!fe.pixelLine){const L=[],me=[],Y=[],ie=fs[N.shape.type];if(ie!=null&&ie.build(N.shape,L)){const we=N.shape.closePath??!0;Oc(L,fe,!1,we,me,Y),n.fillStyle=G,Oy(n,me,Y)}else n.strokeStyle=G,n.beginPath(),mr(n,N.shape),n.stroke()}else n.strokeStyle=G,n.beginPath(),mr(n,N.shape),n.stroke()}else n.fillStyle=G,n.beginPath(),mr(n,N.shape),Ny(n,N.holes)?n.fill("evenodd"):n.fill();Z&&n.restore()}}n.restore()}destroy(){this.shader=null}}Ah.extension={type:[A.CanvasPipesAdaptor],name:"graphics"};class fo{constructor(e){this._renderer=e}addRenderable(e,t){const i=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,i),this._renderer.renderPipes.batch.addToBatch(i,t)}updateRenderable(e){const t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){const t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.bounds=e.visualBounds,t.texture=e._texture}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){const t=new gh;return t.renderable=e,t.transform=e.groupTransform,t.texture=e._texture,t.bounds=e.visualBounds,t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}fo.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"sprite"};const bs={};Q.handle(A.BlendMode,s=>{if(!s.name)throw new Error("BlendMode extension must have a name property");bs[s.name]=s.ref},s=>{delete bs[s.name]});class po{constructor(e){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=e,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(e,t,i){this._blendModeStack.push(t),this.setBlendMode(e,t,i)}popBlendMode(e){this._blendModeStack.pop();const t=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,t,e)}setBlendMode(e,t,i){var n;const r=e instanceof un;if(this._activeBlendMode===t){this._isAdvanced&&e&&!r&&((n=this._renderableList)==null||n.push(e));return}this._isAdvanced&&this._endAdvancedBlendMode(i),this._activeBlendMode=t,e&&(this._isAdvanced=!!bs[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,i))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);const i=this._activeBlendMode;if(!bs[i]){se(`Unable to assign BlendMode: '${i}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const r=this._ensureFilterEffect(i),n=e instanceof un,o={renderPipeId:"filter",action:"pushFilter",filterEffect:r,renderables:n?null:[e],container:n?e.root:null,canBundle:!1};this._renderableList=o.renderables,t.add(o)}_ensureFilterEffect(e){let t=this._filterHash[e];return t||(t=this._filterHash[e]=new zs,t.filters=[new bs[e]]),t}_endAdvancedBlendMode(e){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(e),e.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(e){this._isAdvanced&&this._endAdvancedBlendMode(e)}destroy(){this._renderer=null,this._renderableList=null;for(const e in this._filterHash)this._filterHash[e].destroy();this._filterHash=null}}po.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"blendMode"};function mo(s,e){e||(e=0);for(let t=e;t<s.length&&s[t];t++)s[t]=null}const Fy=new Ve,wh=Ji|Ks|pn;function Ih(s,e=!1){Gy(s);const t=s.childrenToUpdate,i=s.updateTick++;for(const r in t){const n=Number(r),o=t[r],a=o.list,l=o.index;for(let c=0;c<l;c++){const h=a[c];h.parentRenderGroup===s&&h.relativeRenderGroupDepth===n&&Rh(h,i,0)}mo(a,l),o.index=0}if(e)for(let r=0;r<s.renderGroupChildren.length;r++)Ih(s.renderGroupChildren[r],e)}function Gy(s){const e=s.root;let t;if(s.renderGroupParent){const i=s.renderGroupParent;s.worldTransform.appendFrom(e.relativeGroupTransform,i.worldTransform),s.worldColor=js(e.groupColor,i.worldColor),t=e.groupAlpha*i.worldAlpha}else s.worldTransform.copyFrom(e.localTransform),s.worldColor=e.localColor,t=e.localAlpha;t=t<0?0:t>1?1:t,s.worldAlpha=t,s.worldColorAlpha=s.worldColor+((t*255|0)<<24)}function Rh(s,e,t){if(e===s.updateTick)return;s.updateTick=e,s.didChange=!1;const i=s.localTransform;s.updateLocalTransform();const r=s.parent;if(r&&!r.renderGroup?(t|=s._updateFlags,s.relativeGroupTransform.appendFrom(i,r.relativeGroupTransform),t&wh&&Mh(s,r,t)):(t=s._updateFlags,s.relativeGroupTransform.copyFrom(i),t&wh&&Mh(s,Fy,t)),!s.renderGroup){const n=s.children,o=n.length;for(let c=0;c<o;c++)Rh(n[c],e,t);const a=s.parentRenderGroup,l=s;l.renderPipeId&&!a.structureDidChange&&a.updateRenderable(l)}}function Mh(s,e,t){if(t&Ks){s.groupColor=js(s.localColor,e.groupColor);let i=s.localAlpha*e.groupAlpha;i=i<0?0:i>1?1:i,s.groupAlpha=i,s.groupColorAlpha=s.groupColor+((i*255|0)<<24)}t&pn&&(s.groupBlendMode=s.localBlendMode==="inherit"?e.groupBlendMode:s.localBlendMode),t&Ji&&(s.globalDisplayStatus=s.localDisplayStatus&e.globalDisplayStatus),s._updateFlags=0}function Ly(s,e){const{list:t}=s.childrenRenderablesToUpdate;let i=!1;for(let r=0;r<s.childrenRenderablesToUpdate.index;r++){const n=t[r];if(i=e[n.renderPipeId].validateRenderable(n),i)break}return s.structureDidChange=i,i}const Wy=new H;class Ph{constructor(e){this._renderer=e}render({container:e,transform:t}){const i=e.parent,r=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;const n=this._renderer,o=Wy;t&&(o.copyFrom(e.renderGroup.localTransform),e.renderGroup.localTransform.copyFrom(t));const a=n.renderPipes;this._updateCachedRenderGroups(e.renderGroup,null),this._updateRenderGroups(e.renderGroup),n.globalUniforms.start({worldTransformMatrix:t?e.renderGroup.localTransform:e.renderGroup.worldTransform,worldColor:e.renderGroup.worldColorAlpha}),co(e.renderGroup,a),a.uniformBatch&&a.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(o),e.parent=i,e.renderGroup.renderGroupParent=r}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let i=e.renderGroupChildren.length-1;i>=0;i--)this._updateCachedRenderGroups(e.renderGroupChildren[i],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){const i=e.root.getLocalBounds(),r=this._renderer,n=e.textureOptions.resolution||r.view.resolution,o=e.textureOptions.antialias??r.view.antialias,a=e.textureOptions.scaleMode??"linear",l=e.texture;i.ceil(),e.texture&&Qe.returnTexture(e.texture,!0);const c=Qe.getOptimalTexture(i.width,i.height,n,o);c._source.style=new zr({scaleMode:a}),e.texture=c,e._textureBounds||(e._textureBounds=new Ye),e._textureBounds.copyFrom(i),l!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&(Qe.returnTexture(e.texture,!0),e.texture=null)}_updateRenderGroups(e){const t=this._renderer,i=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=i,e.structureDidChange?mo(e.childrenRenderablesToUpdate.list,0):Ly(e,i),Ih(e),e.structureDidChange?(e.structureDidChange=!1,this._buildInstructions(e,t)):this._updateRenderables(e),e.childrenRenderablesToUpdate.index=0,t.renderPipes.batch.upload(e.instructionSet),!(e.isCachedAsTexture&&!e.textureNeedsUpdate))for(let r=0;r<e.renderGroupChildren.length;r++)this._updateRenderGroups(e.renderGroupChildren[r])}_updateRenderables(e){const{list:t,index:i}=e.childrenRenderablesToUpdate;for(let r=0;r<i;r++){const n=t[r];n.didViewUpdate&&e.updateRenderable(n)}mo(t,i)}_buildInstructions(e,t){const i=e.root,r=e.instructionSet;r.reset();const n=t.renderPipes?t:t.batch.renderer,o=n.renderPipes;o.batch.buildStart(r),o.blendMode.buildStart(),o.colorMask.buildStart(),i.sortableChildren&&i.sortChildren(),i.collectRenderablesWithEffects(r,n,null),o.batch.buildEnd(r),o.blendMode.buildEnd(r)}}Ph.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"renderGroup"};const go=class vf{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new Pe(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={...vf.defaultOptions,...e},this.clearBeforeRender=e.clearBeforeRender,this.color=e.background||e.backgroundColor||this._backgroundColor,this.alpha=e.backgroundAlpha,this._backgroundColor.setAlpha(e.backgroundAlpha)}get color(){return this._backgroundColor}set color(e){Pe.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&se("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(e)}get alpha(){return this._backgroundColor.alpha}set alpha(e){this._backgroundColor.setAlpha(e)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};go.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"background",priority:0},go.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let Hy=go;const _o={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},yo=class Cf{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof Ve||e instanceof j?{target:e,...t}:{...t,...e}}async image(e){const t=pe.get().createImage();return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,Cf.defaultImageOptions);const{format:t,quality:i}=e,r=this.canvas(e);if(r.toBlob!==void 0)return new Promise((n,o)=>{r.toBlob(a=>{if(!a){o(new Error("ICanvas.toBlob failed!"));return}const l=new FileReader;l.onload=()=>n(l.result),l.onerror=o,l.readAsDataURL(a)},_o[t],i)});if(r.toDataURL!==void 0)return r.toDataURL(_o[t],i);if(r.convertToBlob!==void 0){const n=await r.convertToBlob({type:_o[t],quality:i});return new Promise((o,a)=>{const l=new FileReader;l.onload=()=>o(l.result),l.onerror=a,l.readAsDataURL(n)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(e){e=this._normalizeOptions(e);const t=e.target,i=this._renderer;if(t instanceof j)return i.texture.generateCanvas(t);const r=i.textureGenerator.generateTexture(e),n=i.texture.generateCanvas(r);return r.destroy(!0),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,i=this._renderer,r=t instanceof j?t:i.textureGenerator.generateTexture(e),n=i.texture.getPixels(r);return t instanceof Ve&&r.destroy(!0),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof j?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),i=document.createElement("a");i.download=e.filename??"image.png",i.href=t.toDataURL("image/png"),document.body.appendChild(i),i.click(),document.body.removeChild(i)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const i=this.canvas(e),r=i.toDataURL();console.log(`[Pixi Texture] ${i.width}px ${i.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${r}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};yo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"extract"},yo.defaultImageOptions={format:"png",quality:1};let Vy=yo;class bo extends j{static create(e){const{dynamic:t,...i}=e;return new bo({source:new De(i),dynamic:t??!1})}resize(e,t,i){return this.source.resize(e,t,i),this}}const zy=new Se,$y=new Ye,jy=[0,0,0,0];class kh{constructor(e){this._renderer=e}generateTexture(e){var c;e instanceof Ve&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,i=e.antialias||this._renderer.view.antialias,r=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:Pe.shared.setValue(n).toArray():n=jy;const o=((c=e.frame)==null?void 0:c.copyTo(zy))||an(r,$y).rectangle;o.width=Math.max(o.width,1/t)|0,o.height=Math.max(o.height,1/t)|0;const a=bo.create({...e.textureSourceOptions,width:o.width,height:o.height,resolution:t,antialias:i}),l=H.shared.translate(-o.x,-o.y);return this._renderer.render({container:r,transform:l,target:a,clearColor:n}),a.source.updateMipmaps(),a}destroy(){this._renderer=null}}kh.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"textureGenerator"};function Xy(s){let e=!1;for(const i in s)if(s[i]==null){e=!0;break}if(!e)return s;const t=Object.create(null);for(const i in s){const r=s[i];r&&(t[i]=r)}return t}function Yy(s){let e=0;for(let t=0;t<s.length;t++)s[t]==null?e++:s[t-e]=s[t];return s.length-=e,s}const xo=class Sf{constructor(e){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._renderer=e}init(e){e={...Sf.defaultOptions,...e},this.maxUnusedTime=e.gcMaxUnusedTime,this._frequency=e.gcFrequency,this.enabled=e.gcActive,this.now=performance.now()}get enabled(){return!!this._handler}set enabled(e){this.enabled!==e&&(e?(this._handler=this._renderer.scheduler.repeat(()=>{this._ready=!0},this._frequency,!1),this._collectionsHandler=this._renderer.scheduler.repeat(()=>{for(const t of this._managedCollections){const{context:i,collection:r,type:n}=t;n==="hash"?i[r]=Xy(i[r]):i[r]=Yy(i[r])}},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._collectionsHandler),this._handler=0,this._collectionsHandler=0))}prerender({container:e}){this.now=performance.now(),e.renderGroup.gcTick=this._renderer.tick++,this._updateInstructionGCTick(e.renderGroup,e.renderGroup.gcTick)}postrender(){!this._ready||!this.enabled||(this.run(),this._ready=!1)}_updateInstructionGCTick(e,t){e.instructionSet.gcTick=t,e.gcTick=t;for(const i of e.renderGroupChildren)this._updateInstructionGCTick(i,t)}addCollection(e,t,i){this._managedCollections.push({context:e,collection:t,type:i})}addResource(e,t){var r,n;if(e._gcLastUsed!==-1){e._gcLastUsed=this.now,(r=e._onTouch)==null||r.call(e,this.now);return}const i=this._managedResources.length;e._gcData={index:i,type:t},e._gcLastUsed=this.now,(n=e._onTouch)==null||n.call(e,this.now),e.once("unload",this.removeResource,this),this._managedResources.push(e)}removeResource(e){const t=e._gcData;if(!t)return;const i=t.index,r=this._managedResources.length-1;if(i!==r){const n=this._managedResources[r];this._managedResources[i]=n,n._gcData.index=i}this._managedResources.length--,e._gcData=null,e._gcLastUsed=-1}addResourceHash(e,t,i,r=0){this._managedResourceHashes.push({context:e,hash:t,type:i,priority:r}),this._managedResourceHashes.sort((n,o)=>n.priority-o.priority)}run(){const e=performance.now(),t=this._managedResourceHashes;for(const r of t)this.runOnHash(r,e);let i=0;for(let r=0;r<this._managedResources.length;r++){const n=this._managedResources[r];i=this.runOnResource(n,e,i)}this._managedResources.length=i}updateRenderableGCTick(e,t){var n,o;const i=e.renderGroup??e.parentRenderGroup,r=((n=i==null?void 0:i.instructionSet)==null?void 0:n.gcTick)??-1;((i==null?void 0:i.gcTick)??0)===r&&(e._gcLastUsed=t,(o=e._onTouch)==null||o.call(e,t))}runOnResource(e,t,i){const r=e._gcData;return r.type==="renderable"&&this.updateRenderableGCTick(e,t),t-e._gcLastUsed<this.maxUnusedTime||!e.autoGarbageCollect?(this._managedResources[i]=e,r.index=i,i++):(e.unload(),e._gcData=null,e._gcLastUsed=-1,e.off("unload",this.removeResource,this)),i}_createHashClone(e,t){const i=Object.create(null);for(const r in e){if(r===t)break;e[r]!==null&&(i[r]=e[r])}return i}runOnHash(e,t){var c;const{context:i,hash:r,type:n}=e,o=i[r];let a=null,l=0;for(const h in o){const u=o[h];if(u===null){l++,l===1e4&&!a&&(a=this._createHashClone(o,h));continue}if(u._gcLastUsed===-1){u._gcLastUsed=t,(c=u._onTouch)==null||c.call(u,t),a&&(a[h]=u);continue}if(n==="renderable"&&this.updateRenderableGCTick(u,t),!(t-u._gcLastUsed<this.maxUnusedTime)&&u.autoGarbageCollect){if(a||(l+1!==1e4?(o[h]=null,l++):a=this._createHashClone(o,h)),n==="renderable"){const d=u,g=d.renderGroup??d.parentRenderGroup;g&&(g.structureDidChange=!0)}u.unload(),u._gcData=null,u._gcLastUsed=-1}else a&&(a[h]=u)}a&&(i[r]=a)}destroy(){this.enabled=!1,this._managedResources.forEach(e=>{e.off("unload",this.removeResource,this)}),this._managedResources.length=0,this._managedResourceHashes.length=0,this._managedCollections.length=0,this._renderer=null}};xo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"gc",priority:0},xo.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4};let qy=xo;class Oh{constructor(e){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=e}reset(){this._stackIndex=0;for(let e=0;e<this._activeUniforms.length;e++)this._uniformsPool.push(this._activeUniforms[e]);for(let e=0;e<this._activeBindGroups.length;e++)this._bindGroupPool.push(this._activeBindGroups[e]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(e){this.reset(),this.push(e)}bind({size:e,projectionMatrix:t,worldTransformMatrix:i,worldColor:r,offset:n}){const o=this._renderer.renderTarget.renderTarget,a=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new H,worldColor:4294967295,offset:new xe},l={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||o.size,worldTransformMatrix:i||a.worldTransformMatrix,worldColor:r||a.worldColor,offset:n||a.offset,bindGroup:null},c=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(c);const h=c.uniforms;h.uProjectionMatrix=l.projectionMatrix,h.uResolution=l.resolution,h.uWorldTransformMatrix.copyFrom(l.worldTransformMatrix),h.uWorldTransformMatrix.tx-=l.offset.x,h.uWorldTransformMatrix.ty-=l.offset.y,uh(l.worldColor,h.uWorldColorAlpha,0),c.update();let u;this._renderer.renderPipes.uniformBatch?u=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(c,!1):(u=this._bindGroupPool.pop()||new Gt,this._activeBindGroups.push(u),u.setResource(c,0)),l.bindGroup=u,this._currentGlobalUniformData=l}push(e){this.bind(e),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===bt.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new ht({uProjectionMatrix:{value:new H,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new H,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}Oh.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"globalUniforms"};let Ky=1;class Bh{constructor(){this._tasks=[],this._offset=0}init(){at.system.add(this._update,this)}repeat(e,t,i=!0){const r=Ky++;let n=0;return i&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:r}),r}cancel(e){for(let t=0;t<this._tasks.length;t++)if(this._tasks[t].id===e){this._tasks.splice(t,1);return}}_update(){const e=performance.now();for(let t=0;t<this._tasks.length;t++){const i=this._tasks[t];if(e-i.offset-i.last>=i.duration){const r=e-i.start;i.func(r),i.last=e}}}destroy(){at.system.remove(this._update,this),this._tasks.length=0}}Bh.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"scheduler",priority:0};let Dh=!1;function Zy(s){if(!Dh){if(pe.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c %c %c %c %c PixiJS %c v${or} (${s}) http://www.pixijs.com/
853
853
 
854
- `,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...e)}else globalThis.console&&globalThis.console.log(`PixiJS ${nr} - ${s} - http://www.pixijs.com/`);Dh=!0}}class vo{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===bt.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),Ky(t)}}}vo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"hello",priority:-2},vo.defaultOptions={hello:!1};const Co=class Ef{constructor(e){this._renderer=e}init(e){e={...Ef.defaultOptions,...e},this.maxUnusedTime=e.renderableGCMaxUnusedTime}get enabled(){return ee("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled}set enabled(e){ee("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled=e}addManagedHash(e,t){ee("8.15.0","RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"hash")}addManagedArray(e,t){ee("8.15.0","RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"array")}addRenderable(e){ee("8.15.0","RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead."),this._renderer.gc.addResource(e,"renderable")}run(){ee("8.15.0","RenderableGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};Co.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"renderableGC",priority:0},Co.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let Zy=Co;const So=class Dr{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._checkCount=e}get maxIdle(){return this._renderer.gc.maxUnusedTime/1e3*60}set maxIdle(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.maxUnusedTime=e/60*1e3}get checkCountMax(){return Math.floor(this._renderer.gc._frequency/1e3)}set checkCountMax(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead.")}get active(){return this._renderer.gc.enabled}set active(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.enabled=e}constructor(e){this._renderer=e,this._checkCount=0}init(e){e.textureGCActive!==Dr.defaultOptions.textureGCActive&&(this.active=e.textureGCActive),e.textureGCMaxIdle!==Dr.defaultOptions.textureGCMaxIdle&&(this.maxIdle=e.textureGCMaxIdle),e.textureGCCheckCountMax!==Dr.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=e.textureGCCheckCountMax)}run(){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};So.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"textureGC"},So.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let Jy=So;const Nh=class Tf{constructor(e={}){if(this.uid=be("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,e={...Tf.defaultOptions,...e},this.stencil=e.stencil,this.depth=e.depth,this.isRoot=e.isRoot,typeof e.colorTextures=="number"){this._managedColorTextures=!0;for(let t=0;t<e.colorTextures;t++)this.colorTextures.push(new De({width:e.width,height:e.height,resolution:e.resolution,antialias:e.antialias}))}else{this.colorTextures=[...e.colorTextures.map(i=>i.source)];const t=this.colorTexture.source;this.resize(t.width,t.height,t._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(e.depthStencilTexture||this.stencil)&&(e.depthStencilTexture instanceof j||e.depthStencilTexture instanceof De?this.depthStencilTexture=e.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new De({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(e,t,i=this.resolution,r=!1){this.dirtyId++,this.colorTextures.forEach((n,o)=>{r&&o===0||n.source.resize(e,t,i)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(e,t,i)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(e=>{e.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};Nh.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let Eo=Nh;const Oi=new Map;_i.register(Oi);function Uh(s,e){if(!Oi.has(s)){const t=new j({source:new yt({resource:s,...e})}),i=()=>{Oi.get(s)===t&&Oi.delete(s)};t.once("destroy",i),t.source.once("destroy",i),Oi.set(s,t)}return Oi.get(s)}const To=class Af{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(e){this.texture.source.autoDensity=e}get resolution(){return this.texture.source._resolution}set resolution(e){this.texture.source.resize(this.texture.source.width,this.texture.source.height,e)}init(e){e={...Af.defaultOptions,...e},e.view&&(ee(Be,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new Se(0,0,e.width,e.height),this.canvas=e.canvas||pe.get().createCanvas(),this.antialias=!!e.antialias,this.texture=Uh(this.canvas,e),this.renderTarget=new Eo({colorTextures:[this.texture],depth:!!e.depth,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.resolution=e.resolution}resize(e,t,i){this.texture.source.resize(e,t,i),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(e=!1){(typeof e=="boolean"?e:!!(e!=null&&e.removeView))&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.destroy()}};To.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"view",priority:0},To.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};const Ao=[Wy,Oh,vo,To,Ph,Yy,Jy,kh,Hy,tc,Zy,Bh],Fh=[po,oo,fo,ho,ao,Sh,xh,lo];function Qy(s,e,t,i,r,n){const o=n?1:-1;return s.identity(),s.a=1/i*2,s.d=o*(1/r*2),s.tx=-1-e*s.a,s.ty=-o-t*s.d,s}function eb(s){const e=s.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}class wo{constructor(e){this.rootViewPort=new Se,this.viewport=new Se,this.mipLevel=0,this.layer=0,this.onRenderTargetChange=new ol("onRenderTargetChange"),this.projectionMatrix=new H,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=e,e.gc.addCollection(this,"_gpuRenderTargetHash","hash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:e,clear:t,clearColor:i,frame:r,mipLevel:n,layer:o}){var a,l;this._renderTargetStack.length=0,this.push(e,t,i,r,n??0,o??0),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=eb(this.rootRenderTarget),(l=(a=this.adaptor).prerender)==null||l.call(a,this.rootRenderTarget)}postrender(){var e,t;(t=(e=this.adaptor).postrender)==null||t.call(e,this.rootRenderTarget)}bind(e,t=!0,i,r,n=0,o=0){const a=this.getRenderTarget(e),l=this.renderTarget!==a;this.renderTarget=a,this.renderSurface=e;const c=this.getGpuRenderTarget(a);(a.pixelWidth!==c.width||a.pixelHeight!==c.height)&&(this.adaptor.resizeGpuRenderTarget(a),c.width=a.pixelWidth,c.height=a.pixelHeight);const h=a.colorTexture,u=this.viewport,f=h.arrayLayerCount||1;if((o|0)!==o&&(o|=0),o<0||o>=f)throw new Error(`[RenderTargetSystem] layer ${o} is out of bounds (arrayLayerCount=${f}).`);this.mipLevel=n|0,this.layer=o|0;const d=Math.max(h.pixelWidth>>n,1),g=Math.max(h.pixelHeight>>n,1);if(!r&&e instanceof j&&(r=e.frame),r){const _=h._resolution,b=1<<Math.max(n|0,0),x=r.x*_+.5|0,C=r.y*_+.5|0,S=r.width*_+.5|0,E=r.height*_+.5|0;let w=Math.floor(x/b),R=Math.floor(C/b),M=Math.ceil(S/b),D=Math.ceil(E/b);w=Math.min(Math.max(w,0),d-1),R=Math.min(Math.max(R,0),g-1),M=Math.min(Math.max(M,1),d-w),D=Math.min(Math.max(D,1),g-R),u.x=w,u.y=R,u.width=M,u.height=D}else u.x=0,u.y=0,u.width=d,u.height=g;return Qy(this.projectionMatrix,0,0,u.width/h.resolution,u.height/h.resolution,!a.isRoot),this.adaptor.startRenderPass(a,t,i,u,n,o),l&&this.onRenderTargetChange.emit(a),a}clear(e,t=it.ALL,i,r=this.mipLevel,n=this.layer){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,i,this.viewport,r,n))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=it.ALL,i,r,n=0,o=0){const a=this.bind(e,t,i,r,n,o);return this._renderTargetStack.push({renderTarget:a,frame:r,mipLevel:n,layer:o}),a}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(e.renderTarget,!1,null,e.frame,e.mipLevel,e.layer)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,i,r,n){i.x<0&&(r.width+=i.x,n.x-=i.x,i.x=0),i.y<0&&(r.height+=i.y,n.y-=i.y,i.y=0);const{pixelWidth:o,pixelHeight:a}=e;return r.width=Math.min(r.width,o-i.x),r.height=Math.min(r.height,a-i.y),this.adaptor.copyToTexture(e,t,i,r,n)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport,0,this.layer))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((e,t)=>{e!==t&&e.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;return yt.test(e)&&(e=Uh(e).source),e instanceof Eo?t=e:e instanceof De&&(t=new Eo({colorTextures:[e]}),e.source instanceof yt&&(t.isRoot=!0),e.once("destroy",()=>{t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e);const i=this._gpuRenderTargetHash[t.uid];i&&(this._gpuRenderTargetHash[t.uid]=null,this.adaptor.destroyGpuRenderTarget(i))})),this._renderSurfaceToRenderTargetHash.set(e,t),t}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this.renderSurface=null}}class tb{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){const t=e.colorTexture,{canvas:i,context:r}=this._ensureCanvas(t);return{canvas:i,context:r,width:i.width,height:i.height}}resizeGpuRenderTarget(e){const t=e.colorTexture,{canvas:i}=this._ensureCanvas(t);i.width=e.pixelWidth,i.height=e.pixelHeight}startRenderPass(e,t,i,r){const n=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=n.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,i,r)}clear(e,t,i,r){const o=this._renderTargetSystem.getGpuRenderTarget(e).context,a=r||{x:0,y:0,width:e.pixelWidth,height:e.pixelHeight};if(o.setTransform(1,0,0,1,0,0),o.clearRect(a.x,a.y,a.width,a.height),i){const l=Pe.shared.setValue(i);l.alpha>0&&(o.globalAlpha=l.alpha,o.fillStyle=l.toHex(),o.fillRect(a.x,a.y,a.width,a.height),o.globalAlpha=1)}}finishRenderPass(){}copyToTexture(e,t,i,r,n){const a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,l=t.source,{context:c}=this._ensureCanvas(l),h=(n==null?void 0:n.x)??0,u=(n==null?void 0:n.y)??0;return c.drawImage(a,i.x,i.y,r.width,r.height,h,u,r.width,r.height),l.update(),t}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;(!t||!yt.test(t))&&(t=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),e.resource=t),(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(t.width=e.pixelWidth,t.height=e.pixelHeight);const i=t.getContext("2d");return{canvas:t,context:i}}}class Gh extends wo{constructor(e){super(e),this.adaptor=new tb,this.adaptor.init(e,this)}}Gh.extension={type:[A.CanvasSystem],name:"renderTarget"};class Lh{constructor(e){}init(){}initSource(e){}generateCanvas(e){const t=pe.get().createCanvas(),i=t.getContext("2d"),r=ne.getCanvasSource(e);if(!r)return t;const n=e.frame,o=e.source._resolution??e.source.resolution??1,a=n.x*o,l=n.y*o,c=n.width*o,h=n.height*o;return t.width=Math.ceil(c),t.height=Math.ceil(h),i.drawImage(r,a,l,c,h,0,0,c,h),t}getPixels(e){const t=this.generateCanvas(e);return{pixels:t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}destroy(){}}Lh.extension={type:[A.CanvasSystem],name:"texture"};const ib=[...Ao,Eh,Th,Lh,Gh],sb=[po,oo,fo,ho,ao,Ch,bh,lo],rb=[xy,Ah],Wh=[],Hh=[],Vh=[];Q.handleByNamedList(A.CanvasSystem,Wh),Q.handleByNamedList(A.CanvasPipes,Hh),Q.handleByNamedList(A.CanvasPipesAdaptor,Vh),Q.add(...ib,...sb,...rb);class nb extends vi{constructor(){const e={name:"canvas",type:bt.CANVAS,systems:Wh,renderPipes:Hh,renderPipeAdaptors:Vh};super(e)}}const ob=Object.freeze(Object.defineProperty({__proto__:null,CanvasRenderer:nb},Symbol.toStringTag,{value:"Module"}));var mr=(s=>(s[s.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",s[s.ARRAY_BUFFER=34962]="ARRAY_BUFFER",s[s.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",s))(mr||{});class ab{constructor(e,t){this._lastBindBaseLocation=-1,this._lastBindCallId=-1,this.buffer=e||null,this.updateID=-1,this.byteLength=-1,this.type=t}destroy(){this.buffer=null,this.updateID=-1,this.byteLength=-1,this.type=-1,this._lastBindBaseLocation=-1,this._lastBindCallId=-1}}class zh{constructor(e){this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=e,this._managedBuffers=new kt({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"glBuffer"})}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gl=null,this._boundBufferBases={}}contextChange(){this._gl=this._renderer.gl,this.destroyAll(!0),this._maxBindings=this._renderer.limits.maxUniformBindings}getGlBuffer(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this.createGLBuffer(e)}bind(e){const{_gl:t}=this,i=this.getGlBuffer(e);t.bindBuffer(i.type,i.buffer)}bindBufferBase(e,t){const{_gl:i}=this;this._boundBufferBases[t]!==e&&(this._boundBufferBases[t]=e,e._lastBindBaseLocation=t,i.bindBufferBase(i.UNIFORM_BUFFER,t,e.buffer))}nextBindBase(e){this._bindCallId++,this._minBaseLocation=0,e&&(this._boundBufferBases[0]=null,this._minBaseLocation=1,this._nextBindBaseIndex<1&&(this._nextBindBaseIndex=1))}freeLocationForBufferBase(e){let t=this.getLastBindBaseLocation(e);if(t>=this._minBaseLocation)return e._lastBindCallId=this._bindCallId,t;let i=0,r=this._nextBindBaseIndex;for(;i<2;){r>=this._maxBindings&&(r=this._minBaseLocation,i++);const n=this._boundBufferBases[r];if(n&&n._lastBindCallId===this._bindCallId){r++;continue}break}return t=r,this._nextBindBaseIndex=r+1,i>=2?-1:(e._lastBindCallId=this._bindCallId,this._boundBufferBases[t]=null,t)}getLastBindBaseLocation(e){const t=e._lastBindBaseLocation;return this._boundBufferBases[t]===e?t:-1}bindBufferRange(e,t,i,r){const{_gl:n}=this;i||(i=0),t||(t=0),this._boundBufferBases[t]=null,n.bindBufferRange(n.UNIFORM_BUFFER,t||0,e.buffer,i*256,r||256)}updateBuffer(e){const{_gl:t}=this,i=this.getGlBuffer(e);if(e._updateID===i.updateID)return i;i.updateID=e._updateID,t.bindBuffer(i.type,i.buffer);const r=e.data,n=e.descriptor.usage&ge.STATIC?t.STATIC_DRAW:t.DYNAMIC_DRAW;return r?i.byteLength>=r.byteLength?t.bufferSubData(i.type,0,r,0,e._updateSize/r.BYTES_PER_ELEMENT):(i.byteLength=r.byteLength,t.bufferData(i.type,r,n)):(i.byteLength=e.descriptor.size,t.bufferData(i.type,i.byteLength,n)),i}destroyAll(e=!1){this._managedBuffers.removeAll(e)}onBufferUnload(e,t=!1){const i=e._gpuData[this._renderer.uid];i&&(t||this._gl.deleteBuffer(i.buffer))}createGLBuffer(e){const{_gl:t}=this;let i=mr.ARRAY_BUFFER;e.descriptor.usage&ge.INDEX?i=mr.ELEMENT_ARRAY_BUFFER:e.descriptor.usage&ge.UNIFORM&&(i=mr.UNIFORM_BUFFER);const r=new ab(t.createBuffer(),i);return e._gpuData[this._renderer.uid]=r,this._managedBuffers.add(e),r}resetState(){this._boundBufferBases=Object.create(null)}}zh.extension={type:[A.WebGLSystem],name:"buffer"};const Io=class wf{constructor(e){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=e,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(e){this.gl=e,this._renderer.gl=e}init(e){e={...wf.defaultOptions,...e};let t=this.multiView=e.multiView;if(e.context&&t&&(se("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),t=!1),t?this.canvas=pe.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,e.context)this.initFromContext(e.context);else{const i=this._renderer.background.alpha<1,r=e.premultipliedAlpha??!0,n=e.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(e.preferWebGLVersion,{alpha:i,premultipliedAlpha:r,antialias:n,stencil:!0,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference??"default"})}}ensureCanvasSize(e){if(!this.multiView){e!==this.canvas&&se("multiView is disabled, but targetCanvas is not the main canvas");return}const{canvas:t}=this;(t.width<e.width||t.height<e.height)&&(t.width=Math.max(e.width,e.width),t.height=Math.max(e.height,e.height))}initFromContext(e){this.gl=e,this.webGLVersion=e instanceof pe.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(e),this._renderer.runners.contextChange.emit(e);const t=this._renderer.view.canvas;t.addEventListener("webglcontextlost",this.handleContextLost,!1),t.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}createContext(e,t){let i;const r=this.canvas;if(e===2&&(i=r.getContext("webgl2",t)),!i&&(i=r.getContext("webgl",t),!i))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=i,this.initFromContext(this.gl)}getExtensions(){const{gl:e}=this,t={anisotropicFiltering:e.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),s3tc:e.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:e.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:e.getExtension("WEBGL_compressed_texture_etc"),etc1:e.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:e.getExtension("WEBGL_compressed_texture_atc"),astc:e.getExtension("WEBGL_compressed_texture_astc"),bptc:e.getExtension("EXT_texture_compression_bptc"),rgtc:e.getExtension("EXT_texture_compression_rgtc"),loseContext:e.getExtension("WEBGL_lose_context")};if(this.webGLVersion===1)this.extensions={...t,drawBuffers:e.getExtension("WEBGL_draw_buffers"),depthTexture:e.getExtension("WEBGL_depth_texture"),vertexArrayObject:e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:e.getExtension("OES_element_index_uint"),floatTexture:e.getExtension("OES_texture_float"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),textureHalfFloat:e.getExtension("OES_texture_half_float"),textureHalfFloatLinear:e.getExtension("OES_texture_half_float_linear"),vertexAttribDivisorANGLE:e.getExtension("ANGLE_instanced_arrays"),srgb:e.getExtension("EXT_sRGB")};else{this.extensions={...t,colorBufferFloat:e.getExtension("EXT_color_buffer_float")};const i=e.getExtension("WEBGL_provoking_vertex");i&&i.provokingVertexWEBGL(i.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(e){e.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{var t;this.gl.isContextLost()&&((t=this.extensions.loseContext)==null||t.restoreContext())},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){var t;const e=this._renderer.view.canvas;this._renderer=null,e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),(t=this.extensions.loseContext)==null||t.loseContext()}forceContextLoss(){var e;(e=this.extensions.loseContext)==null||e.loseContext(),this._contextLossForced=!0}validateContext(e){const t=e.getContextAttributes();t&&!t.stencil&&se("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const i=this.supports,r=this.webGLVersion===2,n=this.extensions;i.uint32Indices=r||!!n.uint32ElementIndex,i.uniformBufferObject=r,i.vertexArrayObject=r||!!n.vertexArrayObject,i.srgbTextures=r||!!n.srgb,i.nonPowOf2wrapping=r,i.nonPowOf2mipmaps=r,i.msaa=r,i.uint32Indices||se("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};Io.extension={type:[A.WebGLSystem],name:"context"},Io.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let lb=Io;function $h(s,e){for(const t in s.attributes){const i=s.attributes[t],r=e[t];r?(i.format??(i.format=r.format),i.offset??(i.offset=r.offset),i.instance??(i.instance=r.instance)):se(`Attribute ${t} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}cb(s)}function cb(s){const{buffers:e,attributes:t}=s,i={},r={};for(const n in e){const o=e[n];i[o.uid]=0,r[o.uid]=0}for(const n in t){const o=t[n];i[o.buffer.uid]+=At(o.format).stride}for(const n in t){const o=t[n];o.stride??(o.stride=i[o.buffer.uid]),o.start??(o.start=r[o.buffer.uid]),r[o.buffer.uid]+=At(o.format).stride}}var Ro=(s=>(s[s.RGBA=6408]="RGBA",s[s.RGB=6407]="RGB",s[s.RG=33319]="RG",s[s.RED=6403]="RED",s[s.RGBA_INTEGER=36249]="RGBA_INTEGER",s[s.RGB_INTEGER=36248]="RGB_INTEGER",s[s.RG_INTEGER=33320]="RG_INTEGER",s[s.RED_INTEGER=36244]="RED_INTEGER",s[s.ALPHA=6406]="ALPHA",s[s.LUMINANCE=6409]="LUMINANCE",s[s.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",s[s.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",s[s.DEPTH_STENCIL=34041]="DEPTH_STENCIL",s))(Ro||{}),Mo=(s=>(s[s.TEXTURE_2D=3553]="TEXTURE_2D",s[s.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",s[s.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",s[s.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",s[s.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",s[s.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",s[s.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",s))(Mo||{}),he=(s=>(s[s.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",s[s.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",s[s.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",s[s.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",s[s.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",s[s.UNSIGNED_INT=5125]="UNSIGNED_INT",s[s.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",s[s.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",s[s.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",s[s.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",s[s.BYTE=5120]="BYTE",s[s.SHORT=5122]="SHORT",s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",s[s.HALF_FLOAT=36193]="HALF_FLOAT",s))(he||{});const jh={uint8x2:he.UNSIGNED_BYTE,uint8x4:he.UNSIGNED_BYTE,sint8x2:he.BYTE,sint8x4:he.BYTE,unorm8x2:he.UNSIGNED_BYTE,unorm8x4:he.UNSIGNED_BYTE,snorm8x2:he.BYTE,snorm8x4:he.BYTE,uint16x2:he.UNSIGNED_SHORT,uint16x4:he.UNSIGNED_SHORT,sint16x2:he.SHORT,sint16x4:he.SHORT,unorm16x2:he.UNSIGNED_SHORT,unorm16x4:he.UNSIGNED_SHORT,snorm16x2:he.SHORT,snorm16x4:he.SHORT,float16x2:he.HALF_FLOAT,float16x4:he.HALF_FLOAT,float32:he.FLOAT,float32x2:he.FLOAT,float32x3:he.FLOAT,float32x4:he.FLOAT,uint32:he.UNSIGNED_INT,uint32x2:he.UNSIGNED_INT,uint32x3:he.UNSIGNED_INT,uint32x4:he.UNSIGNED_INT,sint32:he.INT,sint32x2:he.INT,sint32x3:he.INT,sint32x4:he.INT};function hb(s){return jh[s]??jh.float32}const ub={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class db{constructor(){this.vaoCache=Object.create(null)}destroy(){this.vaoCache=Object.create(null)}}class Xh{constructor(e){this._renderer=e,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._managedGeometries=new kt({renderer:e,type:"resource",onUnload:this.onGeometryUnload.bind(this),name:"glGeometry"})}contextChange(){const e=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");this.destroyAll(!0);const t=this._renderer.context.extensions.vertexArrayObject;t&&(e.createVertexArray=()=>t.createVertexArrayOES(),e.bindVertexArray=r=>t.bindVertexArrayOES(r),e.deleteVertexArray=r=>t.deleteVertexArrayOES(r));const i=this._renderer.context.extensions.vertexAttribDivisorANGLE;i&&(e.drawArraysInstanced=(r,n,o,a)=>{i.drawArraysInstancedANGLE(r,n,o,a)},e.drawElementsInstanced=(r,n,o,a,l)=>{i.drawElementsInstancedANGLE(r,n,o,a,l)},e.vertexAttribDivisor=(r,n)=>i.vertexAttribDivisorANGLE(r,n)),this._activeGeometry=null,this._activeVao=null}bind(e,t){const i=this.gl;this._activeGeometry=e;const r=this.getVao(e,t);this._activeVao!==r&&(this._activeVao=r,i.bindVertexArray(r)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const e=this._activeGeometry,t=this._renderer.buffer;for(let i=0;i<e.buffers.length;i++){const r=e.buffers[i];t.updateBuffer(r)}e._gcLastUsed=this._renderer.gc.now}checkCompatibility(e,t){const i=e.attributes,r=t._attributeData;for(const n in r)if(!i[n])throw new Error(`shader and geometry incompatible, geometry missing the "${n}" attribute`)}getSignature(e,t){const i=e.attributes,r=t._attributeData,n=["g",e.uid];for(const o in i)r[o]&&n.push(o,r[o].location);return n.join("-")}getVao(e,t){var i;return((i=e._gpuData[this._renderer.uid])==null?void 0:i.vaoCache[t._key])||this.initGeometryVao(e,t)}initGeometryVao(e,t,i=!0){const r=this._renderer.gl,n=this._renderer.buffer;this._renderer.shader._getProgramData(t),this.checkCompatibility(e,t);const o=this.getSignature(e,t);let a=e._gpuData[this._renderer.uid];a||(a=new db,e._gpuData[this._renderer.uid]=a,this._managedGeometries.add(e));const l=a.vaoCache;let c=l[o];if(c)return l[t._key]=c,c;$h(e,t._attributeData);const h=e.buffers;c=r.createVertexArray(),r.bindVertexArray(c);for(let u=0;u<h.length;u++){const f=h[u];n.bind(f)}return this.activateVao(e,t),l[t._key]=c,l[o]=c,r.bindVertexArray(null),c}onGeometryUnload(e,t=!1){const i=e._gpuData[this._renderer.uid];if(!i)return;const r=i.vaoCache;if(!t)for(const n in r)this._activeVao!==r[n]&&this.resetState(),this.gl.deleteVertexArray(r[n])}destroyAll(e=!1){this._managedGeometries.removeAll(e)}activateVao(e,t){var a;const i=this._renderer.gl,r=this._renderer.buffer,n=e.attributes;e.indexBuffer&&r.bind(e.indexBuffer);let o=null;for(const l in n){const c=n[l],h=c.buffer,u=r.getGlBuffer(h),f=t._attributeData[l];if(f){o!==u&&(r.bind(h),o=u);const d=f.location;i.enableVertexAttribArray(d);const g=At(c.format),_=hb(c.format);if(((a=f.format)==null?void 0:a.substring(1,4))==="int"?i.vertexAttribIPointer(d,g.size,_,c.stride,c.offset):i.vertexAttribPointer(d,g.size,_,g.normalised,c.stride,c.offset),c.instance)if(this.hasInstance){const b=c.divisor??1;i.vertexAttribDivisor(d,b)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(e,t,i,r){const{gl:n}=this._renderer,o=this._activeGeometry,a=ub[e||o.topology];if(r??(r=o.instanceCount),o.indexBuffer){const l=o.indexBuffer.data.BYTES_PER_ELEMENT,c=l===2?n.UNSIGNED_SHORT:n.UNSIGNED_INT;r!==1?n.drawElementsInstanced(a,t||o.indexBuffer.data.length,c,(i||0)*l,r):n.drawElements(a,t||o.indexBuffer.data.length,c,(i||0)*l)}else r!==1?n.drawArraysInstanced(a,i||0,t||o.getSize(),r):n.drawArrays(a,i||0,t||o.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._managedGeometries.destroy(),this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null}}Xh.extension={type:[A.WebGLSystem],name:"geometry"};const fb=new Js({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),Po=class If{constructor(e){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=e}init(e={}){const{useBackBuffer:t,antialias:i}={...If.defaultOptions,...e};this.useBackBuffer=t,this._antialias=i,this._renderer.context.supports.msaa||(se("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=Pt.for2d();const r=new Ii({vertex:`
854
+ `,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...e)}else globalThis.console&&globalThis.console.log(`PixiJS ${or} - ${s} - http://www.pixijs.com/`);Dh=!0}}class vo{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===bt.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),Zy(t)}}}vo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"hello",priority:-2},vo.defaultOptions={hello:!1};const Co=class Ef{constructor(e){this._renderer=e}init(e){e={...Ef.defaultOptions,...e},this.maxUnusedTime=e.renderableGCMaxUnusedTime}get enabled(){return ee("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled}set enabled(e){ee("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled=e}addManagedHash(e,t){ee("8.15.0","RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"hash")}addManagedArray(e,t){ee("8.15.0","RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"array")}addRenderable(e){ee("8.15.0","RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead."),this._renderer.gc.addResource(e,"renderable")}run(){ee("8.15.0","RenderableGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};Co.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"renderableGC",priority:0},Co.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let Jy=Co;const So=class Nr{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._checkCount=e}get maxIdle(){return this._renderer.gc.maxUnusedTime/1e3*60}set maxIdle(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.maxUnusedTime=e/60*1e3}get checkCountMax(){return Math.floor(this._renderer.gc._frequency/1e3)}set checkCountMax(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead.")}get active(){return this._renderer.gc.enabled}set active(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.enabled=e}constructor(e){this._renderer=e,this._checkCount=0}init(e){e.textureGCActive!==Nr.defaultOptions.textureGCActive&&(this.active=e.textureGCActive),e.textureGCMaxIdle!==Nr.defaultOptions.textureGCMaxIdle&&(this.maxIdle=e.textureGCMaxIdle),e.textureGCCheckCountMax!==Nr.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=e.textureGCCheckCountMax)}run(){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};So.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"textureGC"},So.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let Qy=So;const Nh=class Tf{constructor(e={}){if(this.uid=be("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,e={...Tf.defaultOptions,...e},this.stencil=e.stencil,this.depth=e.depth,this.isRoot=e.isRoot,typeof e.colorTextures=="number"){this._managedColorTextures=!0;for(let t=0;t<e.colorTextures;t++)this.colorTextures.push(new De({width:e.width,height:e.height,resolution:e.resolution,antialias:e.antialias}))}else{this.colorTextures=[...e.colorTextures.map(i=>i.source)];const t=this.colorTexture.source;this.resize(t.width,t.height,t._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(e.depthStencilTexture||this.stencil)&&(e.depthStencilTexture instanceof j||e.depthStencilTexture instanceof De?this.depthStencilTexture=e.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new De({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(e,t,i=this.resolution,r=!1){this.dirtyId++,this.colorTextures.forEach((n,o)=>{r&&o===0||n.source.resize(e,t,i)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(e,t,i)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(e=>{e.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};Nh.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let Eo=Nh;const Oi=new Map;_i.register(Oi);function Uh(s,e){if(!Oi.has(s)){const t=new j({source:new yt({resource:s,...e})}),i=()=>{Oi.get(s)===t&&Oi.delete(s)};t.once("destroy",i),t.source.once("destroy",i),Oi.set(s,t)}return Oi.get(s)}const To=class Af{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(e){this.texture.source.autoDensity=e}get resolution(){return this.texture.source._resolution}set resolution(e){this.texture.source.resize(this.texture.source.width,this.texture.source.height,e)}init(e){e={...Af.defaultOptions,...e},e.view&&(ee(Be,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new Se(0,0,e.width,e.height),this.canvas=e.canvas||pe.get().createCanvas(),this.antialias=!!e.antialias,this.texture=Uh(this.canvas,e),this.renderTarget=new Eo({colorTextures:[this.texture],depth:!!e.depth,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.resolution=e.resolution}resize(e,t,i){this.texture.source.resize(e,t,i),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(e=!1){(typeof e=="boolean"?e:!!(e!=null&&e.removeView))&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.destroy()}};To.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"view",priority:0},To.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};const Ao=[Hy,Oh,vo,To,Ph,qy,Qy,kh,Vy,tc,Jy,Bh],Fh=[po,oo,fo,ho,ao,Sh,xh,lo];function eb(s,e,t,i,r,n){const o=n?1:-1;return s.identity(),s.a=1/i*2,s.d=o*(1/r*2),s.tx=-1-e*s.a,s.ty=-o-t*s.d,s}function tb(s){const e=s.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}class wo{constructor(e){this.rootViewPort=new Se,this.viewport=new Se,this.mipLevel=0,this.layer=0,this.onRenderTargetChange=new ol("onRenderTargetChange"),this.projectionMatrix=new H,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=e,e.gc.addCollection(this,"_gpuRenderTargetHash","hash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:e,clear:t,clearColor:i,frame:r,mipLevel:n,layer:o}){var a,l;this._renderTargetStack.length=0,this.push(e,t,i,r,n??0,o??0),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=tb(this.rootRenderTarget),(l=(a=this.adaptor).prerender)==null||l.call(a,this.rootRenderTarget)}postrender(){var e,t;(t=(e=this.adaptor).postrender)==null||t.call(e,this.rootRenderTarget)}bind(e,t=!0,i,r,n=0,o=0){const a=this.getRenderTarget(e),l=this.renderTarget!==a;this.renderTarget=a,this.renderSurface=e;const c=this.getGpuRenderTarget(a);(a.pixelWidth!==c.width||a.pixelHeight!==c.height)&&(this.adaptor.resizeGpuRenderTarget(a),c.width=a.pixelWidth,c.height=a.pixelHeight);const h=a.colorTexture,u=this.viewport,f=h.arrayLayerCount||1;if((o|0)!==o&&(o|=0),o<0||o>=f)throw new Error(`[RenderTargetSystem] layer ${o} is out of bounds (arrayLayerCount=${f}).`);this.mipLevel=n|0,this.layer=o|0;const d=Math.max(h.pixelWidth>>n,1),g=Math.max(h.pixelHeight>>n,1);if(!r&&e instanceof j&&(r=e.frame),r){const _=h._resolution,y=1<<Math.max(n|0,0),x=r.x*_+.5|0,C=r.y*_+.5|0,S=r.width*_+.5|0,E=r.height*_+.5|0;let w=Math.floor(x/y),R=Math.floor(C/y),M=Math.ceil(S/y),D=Math.ceil(E/y);w=Math.min(Math.max(w,0),d-1),R=Math.min(Math.max(R,0),g-1),M=Math.min(Math.max(M,1),d-w),D=Math.min(Math.max(D,1),g-R),u.x=w,u.y=R,u.width=M,u.height=D}else u.x=0,u.y=0,u.width=d,u.height=g;return eb(this.projectionMatrix,0,0,u.width/h.resolution,u.height/h.resolution,!a.isRoot),this.adaptor.startRenderPass(a,t,i,u,n,o),l&&this.onRenderTargetChange.emit(a),a}clear(e,t=it.ALL,i,r=this.mipLevel,n=this.layer){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,i,this.viewport,r,n))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=it.ALL,i,r,n=0,o=0){const a=this.bind(e,t,i,r,n,o);return this._renderTargetStack.push({renderTarget:a,frame:r,mipLevel:n,layer:o}),a}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(e.renderTarget,!1,null,e.frame,e.mipLevel,e.layer)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,i,r,n){i.x<0&&(r.width+=i.x,n.x-=i.x,i.x=0),i.y<0&&(r.height+=i.y,n.y-=i.y,i.y=0);const{pixelWidth:o,pixelHeight:a}=e;return r.width=Math.min(r.width,o-i.x),r.height=Math.min(r.height,a-i.y),this.adaptor.copyToTexture(e,t,i,r,n)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport,0,this.layer))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((e,t)=>{e!==t&&e.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;return yt.test(e)&&(e=Uh(e).source),e instanceof Eo?t=e:e instanceof De&&(t=new Eo({colorTextures:[e]}),e.source instanceof yt&&(t.isRoot=!0),e.once("destroy",()=>{t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e);const i=this._gpuRenderTargetHash[t.uid];i&&(this._gpuRenderTargetHash[t.uid]=null,this.adaptor.destroyGpuRenderTarget(i))})),this._renderSurfaceToRenderTargetHash.set(e,t),t}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this.renderSurface=null}}class ib{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){const t=e.colorTexture,{canvas:i,context:r}=this._ensureCanvas(t);return{canvas:i,context:r,width:i.width,height:i.height}}resizeGpuRenderTarget(e){const t=e.colorTexture,{canvas:i}=this._ensureCanvas(t);i.width=e.pixelWidth,i.height=e.pixelHeight}startRenderPass(e,t,i,r){const n=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=n.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,i,r)}clear(e,t,i,r){const o=this._renderTargetSystem.getGpuRenderTarget(e).context,a=r||{x:0,y:0,width:e.pixelWidth,height:e.pixelHeight};if(o.setTransform(1,0,0,1,0,0),o.clearRect(a.x,a.y,a.width,a.height),i){const l=Pe.shared.setValue(i);l.alpha>0&&(o.globalAlpha=l.alpha,o.fillStyle=l.toHex(),o.fillRect(a.x,a.y,a.width,a.height),o.globalAlpha=1)}}finishRenderPass(){}copyToTexture(e,t,i,r,n){const a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,l=t.source,{context:c}=this._ensureCanvas(l),h=(n==null?void 0:n.x)??0,u=(n==null?void 0:n.y)??0;return c.drawImage(a,i.x,i.y,r.width,r.height,h,u,r.width,r.height),l.update(),t}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;(!t||!yt.test(t))&&(t=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),e.resource=t),(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(t.width=e.pixelWidth,t.height=e.pixelHeight);const i=t.getContext("2d");return{canvas:t,context:i}}}class Gh extends wo{constructor(e){super(e),this.adaptor=new ib,this.adaptor.init(e,this)}}Gh.extension={type:[A.CanvasSystem],name:"renderTarget"};class Lh{constructor(e){}init(){}initSource(e){}generateCanvas(e){const t=pe.get().createCanvas(),i=t.getContext("2d"),r=ne.getCanvasSource(e);if(!r)return t;const n=e.frame,o=e.source._resolution??e.source.resolution??1,a=n.x*o,l=n.y*o,c=n.width*o,h=n.height*o;return t.width=Math.ceil(c),t.height=Math.ceil(h),i.drawImage(r,a,l,c,h,0,0,c,h),t}getPixels(e){const t=this.generateCanvas(e);return{pixels:t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}destroy(){}}Lh.extension={type:[A.CanvasSystem],name:"texture"};const sb=[...Ao,Eh,Th,Lh,Gh],rb=[po,oo,fo,ho,ao,Ch,bh,lo],nb=[vy,Ah],Wh=[],Hh=[],Vh=[];Q.handleByNamedList(A.CanvasSystem,Wh),Q.handleByNamedList(A.CanvasPipes,Hh),Q.handleByNamedList(A.CanvasPipesAdaptor,Vh),Q.add(...sb,...rb,...nb);class ob extends vi{constructor(){const e={name:"canvas",type:bt.CANVAS,systems:Wh,renderPipes:Hh,renderPipeAdaptors:Vh};super(e)}}const ab=Object.freeze(Object.defineProperty({__proto__:null,CanvasRenderer:ob},Symbol.toStringTag,{value:"Module"}));var gr=(s=>(s[s.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",s[s.ARRAY_BUFFER=34962]="ARRAY_BUFFER",s[s.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",s))(gr||{});class lb{constructor(e,t){this._lastBindBaseLocation=-1,this._lastBindCallId=-1,this.buffer=e||null,this.updateID=-1,this.byteLength=-1,this.type=t}destroy(){this.buffer=null,this.updateID=-1,this.byteLength=-1,this.type=-1,this._lastBindBaseLocation=-1,this._lastBindCallId=-1}}class zh{constructor(e){this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=e,this._managedBuffers=new kt({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"glBuffer"})}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gl=null,this._boundBufferBases={}}contextChange(){this._gl=this._renderer.gl,this.destroyAll(!0),this._maxBindings=this._renderer.limits.maxUniformBindings}getGlBuffer(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this.createGLBuffer(e)}bind(e){const{_gl:t}=this,i=this.getGlBuffer(e);t.bindBuffer(i.type,i.buffer)}bindBufferBase(e,t){const{_gl:i}=this;this._boundBufferBases[t]!==e&&(this._boundBufferBases[t]=e,e._lastBindBaseLocation=t,i.bindBufferBase(i.UNIFORM_BUFFER,t,e.buffer))}nextBindBase(e){this._bindCallId++,this._minBaseLocation=0,e&&(this._boundBufferBases[0]=null,this._minBaseLocation=1,this._nextBindBaseIndex<1&&(this._nextBindBaseIndex=1))}freeLocationForBufferBase(e){let t=this.getLastBindBaseLocation(e);if(t>=this._minBaseLocation)return e._lastBindCallId=this._bindCallId,t;let i=0,r=this._nextBindBaseIndex;for(;i<2;){r>=this._maxBindings&&(r=this._minBaseLocation,i++);const n=this._boundBufferBases[r];if(n&&n._lastBindCallId===this._bindCallId){r++;continue}break}return t=r,this._nextBindBaseIndex=r+1,i>=2?-1:(e._lastBindCallId=this._bindCallId,this._boundBufferBases[t]=null,t)}getLastBindBaseLocation(e){const t=e._lastBindBaseLocation;return this._boundBufferBases[t]===e?t:-1}bindBufferRange(e,t,i,r){const{_gl:n}=this;i||(i=0),t||(t=0),this._boundBufferBases[t]=null,n.bindBufferRange(n.UNIFORM_BUFFER,t||0,e.buffer,i*256,r||256)}updateBuffer(e){const{_gl:t}=this,i=this.getGlBuffer(e);if(e._updateID===i.updateID)return i;i.updateID=e._updateID,t.bindBuffer(i.type,i.buffer);const r=e.data,n=e.descriptor.usage&ge.STATIC?t.STATIC_DRAW:t.DYNAMIC_DRAW;return r?i.byteLength>=r.byteLength?t.bufferSubData(i.type,0,r,0,e._updateSize/r.BYTES_PER_ELEMENT):(i.byteLength=r.byteLength,t.bufferData(i.type,r,n)):(i.byteLength=e.descriptor.size,t.bufferData(i.type,i.byteLength,n)),i}destroyAll(e=!1){this._managedBuffers.removeAll(e)}onBufferUnload(e,t=!1){const i=e._gpuData[this._renderer.uid];i&&(t||this._gl.deleteBuffer(i.buffer))}createGLBuffer(e){const{_gl:t}=this;let i=gr.ARRAY_BUFFER;e.descriptor.usage&ge.INDEX?i=gr.ELEMENT_ARRAY_BUFFER:e.descriptor.usage&ge.UNIFORM&&(i=gr.UNIFORM_BUFFER);const r=new lb(t.createBuffer(),i);return e._gpuData[this._renderer.uid]=r,this._managedBuffers.add(e),r}resetState(){this._boundBufferBases=Object.create(null)}}zh.extension={type:[A.WebGLSystem],name:"buffer"};const Io=class wf{constructor(e){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=e,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(e){this.gl=e,this._renderer.gl=e}init(e){e={...wf.defaultOptions,...e};let t=this.multiView=e.multiView;if(e.context&&t&&(se("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),t=!1),t?this.canvas=pe.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,e.context)this.initFromContext(e.context);else{const i=this._renderer.background.alpha<1,r=e.premultipliedAlpha??!0,n=e.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(e.preferWebGLVersion,{alpha:i,premultipliedAlpha:r,antialias:n,stencil:!0,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference??"default"})}}ensureCanvasSize(e){if(!this.multiView){e!==this.canvas&&se("multiView is disabled, but targetCanvas is not the main canvas");return}const{canvas:t}=this;(t.width<e.width||t.height<e.height)&&(t.width=Math.max(e.width,e.width),t.height=Math.max(e.height,e.height))}initFromContext(e){this.gl=e,this.webGLVersion=e instanceof pe.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(e),this._renderer.runners.contextChange.emit(e);const t=this._renderer.view.canvas;t.addEventListener("webglcontextlost",this.handleContextLost,!1),t.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}createContext(e,t){let i;const r=this.canvas;if(e===2&&(i=r.getContext("webgl2",t)),!i&&(i=r.getContext("webgl",t),!i))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=i,this.initFromContext(this.gl)}getExtensions(){const{gl:e}=this,t={anisotropicFiltering:e.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),s3tc:e.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:e.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:e.getExtension("WEBGL_compressed_texture_etc"),etc1:e.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:e.getExtension("WEBGL_compressed_texture_atc"),astc:e.getExtension("WEBGL_compressed_texture_astc"),bptc:e.getExtension("EXT_texture_compression_bptc"),rgtc:e.getExtension("EXT_texture_compression_rgtc"),loseContext:e.getExtension("WEBGL_lose_context")};if(this.webGLVersion===1)this.extensions={...t,drawBuffers:e.getExtension("WEBGL_draw_buffers"),depthTexture:e.getExtension("WEBGL_depth_texture"),vertexArrayObject:e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:e.getExtension("OES_element_index_uint"),floatTexture:e.getExtension("OES_texture_float"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),textureHalfFloat:e.getExtension("OES_texture_half_float"),textureHalfFloatLinear:e.getExtension("OES_texture_half_float_linear"),vertexAttribDivisorANGLE:e.getExtension("ANGLE_instanced_arrays"),srgb:e.getExtension("EXT_sRGB")};else{this.extensions={...t,colorBufferFloat:e.getExtension("EXT_color_buffer_float")};const i=e.getExtension("WEBGL_provoking_vertex");i&&i.provokingVertexWEBGL(i.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(e){e.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{var t;this.gl.isContextLost()&&((t=this.extensions.loseContext)==null||t.restoreContext())},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){var t;const e=this._renderer.view.canvas;this._renderer=null,e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),(t=this.extensions.loseContext)==null||t.loseContext()}forceContextLoss(){var e;(e=this.extensions.loseContext)==null||e.loseContext(),this._contextLossForced=!0}validateContext(e){const t=e.getContextAttributes();t&&!t.stencil&&se("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const i=this.supports,r=this.webGLVersion===2,n=this.extensions;i.uint32Indices=r||!!n.uint32ElementIndex,i.uniformBufferObject=r,i.vertexArrayObject=r||!!n.vertexArrayObject,i.srgbTextures=r||!!n.srgb,i.nonPowOf2wrapping=r,i.nonPowOf2mipmaps=r,i.msaa=r,i.uint32Indices||se("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};Io.extension={type:[A.WebGLSystem],name:"context"},Io.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let cb=Io;function $h(s,e){for(const t in s.attributes){const i=s.attributes[t],r=e[t];r?(i.format??(i.format=r.format),i.offset??(i.offset=r.offset),i.instance??(i.instance=r.instance)):se(`Attribute ${t} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}hb(s)}function hb(s){const{buffers:e,attributes:t}=s,i={},r={};for(const n in e){const o=e[n];i[o.uid]=0,r[o.uid]=0}for(const n in t){const o=t[n];i[o.buffer.uid]+=At(o.format).stride}for(const n in t){const o=t[n];o.stride??(o.stride=i[o.buffer.uid]),o.start??(o.start=r[o.buffer.uid]),r[o.buffer.uid]+=At(o.format).stride}}var Ro=(s=>(s[s.RGBA=6408]="RGBA",s[s.RGB=6407]="RGB",s[s.RG=33319]="RG",s[s.RED=6403]="RED",s[s.RGBA_INTEGER=36249]="RGBA_INTEGER",s[s.RGB_INTEGER=36248]="RGB_INTEGER",s[s.RG_INTEGER=33320]="RG_INTEGER",s[s.RED_INTEGER=36244]="RED_INTEGER",s[s.ALPHA=6406]="ALPHA",s[s.LUMINANCE=6409]="LUMINANCE",s[s.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",s[s.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",s[s.DEPTH_STENCIL=34041]="DEPTH_STENCIL",s))(Ro||{}),Mo=(s=>(s[s.TEXTURE_2D=3553]="TEXTURE_2D",s[s.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",s[s.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",s[s.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",s[s.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",s[s.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",s[s.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",s))(Mo||{}),he=(s=>(s[s.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",s[s.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",s[s.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",s[s.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",s[s.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",s[s.UNSIGNED_INT=5125]="UNSIGNED_INT",s[s.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",s[s.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",s[s.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",s[s.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",s[s.BYTE=5120]="BYTE",s[s.SHORT=5122]="SHORT",s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",s[s.HALF_FLOAT=36193]="HALF_FLOAT",s))(he||{});const jh={uint8x2:he.UNSIGNED_BYTE,uint8x4:he.UNSIGNED_BYTE,sint8x2:he.BYTE,sint8x4:he.BYTE,unorm8x2:he.UNSIGNED_BYTE,unorm8x4:he.UNSIGNED_BYTE,snorm8x2:he.BYTE,snorm8x4:he.BYTE,uint16x2:he.UNSIGNED_SHORT,uint16x4:he.UNSIGNED_SHORT,sint16x2:he.SHORT,sint16x4:he.SHORT,unorm16x2:he.UNSIGNED_SHORT,unorm16x4:he.UNSIGNED_SHORT,snorm16x2:he.SHORT,snorm16x4:he.SHORT,float16x2:he.HALF_FLOAT,float16x4:he.HALF_FLOAT,float32:he.FLOAT,float32x2:he.FLOAT,float32x3:he.FLOAT,float32x4:he.FLOAT,uint32:he.UNSIGNED_INT,uint32x2:he.UNSIGNED_INT,uint32x3:he.UNSIGNED_INT,uint32x4:he.UNSIGNED_INT,sint32:he.INT,sint32x2:he.INT,sint32x3:he.INT,sint32x4:he.INT};function ub(s){return jh[s]??jh.float32}const db={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class fb{constructor(){this.vaoCache=Object.create(null)}destroy(){this.vaoCache=Object.create(null)}}class Xh{constructor(e){this._renderer=e,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._managedGeometries=new kt({renderer:e,type:"resource",onUnload:this.onGeometryUnload.bind(this),name:"glGeometry"})}contextChange(){const e=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");this.destroyAll(!0);const t=this._renderer.context.extensions.vertexArrayObject;t&&(e.createVertexArray=()=>t.createVertexArrayOES(),e.bindVertexArray=r=>t.bindVertexArrayOES(r),e.deleteVertexArray=r=>t.deleteVertexArrayOES(r));const i=this._renderer.context.extensions.vertexAttribDivisorANGLE;i&&(e.drawArraysInstanced=(r,n,o,a)=>{i.drawArraysInstancedANGLE(r,n,o,a)},e.drawElementsInstanced=(r,n,o,a,l)=>{i.drawElementsInstancedANGLE(r,n,o,a,l)},e.vertexAttribDivisor=(r,n)=>i.vertexAttribDivisorANGLE(r,n)),this._activeGeometry=null,this._activeVao=null}bind(e,t){const i=this.gl;this._activeGeometry=e;const r=this.getVao(e,t);this._activeVao!==r&&(this._activeVao=r,i.bindVertexArray(r)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const e=this._activeGeometry,t=this._renderer.buffer;for(let i=0;i<e.buffers.length;i++){const r=e.buffers[i];t.updateBuffer(r)}e._gcLastUsed=this._renderer.gc.now}checkCompatibility(e,t){const i=e.attributes,r=t._attributeData;for(const n in r)if(!i[n])throw new Error(`shader and geometry incompatible, geometry missing the "${n}" attribute`)}getSignature(e,t){const i=e.attributes,r=t._attributeData,n=["g",e.uid];for(const o in i)r[o]&&n.push(o,r[o].location);return n.join("-")}getVao(e,t){var i;return((i=e._gpuData[this._renderer.uid])==null?void 0:i.vaoCache[t._key])||this.initGeometryVao(e,t)}initGeometryVao(e,t,i=!0){const r=this._renderer.gl,n=this._renderer.buffer;this._renderer.shader._getProgramData(t),this.checkCompatibility(e,t);const o=this.getSignature(e,t);let a=e._gpuData[this._renderer.uid];a||(a=new fb,e._gpuData[this._renderer.uid]=a,this._managedGeometries.add(e));const l=a.vaoCache;let c=l[o];if(c)return l[t._key]=c,c;$h(e,t._attributeData);const h=e.buffers;c=r.createVertexArray(),r.bindVertexArray(c);for(let u=0;u<h.length;u++){const f=h[u];n.bind(f)}return this.activateVao(e,t),l[t._key]=c,l[o]=c,r.bindVertexArray(null),c}onGeometryUnload(e,t=!1){const i=e._gpuData[this._renderer.uid];if(!i)return;const r=i.vaoCache;if(!t)for(const n in r)this._activeVao!==r[n]&&this.resetState(),this.gl.deleteVertexArray(r[n])}destroyAll(e=!1){this._managedGeometries.removeAll(e)}activateVao(e,t){var a;const i=this._renderer.gl,r=this._renderer.buffer,n=e.attributes;e.indexBuffer&&r.bind(e.indexBuffer);let o=null;for(const l in n){const c=n[l],h=c.buffer,u=r.getGlBuffer(h),f=t._attributeData[l];if(f){o!==u&&(r.bind(h),o=u);const d=f.location;i.enableVertexAttribArray(d);const g=At(c.format),_=ub(c.format);if(((a=f.format)==null?void 0:a.substring(1,4))==="int"?i.vertexAttribIPointer(d,g.size,_,c.stride,c.offset):i.vertexAttribPointer(d,g.size,_,g.normalised,c.stride,c.offset),c.instance)if(this.hasInstance){const y=c.divisor??1;i.vertexAttribDivisor(d,y)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(e,t,i,r){const{gl:n}=this._renderer,o=this._activeGeometry,a=db[e||o.topology];if(r??(r=o.instanceCount),o.indexBuffer){const l=o.indexBuffer.data.BYTES_PER_ELEMENT,c=l===2?n.UNSIGNED_SHORT:n.UNSIGNED_INT;r!==1?n.drawElementsInstanced(a,t||o.indexBuffer.data.length,c,(i||0)*l,r):n.drawElements(a,t||o.indexBuffer.data.length,c,(i||0)*l)}else r!==1?n.drawArraysInstanced(a,i||0,t||o.getSize(),r):n.drawArrays(a,i||0,t||o.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._managedGeometries.destroy(),this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null}}Xh.extension={type:[A.WebGLSystem],name:"geometry"};const pb=new Qs({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),Po=class If{constructor(e){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=e}init(e={}){const{useBackBuffer:t,antialias:i}={...If.defaultOptions,...e};this.useBackBuffer=t,this._antialias=i,this._renderer.context.supports.msaa||(se("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=Pt.for2d();const r=new Ii({vertex:`
855
855
  attribute vec2 aPosition;
856
856
  out vec2 vUv;
857
857
 
@@ -870,7 +870,7 @@ fn mainFragment(
870
870
 
871
871
  void main() {
872
872
  finalColor = texture(uTexture, vUv);
873
- }`,name:"big-triangle"});this._bigTriangleShader=new Mt({glProgram:r,resources:{uTexture:j.WHITE.source}})}renderStart(e){const t=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!t.isRoot,this._useBackBufferThisRender){const i=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=i.colorTexture,e.target=this._getBackBufferTexture(i.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind(this._targetTexture,!1),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:fb,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(e){return this._backBufferTexture=this._backBufferTexture||new j({source:new De({width:e.width,height:e.height,resolution:e._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(e.width,e.height,e._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&(this._backBufferTexture.destroy(),this._backBufferTexture=null)}};Po.extension={type:[A.WebGLSystem],name:"backBuffer",priority:1},Po.defaultOptions={useBackBuffer:!1};let pb=Po;class Yh{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.gl.colorMask(!!(e&8),!!(e&4),!!(e&2),!!(e&1)))}}Yh.extension={type:[A.WebGLSystem],name:"colorMask"};class qh{constructor(e){this.commandFinished=Promise.resolve(),this._renderer=e}setGeometry(e,t){this._renderer.geometry.bind(e,t.glProgram)}finishRenderPass(){}draw(e){const t=this._renderer,{geometry:i,shader:r,state:n,skipSync:o,topology:a,size:l,start:c,instanceCount:h}=e;t.shader.bind(r,o),t.geometry.bind(i,t.shader._activeProgram),n&&t.state.set(n),t.geometry.draw(a,l,c,h??i.instanceCount)}destroy(){this._renderer=null}}qh.extension={type:[A.WebGLSystem],name:"encoder"};class Kh{constructor(e){this._renderer=e}contextChange(){const e=this._renderer.gl;this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=cc(this.maxTextures,e);const t=this._renderer.context.webGLVersion===2;this.maxUniformBindings=t?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0}destroy(){}}Kh.extension={type:[A.WebGLSystem],name:"limits"};class mb{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this._attachedMipLevel=0,this._attachedLayer=0,this.msaaRenderBuffer=[]}}const Wt=[];Wt[ke.NONE]=void 0,Wt[ke.DISABLED]={stencilWriteMask:0,stencilReadMask:0},Wt[ke.RENDERING_MASK_ADD]={stencilFront:{compare:"equal",passOp:"increment-clamp"},stencilBack:{compare:"equal",passOp:"increment-clamp"}},Wt[ke.RENDERING_MASK_REMOVE]={stencilFront:{compare:"equal",passOp:"decrement-clamp"},stencilBack:{compare:"equal",passOp:"decrement-clamp"}},Wt[ke.MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"equal",passOp:"keep"},stencilBack:{compare:"equal",passOp:"keep"}},Wt[ke.INVERSE_MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"not-equal",passOp:"keep"},stencilBack:{compare:"not-equal",passOp:"keep"}};class Zh{constructor(e){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:ke.NONE},this._renderTargetStencilState=Object.create(null),e.renderTarget.onRenderTargetChange.add(this)}contextChange(e){this._gl=e,this._comparisonFuncMapping={always:e.ALWAYS,never:e.NEVER,equal:e.EQUAL,"not-equal":e.NOTEQUAL,less:e.LESS,"less-equal":e.LEQUAL,greater:e.GREATER,"greater-equal":e.GEQUAL},this._stencilOpsMapping={keep:e.KEEP,zero:e.ZERO,replace:e.REPLACE,invert:e.INVERT,"increment-clamp":e.INCR,"decrement-clamp":e.DECR,"increment-wrap":e.INCR_WRAP,"decrement-wrap":e.DECR_WRAP},this.resetState()}onRenderTargetChange(e){if(this._activeRenderTarget===e)return;this._activeRenderTarget=e;let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:ke.DISABLED,stencilReference:0}),this.setStencilMode(t.stencilMode,t.stencilReference)}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=ke.NONE,this._stencilCache.stencilReference=0}setStencilMode(e,t){const i=this._renderTargetStencilState[this._activeRenderTarget.uid],r=this._gl,n=Wt[e],o=this._stencilCache;if(i.stencilMode=e,i.stencilReference=t,e===ke.DISABLED){this._stencilCache.enabled&&(this._stencilCache.enabled=!1,r.disable(r.STENCIL_TEST));return}this._stencilCache.enabled||(this._stencilCache.enabled=!0,r.enable(r.STENCIL_TEST)),(e!==o.stencilMode||o.stencilReference!==t)&&(o.stencilMode=e,o.stencilReference=t,r.stencilFunc(this._comparisonFuncMapping[n.stencilBack.compare],t,255),r.stencilOp(r.KEEP,r.KEEP,this._stencilOpsMapping[n.stencilBack.passOp]))}}Zh.extension={type:[A.WebGLSystem],name:"stencil"};class gb{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new Se}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new Se;const e=this._renderer.gl;this._drawBuffersCache=[];for(let t=1;t<=16;t++)this._drawBuffersCache[t]=Array.from({length:t},(i,r)=>e.COLOR_ATTACHMENT0+r)}copyToTexture(e,t,i,r,n){const o=this._renderTargetSystem,a=this._renderer,l=o.getGpuRenderTarget(e),c=a.gl;return this.finishRenderPass(e),c.bindFramebuffer(c.FRAMEBUFFER,l.resolveTargetFramebuffer),a.texture.bind(t,0),c.copyTexSubImage2D(c.TEXTURE_2D,0,n.x,n.y,i.x,i.y,r.width,r.height),t}startRenderPass(e,t=!0,i,r,n=0,o=0){const a=this._renderTargetSystem,l=e.colorTexture,c=a.getGpuRenderTarget(e);if(o!==0&&this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to array layers requires WebGL2.");if(n>0){if(c.msaa)throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");if(this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to mip levels requires WebGL2.")}let h=r.y;e.isRoot&&(h=l.pixelHeight-r.height-r.y),e.colorTextures.forEach(d=>{this._renderer.texture.unbind(d)});const u=this._renderer.gl;u.bindFramebuffer(u.FRAMEBUFFER,c.framebuffer),!e.isRoot&&(c._attachedMipLevel!==n||c._attachedLayer!==o)&&(e.colorTextures.forEach((d,g)=>{const _=this._renderer.texture.getGlSource(d);if(_.target===u.TEXTURE_2D){if(o!==0)throw new Error("[RenderTargetSystem] layer must be 0 when rendering to 2D textures in WebGL.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,u.TEXTURE_2D,_.texture,n)}else if(_.target===u.TEXTURE_2D_ARRAY){if(this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to 2D array textures requires WebGL2.");u.framebufferTextureLayer(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,_.texture,n,o)}else if(_.target===u.TEXTURE_CUBE_MAP){if(o<0||o>5)throw new Error("[RenderTargetSystem] Cube map layer must be between 0 and 5.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,u.TEXTURE_CUBE_MAP_POSITIVE_X+o,_.texture,n)}else throw new Error("[RenderTargetSystem] Unsupported texture target for render-to-layer in WebGL.")}),c._attachedMipLevel=n,c._attachedLayer=o),e.colorTextures.length>1&&this._setDrawBuffers(e,u);const f=this._viewPortCache;(f.x!==r.x||f.y!==h||f.width!==r.width||f.height!==r.height)&&(f.x=r.x,f.y=h,f.width=r.width,f.height=r.height,u.viewport(r.x,h,r.width,r.height)),!c.depthStencilRenderBuffer&&(e.stencil||e.depth)&&this._initStencil(c),this.clear(e,t,i)}finishRenderPass(e){const i=this._renderTargetSystem.getGpuRenderTarget(e);if(!i.msaa)return;const r=this._renderer.gl;r.bindFramebuffer(r.FRAMEBUFFER,i.resolveTargetFramebuffer),r.bindFramebuffer(r.READ_FRAMEBUFFER,i.framebuffer),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST),r.bindFramebuffer(r.FRAMEBUFFER,i.framebuffer)}initGpuRenderTarget(e){const i=this._renderer.gl,r=new mb;return r._attachedMipLevel=0,r._attachedLayer=0,e.colorTexture instanceof yt?(this._renderer.context.ensureCanvasSize(e.colorTexture.resource),r.framebuffer=null,r):(this._initColor(e,r),i.bindFramebuffer(i.FRAMEBUFFER,null),r)}destroyGpuRenderTarget(e){const t=this._renderer.gl;e.framebuffer&&(t.deleteFramebuffer(e.framebuffer),e.framebuffer=null),e.resolveTargetFramebuffer&&(t.deleteFramebuffer(e.resolveTargetFramebuffer),e.resolveTargetFramebuffer=null),e.depthStencilRenderBuffer&&(t.deleteRenderbuffer(e.depthStencilRenderBuffer),e.depthStencilRenderBuffer=null),e.msaaRenderBuffer.forEach(i=>{t.deleteRenderbuffer(i)}),e.msaaRenderBuffer=null}clear(e,t,i,r,n=0,o=0){if(!t)return;if(o!==0)throw new Error("[RenderTargetSystem] Clearing array layers is not supported in WebGL renderer.");const a=this._renderTargetSystem;typeof t=="boolean"&&(t=t?it.ALL:it.NONE);const l=this._renderer.gl;if(t&it.COLOR){i??(i=a.defaultClearColor);const c=this._clearColorCache,h=i;(c[0]!==h[0]||c[1]!==h[1]||c[2]!==h[2]||c[3]!==h[3])&&(c[0]=h[0],c[1]=h[1],c[2]=h[2],c[3]=h[3],l.clearColor(h[0],h[1],h[2],h[3]))}l.clear(t)}resizeGpuRenderTarget(e){if(e.isRoot)return;const i=this._renderTargetSystem.getGpuRenderTarget(e);this._resizeColor(e,i),(e.stencil||e.depth)&&this._resizeStencil(i)}_initColor(e,t){const i=this._renderer,r=i.gl,n=r.createFramebuffer();if(t.resolveTargetFramebuffer=n,r.bindFramebuffer(r.FRAMEBUFFER,n),t.width=e.colorTexture.source.pixelWidth,t.height=e.colorTexture.source.pixelHeight,e.colorTextures.forEach((a,l)=>{const c=a.source;c.antialias&&(i.context.supports.msaa?t.msaa=!0:se("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),i.texture.bindSource(c,0);const h=i.texture.getGlSource(c),u=h.texture;if(h.target===r.TEXTURE_2D)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,r.TEXTURE_2D,u,0);else if(h.target===r.TEXTURE_2D_ARRAY){if(i.context.webGLVersion<2)throw new Error("[RenderTargetSystem] TEXTURE_2D_ARRAY requires WebGL2.");r.framebufferTextureLayer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,u,0,0)}else if(h.target===r.TEXTURE_CUBE_MAP)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,r.TEXTURE_CUBE_MAP_POSITIVE_X,u,0);else throw new Error("[RenderTargetSystem] Unsupported texture target for framebuffer attachment.")}),t.msaa){const a=r.createFramebuffer();t.framebuffer=a,r.bindFramebuffer(r.FRAMEBUFFER,a),e.colorTextures.forEach((l,c)=>{const h=r.createRenderbuffer();t.msaaRenderBuffer[c]=h})}else t.framebuffer=n;this._resizeColor(e,t)}_resizeColor(e,t){const i=e.colorTexture.source;if(t.width=i.pixelWidth,t.height=i.pixelHeight,t._attachedMipLevel=0,t._attachedLayer=0,e.colorTextures.forEach((r,n)=>{n!==0&&r.source.resize(i.width,i.height,i._resolution)}),t.msaa){const r=this._renderer,n=r.gl,o=t.framebuffer;n.bindFramebuffer(n.FRAMEBUFFER,o),e.colorTextures.forEach((a,l)=>{const c=a.source;r.texture.bindSource(c,0);const u=r.texture.getGlSource(c).internalFormat,f=t.msaaRenderBuffer[l];n.bindRenderbuffer(n.RENDERBUFFER,f),n.renderbufferStorageMultisample(n.RENDERBUFFER,4,u,c.pixelWidth,c.pixelHeight),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+l,n.RENDERBUFFER,f)})}}_initStencil(e){if(e.framebuffer===null)return;const t=this._renderer.gl,i=t.createRenderbuffer();e.depthStencilRenderBuffer=i,t.bindRenderbuffer(t.RENDERBUFFER,i),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,i),this._resizeStencil(e)}_resizeStencil(e){const t=this._renderer.gl;t.bindRenderbuffer(t.RENDERBUFFER,e.depthStencilRenderBuffer),e.msaa?t.renderbufferStorageMultisample(t.RENDERBUFFER,4,t.DEPTH24_STENCIL8,e.width,e.height):t.renderbufferStorage(t.RENDERBUFFER,this._renderer.context.webGLVersion===2?t.DEPTH24_STENCIL8:t.DEPTH_STENCIL,e.width,e.height)}prerender(e){const t=e.colorTexture.resource;this._renderer.context.multiView&&yt.test(t)&&this._renderer.context.ensureCanvasSize(t)}postrender(e){if(this._renderer.context.multiView&&yt.test(e.colorTexture.resource)){const t=this._renderer.context.canvas,i=e.colorTexture;i.context2D.drawImage(t,0,i.pixelHeight-t.height)}}_setDrawBuffers(e,t){const i=e.colorTextures.length,r=this._drawBuffersCache[i];if(this._renderer.context.webGLVersion===1){const n=this._renderer.context.extensions.drawBuffers;n?n.drawBuffersWEBGL(r):se("[RenderTexture] This WebGL1 context does not support rendering to multiple targets")}else t.drawBuffers(r)}}class Jh extends wo{constructor(e){super(e),this.adaptor=new gb,this.adaptor.init(e,this)}}Jh.extension={type:[A.WebGLSystem],name:"renderTarget"};function _b(s){const e={};if(e.normal=[s.ONE,s.ONE_MINUS_SRC_ALPHA],e.add=[s.ONE,s.ONE],e.multiply=[s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],e.screen=[s.ONE,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],e.none=[0,0],e["normal-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],e["add-npm"]=[s.SRC_ALPHA,s.ONE,s.ONE,s.ONE],e["screen-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],e.erase=[s.ZERO,s.ONE_MINUS_SRC_ALPHA],!(s instanceof pe.get().getWebGLRenderingContext()))e.min=[s.ONE,s.ONE,s.ONE,s.ONE,s.MIN,s.MIN],e.max=[s.ONE,s.ONE,s.ONE,s.ONE,s.MAX,s.MAX];else{const i=s.getExtension("EXT_blend_minmax");i&&(e.min=[s.ONE,s.ONE,s.ONE,s.ONE,i.MIN_EXT,i.MIN_EXT],e.max=[s.ONE,s.ONE,s.ONE,s.ONE,i.MAX_EXT,i.MAX_EXT])}return e}const yb=0,bb=1,xb=2,vb=3,Cb=4,Sb=5,Qh=class da{constructor(e){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[yb]=this.setBlend,this.map[bb]=this.setOffset,this.map[xb]=this.setCullFace,this.map[vb]=this.setDepthTest,this.map[Cb]=this.setFrontFace,this.map[Sb]=this.setDepthMask,this.checks=[],this.defaultState=Pt.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=!e.isRoot,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=_b(e),this.resetState()}set(e){if(e||(e=this.defaultState),this.stateId!==e.data){let t=this.stateId^e.data,i=0;for(;t;)t&1&&this.map[i].call(this,!!(e.data&1<<i)),t>>=1,i++;this.stateId=e.data}for(let t=0;t<this.checks.length;t++)this.checks[t](this,e)}forceState(e){e||(e=this.defaultState);for(let t=0;t<this.map.length;t++)this.map[t].call(this,!!(e.data&1<<t));for(let t=0;t<this.checks.length;t++)this.checks[t](this,e);this.stateId=e.data}setBlend(e){this._updateCheck(da._checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this._updateCheck(da._checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(e){this.gl[e?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(e){this.gl.depthMask(e)}setCullFace(e){this._cullFace=e,this.gl[e?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(e){this._frontFace=e,this._frontFaceDirty=!1;const t=this._invertFrontFace?!e:e;this._glFrontFace!==t&&(this._glFrontFace=t,this.gl.frontFace(this.gl[t?"CW":"CCW"]))}setBlendMode(e){if(this.blendModesMap[e]||(e="normal"),e===this.blendMode)return;this.blendMode=e;const t=this.blendModesMap[e],i=this.gl;t.length===2?i.blendFunc(t[0],t[1]):i.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,i.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD))}setPolygonOffset(e,t){this.gl.polygonOffset(e,t)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(e,t){const i=this.checks.indexOf(e);t&&i===-1?this.checks.push(e):!t&&i!==-1&&this.checks.splice(i,1)}static _checkBlendMode(e,t){e.setBlendMode(t.blendMode)}static _checkPolygonOffset(e,t){e.setPolygonOffset(1,t.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}};Qh.extension={type:[A.WebGLSystem],name:"state"};let Eb=Qh;class Tb{constructor(e){this.target=Mo.TEXTURE_2D,this._layerInitMask=0,this.texture=e,this.width=-1,this.height=-1,this.type=he.UNSIGNED_BYTE,this.internalFormat=Ro.RGBA,this.format=Ro.RGBA,this.samplerType=0}destroy(){}}const Ab={id:"buffer",upload(s,e,t,i,r,n=!1){const o=r||e.target;!n&&e.width===s.width&&e.height===s.height?t.texSubImage2D(o,0,0,0,s.width,s.height,e.format,e.type,s.resource):t.texImage2D(o,0,e.internalFormat,s.width,s.height,0,e.format,e.type,s.resource),e.width=s.width,e.height=s.height}},wb={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},Ib={id:"compressed",upload(s,e,t,i,r,n){const o=r??e.target;t.pixelStorei(t.UNPACK_ALIGNMENT,4);let a=s.pixelWidth,l=s.pixelHeight;const c=!!wb[s.format];for(let h=0;h<s.resource.length;h++){const u=s.resource[h];c?t.compressedTexImage2D(o,h,e.internalFormat,a,l,0,u):t.texImage2D(o,h,e.internalFormat,a,l,0,e.format,e.type,u),a=Math.max(a>>1,1),l=Math.max(l>>1,1)}}},eu=["right","left","top","bottom","front","back"];function Rb(s){return{id:"cube",upload(e,t,i,r){const n=e.faces;for(let o=0;o<eu.length;o++){const a=eu[o],l=n[a];(s[l.uploadMethodId]||s.image).upload(l,t,i,r,Mo.TEXTURE_CUBE_MAP_POSITIVE_X+o,(t._layerInitMask&1<<o)===0),t._layerInitMask|=1<<o}t.width=e.pixelWidth,t.height=e.pixelHeight}}}const tu={id:"image",upload(s,e,t,i,r,n=!1){const o=r||e.target,a=s.pixelWidth,l=s.pixelHeight,c=s.resourceWidth,h=s.resourceHeight,u=i===2,f=n||e.width!==a||e.height!==l,d=c>=a&&h>=l,g=s.resource;(u?Mb:Pb)(t,o,e,a,l,c,h,g,f,d),e.width=a,e.height=l}};function Mb(s,e,t,i,r,n,o,a,l,c){if(!c){l&&s.texImage2D(e,0,t.internalFormat,i,r,0,t.format,t.type,null),s.texSubImage2D(e,0,0,0,n,o,t.format,t.type,a);return}if(!l){s.texSubImage2D(e,0,0,0,t.format,t.type,a);return}s.texImage2D(e,0,t.internalFormat,i,r,0,t.format,t.type,a)}function Pb(s,e,t,i,r,n,o,a,l,c){if(!c){l&&s.texImage2D(e,0,t.internalFormat,i,r,0,t.format,t.type,null),s.texSubImage2D(e,0,0,0,t.format,t.type,a);return}if(!l){s.texSubImage2D(e,0,0,0,t.format,t.type,a);return}s.texImage2D(e,0,t.internalFormat,t.format,t.type,a)}const kb=by(),Ob={id:"video",upload(s,e,t,i,r,n=kb){if(!s.isValid){const o=r??e.target;t.texImage2D(o,0,e.internalFormat,1,1,0,e.format,e.type,null);return}tu.upload(s,e,t,i,r,n)}},iu={linear:9729,nearest:9728},Bb={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},ko={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},Db={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function su(s,e,t,i,r,n,o,a){const l=n;if(!a||s.addressModeU!=="repeat"||s.addressModeV!=="repeat"||s.addressModeW!=="repeat"){const c=ko[o?"clamp-to-edge":s.addressModeU],h=ko[o?"clamp-to-edge":s.addressModeV],u=ko[o?"clamp-to-edge":s.addressModeW];e[r](l,e.TEXTURE_WRAP_S,c),e[r](l,e.TEXTURE_WRAP_T,h),e.TEXTURE_WRAP_R&&e[r](l,e.TEXTURE_WRAP_R,u)}if((!a||s.magFilter!=="linear")&&e[r](l,e.TEXTURE_MAG_FILTER,iu[s.magFilter]),t){if(!a||s.mipmapFilter!=="linear"){const c=Bb[s.minFilter][s.mipmapFilter];e[r](l,e.TEXTURE_MIN_FILTER,c)}}else e[r](l,e.TEXTURE_MIN_FILTER,iu[s.minFilter]);if(i&&s.maxAnisotropy>1){const c=Math.min(s.maxAnisotropy,e.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT));e[r](l,i.TEXTURE_MAX_ANISOTROPY_EXT,c)}s.compare&&e[r](l,e.TEXTURE_COMPARE_FUNC,Db[s.compare])}function Nb(s){return{r8unorm:s.RED,r8snorm:s.RED,r8uint:s.RED,r8sint:s.RED,r16uint:s.RED,r16sint:s.RED,r16float:s.RED,rg8unorm:s.RG,rg8snorm:s.RG,rg8uint:s.RG,rg8sint:s.RG,r32uint:s.RED,r32sint:s.RED,r32float:s.RED,rg16uint:s.RG,rg16sint:s.RG,rg16float:s.RG,rgba8unorm:s.RGBA,"rgba8unorm-srgb":s.RGBA,rgba8snorm:s.RGBA,rgba8uint:s.RGBA,rgba8sint:s.RGBA,bgra8unorm:s.RGBA,"bgra8unorm-srgb":s.RGBA,rgb9e5ufloat:s.RGB,rgb10a2unorm:s.RGBA,rg11b10ufloat:s.RGB,rg32uint:s.RG,rg32sint:s.RG,rg32float:s.RG,rgba16uint:s.RGBA,rgba16sint:s.RGBA,rgba16float:s.RGBA,rgba32uint:s.RGBA,rgba32sint:s.RGBA,rgba32float:s.RGBA,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT,depth24plus:s.DEPTH_COMPONENT,"depth24plus-stencil8":s.DEPTH_STENCIL,depth32float:s.DEPTH_COMPONENT,"depth32float-stencil8":s.DEPTH_STENCIL}}function Ub(s,e){let t={},i=s.RGBA;return s instanceof pe.get().getWebGLRenderingContext()?e.srgb&&(t={"rgba8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT}):(t={"rgba8unorm-srgb":s.SRGB8_ALPHA8,"bgra8unorm-srgb":s.SRGB8_ALPHA8},i=s.RGBA8),{r8unorm:s.R8,r8snorm:s.R8_SNORM,r8uint:s.R8UI,r8sint:s.R8I,r16uint:s.R16UI,r16sint:s.R16I,r16float:s.R16F,rg8unorm:s.RG8,rg8snorm:s.RG8_SNORM,rg8uint:s.RG8UI,rg8sint:s.RG8I,r32uint:s.R32UI,r32sint:s.R32I,r32float:s.R32F,rg16uint:s.RG16UI,rg16sint:s.RG16I,rg16float:s.RG16F,rgba8unorm:s.RGBA,...t,rgba8snorm:s.RGBA8_SNORM,rgba8uint:s.RGBA8UI,rgba8sint:s.RGBA8I,bgra8unorm:i,rgb9e5ufloat:s.RGB9_E5,rgb10a2unorm:s.RGB10_A2,rg11b10ufloat:s.R11F_G11F_B10F,rg32uint:s.RG32UI,rg32sint:s.RG32I,rg32float:s.RG32F,rgba16uint:s.RGBA16UI,rgba16sint:s.RGBA16I,rgba16float:s.RGBA16F,rgba32uint:s.RGBA32UI,rgba32sint:s.RGBA32I,rgba32float:s.RGBA32F,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT16,depth24plus:s.DEPTH_COMPONENT24,"depth24plus-stencil8":s.DEPTH24_STENCIL8,depth32float:s.DEPTH_COMPONENT32F,"depth32float-stencil8":s.DEPTH32F_STENCIL8,...e.s3tc?{"bc1-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...e.s3tc_sRGB?{"bc1-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...e.rgtc?{"bc4-r-unorm":e.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":e.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":e.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":e.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...e.bptc?{"bc6h-rgb-float":e.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":e.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":e.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":e.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...e.etc?{"etc2-rgb8unorm":e.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":e.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":e.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":e.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":e.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":e.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":e.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":e.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...e.astc?{"astc-4x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function Fb(s){return{r8unorm:s.UNSIGNED_BYTE,r8snorm:s.BYTE,r8uint:s.UNSIGNED_BYTE,r8sint:s.BYTE,r16uint:s.UNSIGNED_SHORT,r16sint:s.SHORT,r16float:s.HALF_FLOAT,rg8unorm:s.UNSIGNED_BYTE,rg8snorm:s.BYTE,rg8uint:s.UNSIGNED_BYTE,rg8sint:s.BYTE,r32uint:s.UNSIGNED_INT,r32sint:s.INT,r32float:s.FLOAT,rg16uint:s.UNSIGNED_SHORT,rg16sint:s.SHORT,rg16float:s.HALF_FLOAT,rgba8unorm:s.UNSIGNED_BYTE,"rgba8unorm-srgb":s.UNSIGNED_BYTE,rgba8snorm:s.BYTE,rgba8uint:s.UNSIGNED_BYTE,rgba8sint:s.BYTE,bgra8unorm:s.UNSIGNED_BYTE,"bgra8unorm-srgb":s.UNSIGNED_BYTE,rgb9e5ufloat:s.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:s.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:s.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:s.UNSIGNED_INT,rg32sint:s.INT,rg32float:s.FLOAT,rgba16uint:s.UNSIGNED_SHORT,rgba16sint:s.SHORT,rgba16float:s.HALF_FLOAT,rgba32uint:s.UNSIGNED_INT,rgba32sint:s.INT,rgba32float:s.FLOAT,stencil8:s.UNSIGNED_BYTE,depth16unorm:s.UNSIGNED_SHORT,depth24plus:s.UNSIGNED_INT,"depth24plus-stencil8":s.UNSIGNED_INT_24_8,depth32float:s.FLOAT,"depth32float-stencil8":s.FLOAT_32_UNSIGNED_INT_24_8_REV}}function Gb(s){return{"2d":s.TEXTURE_2D,cube:s.TEXTURE_CUBE_MAP,"1d":null,"3d":(s==null?void 0:s.TEXTURE_3D)||null,"2d-array":(s==null?void 0:s.TEXTURE_2D_ARRAY)||null,"cube-array":(s==null?void 0:s.TEXTURE_CUBE_MAP_ARRAY)||null}}const Lb=4;class ru{constructor(e){this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=e,this._managedTextures=new kt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"glTexture"});const t={image:tu,buffer:Ab,video:Ob,compressed:Ib};this._uploads={...t,cube:Rb(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=Ub(e,this._renderer.context.extensions),this._mapFormatToType=Fb(e),this._mapFormatToFormat=Nb(e),this._mapViewDimensionToGlTarget=Gb(e)),this._managedTextures.removeAll(!0),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let t=0;t<16;t++)this.bind(j.EMPTY,t)}initSource(e){this.bind(e)}bind(e,t=0){const i=e.source;e?(this.bindSource(i,t),this._useSeparateSamplers&&this._bindSampler(i.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){const i=this._gl;if(e._gcLastUsed=this._renderer.gc.now,this._boundTextures[t]!==e){this._boundTextures[t]=e,this._activateLocation(t),e||(e=j.EMPTY.source);const r=this.getGlSource(e);i.bindTexture(r.target,r.texture)}}_bindSampler(e,t=0){const i=this._gl;if(!e){this._boundSamplers[t]=null,i.bindSampler(t,null);return}const r=this._getGlSampler(e);this._boundSamplers[t]!==r&&(this._boundSamplers[t]=r,i.bindSampler(t,r))}unbind(e){const t=e.source,i=this._boundTextures,r=this._gl;for(let n=0;n<i.length;n++)if(i[n]===t){this._activateLocation(n);const o=this.getGlSource(t);r.bindTexture(o.target,null),i[n]=null}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){const t=this._gl,i=new Tb(t.createTexture());if(i.type=this._mapFormatToType[e.format],i.internalFormat=this._mapFormatToInternalFormat[e.format],i.format=this._mapFormatToFormat[e.format],i.target=this._mapViewDimensionToGlTarget[e.viewDimension],i.target===null)throw new Error(`Unsupported view dimension: ${e.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(e.uploadMethodId==="cube"&&(i.target=t.TEXTURE_CUBE_MAP),e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){const n=Math.max(e.width,e.height);e.mipLevelCount=Math.floor(Math.log2(n))+1}return e._gpuData[this._renderer.uid]=i,this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceUpdate,this),e.on("styleChange",this.onStyleChange,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),this.updateStyle(e,!1),i}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){const i=this._gl,r=this.getGlSource(e);i.bindTexture(r.target,r.texture),this._boundTextures[this._activeTextureLocation]=e,su(e.style,i,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",r.target,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e,t=!1){const i=e._gpuData[this._renderer.uid];i&&(t||(this.unbind(e),this._gl.deleteTexture(i.texture)),e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceUpdate,this),e.off("styleChange",this.onStyleChange,this),e.off("updateMipmaps",this.onUpdateMipmaps,this))}onSourceUpdate(e){const t=this._gl,i=this.getGlSource(e);t.bindTexture(i.target,i.texture),this._boundTextures[this._activeTextureLocation]=e;const r=e.alphaMode==="premultiply-alpha-on-upload";if(this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[e.uploadMethodId])this._uploads[e.uploadMethodId].upload(e,i,t,this._renderer.context.webGLVersion);else if(i.target===t.TEXTURE_2D)this._initEmptyTexture2D(i,e);else if(i.target===t.TEXTURE_2D_ARRAY)this._initEmptyTexture2DArray(i,e);else if(i.target===t.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(i,e);else throw new Error("[GlTextureSystem] Unsupported texture target for empty allocation.");this._applyMipRange(i,e),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);const i=this.getGlSource(e);this._gl.generateMipmap(i.target)}_initEmptyTexture2D(e,t){const i=this._gl;i.texImage2D(i.TEXTURE_2D,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let r=Math.max(t.pixelWidth>>1,1),n=Math.max(t.pixelHeight>>1,1);for(let o=1;o<t.mipLevelCount;o++)i.texImage2D(i.TEXTURE_2D,o,e.internalFormat,r,n,0,e.format,e.type,null),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}_initEmptyTexture2DArray(e,t){if(this._renderer.context.webGLVersion!==2)throw new Error("[GlTextureSystem] TEXTURE_2D_ARRAY requires WebGL2.");const i=this._gl,r=Math.max(t.arrayLayerCount|0,1);i.texImage3D(i.TEXTURE_2D_ARRAY,0,e.internalFormat,t.pixelWidth,t.pixelHeight,r,0,e.format,e.type,null);let n=Math.max(t.pixelWidth>>1,1),o=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++)i.texImage3D(i.TEXTURE_2D_ARRAY,a,e.internalFormat,n,o,r,0,e.format,e.type,null),n=Math.max(n>>1,1),o=Math.max(o>>1,1)}_initEmptyTextureCube(e,t){const i=this._gl,r=6;for(let a=0;a<r;a++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let n=Math.max(t.pixelWidth>>1,1),o=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++){for(let l=0;l<r;l++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+l,a,e.internalFormat,n,o,0,e.format,e.type,null);n=Math.max(n>>1,1),o=Math.max(o>>1,1)}}_applyMipRange(e,t){if(this._renderer.context.webGLVersion!==2)return;const i=this._gl,r=Math.max((t.mipLevelCount|0)-1,0);i.texParameteri(e.target,i.TEXTURE_BASE_LEVEL,0),i.texParameteri(e.target,i.TEXTURE_MAX_LEVEL,r)}_initSampler(e){const t=this._gl,i=this._gl.createSampler();return this._glSamplers[e._resourceId]=i,su(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",i,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this._initSource(e)}generateCanvas(e){const{pixels:t,width:i,height:r}=this.getPixels(e),n=pe.get().createCanvas();n.width=i,n.height=r;const o=n.getContext("2d");if(o){const a=o.createImageData(i,r);a.data.set(t),o.putImageData(a,0,0)}return n}getPixels(e){const t=e.source.resolution,i=e.frame,r=Math.max(Math.round(i.width*t),1),n=Math.max(Math.round(i.height*t),1),o=new Uint8Array(Lb*r*n),a=this._renderer,l=a.renderTarget.getRenderTarget(e),c=a.renderTarget.getGpuRenderTarget(l),h=a.gl;return h.bindFramebuffer(h.FRAMEBUFFER,c.resolveTargetFramebuffer),h.readPixels(Math.round(i.x*t),Math.round(i.y*t),r,n,h.RGBA,h.UNSIGNED_BYTE,o),{pixels:new Uint8ClampedArray(o.buffer),width:r,height:n}}destroy(){this._managedTextures.destroy(),this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(j.EMPTY.source),this._boundSamplers=Object.create(null);const e=this._gl;this._premultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}ru.extension={type:[A.WebGLSystem],name:"texture"};class nu{contextChange(e){const t=new ht({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),i=e.limits.maxBatchableTextures,r=Ln({name:"graphics",bits:[Cc,Ec(i),mh,zn]});this.shader=new Mt({glProgram:r,resources:{localUniforms:t,batchSamplers:Ac(i)}})}execute(e,t){const i=t.context,r=i.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i);r.groups[0]=n.globalUniforms.bindGroup,n.state.set(e.state),n.shader.bind(r),n.geometry.bind(a.geometry,r.glProgram);const c=l.instructions;for(let h=0;h<l.instructionSize;h++){const u=c[h];if(u.size){for(let f=0;f<u.textures.count;f++)n.texture.bind(u.textures.textures[f],f);n.geometry.draw(u.topology,u.size,u.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}nu.extension={type:[A.WebGLPipesAdaptor],name:"graphics"};class ou{init(){const e=Ln({name:"mesh",bits:[mh,Cy,zn]});this._shader=new Mt({glProgram:e,resources:{uTexture:j.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const i=e.renderer;let r=t._shader;if(r){if(!r.glProgram){se("Mesh shader has no glProgram",t.shader);return}}else{r=this._shader;const n=t.texture,o=n.source;r.resources.uTexture=o,r.resources.uSampler=o.style,r.resources.textureUniforms.uniforms.uTextureMatrix=n.textureMatrix.mapCoord}r.groups[100]=i.globalUniforms.bindGroup,r.groups[101]=e.localUniformsBindGroup,i.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}ou.extension={type:[A.WebGLPipesAdaptor],name:"mesh"};const Wb=[...Ao,Hr,pb,lb,Kh,zh,ru,Jh,Xh,Yr,Xr,qh,Eb,Zh,Yh],Hb=[...Fh],Vb=[_h,ou,nu],au=[],lu=[],cu=[];Q.handleByNamedList(A.WebGLSystem,au),Q.handleByNamedList(A.WebGLPipes,lu),Q.handleByNamedList(A.WebGLPipesAdaptor,cu),Q.add(...Wb,...Hb,...Vb);class zb extends vi{constructor(){const e={name:"webgl",type:bt.WEBGL,systems:au,renderPipes:lu,renderPipeAdaptors:cu};super(e)}}const $b=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:zb},Symbol.toStringTag,{value:"Module"}));class hu{constructor(e){this._hash=Object.create(null),this._renderer=e}contextChange(e){this._gpu=e}getBindGroup(e,t,i){return e._updateKey(),this._hash[e._key]||this._createBindGroup(e,t,i)}_createBindGroup(e,t,i){const r=this._gpu.device,n=t.layout[i],o=[],a=this._renderer;for(const h in n){const u=e.resources[h]??e.resources[n[h]];let f;if(u._resourceType==="uniformGroup"){const d=u;a.ubo.updateUniformGroup(d);const g=d.buffer;f={buffer:a.buffer.getGPUBuffer(g),offset:0,size:g.descriptor.size}}else if(u._resourceType==="buffer"){const d=u;f={buffer:a.buffer.getGPUBuffer(d),offset:0,size:d.descriptor.size}}else if(u._resourceType==="bufferResource"){const d=u;f={buffer:a.buffer.getGPUBuffer(d.buffer),offset:d.offset,size:d.size}}else if(u._resourceType==="textureSampler"){const d=u;f=a.texture.getGpuSampler(d)}else if(u._resourceType==="textureSource"){const d=u;f=a.texture.getTextureView(d)}o.push({binding:n[h],resource:f})}const l=a.shader.getProgramData(t).bindGroups[i],c=r.createBindGroup({layout:l,entries:o});return this._hash[e._key]=c,c}destroy(){this._hash=null,this._renderer=null}}hu.extension={type:[A.WebGPUSystem],name:"bindGroup"};class jb{constructor(e){this.gpuBuffer=e}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}}class uu{constructor(e){this._renderer=e,this._managedBuffers=new kt({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"gpuBuffer"})}contextChange(e){this._gpu=e}getGPUBuffer(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuBuffer)||this.createGPUBuffer(e)}updateBuffer(e){const t=this.getGPUBuffer(e),i=e.data;return e._updateID&&i&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,0,i.buffer,0,(e._updateSize||i.byteLength)+3&-4)),t}destroyAll(){this._managedBuffers.removeAll()}onBufferUnload(e){e.off("update",this.updateBuffer,this),e.off("change",this.onBufferChange,this)}createGPUBuffer(e){const t=this._gpu.device.createBuffer(e.descriptor);return e._updateID=0,e._resourceId=be("resource"),e.data&&(Un(e.data.buffer,t.getMappedRange(),e.data.byteOffset,e.data.byteLength),t.unmap()),e._gpuData[this._renderer.uid]=new jb(t),this._managedBuffers.add(e)&&(e.on("update",this.updateBuffer,this),e.on("change",this.onBufferChange,this)),t}onBufferChange(e){this._managedBuffers.remove(e),e._updateID=0,this.createGPUBuffer(e)}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gpu=null}}uu.extension={type:[A.WebGPUSystem],name:"buffer"};class Xb{constructor({minUniformOffsetAlignment:e}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=e,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(e){if(e>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${e*4}`);const t=this.byteIndex;let i=t+e*4;if(i=Math.ceil(i/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,i>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=i,t}addGroup(e){const t=this.addEmptyGroup(e.length);for(let i=0;i<e.length;i++)this.data[t/4+i]=e[i];return t}destroy(){this.data=null}}class du{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.pipeline.setColorMask(e))}destroy(){this._renderer=null,this._colorMaskCache=null}}du.extension={type:[A.WebGPUSystem],name:"colorMask"};class Oo{constructor(e){this._renderer=e}async init(e){return this._initPromise?this._initPromise:(this._initPromise=(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(t=>{this.gpu=t,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){const t=await pe.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter}),i=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(n=>t.features.has(n)),r=await t.requestDevice({requiredFeatures:i});return{adapter:t,device:r}}destroy(){this.gpu=null,this._renderer=null}}Oo.extension={type:[A.WebGPUSystem],name:"device"},Oo.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class fu{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(e.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(e){this.renderPassEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setPipelineFromGeometryProgramAndState(e,t,i,r){const n=this._renderer.pipeline.getPipeline(e,t,i,r);this.setPipeline(n)}setPipeline(e){this._boundPipeline!==e&&(this._boundPipeline=e,this.renderPassEncoder.setPipeline(e))}_setVertexBuffer(e,t){this._boundVertexBuffer[e]!==t&&(this._boundVertexBuffer[e]=t,this.renderPassEncoder.setVertexBuffer(e,this._renderer.buffer.updateBuffer(t)))}_setIndexBuffer(e){if(this._boundIndexBuffer===e)return;this._boundIndexBuffer=e;const t=e.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(e),t)}resetBindGroup(e){this._boundBindGroup[e]=null}setBindGroup(e,t,i){if(this._boundBindGroup[e]===t)return;this._boundBindGroup[e]=t,t._touch(this._renderer.gc.now,this._renderer.tick);const r=this._renderer.bindGroup.getBindGroup(t,i,e);this.renderPassEncoder.setBindGroup(e,r)}setGeometry(e,t){const i=this._renderer.pipeline.getBufferNamesToBind(e,t);for(const r in i)this._setVertexBuffer(parseInt(r,10),e.attributes[i[r]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){for(const i in e.groups){const r=e.groups[i];t||this._syncBindGroup(r),this.setBindGroup(i,r,e.gpuProgram)}}_syncBindGroup(e){for(const t in e.resources){const i=e.resources[t];i.isUniformGroup&&this._renderer.ubo.updateUniformGroup(i)}}draw(e){const{geometry:t,shader:i,state:r,topology:n,size:o,start:a,instanceCount:l,skipSync:c}=e;this.setPipelineFromGeometryProgramAndState(t,i.gpuProgram,r,n),this.setGeometry(t,i.gpuProgram),this._setShaderBindGroups(i,c),t.indexBuffer?this.renderPassEncoder.drawIndexed(o||t.indexBuffer.data.length,l??t.instanceCount,a||0):this.renderPassEncoder.draw(o||t.getSize(),l??t.instanceCount,a||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){const e=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1],this._renderer.renderTarget.mipLevel,this._renderer.renderTarget.layer);this.renderPassEncoder=this.commandEncoder.beginRenderPass(e);const t=this._boundPipeline,i={...this._boundVertexBuffer},r=this._boundIndexBuffer,n={...this._boundBindGroup};this._clearCache();const o=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(o.x,o.y,o.width,o.height,0,1),this.setPipeline(t);for(const a in i)this._setVertexBuffer(a,i[a]);for(const a in n)this.setBindGroup(a,n[a],null);this._setIndexBuffer(r)}_clearCache(){for(let e=0;e<16;e++)this._boundBindGroup[e]=null,this._boundVertexBuffer[e]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(e){this._gpu=e}}fu.extension={type:[A.WebGPUSystem],name:"encoder",priority:1};class pu{constructor(e){this._renderer=e}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}}pu.extension={type:[A.WebGPUSystem],name:"limits"};class mu{constructor(e){this._renderTargetStencilState=Object.create(null),this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:ke.DISABLED,stencilReference:0}),this._activeRenderTarget=e,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){const i=this._renderTargetStencilState[this._activeRenderTarget.uid];i.stencilMode=e,i.stencilReference=t;const r=this._renderer;r.pipeline.setStencilMode(e),r.encoder.renderPassEncoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}mu.extension={type:[A.WebGPUSystem],name:"stencil"};const Ht=128;class gu{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._batchBuffer=new Xb({minUniformOffsetAlignment:Ht});const t=256/Ht;for(let i=0;i<t;i++){let r=ge.UNIFORM|ge.COPY_DST;i===0&&(r|=ge.COPY_SRC),this._buffers.push(new gt({data:this._batchBuffer.data,usage:r}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){this._bindGroupHash=Object.create(null),this._batchBuffer.clear()}getUniformBindGroup(e,t){if(!t&&this._bindGroupHash[e.uid])return this._bindGroupHash[e.uid];this._renderer.ubo.ensureUniformGroup(e);const i=e.buffer.data,r=this._batchBuffer.addEmptyGroup(i.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,r/4),this._bindGroupHash[e.uid]=this._getBindGroup(r/Ht),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);const t=e.buffer.data,i=this._batchBuffer.addGroup(t);return this._getBufferResource(i/Ht)}getArrayBindGroup(e){const t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/Ht)}getArrayBufferResource(e){const i=this._batchBuffer.addGroup(e)/Ht;return this._getBufferResource(i)}_getBufferResource(e){if(!this._bufferResources[e]){const t=this._buffers[e%2];this._bufferResources[e]=new Fs({buffer:t,offset:(e/2|0)*256,size:Ht})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){const t=new Gt({0:this._getBufferResource(e)});this._bindGroups[e]=t}return this._bindGroups[e]}_uploadBindGroups(){const e=this._renderer.buffer,t=this._buffers[0];t.update(this._batchBuffer.byteIndex),e.updateBuffer(t);const i=this._renderer.gpu.device.createCommandEncoder();for(let r=1;r<this._buffers.length;r++){const n=this._buffers[r];i.copyBufferToBuffer(e.getGPUBuffer(t),Ht,e.getGPUBuffer(n),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([i.finish()])}destroy(){var e;for(let t=0;t<this._bindGroups.length;t++)(e=this._bindGroups[t])==null||e.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let t=0;t<this._buffers.length;t++)this._buffers[t].destroy();this._buffers=null;for(let t=0;t<this._bufferResources.length;t++)this._bufferResources[t].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._renderer=null}}gu.extension={type:[A.WebGPUPipes],name:"uniformBatch"};const Yb={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function qb(s,e,t,i,r){return s<<24|e<<16|t<<10|i<<5|r}function Kb(s,e,t,i,r){return t<<8|s<<5|i<<3|r<<1|e}class _u{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._renderer=e}contextChange(e){this._gpu=e,this.setStencilMode(ke.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){this._multisampleCount=e.msaaSamples,this._depthStencilAttachment=e.descriptor.depthStencilAttachment?1:0,this._colorTargetCount=e.colorTargetCount,this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=Wt[e],this._updatePipeHash())}setPipeline(e,t,i,r){const n=this.getPipeline(e,t,i);r.setPipeline(n)}getPipeline(e,t,i,r){e._layoutKey||($h(e,t.attributeData),this._generateBufferKey(e)),r||(r=e.topology);const n=qb(e._layoutKey,t._layoutKey,i.data,i._blendModeId,Yb[r]);return this._pipeCache[n]?this._pipeCache[n]:(this._pipeCache[n]=this._createPipeline(e,t,i,r),this._pipeCache[n])}_createPipeline(e,t,i,r){const n=this._gpu.device,o=this._createVertexBufferLayouts(e,t),a=this._renderer.state.getColorTargets(i,this._colorTargetCount),l=this._stencilMode===ke.RENDERING_MASK_ADD?0:this._colorMask;for(let f=0;f<a.length;f++)a[f].writeMask=l;const c=this._renderer.shader.getProgramData(t).pipeline,h={vertex:{module:this._getModule(t.vertex.source),entryPoint:t.vertex.entryPoint,buffers:o},fragment:{module:this._getModule(t.fragment.source),entryPoint:t.fragment.entryPoint,targets:a},primitive:{topology:r,cullMode:i.cullMode},layout:c,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(h.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:i.depthTest,depthCompare:i.depthTest?"less":"always"}),n.createRenderPipeline(h)}_getModule(e){return this._moduleCache[e]||this._createModule(e)}_createModule(e){const t=this._gpu.device;return this._moduleCache[e]=t.createShaderModule({code:e}),this._moduleCache[e]}_generateBufferKey(e){const t=[];let i=0;const r=Object.keys(e.attributes).sort();for(let o=0;o<r.length;o++){const a=e.attributes[r[o]];t[i++]=a.offset,t[i++]=a.format,t[i++]=a.stride,t[i++]=a.instance}const n=t.join("|");return e._layoutKey=qi(n,"geometry"),e._layoutKey}_generateAttributeLocationsKey(e){const t=[];let i=0;const r=Object.keys(e.attributeData).sort();for(let o=0;o<r.length;o++){const a=e.attributeData[r[o]];t[i++]=a.location}const n=t.join("|");return e._attributeLocationsKey=qi(n,"programAttributes"),e._attributeLocationsKey}getBufferNamesToBind(e,t){const i=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[i])return this._bindingNamesCache[i];const r=this._createVertexBufferLayouts(e,t),n=Object.create(null),o=t.attributeData;for(let a=0;a<r.length;a++){const c=Object.values(r[a].attributes)[0].shaderLocation;for(const h in o)if(o[h].location===c){n[a]=h;break}}return this._bindingNamesCache[i]=n,n}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);const i=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[i])return this._bufferLayoutsCache[i];const r=[];return e.buffers.forEach(n=>{const o={arrayStride:0,stepMode:"vertex",attributes:[]},a=o.attributes;for(const l in t.attributeData){const c=e.attributes[l];(c.divisor??1)!==1&&se(`Attribute ${l} has an invalid divisor value of '${c.divisor}'. WebGPU only supports a divisor value of 1`),c.buffer===n&&(o.arrayStride=c.stride,o.stepMode=c.instance?"instance":"vertex",a.push({shaderLocation:t.attributeData[l].location,offset:c.offset,format:c.format}))}a.length&&r.push(o)}),this._bufferLayoutsCache[i]=r,r}_updatePipeHash(){const e=Kb(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment,this._colorTargetCount);this._pipeStateCaches[e]||(this._pipeStateCaches[e]=Object.create(null)),this._pipeCache=this._pipeStateCaches[e]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}_u.extension={type:[A.WebGPUSystem],name:"pipeline"};class Zb{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class Jb{init(e,t){this._renderer=e,this._renderTargetSystem=t}copyToTexture(e,t,i,r,n){const o=this._renderer,a=this._getGpuColorTexture(e),l=o.texture.getGpuSource(t.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:i},{texture:l,origin:n},r),t}startRenderPass(e,t=!0,i,r,n=0,o=0){var h,u;const l=this._renderTargetSystem.getGpuRenderTarget(e);if(o!==0&&((h=l.msaaTextures)!=null&&h.length))throw new Error("[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.");if(n>0&&((u=l.msaaTextures)!=null&&u.length))throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");const c=this.getDescriptor(e,t,i,n,o);l.descriptor=c,this._renderer.pipeline.setRenderTarget(l),this._renderer.encoder.beginRenderPass(l),this._renderer.encoder.setViewport(r)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);return t.contexts[0]?t.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(e.colorTextures[0].source)}getDescriptor(e,t,i,r=0,n=0){typeof t=="boolean"&&(t=t?it.ALL:it.NONE);const o=this._renderTargetSystem,a=o.getGpuRenderTarget(e),l=e.colorTextures.map((u,f)=>{const d=a.contexts[f];let g,_;if(d){if(n!==0)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.");g=d.getCurrentTexture().createView()}else g=this._renderer.texture.getGpuSource(u).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1});a.msaaTextures[f]&&(_=g,g=this._renderer.texture.getTextureView(a.msaaTextures[f]));const b=t&it.COLOR?"clear":"load";return i??(i=o.defaultClearColor),{view:g,resolveTarget:_,clearValue:i,storeOp:"store",loadOp:b}});let c;if((e.stencil||e.depth)&&!e.depthStencilTexture&&(e.ensureDepthStencilTexture(),e.depthStencilTexture.source.sampleCount=a.msaa?4:1),e.depthStencilTexture){const u=t&it.STENCIL?"clear":"load",f=t&it.DEPTH?"clear":"load";c={view:this._renderer.texture.getGpuSource(e.depthStencilTexture.source).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1}),stencilStoreOp:"store",stencilLoadOp:u,depthClearValue:1,depthLoadOp:f,depthStoreOp:"store"}}return{colorAttachments:l,depthStencilAttachment:c}}clear(e,t=!0,i,r,n=0,o=0){if(!t)return;const{gpu:a,encoder:l}=this._renderer,c=a.device;if(l.commandEncoder===null){const u=c.createCommandEncoder(),f=this.getDescriptor(e,t,i,n,o),d=u.beginRenderPass(f);d.setViewport(r.x,r.y,r.width,r.height,0,1),d.end();const g=u.finish();c.queue.submit([g])}else this.startRenderPass(e,t,i,r,n,o)}initGpuRenderTarget(e){e.isRoot=!0;const t=new Zb;return t.colorTargetCount=e.colorTextures.length,e.colorTextures.forEach((i,r)=>{if(i instanceof yt){const n=i.resource.getContext("webgpu"),o=i.transparent?"premultiplied":"opaque";try{n.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:o})}catch(a){console.error(a)}t.contexts[r]=n}if(t.msaa=i.source.antialias,i.source.antialias){const n=new De({width:0,height:0,sampleCount:4,arrayLayerCount:i.source.arrayLayerCount});t.msaaTextures[r]=n}}),t.msaa&&(t.msaaSamples=4,e.depthStencilTexture&&(e.depthStencilTexture.source.sampleCount=4)),t}destroyGpuRenderTarget(e){e.contexts.forEach(t=>{t.unconfigure()}),e.msaaTextures.forEach(t=>{t.destroy()}),e.msaaTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);e.depthStencilTexture&&t.msaa&&(e.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorTextures.forEach((i,r)=>{const n=t.msaaTextures[r];n==null||n.resize(i.source.width,i.source.height,i.source._resolution)})}}class yu extends wo{constructor(e){super(e),this.adaptor=new Jb,this.adaptor.init(e,this)}}yu.extension={type:[A.WebGPUSystem],name:"renderTarget"};class bu{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){const t=this._gpu.device,i=e.gpuLayout.map(n=>t.createBindGroupLayout({entries:n})),r={bindGroupLayouts:i};return this._gpuProgramData[e._layoutKey]={bindGroups:i,pipeline:t.createPipelineLayout(r)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}bu.extension={type:[A.WebGPUSystem],name:"shader"};const et={};et.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},et.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},et.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},et.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},et.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},et.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},et["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},et["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},et["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},et.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},et.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},et.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class xu{constructor(){this.defaultState=new Pt,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e,t){const i=et[e.blendMode]||et.normal,r=[],n={format:"bgra8unorm",writeMask:0,blend:i};for(let o=0;o<t;o++)r[o]=n;return r}destroy(){this.gpu=null}}xu.extension={type:[A.WebGPUSystem],name:"state"};const Qb={type:"image",upload(s,e,t,i=0){const r=s.resource,n=(s.pixelWidth|0)*(s.pixelHeight|0),o=r.byteLength/n;t.device.queue.writeTexture({texture:e,origin:{x:0,y:0,z:i}},r,{offset:0,rowsPerImage:s.pixelHeight,bytesPerRow:s.pixelWidth*o},{width:s.pixelWidth,height:s.pixelHeight,depthOrArrayLayers:1})}},vu={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},ex={blockBytes:4,blockWidth:1,blockHeight:1},tx={type:"compressed",upload(s,e,t,i=0){let r=s.pixelWidth,n=s.pixelHeight;const o=vu[s.format]||ex;for(let a=0;a<s.resource.length;a++){const l=s.resource[a],c=Math.ceil(r/o.blockWidth)*o.blockBytes;t.device.queue.writeTexture({texture:e,mipLevel:a,origin:{x:0,y:0,z:i}},l,{offset:0,bytesPerRow:c},{width:Math.ceil(r/o.blockWidth)*o.blockWidth,height:Math.ceil(n/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}}},Cu=["right","left","top","bottom","front","back"];function ix(s){return{type:"cube",upload(e,t,i){const r=e.faces;for(let n=0;n<Cu.length;n++){const o=Cu[n],a=r[o];(s[a.uploadMethodId]||s.image).upload(a,t,i,n)}}}}const Su={type:"image",upload(s,e,t,i=0){const r=s.resource;if(!r)return;if(globalThis.HTMLImageElement&&r instanceof HTMLImageElement){const l=pe.get().createCanvas(r.width,r.height);l.getContext("2d").drawImage(r,0,0,r.width,r.height),s.resource=l,se("ImageSource: Image element passed, converting to canvas and replacing resource.")}const n=Math.min(e.width,s.resourceWidth||s.pixelWidth),o=Math.min(e.height,s.resourceHeight||s.pixelHeight),a=s.alphaMode==="premultiply-alpha-on-upload";t.device.queue.copyExternalImageToTexture({source:r},{texture:e,origin:{x:0,y:0,z:i},premultipliedAlpha:a},{width:n,height:o})}},sx={type:"video",upload(s,e,t,i){Su.upload(s,e,t,i)}};class rx{constructor(e){this.device=e,this.sampler=e.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(e){let t=this.pipelines[e];return t||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:`
873
+ }`,name:"big-triangle"});this._bigTriangleShader=new Mt({glProgram:r,resources:{uTexture:j.WHITE.source}})}renderStart(e){const t=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!t.isRoot,this._useBackBufferThisRender){const i=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=i.colorTexture,e.target=this._getBackBufferTexture(i.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind(this._targetTexture,!1),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:pb,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(e){return this._backBufferTexture=this._backBufferTexture||new j({source:new De({width:e.width,height:e.height,resolution:e._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(e.width,e.height,e._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&(this._backBufferTexture.destroy(),this._backBufferTexture=null)}};Po.extension={type:[A.WebGLSystem],name:"backBuffer",priority:1},Po.defaultOptions={useBackBuffer:!1};let mb=Po;class Yh{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.gl.colorMask(!!(e&8),!!(e&4),!!(e&2),!!(e&1)))}}Yh.extension={type:[A.WebGLSystem],name:"colorMask"};class qh{constructor(e){this.commandFinished=Promise.resolve(),this._renderer=e}setGeometry(e,t){this._renderer.geometry.bind(e,t.glProgram)}finishRenderPass(){}draw(e){const t=this._renderer,{geometry:i,shader:r,state:n,skipSync:o,topology:a,size:l,start:c,instanceCount:h}=e;t.shader.bind(r,o),t.geometry.bind(i,t.shader._activeProgram),n&&t.state.set(n),t.geometry.draw(a,l,c,h??i.instanceCount)}destroy(){this._renderer=null}}qh.extension={type:[A.WebGLSystem],name:"encoder"};class Kh{constructor(e){this._renderer=e}contextChange(){const e=this._renderer.gl;this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=cc(this.maxTextures,e);const t=this._renderer.context.webGLVersion===2;this.maxUniformBindings=t?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0}destroy(){}}Kh.extension={type:[A.WebGLSystem],name:"limits"};class gb{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this._attachedMipLevel=0,this._attachedLayer=0,this.msaaRenderBuffer=[]}}const Wt=[];Wt[ke.NONE]=void 0,Wt[ke.DISABLED]={stencilWriteMask:0,stencilReadMask:0},Wt[ke.RENDERING_MASK_ADD]={stencilFront:{compare:"equal",passOp:"increment-clamp"},stencilBack:{compare:"equal",passOp:"increment-clamp"}},Wt[ke.RENDERING_MASK_REMOVE]={stencilFront:{compare:"equal",passOp:"decrement-clamp"},stencilBack:{compare:"equal",passOp:"decrement-clamp"}},Wt[ke.MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"equal",passOp:"keep"},stencilBack:{compare:"equal",passOp:"keep"}},Wt[ke.INVERSE_MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"not-equal",passOp:"keep"},stencilBack:{compare:"not-equal",passOp:"keep"}};class Zh{constructor(e){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:ke.NONE},this._renderTargetStencilState=Object.create(null),e.renderTarget.onRenderTargetChange.add(this)}contextChange(e){this._gl=e,this._comparisonFuncMapping={always:e.ALWAYS,never:e.NEVER,equal:e.EQUAL,"not-equal":e.NOTEQUAL,less:e.LESS,"less-equal":e.LEQUAL,greater:e.GREATER,"greater-equal":e.GEQUAL},this._stencilOpsMapping={keep:e.KEEP,zero:e.ZERO,replace:e.REPLACE,invert:e.INVERT,"increment-clamp":e.INCR,"decrement-clamp":e.DECR,"increment-wrap":e.INCR_WRAP,"decrement-wrap":e.DECR_WRAP},this.resetState()}onRenderTargetChange(e){if(this._activeRenderTarget===e)return;this._activeRenderTarget=e;let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:ke.DISABLED,stencilReference:0}),this.setStencilMode(t.stencilMode,t.stencilReference)}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=ke.NONE,this._stencilCache.stencilReference=0}setStencilMode(e,t){const i=this._renderTargetStencilState[this._activeRenderTarget.uid],r=this._gl,n=Wt[e],o=this._stencilCache;if(i.stencilMode=e,i.stencilReference=t,e===ke.DISABLED){this._stencilCache.enabled&&(this._stencilCache.enabled=!1,r.disable(r.STENCIL_TEST));return}this._stencilCache.enabled||(this._stencilCache.enabled=!0,r.enable(r.STENCIL_TEST)),(e!==o.stencilMode||o.stencilReference!==t)&&(o.stencilMode=e,o.stencilReference=t,r.stencilFunc(this._comparisonFuncMapping[n.stencilBack.compare],t,255),r.stencilOp(r.KEEP,r.KEEP,this._stencilOpsMapping[n.stencilBack.passOp]))}}Zh.extension={type:[A.WebGLSystem],name:"stencil"};class _b{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new Se}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new Se;const e=this._renderer.gl;this._drawBuffersCache=[];for(let t=1;t<=16;t++)this._drawBuffersCache[t]=Array.from({length:t},(i,r)=>e.COLOR_ATTACHMENT0+r)}copyToTexture(e,t,i,r,n){const o=this._renderTargetSystem,a=this._renderer,l=o.getGpuRenderTarget(e),c=a.gl;return this.finishRenderPass(e),c.bindFramebuffer(c.FRAMEBUFFER,l.resolveTargetFramebuffer),a.texture.bind(t,0),c.copyTexSubImage2D(c.TEXTURE_2D,0,n.x,n.y,i.x,i.y,r.width,r.height),t}startRenderPass(e,t=!0,i,r,n=0,o=0){const a=this._renderTargetSystem,l=e.colorTexture,c=a.getGpuRenderTarget(e);if(o!==0&&this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to array layers requires WebGL2.");if(n>0){if(c.msaa)throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");if(this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to mip levels requires WebGL2.")}let h=r.y;e.isRoot&&(h=l.pixelHeight-r.height-r.y),e.colorTextures.forEach(d=>{this._renderer.texture.unbind(d)});const u=this._renderer.gl;u.bindFramebuffer(u.FRAMEBUFFER,c.framebuffer),!e.isRoot&&(c._attachedMipLevel!==n||c._attachedLayer!==o)&&(e.colorTextures.forEach((d,g)=>{const _=this._renderer.texture.getGlSource(d);if(_.target===u.TEXTURE_2D){if(o!==0)throw new Error("[RenderTargetSystem] layer must be 0 when rendering to 2D textures in WebGL.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,u.TEXTURE_2D,_.texture,n)}else if(_.target===u.TEXTURE_2D_ARRAY){if(this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to 2D array textures requires WebGL2.");u.framebufferTextureLayer(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,_.texture,n,o)}else if(_.target===u.TEXTURE_CUBE_MAP){if(o<0||o>5)throw new Error("[RenderTargetSystem] Cube map layer must be between 0 and 5.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,u.TEXTURE_CUBE_MAP_POSITIVE_X+o,_.texture,n)}else throw new Error("[RenderTargetSystem] Unsupported texture target for render-to-layer in WebGL.")}),c._attachedMipLevel=n,c._attachedLayer=o),e.colorTextures.length>1&&this._setDrawBuffers(e,u);const f=this._viewPortCache;(f.x!==r.x||f.y!==h||f.width!==r.width||f.height!==r.height)&&(f.x=r.x,f.y=h,f.width=r.width,f.height=r.height,u.viewport(r.x,h,r.width,r.height)),!c.depthStencilRenderBuffer&&(e.stencil||e.depth)&&this._initStencil(c),this.clear(e,t,i)}finishRenderPass(e){const i=this._renderTargetSystem.getGpuRenderTarget(e);if(!i.msaa)return;const r=this._renderer.gl;r.bindFramebuffer(r.FRAMEBUFFER,i.resolveTargetFramebuffer),r.bindFramebuffer(r.READ_FRAMEBUFFER,i.framebuffer),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST),r.bindFramebuffer(r.FRAMEBUFFER,i.framebuffer)}initGpuRenderTarget(e){const i=this._renderer.gl,r=new gb;return r._attachedMipLevel=0,r._attachedLayer=0,e.colorTexture instanceof yt?(this._renderer.context.ensureCanvasSize(e.colorTexture.resource),r.framebuffer=null,r):(this._initColor(e,r),i.bindFramebuffer(i.FRAMEBUFFER,null),r)}destroyGpuRenderTarget(e){const t=this._renderer.gl;e.framebuffer&&(t.deleteFramebuffer(e.framebuffer),e.framebuffer=null),e.resolveTargetFramebuffer&&(t.deleteFramebuffer(e.resolveTargetFramebuffer),e.resolveTargetFramebuffer=null),e.depthStencilRenderBuffer&&(t.deleteRenderbuffer(e.depthStencilRenderBuffer),e.depthStencilRenderBuffer=null),e.msaaRenderBuffer.forEach(i=>{t.deleteRenderbuffer(i)}),e.msaaRenderBuffer=null}clear(e,t,i,r,n=0,o=0){if(!t)return;if(o!==0)throw new Error("[RenderTargetSystem] Clearing array layers is not supported in WebGL renderer.");const a=this._renderTargetSystem;typeof t=="boolean"&&(t=t?it.ALL:it.NONE);const l=this._renderer.gl;if(t&it.COLOR){i??(i=a.defaultClearColor);const c=this._clearColorCache,h=i;(c[0]!==h[0]||c[1]!==h[1]||c[2]!==h[2]||c[3]!==h[3])&&(c[0]=h[0],c[1]=h[1],c[2]=h[2],c[3]=h[3],l.clearColor(h[0],h[1],h[2],h[3]))}l.clear(t)}resizeGpuRenderTarget(e){if(e.isRoot)return;const i=this._renderTargetSystem.getGpuRenderTarget(e);this._resizeColor(e,i),(e.stencil||e.depth)&&this._resizeStencil(i)}_initColor(e,t){const i=this._renderer,r=i.gl,n=r.createFramebuffer();if(t.resolveTargetFramebuffer=n,r.bindFramebuffer(r.FRAMEBUFFER,n),t.width=e.colorTexture.source.pixelWidth,t.height=e.colorTexture.source.pixelHeight,e.colorTextures.forEach((a,l)=>{const c=a.source;c.antialias&&(i.context.supports.msaa?t.msaa=!0:se("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),i.texture.bindSource(c,0);const h=i.texture.getGlSource(c),u=h.texture;if(h.target===r.TEXTURE_2D)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,r.TEXTURE_2D,u,0);else if(h.target===r.TEXTURE_2D_ARRAY){if(i.context.webGLVersion<2)throw new Error("[RenderTargetSystem] TEXTURE_2D_ARRAY requires WebGL2.");r.framebufferTextureLayer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,u,0,0)}else if(h.target===r.TEXTURE_CUBE_MAP)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,r.TEXTURE_CUBE_MAP_POSITIVE_X,u,0);else throw new Error("[RenderTargetSystem] Unsupported texture target for framebuffer attachment.")}),t.msaa){const a=r.createFramebuffer();t.framebuffer=a,r.bindFramebuffer(r.FRAMEBUFFER,a),e.colorTextures.forEach((l,c)=>{const h=r.createRenderbuffer();t.msaaRenderBuffer[c]=h})}else t.framebuffer=n;this._resizeColor(e,t)}_resizeColor(e,t){const i=e.colorTexture.source;if(t.width=i.pixelWidth,t.height=i.pixelHeight,t._attachedMipLevel=0,t._attachedLayer=0,e.colorTextures.forEach((r,n)=>{n!==0&&r.source.resize(i.width,i.height,i._resolution)}),t.msaa){const r=this._renderer,n=r.gl,o=t.framebuffer;n.bindFramebuffer(n.FRAMEBUFFER,o),e.colorTextures.forEach((a,l)=>{const c=a.source;r.texture.bindSource(c,0);const u=r.texture.getGlSource(c).internalFormat,f=t.msaaRenderBuffer[l];n.bindRenderbuffer(n.RENDERBUFFER,f),n.renderbufferStorageMultisample(n.RENDERBUFFER,4,u,c.pixelWidth,c.pixelHeight),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+l,n.RENDERBUFFER,f)})}}_initStencil(e){if(e.framebuffer===null)return;const t=this._renderer.gl,i=t.createRenderbuffer();e.depthStencilRenderBuffer=i,t.bindRenderbuffer(t.RENDERBUFFER,i),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,i),this._resizeStencil(e)}_resizeStencil(e){const t=this._renderer.gl;t.bindRenderbuffer(t.RENDERBUFFER,e.depthStencilRenderBuffer),e.msaa?t.renderbufferStorageMultisample(t.RENDERBUFFER,4,t.DEPTH24_STENCIL8,e.width,e.height):t.renderbufferStorage(t.RENDERBUFFER,this._renderer.context.webGLVersion===2?t.DEPTH24_STENCIL8:t.DEPTH_STENCIL,e.width,e.height)}prerender(e){const t=e.colorTexture.resource;this._renderer.context.multiView&&yt.test(t)&&this._renderer.context.ensureCanvasSize(t)}postrender(e){if(this._renderer.context.multiView&&yt.test(e.colorTexture.resource)){const t=this._renderer.context.canvas,i=e.colorTexture;i.context2D.drawImage(t,0,i.pixelHeight-t.height)}}_setDrawBuffers(e,t){const i=e.colorTextures.length,r=this._drawBuffersCache[i];if(this._renderer.context.webGLVersion===1){const n=this._renderer.context.extensions.drawBuffers;n?n.drawBuffersWEBGL(r):se("[RenderTexture] This WebGL1 context does not support rendering to multiple targets")}else t.drawBuffers(r)}}class Jh extends wo{constructor(e){super(e),this.adaptor=new _b,this.adaptor.init(e,this)}}Jh.extension={type:[A.WebGLSystem],name:"renderTarget"};function yb(s){const e={};if(e.normal=[s.ONE,s.ONE_MINUS_SRC_ALPHA],e.add=[s.ONE,s.ONE],e.multiply=[s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],e.screen=[s.ONE,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],e.none=[0,0],e["normal-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],e["add-npm"]=[s.SRC_ALPHA,s.ONE,s.ONE,s.ONE],e["screen-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],e.erase=[s.ZERO,s.ONE_MINUS_SRC_ALPHA],!(s instanceof pe.get().getWebGLRenderingContext()))e.min=[s.ONE,s.ONE,s.ONE,s.ONE,s.MIN,s.MIN],e.max=[s.ONE,s.ONE,s.ONE,s.ONE,s.MAX,s.MAX];else{const i=s.getExtension("EXT_blend_minmax");i&&(e.min=[s.ONE,s.ONE,s.ONE,s.ONE,i.MIN_EXT,i.MIN_EXT],e.max=[s.ONE,s.ONE,s.ONE,s.ONE,i.MAX_EXT,i.MAX_EXT])}return e}const bb=0,xb=1,vb=2,Cb=3,Sb=4,Eb=5,Qh=class da{constructor(e){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[bb]=this.setBlend,this.map[xb]=this.setOffset,this.map[vb]=this.setCullFace,this.map[Cb]=this.setDepthTest,this.map[Sb]=this.setFrontFace,this.map[Eb]=this.setDepthMask,this.checks=[],this.defaultState=Pt.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=!e.isRoot,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=yb(e),this.resetState()}set(e){if(e||(e=this.defaultState),this.stateId!==e.data){let t=this.stateId^e.data,i=0;for(;t;)t&1&&this.map[i].call(this,!!(e.data&1<<i)),t>>=1,i++;this.stateId=e.data}for(let t=0;t<this.checks.length;t++)this.checks[t](this,e)}forceState(e){e||(e=this.defaultState);for(let t=0;t<this.map.length;t++)this.map[t].call(this,!!(e.data&1<<t));for(let t=0;t<this.checks.length;t++)this.checks[t](this,e);this.stateId=e.data}setBlend(e){this._updateCheck(da._checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this._updateCheck(da._checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(e){this.gl[e?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(e){this.gl.depthMask(e)}setCullFace(e){this._cullFace=e,this.gl[e?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(e){this._frontFace=e,this._frontFaceDirty=!1;const t=this._invertFrontFace?!e:e;this._glFrontFace!==t&&(this._glFrontFace=t,this.gl.frontFace(this.gl[t?"CW":"CCW"]))}setBlendMode(e){if(this.blendModesMap[e]||(e="normal"),e===this.blendMode)return;this.blendMode=e;const t=this.blendModesMap[e],i=this.gl;t.length===2?i.blendFunc(t[0],t[1]):i.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,i.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD))}setPolygonOffset(e,t){this.gl.polygonOffset(e,t)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(e,t){const i=this.checks.indexOf(e);t&&i===-1?this.checks.push(e):!t&&i!==-1&&this.checks.splice(i,1)}static _checkBlendMode(e,t){e.setBlendMode(t.blendMode)}static _checkPolygonOffset(e,t){e.setPolygonOffset(1,t.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}};Qh.extension={type:[A.WebGLSystem],name:"state"};let Tb=Qh;class Ab{constructor(e){this.target=Mo.TEXTURE_2D,this._layerInitMask=0,this.texture=e,this.width=-1,this.height=-1,this.type=he.UNSIGNED_BYTE,this.internalFormat=Ro.RGBA,this.format=Ro.RGBA,this.samplerType=0}destroy(){}}const wb={id:"buffer",upload(s,e,t,i,r,n=!1){const o=r||e.target;!n&&e.width===s.width&&e.height===s.height?t.texSubImage2D(o,0,0,0,s.width,s.height,e.format,e.type,s.resource):t.texImage2D(o,0,e.internalFormat,s.width,s.height,0,e.format,e.type,s.resource),e.width=s.width,e.height=s.height}},Ib={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},Rb={id:"compressed",upload(s,e,t,i,r,n){const o=r??e.target;t.pixelStorei(t.UNPACK_ALIGNMENT,4);let a=s.pixelWidth,l=s.pixelHeight;const c=!!Ib[s.format];for(let h=0;h<s.resource.length;h++){const u=s.resource[h];c?t.compressedTexImage2D(o,h,e.internalFormat,a,l,0,u):t.texImage2D(o,h,e.internalFormat,a,l,0,e.format,e.type,u),a=Math.max(a>>1,1),l=Math.max(l>>1,1)}}},eu=["right","left","top","bottom","front","back"];function Mb(s){return{id:"cube",upload(e,t,i,r){const n=e.faces;for(let o=0;o<eu.length;o++){const a=eu[o],l=n[a];(s[l.uploadMethodId]||s.image).upload(l,t,i,r,Mo.TEXTURE_CUBE_MAP_POSITIVE_X+o,(t._layerInitMask&1<<o)===0),t._layerInitMask|=1<<o}t.width=e.pixelWidth,t.height=e.pixelHeight}}}const tu={id:"image",upload(s,e,t,i,r,n=!1){const o=r||e.target,a=s.pixelWidth,l=s.pixelHeight,c=s.resourceWidth,h=s.resourceHeight,u=i===2,f=n||e.width!==a||e.height!==l,d=c>=a&&h>=l,g=s.resource;(u?Pb:kb)(t,o,e,a,l,c,h,g,f,d),e.width=a,e.height=l}};function Pb(s,e,t,i,r,n,o,a,l,c){if(!c){l&&s.texImage2D(e,0,t.internalFormat,i,r,0,t.format,t.type,null),s.texSubImage2D(e,0,0,0,n,o,t.format,t.type,a);return}if(!l){s.texSubImage2D(e,0,0,0,t.format,t.type,a);return}s.texImage2D(e,0,t.internalFormat,i,r,0,t.format,t.type,a)}function kb(s,e,t,i,r,n,o,a,l,c){if(!c){l&&s.texImage2D(e,0,t.internalFormat,i,r,0,t.format,t.type,null),s.texSubImage2D(e,0,0,0,t.format,t.type,a);return}if(!l){s.texSubImage2D(e,0,0,0,t.format,t.type,a);return}s.texImage2D(e,0,t.internalFormat,t.format,t.type,a)}const Ob=xy(),Bb={id:"video",upload(s,e,t,i,r,n=Ob){if(!s.isValid){const o=r??e.target;t.texImage2D(o,0,e.internalFormat,1,1,0,e.format,e.type,null);return}tu.upload(s,e,t,i,r,n)}},iu={linear:9729,nearest:9728},Db={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},ko={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},Nb={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function su(s,e,t,i,r,n,o,a){const l=n;if(!a||s.addressModeU!=="repeat"||s.addressModeV!=="repeat"||s.addressModeW!=="repeat"){const c=ko[o?"clamp-to-edge":s.addressModeU],h=ko[o?"clamp-to-edge":s.addressModeV],u=ko[o?"clamp-to-edge":s.addressModeW];e[r](l,e.TEXTURE_WRAP_S,c),e[r](l,e.TEXTURE_WRAP_T,h),e.TEXTURE_WRAP_R&&e[r](l,e.TEXTURE_WRAP_R,u)}if((!a||s.magFilter!=="linear")&&e[r](l,e.TEXTURE_MAG_FILTER,iu[s.magFilter]),t){if(!a||s.mipmapFilter!=="linear"){const c=Db[s.minFilter][s.mipmapFilter];e[r](l,e.TEXTURE_MIN_FILTER,c)}}else e[r](l,e.TEXTURE_MIN_FILTER,iu[s.minFilter]);if(i&&s.maxAnisotropy>1){const c=Math.min(s.maxAnisotropy,e.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT));e[r](l,i.TEXTURE_MAX_ANISOTROPY_EXT,c)}s.compare&&e[r](l,e.TEXTURE_COMPARE_FUNC,Nb[s.compare])}function Ub(s){return{r8unorm:s.RED,r8snorm:s.RED,r8uint:s.RED,r8sint:s.RED,r16uint:s.RED,r16sint:s.RED,r16float:s.RED,rg8unorm:s.RG,rg8snorm:s.RG,rg8uint:s.RG,rg8sint:s.RG,r32uint:s.RED,r32sint:s.RED,r32float:s.RED,rg16uint:s.RG,rg16sint:s.RG,rg16float:s.RG,rgba8unorm:s.RGBA,"rgba8unorm-srgb":s.RGBA,rgba8snorm:s.RGBA,rgba8uint:s.RGBA,rgba8sint:s.RGBA,bgra8unorm:s.RGBA,"bgra8unorm-srgb":s.RGBA,rgb9e5ufloat:s.RGB,rgb10a2unorm:s.RGBA,rg11b10ufloat:s.RGB,rg32uint:s.RG,rg32sint:s.RG,rg32float:s.RG,rgba16uint:s.RGBA,rgba16sint:s.RGBA,rgba16float:s.RGBA,rgba32uint:s.RGBA,rgba32sint:s.RGBA,rgba32float:s.RGBA,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT,depth24plus:s.DEPTH_COMPONENT,"depth24plus-stencil8":s.DEPTH_STENCIL,depth32float:s.DEPTH_COMPONENT,"depth32float-stencil8":s.DEPTH_STENCIL}}function Fb(s,e){let t={},i=s.RGBA;return s instanceof pe.get().getWebGLRenderingContext()?e.srgb&&(t={"rgba8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT}):(t={"rgba8unorm-srgb":s.SRGB8_ALPHA8,"bgra8unorm-srgb":s.SRGB8_ALPHA8},i=s.RGBA8),{r8unorm:s.R8,r8snorm:s.R8_SNORM,r8uint:s.R8UI,r8sint:s.R8I,r16uint:s.R16UI,r16sint:s.R16I,r16float:s.R16F,rg8unorm:s.RG8,rg8snorm:s.RG8_SNORM,rg8uint:s.RG8UI,rg8sint:s.RG8I,r32uint:s.R32UI,r32sint:s.R32I,r32float:s.R32F,rg16uint:s.RG16UI,rg16sint:s.RG16I,rg16float:s.RG16F,rgba8unorm:s.RGBA,...t,rgba8snorm:s.RGBA8_SNORM,rgba8uint:s.RGBA8UI,rgba8sint:s.RGBA8I,bgra8unorm:i,rgb9e5ufloat:s.RGB9_E5,rgb10a2unorm:s.RGB10_A2,rg11b10ufloat:s.R11F_G11F_B10F,rg32uint:s.RG32UI,rg32sint:s.RG32I,rg32float:s.RG32F,rgba16uint:s.RGBA16UI,rgba16sint:s.RGBA16I,rgba16float:s.RGBA16F,rgba32uint:s.RGBA32UI,rgba32sint:s.RGBA32I,rgba32float:s.RGBA32F,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT16,depth24plus:s.DEPTH_COMPONENT24,"depth24plus-stencil8":s.DEPTH24_STENCIL8,depth32float:s.DEPTH_COMPONENT32F,"depth32float-stencil8":s.DEPTH32F_STENCIL8,...e.s3tc?{"bc1-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...e.s3tc_sRGB?{"bc1-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...e.rgtc?{"bc4-r-unorm":e.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":e.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":e.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":e.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...e.bptc?{"bc6h-rgb-float":e.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":e.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":e.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":e.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...e.etc?{"etc2-rgb8unorm":e.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":e.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":e.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":e.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":e.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":e.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":e.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":e.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...e.astc?{"astc-4x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function Gb(s){return{r8unorm:s.UNSIGNED_BYTE,r8snorm:s.BYTE,r8uint:s.UNSIGNED_BYTE,r8sint:s.BYTE,r16uint:s.UNSIGNED_SHORT,r16sint:s.SHORT,r16float:s.HALF_FLOAT,rg8unorm:s.UNSIGNED_BYTE,rg8snorm:s.BYTE,rg8uint:s.UNSIGNED_BYTE,rg8sint:s.BYTE,r32uint:s.UNSIGNED_INT,r32sint:s.INT,r32float:s.FLOAT,rg16uint:s.UNSIGNED_SHORT,rg16sint:s.SHORT,rg16float:s.HALF_FLOAT,rgba8unorm:s.UNSIGNED_BYTE,"rgba8unorm-srgb":s.UNSIGNED_BYTE,rgba8snorm:s.BYTE,rgba8uint:s.UNSIGNED_BYTE,rgba8sint:s.BYTE,bgra8unorm:s.UNSIGNED_BYTE,"bgra8unorm-srgb":s.UNSIGNED_BYTE,rgb9e5ufloat:s.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:s.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:s.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:s.UNSIGNED_INT,rg32sint:s.INT,rg32float:s.FLOAT,rgba16uint:s.UNSIGNED_SHORT,rgba16sint:s.SHORT,rgba16float:s.HALF_FLOAT,rgba32uint:s.UNSIGNED_INT,rgba32sint:s.INT,rgba32float:s.FLOAT,stencil8:s.UNSIGNED_BYTE,depth16unorm:s.UNSIGNED_SHORT,depth24plus:s.UNSIGNED_INT,"depth24plus-stencil8":s.UNSIGNED_INT_24_8,depth32float:s.FLOAT,"depth32float-stencil8":s.FLOAT_32_UNSIGNED_INT_24_8_REV}}function Lb(s){return{"2d":s.TEXTURE_2D,cube:s.TEXTURE_CUBE_MAP,"1d":null,"3d":(s==null?void 0:s.TEXTURE_3D)||null,"2d-array":(s==null?void 0:s.TEXTURE_2D_ARRAY)||null,"cube-array":(s==null?void 0:s.TEXTURE_CUBE_MAP_ARRAY)||null}}const Wb=4;class ru{constructor(e){this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=e,this._managedTextures=new kt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"glTexture"});const t={image:tu,buffer:wb,video:Bb,compressed:Rb};this._uploads={...t,cube:Mb(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=Fb(e,this._renderer.context.extensions),this._mapFormatToType=Gb(e),this._mapFormatToFormat=Ub(e),this._mapViewDimensionToGlTarget=Lb(e)),this._managedTextures.removeAll(!0),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let t=0;t<16;t++)this.bind(j.EMPTY,t)}initSource(e){this.bind(e)}bind(e,t=0){const i=e.source;e?(this.bindSource(i,t),this._useSeparateSamplers&&this._bindSampler(i.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){const i=this._gl;if(e._gcLastUsed=this._renderer.gc.now,this._boundTextures[t]!==e){this._boundTextures[t]=e,this._activateLocation(t),e||(e=j.EMPTY.source);const r=this.getGlSource(e);i.bindTexture(r.target,r.texture)}}_bindSampler(e,t=0){const i=this._gl;if(!e){this._boundSamplers[t]=null,i.bindSampler(t,null);return}const r=this._getGlSampler(e);this._boundSamplers[t]!==r&&(this._boundSamplers[t]=r,i.bindSampler(t,r))}unbind(e){const t=e.source,i=this._boundTextures,r=this._gl;for(let n=0;n<i.length;n++)if(i[n]===t){this._activateLocation(n);const o=this.getGlSource(t);r.bindTexture(o.target,null),i[n]=null}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){const t=this._gl,i=new Ab(t.createTexture());if(i.type=this._mapFormatToType[e.format],i.internalFormat=this._mapFormatToInternalFormat[e.format],i.format=this._mapFormatToFormat[e.format],i.target=this._mapViewDimensionToGlTarget[e.viewDimension],i.target===null)throw new Error(`Unsupported view dimension: ${e.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(e.uploadMethodId==="cube"&&(i.target=t.TEXTURE_CUBE_MAP),e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){const n=Math.max(e.width,e.height);e.mipLevelCount=Math.floor(Math.log2(n))+1}return e._gpuData[this._renderer.uid]=i,this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceUpdate,this),e.on("styleChange",this.onStyleChange,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),this.updateStyle(e,!1),i}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){const i=this._gl,r=this.getGlSource(e);i.bindTexture(r.target,r.texture),this._boundTextures[this._activeTextureLocation]=e,su(e.style,i,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",r.target,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e,t=!1){const i=e._gpuData[this._renderer.uid];i&&(t||(this.unbind(e),this._gl.deleteTexture(i.texture)),e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceUpdate,this),e.off("styleChange",this.onStyleChange,this),e.off("updateMipmaps",this.onUpdateMipmaps,this))}onSourceUpdate(e){const t=this._gl,i=this.getGlSource(e);t.bindTexture(i.target,i.texture),this._boundTextures[this._activeTextureLocation]=e;const r=e.alphaMode==="premultiply-alpha-on-upload";if(this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[e.uploadMethodId])this._uploads[e.uploadMethodId].upload(e,i,t,this._renderer.context.webGLVersion);else if(i.target===t.TEXTURE_2D)this._initEmptyTexture2D(i,e);else if(i.target===t.TEXTURE_2D_ARRAY)this._initEmptyTexture2DArray(i,e);else if(i.target===t.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(i,e);else throw new Error("[GlTextureSystem] Unsupported texture target for empty allocation.");this._applyMipRange(i,e),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);const i=this.getGlSource(e);this._gl.generateMipmap(i.target)}_initEmptyTexture2D(e,t){const i=this._gl;i.texImage2D(i.TEXTURE_2D,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let r=Math.max(t.pixelWidth>>1,1),n=Math.max(t.pixelHeight>>1,1);for(let o=1;o<t.mipLevelCount;o++)i.texImage2D(i.TEXTURE_2D,o,e.internalFormat,r,n,0,e.format,e.type,null),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}_initEmptyTexture2DArray(e,t){if(this._renderer.context.webGLVersion!==2)throw new Error("[GlTextureSystem] TEXTURE_2D_ARRAY requires WebGL2.");const i=this._gl,r=Math.max(t.arrayLayerCount|0,1);i.texImage3D(i.TEXTURE_2D_ARRAY,0,e.internalFormat,t.pixelWidth,t.pixelHeight,r,0,e.format,e.type,null);let n=Math.max(t.pixelWidth>>1,1),o=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++)i.texImage3D(i.TEXTURE_2D_ARRAY,a,e.internalFormat,n,o,r,0,e.format,e.type,null),n=Math.max(n>>1,1),o=Math.max(o>>1,1)}_initEmptyTextureCube(e,t){const i=this._gl,r=6;for(let a=0;a<r;a++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let n=Math.max(t.pixelWidth>>1,1),o=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++){for(let l=0;l<r;l++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+l,a,e.internalFormat,n,o,0,e.format,e.type,null);n=Math.max(n>>1,1),o=Math.max(o>>1,1)}}_applyMipRange(e,t){if(this._renderer.context.webGLVersion!==2)return;const i=this._gl,r=Math.max((t.mipLevelCount|0)-1,0);i.texParameteri(e.target,i.TEXTURE_BASE_LEVEL,0),i.texParameteri(e.target,i.TEXTURE_MAX_LEVEL,r)}_initSampler(e){const t=this._gl,i=this._gl.createSampler();return this._glSamplers[e._resourceId]=i,su(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",i,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this._initSource(e)}generateCanvas(e){const{pixels:t,width:i,height:r}=this.getPixels(e),n=pe.get().createCanvas();n.width=i,n.height=r;const o=n.getContext("2d");if(o){const a=o.createImageData(i,r);a.data.set(t),o.putImageData(a,0,0)}return n}getPixels(e){const t=e.source.resolution,i=e.frame,r=Math.max(Math.round(i.width*t),1),n=Math.max(Math.round(i.height*t),1),o=new Uint8Array(Wb*r*n),a=this._renderer,l=a.renderTarget.getRenderTarget(e),c=a.renderTarget.getGpuRenderTarget(l),h=a.gl;return h.bindFramebuffer(h.FRAMEBUFFER,c.resolveTargetFramebuffer),h.readPixels(Math.round(i.x*t),Math.round(i.y*t),r,n,h.RGBA,h.UNSIGNED_BYTE,o),{pixels:new Uint8ClampedArray(o.buffer),width:r,height:n}}destroy(){this._managedTextures.destroy(),this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(j.EMPTY.source),this._boundSamplers=Object.create(null);const e=this._gl;this._premultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}ru.extension={type:[A.WebGLSystem],name:"texture"};class nu{contextChange(e){const t=new ht({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),i=e.limits.maxBatchableTextures,r=Ln({name:"graphics",bits:[Cc,Ec(i),mh,zn]});this.shader=new Mt({glProgram:r,resources:{localUniforms:t,batchSamplers:Ac(i)}})}execute(e,t){const i=t.context,r=i.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i);r.groups[0]=n.globalUniforms.bindGroup,n.state.set(e.state),n.shader.bind(r),n.geometry.bind(a.geometry,r.glProgram);const c=l.instructions;for(let h=0;h<l.instructionSize;h++){const u=c[h];if(u.size){for(let f=0;f<u.textures.count;f++)n.texture.bind(u.textures.textures[f],f);n.geometry.draw(u.topology,u.size,u.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}nu.extension={type:[A.WebGLPipesAdaptor],name:"graphics"};class ou{init(){const e=Ln({name:"mesh",bits:[mh,Sy,zn]});this._shader=new Mt({glProgram:e,resources:{uTexture:j.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const i=e.renderer;let r=t._shader;if(r){if(!r.glProgram){se("Mesh shader has no glProgram",t.shader);return}}else{r=this._shader;const n=t.texture,o=n.source;r.resources.uTexture=o,r.resources.uSampler=o.style,r.resources.textureUniforms.uniforms.uTextureMatrix=n.textureMatrix.mapCoord}r.groups[100]=i.globalUniforms.bindGroup,r.groups[101]=e.localUniformsBindGroup,i.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}ou.extension={type:[A.WebGLPipesAdaptor],name:"mesh"};const Hb=[...Ao,Hr,mb,cb,Kh,zh,ru,Jh,Xh,Yr,Xr,qh,Tb,Zh,Yh],Vb=[...Fh],zb=[_h,ou,nu],au=[],lu=[],cu=[];Q.handleByNamedList(A.WebGLSystem,au),Q.handleByNamedList(A.WebGLPipes,lu),Q.handleByNamedList(A.WebGLPipesAdaptor,cu),Q.add(...Hb,...Vb,...zb);class $b extends vi{constructor(){const e={name:"webgl",type:bt.WEBGL,systems:au,renderPipes:lu,renderPipeAdaptors:cu};super(e)}}const jb=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:$b},Symbol.toStringTag,{value:"Module"}));class hu{constructor(e){this._hash=Object.create(null),this._renderer=e}contextChange(e){this._gpu=e}getBindGroup(e,t,i){return e._updateKey(),this._hash[e._key]||this._createBindGroup(e,t,i)}_createBindGroup(e,t,i){const r=this._gpu.device,n=t.layout[i],o=[],a=this._renderer;for(const h in n){const u=e.resources[h]??e.resources[n[h]];let f;if(u._resourceType==="uniformGroup"){const d=u;a.ubo.updateUniformGroup(d);const g=d.buffer;f={buffer:a.buffer.getGPUBuffer(g),offset:0,size:g.descriptor.size}}else if(u._resourceType==="buffer"){const d=u;f={buffer:a.buffer.getGPUBuffer(d),offset:0,size:d.descriptor.size}}else if(u._resourceType==="bufferResource"){const d=u;f={buffer:a.buffer.getGPUBuffer(d.buffer),offset:d.offset,size:d.size}}else if(u._resourceType==="textureSampler"){const d=u;f=a.texture.getGpuSampler(d)}else if(u._resourceType==="textureSource"){const d=u;f=a.texture.getTextureView(d)}o.push({binding:n[h],resource:f})}const l=a.shader.getProgramData(t).bindGroups[i],c=r.createBindGroup({layout:l,entries:o});return this._hash[e._key]=c,c}destroy(){this._hash=null,this._renderer=null}}hu.extension={type:[A.WebGPUSystem],name:"bindGroup"};class Xb{constructor(e){this.gpuBuffer=e}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}}class uu{constructor(e){this._renderer=e,this._managedBuffers=new kt({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"gpuBuffer"})}contextChange(e){this._gpu=e}getGPUBuffer(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuBuffer)||this.createGPUBuffer(e)}updateBuffer(e){const t=this.getGPUBuffer(e),i=e.data;return e._updateID&&i&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,0,i.buffer,0,(e._updateSize||i.byteLength)+3&-4)),t}destroyAll(){this._managedBuffers.removeAll()}onBufferUnload(e){e.off("update",this.updateBuffer,this),e.off("change",this.onBufferChange,this)}createGPUBuffer(e){const t=this._gpu.device.createBuffer(e.descriptor);return e._updateID=0,e._resourceId=be("resource"),e.data&&(Un(e.data.buffer,t.getMappedRange(),e.data.byteOffset,e.data.byteLength),t.unmap()),e._gpuData[this._renderer.uid]=new Xb(t),this._managedBuffers.add(e)&&(e.on("update",this.updateBuffer,this),e.on("change",this.onBufferChange,this)),t}onBufferChange(e){this._managedBuffers.remove(e),e._updateID=0,this.createGPUBuffer(e)}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gpu=null}}uu.extension={type:[A.WebGPUSystem],name:"buffer"};class Yb{constructor({minUniformOffsetAlignment:e}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=e,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(e){if(e>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${e*4}`);const t=this.byteIndex;let i=t+e*4;if(i=Math.ceil(i/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,i>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=i,t}addGroup(e){const t=this.addEmptyGroup(e.length);for(let i=0;i<e.length;i++)this.data[t/4+i]=e[i];return t}destroy(){this.data=null}}class du{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.pipeline.setColorMask(e))}destroy(){this._renderer=null,this._colorMaskCache=null}}du.extension={type:[A.WebGPUSystem],name:"colorMask"};class Oo{constructor(e){this._renderer=e}async init(e){return this._initPromise?this._initPromise:(this._initPromise=(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(t=>{this.gpu=t,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){const t=await pe.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter}),i=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(n=>t.features.has(n)),r=await t.requestDevice({requiredFeatures:i});return{adapter:t,device:r}}destroy(){this.gpu=null,this._renderer=null}}Oo.extension={type:[A.WebGPUSystem],name:"device"},Oo.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class fu{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(e.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(e){this.renderPassEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setPipelineFromGeometryProgramAndState(e,t,i,r){const n=this._renderer.pipeline.getPipeline(e,t,i,r);this.setPipeline(n)}setPipeline(e){this._boundPipeline!==e&&(this._boundPipeline=e,this.renderPassEncoder.setPipeline(e))}_setVertexBuffer(e,t){this._boundVertexBuffer[e]!==t&&(this._boundVertexBuffer[e]=t,this.renderPassEncoder.setVertexBuffer(e,this._renderer.buffer.updateBuffer(t)))}_setIndexBuffer(e){if(this._boundIndexBuffer===e)return;this._boundIndexBuffer=e;const t=e.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(e),t)}resetBindGroup(e){this._boundBindGroup[e]=null}setBindGroup(e,t,i){if(this._boundBindGroup[e]===t)return;this._boundBindGroup[e]=t,t._touch(this._renderer.gc.now,this._renderer.tick);const r=this._renderer.bindGroup.getBindGroup(t,i,e);this.renderPassEncoder.setBindGroup(e,r)}setGeometry(e,t){const i=this._renderer.pipeline.getBufferNamesToBind(e,t);for(const r in i)this._setVertexBuffer(parseInt(r,10),e.attributes[i[r]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){for(const i in e.groups){const r=e.groups[i];t||this._syncBindGroup(r),this.setBindGroup(i,r,e.gpuProgram)}}_syncBindGroup(e){for(const t in e.resources){const i=e.resources[t];i.isUniformGroup&&this._renderer.ubo.updateUniformGroup(i)}}draw(e){const{geometry:t,shader:i,state:r,topology:n,size:o,start:a,instanceCount:l,skipSync:c}=e;this.setPipelineFromGeometryProgramAndState(t,i.gpuProgram,r,n),this.setGeometry(t,i.gpuProgram),this._setShaderBindGroups(i,c),t.indexBuffer?this.renderPassEncoder.drawIndexed(o||t.indexBuffer.data.length,l??t.instanceCount,a||0):this.renderPassEncoder.draw(o||t.getSize(),l??t.instanceCount,a||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){const e=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1],this._renderer.renderTarget.mipLevel,this._renderer.renderTarget.layer);this.renderPassEncoder=this.commandEncoder.beginRenderPass(e);const t=this._boundPipeline,i={...this._boundVertexBuffer},r=this._boundIndexBuffer,n={...this._boundBindGroup};this._clearCache();const o=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(o.x,o.y,o.width,o.height,0,1),this.setPipeline(t);for(const a in i)this._setVertexBuffer(a,i[a]);for(const a in n)this.setBindGroup(a,n[a],null);this._setIndexBuffer(r)}_clearCache(){for(let e=0;e<16;e++)this._boundBindGroup[e]=null,this._boundVertexBuffer[e]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(e){this._gpu=e}}fu.extension={type:[A.WebGPUSystem],name:"encoder",priority:1};class pu{constructor(e){this._renderer=e}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}}pu.extension={type:[A.WebGPUSystem],name:"limits"};class mu{constructor(e){this._renderTargetStencilState=Object.create(null),this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:ke.DISABLED,stencilReference:0}),this._activeRenderTarget=e,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){const i=this._renderTargetStencilState[this._activeRenderTarget.uid];i.stencilMode=e,i.stencilReference=t;const r=this._renderer;r.pipeline.setStencilMode(e),r.encoder.renderPassEncoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}mu.extension={type:[A.WebGPUSystem],name:"stencil"};const Ht=128;class gu{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._batchBuffer=new Yb({minUniformOffsetAlignment:Ht});const t=256/Ht;for(let i=0;i<t;i++){let r=ge.UNIFORM|ge.COPY_DST;i===0&&(r|=ge.COPY_SRC),this._buffers.push(new gt({data:this._batchBuffer.data,usage:r}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){this._bindGroupHash=Object.create(null),this._batchBuffer.clear()}getUniformBindGroup(e,t){if(!t&&this._bindGroupHash[e.uid])return this._bindGroupHash[e.uid];this._renderer.ubo.ensureUniformGroup(e);const i=e.buffer.data,r=this._batchBuffer.addEmptyGroup(i.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,r/4),this._bindGroupHash[e.uid]=this._getBindGroup(r/Ht),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);const t=e.buffer.data,i=this._batchBuffer.addGroup(t);return this._getBufferResource(i/Ht)}getArrayBindGroup(e){const t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/Ht)}getArrayBufferResource(e){const i=this._batchBuffer.addGroup(e)/Ht;return this._getBufferResource(i)}_getBufferResource(e){if(!this._bufferResources[e]){const t=this._buffers[e%2];this._bufferResources[e]=new Gs({buffer:t,offset:(e/2|0)*256,size:Ht})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){const t=new Gt({0:this._getBufferResource(e)});this._bindGroups[e]=t}return this._bindGroups[e]}_uploadBindGroups(){const e=this._renderer.buffer,t=this._buffers[0];t.update(this._batchBuffer.byteIndex),e.updateBuffer(t);const i=this._renderer.gpu.device.createCommandEncoder();for(let r=1;r<this._buffers.length;r++){const n=this._buffers[r];i.copyBufferToBuffer(e.getGPUBuffer(t),Ht,e.getGPUBuffer(n),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([i.finish()])}destroy(){var e;for(let t=0;t<this._bindGroups.length;t++)(e=this._bindGroups[t])==null||e.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let t=0;t<this._buffers.length;t++)this._buffers[t].destroy();this._buffers=null;for(let t=0;t<this._bufferResources.length;t++)this._bufferResources[t].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._renderer=null}}gu.extension={type:[A.WebGPUPipes],name:"uniformBatch"};const qb={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function Kb(s,e,t,i,r){return s<<24|e<<16|t<<10|i<<5|r}function Zb(s,e,t,i,r){return t<<8|s<<5|i<<3|r<<1|e}class _u{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._renderer=e}contextChange(e){this._gpu=e,this.setStencilMode(ke.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){this._multisampleCount=e.msaaSamples,this._depthStencilAttachment=e.descriptor.depthStencilAttachment?1:0,this._colorTargetCount=e.colorTargetCount,this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=Wt[e],this._updatePipeHash())}setPipeline(e,t,i,r){const n=this.getPipeline(e,t,i);r.setPipeline(n)}getPipeline(e,t,i,r){e._layoutKey||($h(e,t.attributeData),this._generateBufferKey(e)),r||(r=e.topology);const n=Kb(e._layoutKey,t._layoutKey,i.data,i._blendModeId,qb[r]);return this._pipeCache[n]?this._pipeCache[n]:(this._pipeCache[n]=this._createPipeline(e,t,i,r),this._pipeCache[n])}_createPipeline(e,t,i,r){const n=this._gpu.device,o=this._createVertexBufferLayouts(e,t),a=this._renderer.state.getColorTargets(i,this._colorTargetCount),l=this._stencilMode===ke.RENDERING_MASK_ADD?0:this._colorMask;for(let f=0;f<a.length;f++)a[f].writeMask=l;const c=this._renderer.shader.getProgramData(t).pipeline,h={vertex:{module:this._getModule(t.vertex.source),entryPoint:t.vertex.entryPoint,buffers:o},fragment:{module:this._getModule(t.fragment.source),entryPoint:t.fragment.entryPoint,targets:a},primitive:{topology:r,cullMode:i.cullMode},layout:c,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(h.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:i.depthTest,depthCompare:i.depthTest?"less":"always"}),n.createRenderPipeline(h)}_getModule(e){return this._moduleCache[e]||this._createModule(e)}_createModule(e){const t=this._gpu.device;return this._moduleCache[e]=t.createShaderModule({code:e}),this._moduleCache[e]}_generateBufferKey(e){const t=[];let i=0;const r=Object.keys(e.attributes).sort();for(let o=0;o<r.length;o++){const a=e.attributes[r[o]];t[i++]=a.offset,t[i++]=a.format,t[i++]=a.stride,t[i++]=a.instance}const n=t.join("|");return e._layoutKey=qi(n,"geometry"),e._layoutKey}_generateAttributeLocationsKey(e){const t=[];let i=0;const r=Object.keys(e.attributeData).sort();for(let o=0;o<r.length;o++){const a=e.attributeData[r[o]];t[i++]=a.location}const n=t.join("|");return e._attributeLocationsKey=qi(n,"programAttributes"),e._attributeLocationsKey}getBufferNamesToBind(e,t){const i=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[i])return this._bindingNamesCache[i];const r=this._createVertexBufferLayouts(e,t),n=Object.create(null),o=t.attributeData;for(let a=0;a<r.length;a++){const c=Object.values(r[a].attributes)[0].shaderLocation;for(const h in o)if(o[h].location===c){n[a]=h;break}}return this._bindingNamesCache[i]=n,n}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);const i=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[i])return this._bufferLayoutsCache[i];const r=[];return e.buffers.forEach(n=>{const o={arrayStride:0,stepMode:"vertex",attributes:[]},a=o.attributes;for(const l in t.attributeData){const c=e.attributes[l];(c.divisor??1)!==1&&se(`Attribute ${l} has an invalid divisor value of '${c.divisor}'. WebGPU only supports a divisor value of 1`),c.buffer===n&&(o.arrayStride=c.stride,o.stepMode=c.instance?"instance":"vertex",a.push({shaderLocation:t.attributeData[l].location,offset:c.offset,format:c.format}))}a.length&&r.push(o)}),this._bufferLayoutsCache[i]=r,r}_updatePipeHash(){const e=Zb(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment,this._colorTargetCount);this._pipeStateCaches[e]||(this._pipeStateCaches[e]=Object.create(null)),this._pipeCache=this._pipeStateCaches[e]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}_u.extension={type:[A.WebGPUSystem],name:"pipeline"};class Jb{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class Qb{init(e,t){this._renderer=e,this._renderTargetSystem=t}copyToTexture(e,t,i,r,n){const o=this._renderer,a=this._getGpuColorTexture(e),l=o.texture.getGpuSource(t.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:i},{texture:l,origin:n},r),t}startRenderPass(e,t=!0,i,r,n=0,o=0){var h,u;const l=this._renderTargetSystem.getGpuRenderTarget(e);if(o!==0&&((h=l.msaaTextures)!=null&&h.length))throw new Error("[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.");if(n>0&&((u=l.msaaTextures)!=null&&u.length))throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");const c=this.getDescriptor(e,t,i,n,o);l.descriptor=c,this._renderer.pipeline.setRenderTarget(l),this._renderer.encoder.beginRenderPass(l),this._renderer.encoder.setViewport(r)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);return t.contexts[0]?t.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(e.colorTextures[0].source)}getDescriptor(e,t,i,r=0,n=0){typeof t=="boolean"&&(t=t?it.ALL:it.NONE);const o=this._renderTargetSystem,a=o.getGpuRenderTarget(e),l=e.colorTextures.map((u,f)=>{const d=a.contexts[f];let g,_;if(d){if(n!==0)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.");g=d.getCurrentTexture().createView()}else g=this._renderer.texture.getGpuSource(u).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1});a.msaaTextures[f]&&(_=g,g=this._renderer.texture.getTextureView(a.msaaTextures[f]));const y=t&it.COLOR?"clear":"load";return i??(i=o.defaultClearColor),{view:g,resolveTarget:_,clearValue:i,storeOp:"store",loadOp:y}});let c;if((e.stencil||e.depth)&&!e.depthStencilTexture&&(e.ensureDepthStencilTexture(),e.depthStencilTexture.source.sampleCount=a.msaa?4:1),e.depthStencilTexture){const u=t&it.STENCIL?"clear":"load",f=t&it.DEPTH?"clear":"load";c={view:this._renderer.texture.getGpuSource(e.depthStencilTexture.source).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1}),stencilStoreOp:"store",stencilLoadOp:u,depthClearValue:1,depthLoadOp:f,depthStoreOp:"store"}}return{colorAttachments:l,depthStencilAttachment:c}}clear(e,t=!0,i,r,n=0,o=0){if(!t)return;const{gpu:a,encoder:l}=this._renderer,c=a.device;if(l.commandEncoder===null){const u=c.createCommandEncoder(),f=this.getDescriptor(e,t,i,n,o),d=u.beginRenderPass(f);d.setViewport(r.x,r.y,r.width,r.height,0,1),d.end();const g=u.finish();c.queue.submit([g])}else this.startRenderPass(e,t,i,r,n,o)}initGpuRenderTarget(e){e.isRoot=!0;const t=new Jb;return t.colorTargetCount=e.colorTextures.length,e.colorTextures.forEach((i,r)=>{if(i instanceof yt){const n=i.resource.getContext("webgpu"),o=i.transparent?"premultiplied":"opaque";try{n.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:o})}catch(a){console.error(a)}t.contexts[r]=n}if(t.msaa=i.source.antialias,i.source.antialias){const n=new De({width:0,height:0,sampleCount:4,arrayLayerCount:i.source.arrayLayerCount});t.msaaTextures[r]=n}}),t.msaa&&(t.msaaSamples=4,e.depthStencilTexture&&(e.depthStencilTexture.source.sampleCount=4)),t}destroyGpuRenderTarget(e){e.contexts.forEach(t=>{t.unconfigure()}),e.msaaTextures.forEach(t=>{t.destroy()}),e.msaaTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);e.depthStencilTexture&&t.msaa&&(e.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorTextures.forEach((i,r)=>{const n=t.msaaTextures[r];n==null||n.resize(i.source.width,i.source.height,i.source._resolution)})}}class yu extends wo{constructor(e){super(e),this.adaptor=new Qb,this.adaptor.init(e,this)}}yu.extension={type:[A.WebGPUSystem],name:"renderTarget"};class bu{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){const t=this._gpu.device,i=e.gpuLayout.map(n=>t.createBindGroupLayout({entries:n})),r={bindGroupLayouts:i};return this._gpuProgramData[e._layoutKey]={bindGroups:i,pipeline:t.createPipelineLayout(r)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}bu.extension={type:[A.WebGPUSystem],name:"shader"};const et={};et.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},et.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},et.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},et.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},et.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},et.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},et["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},et["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},et["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},et.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},et.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},et.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class xu{constructor(){this.defaultState=new Pt,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e,t){const i=et[e.blendMode]||et.normal,r=[],n={format:"bgra8unorm",writeMask:0,blend:i};for(let o=0;o<t;o++)r[o]=n;return r}destroy(){this.gpu=null}}xu.extension={type:[A.WebGPUSystem],name:"state"};const ex={type:"image",upload(s,e,t,i=0){const r=s.resource,n=(s.pixelWidth|0)*(s.pixelHeight|0),o=r.byteLength/n;t.device.queue.writeTexture({texture:e,origin:{x:0,y:0,z:i}},r,{offset:0,rowsPerImage:s.pixelHeight,bytesPerRow:s.pixelWidth*o},{width:s.pixelWidth,height:s.pixelHeight,depthOrArrayLayers:1})}},vu={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},tx={blockBytes:4,blockWidth:1,blockHeight:1},ix={type:"compressed",upload(s,e,t,i=0){let r=s.pixelWidth,n=s.pixelHeight;const o=vu[s.format]||tx;for(let a=0;a<s.resource.length;a++){const l=s.resource[a],c=Math.ceil(r/o.blockWidth)*o.blockBytes;t.device.queue.writeTexture({texture:e,mipLevel:a,origin:{x:0,y:0,z:i}},l,{offset:0,bytesPerRow:c},{width:Math.ceil(r/o.blockWidth)*o.blockWidth,height:Math.ceil(n/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}}},Cu=["right","left","top","bottom","front","back"];function sx(s){return{type:"cube",upload(e,t,i){const r=e.faces;for(let n=0;n<Cu.length;n++){const o=Cu[n],a=r[o];(s[a.uploadMethodId]||s.image).upload(a,t,i,n)}}}}const Su={type:"image",upload(s,e,t,i=0){const r=s.resource;if(!r)return;if(globalThis.HTMLImageElement&&r instanceof HTMLImageElement){const l=pe.get().createCanvas(r.width,r.height);l.getContext("2d").drawImage(r,0,0,r.width,r.height),s.resource=l,se("ImageSource: Image element passed, converting to canvas and replacing resource.")}const n=Math.min(e.width,s.resourceWidth||s.pixelWidth),o=Math.min(e.height,s.resourceHeight||s.pixelHeight),a=s.alphaMode==="premultiply-alpha-on-upload";t.device.queue.copyExternalImageToTexture({source:r},{texture:e,origin:{x:0,y:0,z:i},premultipliedAlpha:a},{width:n,height:o})}},rx={type:"video",upload(s,e,t,i){Su.upload(s,e,t,i)}};class nx{constructor(e){this.device=e,this.sampler=e.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(e){let t=this.pipelines[e];return t||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:`
874
874
  var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
875
875
  vec2<f32>(-1.0, -1.0), vec2<f32>(-1.0, 3.0), vec2<f32>(3.0, -1.0));
876
876
 
@@ -894,7 +894,7 @@ fn mainFragment(
894
894
  fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
895
895
  return textureSample(img, imgSampler, texCoord);
896
896
  }
897
- `})),t=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:e}]}}),this.pipelines[e]=t),t}generateMipmap(e){const t=this._getMipmapPipeline(e.format);if(e.dimension==="3d"||e.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let i=e;const r=e.depthOrArrayLayers||1,n=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!n){const l={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};i=this.device.createTexture(l)}const o=this.device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let l=0;l<r;++l){let c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),h=n?1:0;for(let u=1;u<e.mipLevelCount;++u){const f=i.createView({baseMipLevel:h++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),d=o.beginRenderPass({colorAttachments:[{view:f,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),g=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.sampler},{binding:1,resource:c}]});d.setPipeline(t),d.setBindGroup(0,g),d.draw(3,1,0,0),d.end(),c=f}}if(!n){const l={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r};for(let c=1;c<e.mipLevelCount;++c)o.copyTextureToTexture({texture:i,mipLevel:c-1},{texture:e,mipLevel:c},l),l.width=Math.ceil(l.width/2),l.height=Math.ceil(l.height/2)}return this.device.queue.submit([o.finish()]),n||i.destroy(),e}}class nx{constructor(e){this.textureView=null,this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}}class Eu{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new kt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:Su,buffer:Qb,video:sx,compressed:tx};this._uploads={...t,cube:ix(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e}initSource(e){var t;return((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){const c=Math.max(e.pixelWidth,e.pixelHeight);e.mipLevelCount=Math.floor(Math.log2(c))+1}let t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC);const i=vu[e.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(e.pixelWidth/i.blockWidth)*i.blockWidth,n=Math.ceil(e.pixelHeight/i.blockHeight)*i.blockHeight,o={label:e.label,size:{width:r,height:n,depthOrArrayLayers:e.arrayLayerCount},format:e.format,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},a=this._gpu.device.createTexture(o);return e._gpuData[this._renderer.uid]=new nx(a),this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceResize,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),a}onSourceUpdate(e){const t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onUpdateMipmaps(e){this._mipmapGenerator||(this._mipmapGenerator=new rx(this._gpu.device));const t=this.getGpuSource(e);this._mipmapGenerator.generateMipmap(t)}onSourceUnload(e){e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceResize,this),e.off("updateMipmaps",this.onUpdateMipmaps,this)}onSourceResize(e){e._gcLastUsed=this._renderer.gc.now;const t=e._gpuData[this._renderer.uid],i=t==null?void 0:t.gpuTexture;i?(i.width!==e.pixelWidth||i.height!==e.pixelHeight)&&(t.destroy(),this._bindGroupHash[e.uid]=null,e._gpuData[this._renderer.uid]=null,this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]||this._createTextureBindGroup(e)}_createTextureBindGroup(e){const t=e.source;return this._bindGroupHash[e.uid]=new Gt({0:t,1:t.style,2:new ht({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e){const t=e.source;t._gcLastUsed=this._renderer.gc.now;let i=t._gpuData[this._renderer.uid];return i||(this.initSource(t),i=t._gpuData[this._renderer.uid]),i.textureView||(i.textureView=i.gpuTexture.createView({dimension:t.viewDimension})),i.textureView}generateCanvas(e){const t=this._renderer,i=t.gpu.device.createCommandEncoder(),r=pe.get().createCanvas();r.width=e.source.pixelWidth,r.height=e.source.pixelHeight;const n=r.getContext("webgpu");return n.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:pe.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),i.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:r.width,height:r.height}),t.gpu.device.queue.submit([i.finish()]),r}getPixels(e){const t=this.generateCanvas(e),i=so.getOptimalCanvasAndContext(t.width,t.height),r=i.context;r.drawImage(t,0,0);const{width:n,height:o}=t,a=r.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return so.returnCanvasAndContext(i),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e),i=this._bindGroupHash[t];i==null||i.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}}Eu.extension={type:[A.WebGPUSystem],name:"texture"};class Tu{constructor(){this._maxTextures=0}contextChange(e){const t=new ht({uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=e.limits.maxBatchableTextures;const i=Gn({name:"graphics",bits:[vc,Sc(this._maxTextures),_y,Vn]});this.shader=new Mt({gpuProgram:i,resources:{localUniforms:t}})}execute(e,t){const i=t.context,r=i.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i),c=n.encoder;c.setGeometry(a.geometry,r.gpuProgram);const h=n.globalUniforms.bindGroup;c.setBindGroup(0,h,r.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);c.setBindGroup(2,u,r.gpuProgram);const f=l.instructions;let d=null;for(let g=0;g<l.instructionSize;g++){const _=f[g];if(_.topology!==d&&(d=_.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,_.topology)),r.groups[1]=_.bindGroup,!_.gpuBindGroup){const b=_.textures;_.bindGroup=Nn(b.textures,b.count,this._maxTextures),_.gpuBindGroup=n.bindGroup.getBindGroup(_.bindGroup,r.gpuProgram,1)}c.setBindGroup(1,_.bindGroup,r.gpuProgram),c.renderPassEncoder.drawIndexed(_.size,1,_.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}Tu.extension={type:[A.WebGPUPipesAdaptor],name:"graphics"};class Au{init(){const e=Gn({name:"mesh",bits:[ur,vy,Vn]});this._shader=new Mt({gpuProgram:e,resources:{uTexture:j.EMPTY._source,uSampler:j.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const i=e.renderer;let r=t._shader;if(!r)r=this._shader,r.groups[2]=i.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){se("Mesh shader has no gpuProgram",t.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=i.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;r.groups[1]=i.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}i.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Au.extension={type:[A.WebGPUPipesAdaptor],name:"mesh"};const ox=[...Ao,qr,fu,Oo,pu,uu,Eu,yu,bu,xu,_u,du,mu,hu],ax=[...Fh,gu],lx=[yh,Au,Tu],wu=[],Iu=[],Ru=[];Q.handleByNamedList(A.WebGPUSystem,wu),Q.handleByNamedList(A.WebGPUPipes,Iu),Q.handleByNamedList(A.WebGPUPipesAdaptor,Ru),Q.add(...ox,...ax,...lx);class cx extends vi{constructor(){const e={name:"webgpu",type:bt.WEBGPU,systems:wu,renderPipes:Iu,renderPipeAdaptors:Ru};super(e)}}const hx=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:cx},Symbol.toStringTag,{value:"Module"}));Q.add(Rm,Mm);const Bi=480,xs=480;class ux{constructor(){this.container=null,this.resizeObserver=null,this.mode="floating",this.targetEl=null,this.app=new nc}async init(e="floating",t){this.mode=e,e==="inline"&&t&&(this.targetEl=document.querySelector(t),this.targetEl||(console.warn(`[HolostaffWidget] Container "${t}" not found, falling back to floating mode`),this.mode="floating")),await this.app.init({width:Bi,height:xs,backgroundAlpha:0,antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0,preference:"webgl"}),this.container=document.createElement("div"),this.container.id="holostaff-widget-root",this.mode==="inline"&&this.targetEl?(Object.assign(this.container.style,{position:"relative",width:"100%",height:"100%",overflow:"visible",pointerEvents:"none"}),this.targetEl.style.position="relative",this.targetEl.style.cursor="pointer",this.targetEl.appendChild(this.container)):(Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"50%",transform:"translateX(-50%)",width:`${Bi}px`,height:`${xs}px`,zIndex:"2147483646",pointerEvents:"none",overflow:"visible"}),document.documentElement.appendChild(this.container));const i=this.app.canvas;return Object.assign(i.style,{width:"100%",height:"100%",display:"block",pointerEvents:"auto"}),this.container.appendChild(i),this.setupResize(),i}setupResize(){const e=()=>{if(this.mode==="inline"&&this.targetEl){const t=this.targetEl.getBoundingClientRect();this.container&&(this.container.style.width=`${t.width}px`,this.container.style.height=`${t.height}px`)}else{const t=window.innerWidth,i=Math.min(Bi,t),r=i/Bi,n=xs*r;this.container&&(this.container.style.width=`${i}px`,this.container.style.height=`${n}px`)}this.app.renderer.resize(Bi,xs)};window.addEventListener("resize",e),this.mode==="inline"&&this.targetEl&&(this.resizeObserver=new ResizeObserver(e),this.resizeObserver.observe(this.targetEl)),e()}get isInline(){return this.mode==="inline"&&this.targetEl!==null}get inlineTarget(){return this.targetEl}get rootElement(){return this.container}get stageWidth(){return Bi}get stageHeight(){return xs}getInlineRect(){var e;return((e=this.targetEl)==null?void 0:e.getBoundingClientRect())??null}destroy(){var e,t;window.removeEventListener("resize",this.setupResize),(e=this.resizeObserver)==null||e.disconnect(),(t=this.container)==null||t.remove(),this.app.destroy(!0)}}function dx(){var s,e;return((e=(s=globalThis.matchMedia)==null?void 0:s.call(globalThis,"(prefers-reduced-motion: reduce)"))==null?void 0:e.matches)??!1}const vs={easeOutCubic:s=>1-Math.pow(1-s,3),easeInCubic:s=>s*s*s,easeOutBack:s=>1+2.70158*Math.pow(s-1,3)+1.70158*Math.pow(s-1,2),easeInOutSine:s=>-(Math.cos(Math.PI*s)-1)/2};function gr(s){const{target:e,props:t,duration:i,easing:r=vs.easeOutCubic,delay:n=0,onComplete:o,ticker:a}=s;if(dx()){for(const f of Object.keys(t))e[f]=t[f];return o==null||o(),()=>{}}const l={};for(const f of Object.keys(t))l[f]=e[f];let c=-n,h=!1;const u=f=>{if(h||(c+=f.deltaMS,c<0))return;const d=Math.min(c/i,1),g=r(d);for(const _ of Object.keys(t))e[_]=l[_]+(t[_]-l[_])*g;d>=1&&(a.remove(u),o==null||o())};return a.add(u),()=>{h=!0,a.remove(u)}}const Cs=200,Vt=Cs*(480/854),Mu=280;class fx{constructor(e,t){this.idleVideoEl=null,this.idleGroup=null,this.liveSprite=null,this.cancelGlow=null,this.cancelEntrance=null,this.visible=!1,this.widgetRoot=null,this.stageWidth=e,this.stageHeight=t,this.container=new Ve,this.container.visible=!1,this.container.x=e/2,this.container.y=t+Vt}async loadIdleVideo(e,t){this.widgetRoot=t,this.idleVideoEl=document.createElement("video"),this.idleVideoEl.src=e,this.idleVideoEl.loop=!0,this.idleVideoEl.muted=!0,this.idleVideoEl.playsInline=!0,this.idleVideoEl.crossOrigin="anonymous",Object.assign(this.idleVideoEl.style,{position:"absolute",bottom:"10px",left:"50%",transform:"translateX(-50%) translateY(100%)",width:`${Cs}px`,height:"auto",pointerEvents:"none",zIndex:"0",transition:"none"}),t.insertBefore(this.idleVideoEl,t.firstChild),await this.idleVideoEl.play(),this.idleGroup=new Ve,this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}async loadIdleImage(e){const t=j.from(e),i=new Ft(t);i.width=Cs,i.height=Vt,i.anchor.set(.5,1),this.idleGroup=new Ve,this.idleGroup.addChild(i),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}slideIn(e){if(this.visible)return;this.visible=!0;const t=this.stageHeight-10;this.container.alpha=1,this.container.visible=!0,this.container.y=this.stageHeight+Vt,this.cancelEntrance=gr({target:this.container,props:{y:t},duration:700,easing:vs.easeOutBack,ticker:e}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.7s cubic-bezier(0.34, 1.56, 0.64, 1)",this.idleVideoEl.style.transform="translateX(-50%) translateY(0)")}slideOut(e){var t;this.visible&&(this.visible=!1,(t=this.cancelGlow)==null||t.call(this),this.cancelGlow=null,gr({target:this.container,props:{y:this.stageHeight+Vt},duration:450,easing:vs.easeInCubic,ticker:e,onComplete:()=>{this.container.visible=!1}}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.45s cubic-bezier(0.32, 0, 0.67, 0)",this.idleVideoEl.style.transform="translateX(-50%) translateY(100%)"))}get isVisible(){return this.visible}setInteractive(e){this.container.eventMode="static",this.container.cursor="pointer",this.container.hitArea=new Se(-Cs/2,-Vt,Cs,Vt),this.container.on("pointertap",e),this.idleVideoEl&&(this.idleVideoEl.style.pointerEvents="auto",this.idleVideoEl.style.cursor="pointer",this.idleVideoEl.addEventListener("click",e))}setLiveVideo(e,t){const i=()=>{var l;const r=j.from(e);this.liveSprite=new Ft(r);const n=e.videoWidth||1,o=e.videoHeight||1,a=Mu/n;this.liveSprite.width=Mu,this.liveSprite.height=o*a,this.liveSprite.anchor.set(.5,1),this.liveSprite.alpha=0,this.container.addChild(this.liveSprite),this.idleVideoEl&&(this.idleVideoEl.style.display="none"),this.idleGroup&&(this.idleGroup.visible=!1),(l=this.cancelGlow)==null||l.call(this),this.cancelGlow=null,gr({target:this.liveSprite,props:{alpha:1},duration:500,easing:vs.easeInOutSine,ticker:t})};if(e.videoWidth>0&&e.videoHeight>0)i();else{const r=()=>{e.removeEventListener("loadeddata",r),e.removeEventListener("resize",r),i()};e.addEventListener("loadeddata",r),e.addEventListener("resize",r)}}clearLiveVideo(e){this.liveSprite&&gr({target:this.liveSprite,props:{alpha:0},duration:400,easing:vs.easeInCubic,ticker:e,onComplete:()=>{var t;(t=this.liveSprite)==null||t.destroy(),this.liveSprite=null}}),this.idleVideoEl&&(this.idleVideoEl.style.display=""),this.idleGroup&&(this.idleGroup.visible=!0)}destroy(){var e,t;(e=this.cancelGlow)==null||e.call(this),(t=this.cancelEntrance)==null||t.call(this),this.idleVideoEl&&(this.idleVideoEl.pause(),this.idleVideoEl.remove()),this.container.destroy({children:!0})}}const px=[{urls:"stun:stun.l.google.com:19302"}],mx=3e3,gx="oai-events";class _x{constructor(e){this.onConnected=null,this.onDisconnected=null,this.onRemoteTrack=null,this.onDataMessage=null,this.onError=null,this.pc=null,this.dc=null,this.micStream=null,this._remoteAudioStream=null,this._connected=!1,this.opts={model:"gpt-4o-realtime-preview",voice:"verse",instructions:"",tools:[],...e}}get isConnected(){return this._connected}get dataChannel(){return this.dc}get remoteAudioStream(){return this._remoteAudioStream}async connect(){var e,t;try{console.log("[RealtimeSession] Requesting microphone..."),this.micStream=await navigator.mediaDevices.getUserMedia({audio:!0}),console.log("[RealtimeSession] Microphone granted"),this.pc=new RTCPeerConnection({iceServers:px}),this.setupPeerConnectionHandlers();for(const o of this.micStream.getAudioTracks())this.pc.addTrack(o,this.micStream);this.dc=this.pc.createDataChannel(gx),this.setupDataChannelHandlers();const i=await this.pc.createOffer();await this.pc.setLocalDescription(i),await this.waitForIceGathering();const r=(e=this.pc.localDescription)==null?void 0:e.sdp;if(!r)throw new Error("No local SDP after ICE gathering");console.log("[RealtimeSession] Exchanging SDP...");const n=await this.exchangeSDP(r);await this.pc.setRemoteDescription({type:"answer",sdp:n}),console.log("[RealtimeSession] Remote description set")}catch(i){const r=i instanceof Error?i:new Error(String(i));throw console.error("[RealtimeSession] Connection failed:",r.message),(t=this.onError)==null||t.call(this,r),this.close(),r}}sendJSON(e){if(!this.dc||this.dc.readyState!=="open"){console.warn("[RealtimeSession] Data channel not open, cannot send:",e);return}this.dc.send(JSON.stringify(e))}close(){var e;if(console.log("[RealtimeSession] Closing..."),this.dc){try{this.dc.close()}catch{}this.dc=null}if(this.pc){try{this.pc.close()}catch{}this.pc=null}if(this.micStream){for(const t of this.micStream.getTracks())t.stop();this.micStream=null}this._remoteAudioStream=null,this._connected&&(this._connected=!1,(e=this.onDisconnected)==null||e.call(this))}setupPeerConnectionHandlers(){this.pc&&(this.pc.ontrack=e=>{var t;console.log("[RealtimeSession] Remote audio track received"),this._remoteAudioStream=e.streams[0]??new MediaStream([e.track]),(t=this.onRemoteTrack)==null||t.call(this,this._remoteAudioStream)},this.pc.onconnectionstatechange=()=>{var t,i,r,n;const e=(t=this.pc)==null?void 0:t.connectionState;console.log("[RealtimeSession] Connection state:",e),e==="connected"?(this._connected=!0,(i=this.onConnected)==null||i.call(this)):(e==="failed"||e==="closed"||e==="disconnected")&&(this._connected&&(this._connected=!1,(r=this.onDisconnected)==null||r.call(this)),e==="failed"&&((n=this.onError)==null||n.call(this,new Error("WebRTC connection failed"))))})}waitForIceGathering(){return!this.pc||this.pc.iceGatheringState==="complete"?Promise.resolve():new Promise(e=>{const t=this.pc;let i;const r=()=>{clearTimeout(i);try{t.removeEventListener("icegatheringstatechange",n)}catch{}e()},n=()=>{t.iceGatheringState==="complete"&&r()};t.addEventListener("icegatheringstatechange",n),i=setTimeout(r,mx)})}async exchangeSDP(e){const{webrtcUrl:t,ephemeralKey:i,model:r,voice:n}=this.opts,o=t.includes("?")?"&":"?",a=`${t}${o}model=${encodeURIComponent(r)}&voice=${encodeURIComponent(n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/sdp",Accept:"application/sdp"},body:e});if(!l.ok){const c=await l.text().catch(()=>"");throw new Error(`SDP exchange failed (${l.status}): ${c}`)}return l.text()}setupDataChannelHandlers(){this.dc&&(this.dc.onopen=()=>{console.log("[RealtimeSession] Data channel open"),this.sendSessionUpdate(),this.sendJSON({type:"response.create"})},this.dc.onmessage=e=>{var t;try{const i=JSON.parse(e.data);(t=this.onDataMessage)==null||t.call(this,i)}catch(i){console.warn("[RealtimeSession] Failed to parse data channel message:",i)}},this.dc.onclose=()=>{console.log("[RealtimeSession] Data channel closed")},this.dc.onerror=e=>{console.error("[RealtimeSession] Data channel error:",e)})}sendSessionUpdate(){const e={instructions:this.opts.instructions,modalities:["audio","text"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:700,create_response:!0}};this.opts.tools&&this.opts.tools.length>0&&(e.tools=this.opts.tools),this.sendJSON({type:"session.update",session:e})}}const yx=24e3,bx=`
897
+ `})),t=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:e}]}}),this.pipelines[e]=t),t}generateMipmap(e){const t=this._getMipmapPipeline(e.format);if(e.dimension==="3d"||e.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let i=e;const r=e.depthOrArrayLayers||1,n=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!n){const l={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};i=this.device.createTexture(l)}const o=this.device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let l=0;l<r;++l){let c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),h=n?1:0;for(let u=1;u<e.mipLevelCount;++u){const f=i.createView({baseMipLevel:h++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),d=o.beginRenderPass({colorAttachments:[{view:f,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),g=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.sampler},{binding:1,resource:c}]});d.setPipeline(t),d.setBindGroup(0,g),d.draw(3,1,0,0),d.end(),c=f}}if(!n){const l={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r};for(let c=1;c<e.mipLevelCount;++c)o.copyTextureToTexture({texture:i,mipLevel:c-1},{texture:e,mipLevel:c},l),l.width=Math.ceil(l.width/2),l.height=Math.ceil(l.height/2)}return this.device.queue.submit([o.finish()]),n||i.destroy(),e}}class ox{constructor(e){this.textureView=null,this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}}class Eu{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new kt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:Su,buffer:ex,video:rx,compressed:ix};this._uploads={...t,cube:sx(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e}initSource(e){var t;return((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){const c=Math.max(e.pixelWidth,e.pixelHeight);e.mipLevelCount=Math.floor(Math.log2(c))+1}let t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC);const i=vu[e.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(e.pixelWidth/i.blockWidth)*i.blockWidth,n=Math.ceil(e.pixelHeight/i.blockHeight)*i.blockHeight,o={label:e.label,size:{width:r,height:n,depthOrArrayLayers:e.arrayLayerCount},format:e.format,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},a=this._gpu.device.createTexture(o);return e._gpuData[this._renderer.uid]=new ox(a),this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceResize,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),a}onSourceUpdate(e){const t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onUpdateMipmaps(e){this._mipmapGenerator||(this._mipmapGenerator=new nx(this._gpu.device));const t=this.getGpuSource(e);this._mipmapGenerator.generateMipmap(t)}onSourceUnload(e){e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceResize,this),e.off("updateMipmaps",this.onUpdateMipmaps,this)}onSourceResize(e){e._gcLastUsed=this._renderer.gc.now;const t=e._gpuData[this._renderer.uid],i=t==null?void 0:t.gpuTexture;i?(i.width!==e.pixelWidth||i.height!==e.pixelHeight)&&(t.destroy(),this._bindGroupHash[e.uid]=null,e._gpuData[this._renderer.uid]=null,this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]||this._createTextureBindGroup(e)}_createTextureBindGroup(e){const t=e.source;return this._bindGroupHash[e.uid]=new Gt({0:t,1:t.style,2:new ht({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e){const t=e.source;t._gcLastUsed=this._renderer.gc.now;let i=t._gpuData[this._renderer.uid];return i||(this.initSource(t),i=t._gpuData[this._renderer.uid]),i.textureView||(i.textureView=i.gpuTexture.createView({dimension:t.viewDimension})),i.textureView}generateCanvas(e){const t=this._renderer,i=t.gpu.device.createCommandEncoder(),r=pe.get().createCanvas();r.width=e.source.pixelWidth,r.height=e.source.pixelHeight;const n=r.getContext("webgpu");return n.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:pe.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),i.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:r.width,height:r.height}),t.gpu.device.queue.submit([i.finish()]),r}getPixels(e){const t=this.generateCanvas(e),i=so.getOptimalCanvasAndContext(t.width,t.height),r=i.context;r.drawImage(t,0,0);const{width:n,height:o}=t,a=r.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return so.returnCanvasAndContext(i),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e),i=this._bindGroupHash[t];i==null||i.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}}Eu.extension={type:[A.WebGPUSystem],name:"texture"};class Tu{constructor(){this._maxTextures=0}contextChange(e){const t=new ht({uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=e.limits.maxBatchableTextures;const i=Gn({name:"graphics",bits:[vc,Sc(this._maxTextures),yy,Vn]});this.shader=new Mt({gpuProgram:i,resources:{localUniforms:t}})}execute(e,t){const i=t.context,r=i.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i),c=n.encoder;c.setGeometry(a.geometry,r.gpuProgram);const h=n.globalUniforms.bindGroup;c.setBindGroup(0,h,r.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);c.setBindGroup(2,u,r.gpuProgram);const f=l.instructions;let d=null;for(let g=0;g<l.instructionSize;g++){const _=f[g];if(_.topology!==d&&(d=_.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,_.topology)),r.groups[1]=_.bindGroup,!_.gpuBindGroup){const y=_.textures;_.bindGroup=Nn(y.textures,y.count,this._maxTextures),_.gpuBindGroup=n.bindGroup.getBindGroup(_.bindGroup,r.gpuProgram,1)}c.setBindGroup(1,_.bindGroup,r.gpuProgram),c.renderPassEncoder.drawIndexed(_.size,1,_.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}Tu.extension={type:[A.WebGPUPipesAdaptor],name:"graphics"};class Au{init(){const e=Gn({name:"mesh",bits:[dr,Cy,Vn]});this._shader=new Mt({gpuProgram:e,resources:{uTexture:j.EMPTY._source,uSampler:j.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const i=e.renderer;let r=t._shader;if(!r)r=this._shader,r.groups[2]=i.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){se("Mesh shader has no gpuProgram",t.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=i.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;r.groups[1]=i.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}i.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Au.extension={type:[A.WebGPUPipesAdaptor],name:"mesh"};const ax=[...Ao,qr,fu,Oo,pu,uu,Eu,yu,bu,xu,_u,du,mu,hu],lx=[...Fh,gu],cx=[yh,Au,Tu],wu=[],Iu=[],Ru=[];Q.handleByNamedList(A.WebGPUSystem,wu),Q.handleByNamedList(A.WebGPUPipes,Iu),Q.handleByNamedList(A.WebGPUPipesAdaptor,Ru),Q.add(...ax,...lx,...cx);class hx extends vi{constructor(){const e={name:"webgpu",type:bt.WEBGPU,systems:wu,renderPipes:Iu,renderPipeAdaptors:Ru};super(e)}}const ux=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:hx},Symbol.toStringTag,{value:"Module"}));Q.add(Mm,Pm);const Bi=480,xs=480;class dx{constructor(){this.container=null,this.resizeObserver=null,this.mode="floating",this.targetEl=null,this.app=new nc}async init(e="floating",t){this.mode=e,e==="inline"&&t&&(this.targetEl=document.querySelector(t),this.targetEl||(console.warn(`[HolostaffWidget] Container "${t}" not found, falling back to floating mode`),this.mode="floating")),await this.app.init({width:Bi,height:xs,backgroundAlpha:0,antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0,preference:"webgl"}),this.container=document.createElement("div"),this.container.id="holostaff-widget-root",this.mode==="inline"&&this.targetEl?(Object.assign(this.container.style,{position:"relative",width:"100%",height:"100%",overflow:"visible",pointerEvents:"none"}),this.targetEl.style.position="relative",this.targetEl.style.cursor="pointer",this.targetEl.appendChild(this.container)):(Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"50%",transform:"translateX(-50%)",width:`${Bi}px`,height:`${xs}px`,zIndex:"2147483646",pointerEvents:"none",overflow:"visible"}),document.documentElement.appendChild(this.container));const i=this.app.canvas;return Object.assign(i.style,{width:"100%",height:"100%",display:"block",pointerEvents:"auto"}),this.container.appendChild(i),this.setupResize(),i}setupResize(){const e=()=>{if(this.mode==="inline"&&this.targetEl){const t=this.targetEl.getBoundingClientRect();this.container&&(this.container.style.width=`${t.width}px`,this.container.style.height=`${t.height}px`)}else{const t=window.innerWidth,i=Math.min(Bi,t),r=i/Bi,n=xs*r;this.container&&(this.container.style.width=`${i}px`,this.container.style.height=`${n}px`)}this.app.renderer.resize(Bi,xs)};window.addEventListener("resize",e),this.mode==="inline"&&this.targetEl&&(this.resizeObserver=new ResizeObserver(e),this.resizeObserver.observe(this.targetEl)),e()}get isInline(){return this.mode==="inline"&&this.targetEl!==null}get inlineTarget(){return this.targetEl}get rootElement(){return this.container}get stageWidth(){return Bi}get stageHeight(){return xs}getInlineRect(){var e;return((e=this.targetEl)==null?void 0:e.getBoundingClientRect())??null}destroy(){var e,t;window.removeEventListener("resize",this.setupResize),(e=this.resizeObserver)==null||e.disconnect(),(t=this.container)==null||t.remove(),this.app.destroy(!0)}}function fx(){var s,e;return((e=(s=globalThis.matchMedia)==null?void 0:s.call(globalThis,"(prefers-reduced-motion: reduce)"))==null?void 0:e.matches)??!1}const vs={easeOutCubic:s=>1-Math.pow(1-s,3),easeInCubic:s=>s*s*s,easeOutBack:s=>1+2.70158*Math.pow(s-1,3)+1.70158*Math.pow(s-1,2),easeInOutSine:s=>-(Math.cos(Math.PI*s)-1)/2};function _r(s){const{target:e,props:t,duration:i,easing:r=vs.easeOutCubic,delay:n=0,onComplete:o,ticker:a}=s;if(fx()){for(const f of Object.keys(t))e[f]=t[f];return o==null||o(),()=>{}}const l={};for(const f of Object.keys(t))l[f]=e[f];let c=-n,h=!1;const u=f=>{if(h||(c+=f.deltaMS,c<0))return;const d=Math.min(c/i,1),g=r(d);for(const _ of Object.keys(t))e[_]=l[_]+(t[_]-l[_])*g;d>=1&&(a.remove(u),o==null||o())};return a.add(u),()=>{h=!0,a.remove(u)}}const Cs=200,Vt=Cs*(480/854),Mu=280;class px{constructor(e,t){this.idleVideoEl=null,this.idleGroup=null,this.liveSprite=null,this.cancelGlow=null,this.cancelEntrance=null,this.visible=!1,this.widgetRoot=null,this.stageWidth=e,this.stageHeight=t,this.container=new Ve,this.container.visible=!1,this.container.x=e/2,this.container.y=t+Vt}async loadIdleVideo(e,t){this.widgetRoot=t,this.idleVideoEl=document.createElement("video"),this.idleVideoEl.src=e,this.idleVideoEl.loop=!0,this.idleVideoEl.muted=!0,this.idleVideoEl.playsInline=!0,this.idleVideoEl.crossOrigin="anonymous",Object.assign(this.idleVideoEl.style,{position:"absolute",bottom:"10px",left:"50%",transform:"translateX(-50%) translateY(100%)",width:`${Cs}px`,height:"auto",pointerEvents:"none",zIndex:"0",transition:"none"}),t.insertBefore(this.idleVideoEl,t.firstChild),await this.idleVideoEl.play(),this.idleGroup=new Ve,this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}async loadIdleImage(e){const t=j.from(e),i=new Ft(t);i.width=Cs,i.height=Vt,i.anchor.set(.5,1),this.idleGroup=new Ve,this.idleGroup.addChild(i),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}slideIn(e){if(this.visible)return;this.visible=!0;const t=this.stageHeight-10;this.container.alpha=1,this.container.visible=!0,this.container.y=this.stageHeight+Vt,this.cancelEntrance=_r({target:this.container,props:{y:t},duration:700,easing:vs.easeOutBack,ticker:e}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.7s cubic-bezier(0.34, 1.56, 0.64, 1)",this.idleVideoEl.style.transform="translateX(-50%) translateY(0)")}slideOut(e){var t;this.visible&&(this.visible=!1,(t=this.cancelGlow)==null||t.call(this),this.cancelGlow=null,_r({target:this.container,props:{y:this.stageHeight+Vt},duration:450,easing:vs.easeInCubic,ticker:e,onComplete:()=>{this.container.visible=!1}}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.45s cubic-bezier(0.32, 0, 0.67, 0)",this.idleVideoEl.style.transform="translateX(-50%) translateY(100%)"))}get isVisible(){return this.visible}setInteractive(e){this.container.eventMode="static",this.container.cursor="pointer",this.container.hitArea=new Se(-Cs/2,-Vt,Cs,Vt),this.container.on("pointertap",e),this.idleVideoEl&&(this.idleVideoEl.style.pointerEvents="auto",this.idleVideoEl.style.cursor="pointer",this.idleVideoEl.addEventListener("click",e))}setLiveVideo(e,t){const i=()=>{var l;const r=j.from(e);this.liveSprite=new Ft(r);const n=e.videoWidth||1,o=e.videoHeight||1,a=Mu/n;this.liveSprite.width=Mu,this.liveSprite.height=o*a,this.liveSprite.anchor.set(.5,1),this.liveSprite.alpha=0,this.container.addChild(this.liveSprite),this.idleVideoEl&&(this.idleVideoEl.style.display="none"),this.idleGroup&&(this.idleGroup.visible=!1),(l=this.cancelGlow)==null||l.call(this),this.cancelGlow=null,_r({target:this.liveSprite,props:{alpha:1},duration:500,easing:vs.easeInOutSine,ticker:t})};if(e.videoWidth>0&&e.videoHeight>0)i();else{const r=()=>{e.removeEventListener("loadeddata",r),e.removeEventListener("resize",r),i()};e.addEventListener("loadeddata",r),e.addEventListener("resize",r)}}clearLiveVideo(e){this.liveSprite&&_r({target:this.liveSprite,props:{alpha:0},duration:400,easing:vs.easeInCubic,ticker:e,onComplete:()=>{var t;(t=this.liveSprite)==null||t.destroy(),this.liveSprite=null}}),this.idleVideoEl&&(this.idleVideoEl.style.display=""),this.idleGroup&&(this.idleGroup.visible=!0)}destroy(){var e,t;(e=this.cancelGlow)==null||e.call(this),(t=this.cancelEntrance)==null||t.call(this),this.idleVideoEl&&(this.idleVideoEl.pause(),this.idleVideoEl.remove()),this.container.destroy({children:!0})}}const mx=[{urls:"stun:stun.l.google.com:19302"}],gx=3e3,_x="oai-events";class yx{constructor(e){this.onConnected=null,this.onDisconnected=null,this.onRemoteTrack=null,this.onDataMessage=null,this.onError=null,this.pc=null,this.dc=null,this.micStream=null,this._remoteAudioStream=null,this._connected=!1,this.opts={model:"gpt-4o-realtime-preview",voice:"verse",instructions:"",tools:[],...e}}get isConnected(){return this._connected}get dataChannel(){return this.dc}get remoteAudioStream(){return this._remoteAudioStream}async connect(){var e,t;try{console.log("[RealtimeSession] Requesting microphone..."),this.micStream=await navigator.mediaDevices.getUserMedia({audio:!0}),console.log("[RealtimeSession] Microphone granted"),this.pc=new RTCPeerConnection({iceServers:mx}),this.setupPeerConnectionHandlers();for(const o of this.micStream.getAudioTracks())this.pc.addTrack(o,this.micStream);this.dc=this.pc.createDataChannel(_x),this.setupDataChannelHandlers();const i=await this.pc.createOffer();await this.pc.setLocalDescription(i),await this.waitForIceGathering();const r=(e=this.pc.localDescription)==null?void 0:e.sdp;if(!r)throw new Error("No local SDP after ICE gathering");console.log("[RealtimeSession] Exchanging SDP...");const n=await this.exchangeSDP(r);await this.pc.setRemoteDescription({type:"answer",sdp:n}),console.log("[RealtimeSession] Remote description set")}catch(i){const r=i instanceof Error?i:new Error(String(i));throw console.error("[RealtimeSession] Connection failed:",r.message),(t=this.onError)==null||t.call(this,r),this.close(),r}}sendJSON(e){if(!this.dc||this.dc.readyState!=="open"){console.warn("[RealtimeSession] Data channel not open, cannot send:",e);return}this.dc.send(JSON.stringify(e))}close(){var e;if(console.log("[RealtimeSession] Closing..."),this.dc){try{this.dc.close()}catch{}this.dc=null}if(this.pc){try{this.pc.close()}catch{}this.pc=null}if(this.micStream){for(const t of this.micStream.getTracks())t.stop();this.micStream=null}this._remoteAudioStream=null,this._connected&&(this._connected=!1,(e=this.onDisconnected)==null||e.call(this))}setupPeerConnectionHandlers(){this.pc&&(this.pc.ontrack=e=>{var t;console.log("[RealtimeSession] Remote audio track received"),this._remoteAudioStream=e.streams[0]??new MediaStream([e.track]),(t=this.onRemoteTrack)==null||t.call(this,this._remoteAudioStream)},this.pc.onconnectionstatechange=()=>{var t,i,r,n;const e=(t=this.pc)==null?void 0:t.connectionState;console.log("[RealtimeSession] Connection state:",e),e==="connected"?(this._connected=!0,(i=this.onConnected)==null||i.call(this)):(e==="failed"||e==="closed"||e==="disconnected")&&(this._connected&&(this._connected=!1,(r=this.onDisconnected)==null||r.call(this)),e==="failed"&&((n=this.onError)==null||n.call(this,new Error("WebRTC connection failed"))))})}waitForIceGathering(){return!this.pc||this.pc.iceGatheringState==="complete"?Promise.resolve():new Promise(e=>{const t=this.pc;let i;const r=()=>{clearTimeout(i);try{t.removeEventListener("icegatheringstatechange",n)}catch{}e()},n=()=>{t.iceGatheringState==="complete"&&r()};t.addEventListener("icegatheringstatechange",n),i=setTimeout(r,gx)})}async exchangeSDP(e){const{webrtcUrl:t,ephemeralKey:i,model:r,voice:n}=this.opts,o=t.includes("?")?"&":"?",a=`${t}${o}model=${encodeURIComponent(r)}&voice=${encodeURIComponent(n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/sdp",Accept:"application/sdp"},body:e});if(!l.ok){const c=await l.text().catch(()=>"");throw new Error(`SDP exchange failed (${l.status}): ${c}`)}return l.text()}setupDataChannelHandlers(){this.dc&&(this.dc.onopen=()=>{console.log("[RealtimeSession] Data channel open"),this.sendSessionUpdate(),this.sendJSON({type:"response.create"})},this.dc.onmessage=e=>{var t;try{const i=JSON.parse(e.data);(t=this.onDataMessage)==null||t.call(this,i)}catch(i){console.warn("[RealtimeSession] Failed to parse data channel message:",i)}},this.dc.onclose=()=>{console.log("[RealtimeSession] Data channel closed")},this.dc.onerror=e=>{console.error("[RealtimeSession] Data channel error:",e)})}sendSessionUpdate(){const e={instructions:this.opts.instructions,modalities:["audio","text"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:700,create_response:!0}};this.opts.tools&&this.opts.tools.length>0&&(e.tools=this.opts.tools),this.sendJSON({type:"session.update",session:e})}}const bx=24e3,xx=`
898
898
  class PcmBufferProcessor extends AudioWorkletProcessor {
899
899
  constructor() {
900
900
  super()
@@ -932,12 +932,12 @@ class PcmBufferProcessor extends AudioWorkletProcessor {
932
932
  }
933
933
 
934
934
  registerProcessor('pcm-buffer-processor', PcmBufferProcessor)
935
- `;function xx(s){const e=new Int16Array(s.length);for(let t=0;t<s.length;t++){const i=Math.max(-1,Math.min(1,s[t]));e[t]=i<0?i*32768:i*32767}return e}class vx{constructor(){this.onAudioChunk=null,this.audioCtx=null,this.sourceNode=null,this.workletNode=null,this._started=!1,this._paused=!1}get isStarted(){return this._started}get isPaused(){return this._paused}async start(e){if(this._started)return;this.audioCtx=new AudioContext({sampleRate:yx});const t=new Blob([bx],{type:"application/javascript"}),i=URL.createObjectURL(t);await this.audioCtx.audioWorklet.addModule(i),URL.revokeObjectURL(i),this.sourceNode=this.audioCtx.createMediaStreamSource(e),this.workletNode=new AudioWorkletNode(this.audioCtx,"pcm-buffer-processor"),this.workletNode.port.onmessage=n=>{var o;if(n.data.type==="chunk"){const a=n.data.samples,l=xx(a);(o=this.onAudioChunk)==null||o.call(this,new Uint8Array(l.buffer))}},this.sourceNode.connect(this.workletNode);const r=this.audioCtx.createGain();r.gain.value=0,r.connect(this.audioCtx.destination),this.workletNode.connect(r),this._started=!0,this._paused=!1,console.log("[AudioForwarder] Started capturing remote audio at 24kHz")}pause(){var e;!this._started||this._paused||(this._paused=!0,(e=this.workletNode)==null||e.port.postMessage({type:"pause"}),console.log("[AudioForwarder] Paused"))}resume(){var e;!this._started||!this._paused||(this._paused=!1,(e=this.workletNode)==null||e.port.postMessage({type:"resume"}),console.log("[AudioForwarder] Resumed"))}stop(){var e,t,i;if(this._started){try{(e=this.workletNode)==null||e.disconnect()}catch{}try{(t=this.sourceNode)==null||t.disconnect()}catch{}try{(i=this.audioCtx)==null||i.close()}catch{}this.workletNode=null,this.sourceNode=null,this.audioCtx=null,this._started=!1,this._paused=!1,console.log("[AudioForwarder] Stopped")}}}var Bo={},Ss={},Pu;function Cx(){if(Pu)return Ss;Pu=1,Ss.byteLength=a,Ss.toByteArray=c,Ss.fromByteArray=f;for(var s=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0,n=i.length;r<n;++r)s[r]=i[r],e[i.charCodeAt(r)]=r;e[45]=62,e[95]=63;function o(d){var g=d.length;if(g%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var _=d.indexOf("=");_===-1&&(_=g);var b=_===g?0:4-_%4;return[_,b]}function a(d){var g=o(d),_=g[0],b=g[1];return(_+b)*3/4-b}function l(d,g,_){return(g+_)*3/4-_}function c(d){var g,_=o(d),b=_[0],x=_[1],C=new t(l(d,b,x)),S=0,E=x>0?b-4:b,w;for(w=0;w<E;w+=4)g=e[d.charCodeAt(w)]<<18|e[d.charCodeAt(w+1)]<<12|e[d.charCodeAt(w+2)]<<6|e[d.charCodeAt(w+3)],C[S++]=g>>16&255,C[S++]=g>>8&255,C[S++]=g&255;return x===2&&(g=e[d.charCodeAt(w)]<<2|e[d.charCodeAt(w+1)]>>4,C[S++]=g&255),x===1&&(g=e[d.charCodeAt(w)]<<10|e[d.charCodeAt(w+1)]<<4|e[d.charCodeAt(w+2)]>>2,C[S++]=g>>8&255,C[S++]=g&255),C}function h(d){return s[d>>18&63]+s[d>>12&63]+s[d>>6&63]+s[d&63]}function u(d,g,_){for(var b,x=[],C=g;C<_;C+=3)b=(d[C]<<16&16711680)+(d[C+1]<<8&65280)+(d[C+2]&255),x.push(h(b));return x.join("")}function f(d){for(var g,_=d.length,b=_%3,x=[],C=16383,S=0,E=_-b;S<E;S+=C)x.push(u(d,S,S+C>E?E:S+C));return b===1?(g=d[_-1],x.push(s[g>>2]+s[g<<4&63]+"==")):b===2&&(g=(d[_-2]<<8)+d[_-1],x.push(s[g>>10]+s[g>>4&63]+s[g<<2&63]+"=")),x.join("")}return Ss}var _r={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */var ku;function Sx(){return ku||(ku=1,_r.read=function(s,e,t,i,r){var n,o,a=r*8-i-1,l=(1<<a)-1,c=l>>1,h=-7,u=t?r-1:0,f=t?-1:1,d=s[e+u];for(u+=f,n=d&(1<<-h)-1,d>>=-h,h+=a;h>0;n=n*256+s[e+u],u+=f,h-=8);for(o=n&(1<<-h)-1,n>>=-h,h+=i;h>0;o=o*256+s[e+u],u+=f,h-=8);if(n===0)n=1-c;else{if(n===l)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,i),n=n-c}return(d?-1:1)*o*Math.pow(2,n-i)},_r.write=function(s,e,t,i,r,n){var o,a,l,c=n*8-r-1,h=(1<<c)-1,u=h>>1,f=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:n-1,g=i?1:-1,_=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=h):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+u>=1?e+=f/l:e+=f*Math.pow(2,1-u),e*l>=2&&(o++,l/=2),o+u>=h?(a=0,o=h):o+u>=1?(a=(e*l-1)*Math.pow(2,r),o=o+u):(a=e*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;s[t+d]=a&255,d+=g,a/=256,r-=8);for(o=o<<r|a,c+=r;c>0;s[t+d]=o&255,d+=g,o/=256,c-=8);s[t+d-g]|=_*128}),_r}/*!
935
+ `;function vx(s){const e=new Int16Array(s.length);for(let t=0;t<s.length;t++){const i=Math.max(-1,Math.min(1,s[t]));e[t]=i<0?i*32768:i*32767}return e}class Cx{constructor(){this.onAudioChunk=null,this.audioCtx=null,this.sourceNode=null,this.workletNode=null,this._started=!1,this._paused=!1}get isStarted(){return this._started}get isPaused(){return this._paused}async start(e){if(this._started)return;this.audioCtx=new AudioContext({sampleRate:bx});const t=new Blob([xx],{type:"application/javascript"}),i=URL.createObjectURL(t);await this.audioCtx.audioWorklet.addModule(i),URL.revokeObjectURL(i),this.sourceNode=this.audioCtx.createMediaStreamSource(e),this.workletNode=new AudioWorkletNode(this.audioCtx,"pcm-buffer-processor"),this.workletNode.port.onmessage=n=>{var o;if(n.data.type==="chunk"){const a=n.data.samples,l=vx(a);(o=this.onAudioChunk)==null||o.call(this,new Uint8Array(l.buffer))}},this.sourceNode.connect(this.workletNode);const r=this.audioCtx.createGain();r.gain.value=0,r.connect(this.audioCtx.destination),this.workletNode.connect(r),this._started=!0,this._paused=!1,console.log("[AudioForwarder] Started capturing remote audio at 24kHz")}pause(){var e;!this._started||this._paused||(this._paused=!0,(e=this.workletNode)==null||e.port.postMessage({type:"pause"}),console.log("[AudioForwarder] Paused"))}resume(){var e;!this._started||!this._paused||(this._paused=!1,(e=this.workletNode)==null||e.port.postMessage({type:"resume"}),console.log("[AudioForwarder] Resumed"))}stop(){var e,t,i;if(this._started){try{(e=this.workletNode)==null||e.disconnect()}catch{}try{(t=this.sourceNode)==null||t.disconnect()}catch{}try{(i=this.audioCtx)==null||i.close()}catch{}this.workletNode=null,this.sourceNode=null,this.audioCtx=null,this._started=!1,this._paused=!1,console.log("[AudioForwarder] Stopped")}}}var Bo={},Ss={},Pu;function Sx(){if(Pu)return Ss;Pu=1,Ss.byteLength=a,Ss.toByteArray=c,Ss.fromByteArray=f;for(var s=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0,n=i.length;r<n;++r)s[r]=i[r],e[i.charCodeAt(r)]=r;e[45]=62,e[95]=63;function o(d){var g=d.length;if(g%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var _=d.indexOf("=");_===-1&&(_=g);var y=_===g?0:4-_%4;return[_,y]}function a(d){var g=o(d),_=g[0],y=g[1];return(_+y)*3/4-y}function l(d,g,_){return(g+_)*3/4-_}function c(d){var g,_=o(d),y=_[0],x=_[1],C=new t(l(d,y,x)),S=0,E=x>0?y-4:y,w;for(w=0;w<E;w+=4)g=e[d.charCodeAt(w)]<<18|e[d.charCodeAt(w+1)]<<12|e[d.charCodeAt(w+2)]<<6|e[d.charCodeAt(w+3)],C[S++]=g>>16&255,C[S++]=g>>8&255,C[S++]=g&255;return x===2&&(g=e[d.charCodeAt(w)]<<2|e[d.charCodeAt(w+1)]>>4,C[S++]=g&255),x===1&&(g=e[d.charCodeAt(w)]<<10|e[d.charCodeAt(w+1)]<<4|e[d.charCodeAt(w+2)]>>2,C[S++]=g>>8&255,C[S++]=g&255),C}function h(d){return s[d>>18&63]+s[d>>12&63]+s[d>>6&63]+s[d&63]}function u(d,g,_){for(var y,x=[],C=g;C<_;C+=3)y=(d[C]<<16&16711680)+(d[C+1]<<8&65280)+(d[C+2]&255),x.push(h(y));return x.join("")}function f(d){for(var g,_=d.length,y=_%3,x=[],C=16383,S=0,E=_-y;S<E;S+=C)x.push(u(d,S,S+C>E?E:S+C));return y===1?(g=d[_-1],x.push(s[g>>2]+s[g<<4&63]+"==")):y===2&&(g=(d[_-2]<<8)+d[_-1],x.push(s[g>>10]+s[g>>4&63]+s[g<<2&63]+"=")),x.join("")}return Ss}var yr={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */var ku;function Ex(){return ku||(ku=1,yr.read=function(s,e,t,i,r){var n,o,a=r*8-i-1,l=(1<<a)-1,c=l>>1,h=-7,u=t?r-1:0,f=t?-1:1,d=s[e+u];for(u+=f,n=d&(1<<-h)-1,d>>=-h,h+=a;h>0;n=n*256+s[e+u],u+=f,h-=8);for(o=n&(1<<-h)-1,n>>=-h,h+=i;h>0;o=o*256+s[e+u],u+=f,h-=8);if(n===0)n=1-c;else{if(n===l)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,i),n=n-c}return(d?-1:1)*o*Math.pow(2,n-i)},yr.write=function(s,e,t,i,r,n){var o,a,l,c=n*8-r-1,h=(1<<c)-1,u=h>>1,f=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:n-1,g=i?1:-1,_=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=h):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+u>=1?e+=f/l:e+=f*Math.pow(2,1-u),e*l>=2&&(o++,l/=2),o+u>=h?(a=0,o=h):o+u>=1?(a=(e*l-1)*Math.pow(2,r),o=o+u):(a=e*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;s[t+d]=a&255,d+=g,a/=256,r-=8);for(o=o<<r|a,c+=r;c>0;s[t+d]=o&255,d+=g,o/=256,c-=8);s[t+d-g]|=_*128}),yr}/*!
936
936
  * The buffer module from node.js, for the browser.
937
937
  *
938
938
  * @author Feross Aboukhadijeh <https://feross.org>
939
939
  * @license MIT
940
- */var Ou;function Ex(){return Ou||(Ou=1,(function(s){const e=Cx(),t=Sx(),i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;s.Buffer=a,s.SlowBuffer=C,s.INSPECT_MAX_BYTES=50;const r=2147483647;s.kMaxLength=r,a.TYPED_ARRAY_SUPPORT=n(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function n(){try{const y=new Uint8Array(1),p={foo:function(){return 42}};return Object.setPrototypeOf(p,Uint8Array.prototype),Object.setPrototypeOf(y,p),y.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(y){if(y>r)throw new RangeError('The value "'+y+'" is invalid for option "size"');const p=new Uint8Array(y);return Object.setPrototypeOf(p,a.prototype),p}function a(y,p,m){if(typeof y=="number"){if(typeof p=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(y)}return l(y,p,m)}a.poolSize=8192;function l(y,p,m){if(typeof y=="string")return f(y,p);if(ArrayBuffer.isView(y))return g(y);if(y==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof y);if(tt(y,ArrayBuffer)||y&&tt(y.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(tt(y,SharedArrayBuffer)||y&&tt(y.buffer,SharedArrayBuffer)))return _(y,p,m);if(typeof y=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const v=y.valueOf&&y.valueOf();if(v!=null&&v!==y)return a.from(v,p,m);const T=b(y);if(T)return T;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof y[Symbol.toPrimitive]=="function")return a.from(y[Symbol.toPrimitive]("string"),p,m);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof y)}a.from=function(y,p,m){return l(y,p,m)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function c(y){if(typeof y!="number")throw new TypeError('"size" argument must be of type number');if(y<0)throw new RangeError('The value "'+y+'" is invalid for option "size"')}function h(y,p,m){return c(y),y<=0?o(y):p!==void 0?typeof m=="string"?o(y).fill(p,m):o(y).fill(p):o(y)}a.alloc=function(y,p,m){return h(y,p,m)};function u(y){return c(y),o(y<0?0:x(y)|0)}a.allocUnsafe=function(y){return u(y)},a.allocUnsafeSlow=function(y){return u(y)};function f(y,p){if((typeof p!="string"||p==="")&&(p="utf8"),!a.isEncoding(p))throw new TypeError("Unknown encoding: "+p);const m=S(y,p)|0;let v=o(m);const T=v.write(y,p);return T!==m&&(v=v.slice(0,T)),v}function d(y){const p=y.length<0?0:x(y.length)|0,m=o(p);for(let v=0;v<p;v+=1)m[v]=y[v]&255;return m}function g(y){if(tt(y,Uint8Array)){const p=new Uint8Array(y);return _(p.buffer,p.byteOffset,p.byteLength)}return d(y)}function _(y,p,m){if(p<0||y.byteLength<p)throw new RangeError('"offset" is outside of buffer bounds');if(y.byteLength<p+(m||0))throw new RangeError('"length" is outside of buffer bounds');let v;return p===void 0&&m===void 0?v=new Uint8Array(y):m===void 0?v=new Uint8Array(y,p):v=new Uint8Array(y,p,m),Object.setPrototypeOf(v,a.prototype),v}function b(y){if(a.isBuffer(y)){const p=x(y.length)|0,m=o(p);return m.length===0||y.copy(m,0,0,p),m}if(y.length!==void 0)return typeof y.length!="number"||Xi(y.length)?o(0):d(y);if(y.type==="Buffer"&&Array.isArray(y.data))return d(y.data)}function x(y){if(y>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return y|0}function C(y){return+y!=y&&(y=0),a.alloc(+y)}a.isBuffer=function(p){return p!=null&&p._isBuffer===!0&&p!==a.prototype},a.compare=function(p,m){if(tt(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),tt(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),!a.isBuffer(p)||!a.isBuffer(m))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(p===m)return 0;let v=p.length,T=m.length;for(let I=0,P=Math.min(v,T);I<P;++I)if(p[I]!==m[I]){v=p[I],T=m[I];break}return v<T?-1:T<v?1:0},a.isEncoding=function(p){switch(String(p).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(p,m){if(!Array.isArray(p))throw new TypeError('"list" argument must be an Array of Buffers');if(p.length===0)return a.alloc(0);let v;if(m===void 0)for(m=0,v=0;v<p.length;++v)m+=p[v].length;const T=a.allocUnsafe(m);let I=0;for(v=0;v<p.length;++v){let P=p[v];if(tt(P,Uint8Array))I+P.length>T.length?(a.isBuffer(P)||(P=a.from(P)),P.copy(T,I)):Uint8Array.prototype.set.call(T,P,I);else if(a.isBuffer(P))P.copy(T,I);else throw new TypeError('"list" argument must be an Array of Buffers');I+=P.length}return T};function S(y,p){if(a.isBuffer(y))return y.length;if(ArrayBuffer.isView(y)||tt(y,ArrayBuffer))return y.byteLength;if(typeof y!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof y);const m=y.length,v=arguments.length>2&&arguments[2]===!0;if(!v&&m===0)return 0;let T=!1;for(;;)switch(p){case"ascii":case"latin1":case"binary":return m;case"utf8":case"utf-8":return Et(y).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return m*2;case"hex":return m>>>1;case"base64":return Ut(y).length;default:if(T)return v?-1:Et(y).length;p=(""+p).toLowerCase(),T=!0}}a.byteLength=S;function E(y,p,m){let v=!1;if((p===void 0||p<0)&&(p=0),p>this.length||((m===void 0||m>this.length)&&(m=this.length),m<=0)||(m>>>=0,p>>>=0,m<=p))return"";for(y||(y="utf8");;)switch(y){case"hex":return N(this,p,m);case"utf8":case"utf-8":return z(this,p,m);case"ascii":return U(this,p,m);case"latin1":case"binary":return q(this,p,m);case"base64":return X(this,p,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K(this,p,m);default:if(v)throw new TypeError("Unknown encoding: "+y);y=(y+"").toLowerCase(),v=!0}}a.prototype._isBuffer=!0;function w(y,p,m){const v=y[p];y[p]=y[m],y[m]=v}a.prototype.swap16=function(){const p=this.length;if(p%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let m=0;m<p;m+=2)w(this,m,m+1);return this},a.prototype.swap32=function(){const p=this.length;if(p%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let m=0;m<p;m+=4)w(this,m,m+3),w(this,m+1,m+2);return this},a.prototype.swap64=function(){const p=this.length;if(p%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let m=0;m<p;m+=8)w(this,m,m+7),w(this,m+1,m+6),w(this,m+2,m+5),w(this,m+3,m+4);return this},a.prototype.toString=function(){const p=this.length;return p===0?"":arguments.length===0?z(this,0,p):E.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(p){if(!a.isBuffer(p))throw new TypeError("Argument must be a Buffer");return this===p?!0:a.compare(this,p)===0},a.prototype.inspect=function(){let p="";const m=s.INSPECT_MAX_BYTES;return p=this.toString("hex",0,m).replace(/(.{2})/g,"$1 ").trim(),this.length>m&&(p+=" ... "),"<Buffer "+p+">"},i&&(a.prototype[i]=a.prototype.inspect),a.prototype.compare=function(p,m,v,T,I){if(tt(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),!a.isBuffer(p))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof p);if(m===void 0&&(m=0),v===void 0&&(v=p?p.length:0),T===void 0&&(T=0),I===void 0&&(I=this.length),m<0||v>p.length||T<0||I>this.length)throw new RangeError("out of range index");if(T>=I&&m>=v)return 0;if(T>=I)return-1;if(m>=v)return 1;if(m>>>=0,v>>>=0,T>>>=0,I>>>=0,this===p)return 0;let P=I-T,J=v-m;const Re=Math.min(P,J),Te=this.slice(T,I),Me=p.slice(m,v);for(let ye=0;ye<Re;++ye)if(Te[ye]!==Me[ye]){P=Te[ye],J=Me[ye];break}return P<J?-1:J<P?1:0};function R(y,p,m,v,T){if(y.length===0)return-1;if(typeof m=="string"?(v=m,m=0):m>2147483647?m=2147483647:m<-2147483648&&(m=-2147483648),m=+m,Xi(m)&&(m=T?0:y.length-1),m<0&&(m=y.length+m),m>=y.length){if(T)return-1;m=y.length-1}else if(m<0)if(T)m=0;else return-1;if(typeof p=="string"&&(p=a.from(p,v)),a.isBuffer(p))return p.length===0?-1:M(y,p,m,v,T);if(typeof p=="number")return p=p&255,typeof Uint8Array.prototype.indexOf=="function"?T?Uint8Array.prototype.indexOf.call(y,p,m):Uint8Array.prototype.lastIndexOf.call(y,p,m):M(y,[p],m,v,T);throw new TypeError("val must be string, number or Buffer")}function M(y,p,m,v,T){let I=1,P=y.length,J=p.length;if(v!==void 0&&(v=String(v).toLowerCase(),v==="ucs2"||v==="ucs-2"||v==="utf16le"||v==="utf-16le")){if(y.length<2||p.length<2)return-1;I=2,P/=2,J/=2,m/=2}function Re(Me,ye){return I===1?Me[ye]:Me.readUInt16BE(ye*I)}let Te;if(T){let Me=-1;for(Te=m;Te<P;Te++)if(Re(y,Te)===Re(p,Me===-1?0:Te-Me)){if(Me===-1&&(Me=Te),Te-Me+1===J)return Me*I}else Me!==-1&&(Te-=Te-Me),Me=-1}else for(m+J>P&&(m=P-J),Te=m;Te>=0;Te--){let Me=!0;for(let ye=0;ye<J;ye++)if(Re(y,Te+ye)!==Re(p,ye)){Me=!1;break}if(Me)return Te}return-1}a.prototype.includes=function(p,m,v){return this.indexOf(p,m,v)!==-1},a.prototype.indexOf=function(p,m,v){return R(this,p,m,v,!0)},a.prototype.lastIndexOf=function(p,m,v){return R(this,p,m,v,!1)};function D(y,p,m,v){m=Number(m)||0;const T=y.length-m;v?(v=Number(v),v>T&&(v=T)):v=T;const I=p.length;v>I/2&&(v=I/2);let P;for(P=0;P<v;++P){const J=parseInt(p.substr(P*2,2),16);if(Xi(J))return P;y[m+P]=J}return P}function F(y,p,m,v){return pt(Et(p,y.length-m),y,m,v)}function k(y,p,m,v){return pt(ui(p),y,m,v)}function O(y,p,m,v){return pt(Ut(p),y,m,v)}function V(y,p,m,v){return pt(ji(p,y.length-m),y,m,v)}a.prototype.write=function(p,m,v,T){if(m===void 0)T="utf8",v=this.length,m=0;else if(v===void 0&&typeof m=="string")T=m,v=this.length,m=0;else if(isFinite(m))m=m>>>0,isFinite(v)?(v=v>>>0,T===void 0&&(T="utf8")):(T=v,v=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const I=this.length-m;if((v===void 0||v>I)&&(v=I),p.length>0&&(v<0||m<0)||m>this.length)throw new RangeError("Attempt to write outside buffer bounds");T||(T="utf8");let P=!1;for(;;)switch(T){case"hex":return D(this,p,m,v);case"utf8":case"utf-8":return F(this,p,m,v);case"ascii":case"latin1":case"binary":return k(this,p,m,v);case"base64":return O(this,p,m,v);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,p,m,v);default:if(P)throw new TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),P=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function X(y,p,m){return p===0&&m===y.length?e.fromByteArray(y):e.fromByteArray(y.slice(p,m))}function z(y,p,m){m=Math.min(y.length,m);const v=[];let T=p;for(;T<m;){const I=y[T];let P=null,J=I>239?4:I>223?3:I>191?2:1;if(T+J<=m){let Re,Te,Me,ye;switch(J){case 1:I<128&&(P=I);break;case 2:Re=y[T+1],(Re&192)===128&&(ye=(I&31)<<6|Re&63,ye>127&&(P=ye));break;case 3:Re=y[T+1],Te=y[T+2],(Re&192)===128&&(Te&192)===128&&(ye=(I&15)<<12|(Re&63)<<6|Te&63,ye>2047&&(ye<55296||ye>57343)&&(P=ye));break;case 4:Re=y[T+1],Te=y[T+2],Me=y[T+3],(Re&192)===128&&(Te&192)===128&&(Me&192)===128&&(ye=(I&15)<<18|(Re&63)<<12|(Te&63)<<6|Me&63,ye>65535&&ye<1114112&&(P=ye))}}P===null?(P=65533,J=1):P>65535&&(P-=65536,v.push(P>>>10&1023|55296),P=56320|P&1023),v.push(P),T+=J}return B(v)}const de=4096;function B(y){const p=y.length;if(p<=de)return String.fromCharCode.apply(String,y);let m="",v=0;for(;v<p;)m+=String.fromCharCode.apply(String,y.slice(v,v+=de));return m}function U(y,p,m){let v="";m=Math.min(y.length,m);for(let T=p;T<m;++T)v+=String.fromCharCode(y[T]&127);return v}function q(y,p,m){let v="";m=Math.min(y.length,m);for(let T=p;T<m;++T)v+=String.fromCharCode(y[T]);return v}function N(y,p,m){const v=y.length;(!p||p<0)&&(p=0),(!m||m<0||m>v)&&(m=v);let T="";for(let I=p;I<m;++I)T+=Or[y[I]];return T}function K(y,p,m){const v=y.slice(p,m);let T="";for(let I=0;I<v.length-1;I+=2)T+=String.fromCharCode(v[I]+v[I+1]*256);return T}a.prototype.slice=function(p,m){const v=this.length;p=~~p,m=m===void 0?v:~~m,p<0?(p+=v,p<0&&(p=0)):p>v&&(p=v),m<0?(m+=v,m<0&&(m=0)):m>v&&(m=v),m<p&&(m=p);const T=this.subarray(p,m);return Object.setPrototypeOf(T,a.prototype),T};function Z(y,p,m){if(y%1!==0||y<0)throw new RangeError("offset is not uint");if(y+p>m)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(p,m,v){p=p>>>0,m=m>>>0,v||Z(p,m,this.length);let T=this[p],I=1,P=0;for(;++P<m&&(I*=256);)T+=this[p+P]*I;return T},a.prototype.readUintBE=a.prototype.readUIntBE=function(p,m,v){p=p>>>0,m=m>>>0,v||Z(p,m,this.length);let T=this[p+--m],I=1;for(;m>0&&(I*=256);)T+=this[p+--m]*I;return T},a.prototype.readUint8=a.prototype.readUInt8=function(p,m){return p=p>>>0,m||Z(p,1,this.length),this[p]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(p,m){return p=p>>>0,m||Z(p,2,this.length),this[p]|this[p+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(p,m){return p=p>>>0,m||Z(p,2,this.length),this[p]<<8|this[p+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),(this[p]|this[p+1]<<8|this[p+2]<<16)+this[p+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),this[p]*16777216+(this[p+1]<<16|this[p+2]<<8|this[p+3])},a.prototype.readBigUInt64LE=mt(function(p){p=p>>>0,we(p,"offset");const m=this[p],v=this[p+7];(m===void 0||v===void 0)&&ce(p,this.length-8);const T=m+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,I=this[++p]+this[++p]*2**8+this[++p]*2**16+v*2**24;return BigInt(T)+(BigInt(I)<<BigInt(32))}),a.prototype.readBigUInt64BE=mt(function(p){p=p>>>0,we(p,"offset");const m=this[p],v=this[p+7];(m===void 0||v===void 0)&&ce(p,this.length-8);const T=m*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],I=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+v;return(BigInt(T)<<BigInt(32))+BigInt(I)}),a.prototype.readIntLE=function(p,m,v){p=p>>>0,m=m>>>0,v||Z(p,m,this.length);let T=this[p],I=1,P=0;for(;++P<m&&(I*=256);)T+=this[p+P]*I;return I*=128,T>=I&&(T-=Math.pow(2,8*m)),T},a.prototype.readIntBE=function(p,m,v){p=p>>>0,m=m>>>0,v||Z(p,m,this.length);let T=m,I=1,P=this[p+--T];for(;T>0&&(I*=256);)P+=this[p+--T]*I;return I*=128,P>=I&&(P-=Math.pow(2,8*m)),P},a.prototype.readInt8=function(p,m){return p=p>>>0,m||Z(p,1,this.length),this[p]&128?(255-this[p]+1)*-1:this[p]},a.prototype.readInt16LE=function(p,m){p=p>>>0,m||Z(p,2,this.length);const v=this[p]|this[p+1]<<8;return v&32768?v|4294901760:v},a.prototype.readInt16BE=function(p,m){p=p>>>0,m||Z(p,2,this.length);const v=this[p+1]|this[p]<<8;return v&32768?v|4294901760:v},a.prototype.readInt32LE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),this[p]|this[p+1]<<8|this[p+2]<<16|this[p+3]<<24},a.prototype.readInt32BE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),this[p]<<24|this[p+1]<<16|this[p+2]<<8|this[p+3]},a.prototype.readBigInt64LE=mt(function(p){p=p>>>0,we(p,"offset");const m=this[p],v=this[p+7];(m===void 0||v===void 0)&&ce(p,this.length-8);const T=this[p+4]+this[p+5]*2**8+this[p+6]*2**16+(v<<24);return(BigInt(T)<<BigInt(32))+BigInt(m+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24)}),a.prototype.readBigInt64BE=mt(function(p){p=p>>>0,we(p,"offset");const m=this[p],v=this[p+7];(m===void 0||v===void 0)&&ce(p,this.length-8);const T=(m<<24)+this[++p]*2**16+this[++p]*2**8+this[++p];return(BigInt(T)<<BigInt(32))+BigInt(this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+v)}),a.prototype.readFloatLE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),t.read(this,p,!0,23,4)},a.prototype.readFloatBE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),t.read(this,p,!1,23,4)},a.prototype.readDoubleLE=function(p,m){return p=p>>>0,m||Z(p,8,this.length),t.read(this,p,!0,52,8)},a.prototype.readDoubleBE=function(p,m){return p=p>>>0,m||Z(p,8,this.length),t.read(this,p,!1,52,8)};function $(y,p,m,v,T,I){if(!a.isBuffer(y))throw new TypeError('"buffer" argument must be a Buffer instance');if(p>T||p<I)throw new RangeError('"value" argument is out of bounds');if(m+v>y.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(p,m,v,T){if(p=+p,m=m>>>0,v=v>>>0,!T){const J=Math.pow(2,8*v)-1;$(this,p,m,v,J,0)}let I=1,P=0;for(this[m]=p&255;++P<v&&(I*=256);)this[m+P]=p/I&255;return m+v},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(p,m,v,T){if(p=+p,m=m>>>0,v=v>>>0,!T){const J=Math.pow(2,8*v)-1;$(this,p,m,v,J,0)}let I=v-1,P=1;for(this[m+I]=p&255;--I>=0&&(P*=256);)this[m+I]=p/P&255;return m+v},a.prototype.writeUint8=a.prototype.writeUInt8=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,1,255,0),this[m]=p&255,m+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,2,65535,0),this[m]=p&255,this[m+1]=p>>>8,m+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,2,65535,0),this[m]=p>>>8,this[m+1]=p&255,m+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,4,4294967295,0),this[m+3]=p>>>24,this[m+2]=p>>>16,this[m+1]=p>>>8,this[m]=p&255,m+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,4,4294967295,0),this[m]=p>>>24,this[m+1]=p>>>16,this[m+2]=p>>>8,this[m+3]=p&255,m+4};function ae(y,p,m,v,T){ie(p,v,T,y,m,7);let I=Number(p&BigInt(4294967295));y[m++]=I,I=I>>8,y[m++]=I,I=I>>8,y[m++]=I,I=I>>8,y[m++]=I;let P=Number(p>>BigInt(32)&BigInt(4294967295));return y[m++]=P,P=P>>8,y[m++]=P,P=P>>8,y[m++]=P,P=P>>8,y[m++]=P,m}function Ce(y,p,m,v,T){ie(p,v,T,y,m,7);let I=Number(p&BigInt(4294967295));y[m+7]=I,I=I>>8,y[m+6]=I,I=I>>8,y[m+5]=I,I=I>>8,y[m+4]=I;let P=Number(p>>BigInt(32)&BigInt(4294967295));return y[m+3]=P,P=P>>8,y[m+2]=P,P=P>>8,y[m+1]=P,P=P>>8,y[m]=P,m+8}a.prototype.writeBigUInt64LE=mt(function(p,m=0){return ae(this,p,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=mt(function(p,m=0){return Ce(this,p,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(p,m,v,T){if(p=+p,m=m>>>0,!T){const Re=Math.pow(2,8*v-1);$(this,p,m,v,Re-1,-Re)}let I=0,P=1,J=0;for(this[m]=p&255;++I<v&&(P*=256);)p<0&&J===0&&this[m+I-1]!==0&&(J=1),this[m+I]=(p/P>>0)-J&255;return m+v},a.prototype.writeIntBE=function(p,m,v,T){if(p=+p,m=m>>>0,!T){const Re=Math.pow(2,8*v-1);$(this,p,m,v,Re-1,-Re)}let I=v-1,P=1,J=0;for(this[m+I]=p&255;--I>=0&&(P*=256);)p<0&&J===0&&this[m+I+1]!==0&&(J=1),this[m+I]=(p/P>>0)-J&255;return m+v},a.prototype.writeInt8=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,1,127,-128),p<0&&(p=255+p+1),this[m]=p&255,m+1},a.prototype.writeInt16LE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,2,32767,-32768),this[m]=p&255,this[m+1]=p>>>8,m+2},a.prototype.writeInt16BE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,2,32767,-32768),this[m]=p>>>8,this[m+1]=p&255,m+2},a.prototype.writeInt32LE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,4,2147483647,-2147483648),this[m]=p&255,this[m+1]=p>>>8,this[m+2]=p>>>16,this[m+3]=p>>>24,m+4},a.prototype.writeInt32BE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,4,2147483647,-2147483648),p<0&&(p=4294967295+p+1),this[m]=p>>>24,this[m+1]=p>>>16,this[m+2]=p>>>8,this[m+3]=p&255,m+4},a.prototype.writeBigInt64LE=mt(function(p,m=0){return ae(this,p,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=mt(function(p,m=0){return Ce(this,p,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Ee(y,p,m,v,T,I){if(m+v>y.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("Index out of range")}function G(y,p,m,v,T){return p=+p,m=m>>>0,T||Ee(y,p,m,4),t.write(y,p,m,v,23,4),m+4}a.prototype.writeFloatLE=function(p,m,v){return G(this,p,m,!0,v)},a.prototype.writeFloatBE=function(p,m,v){return G(this,p,m,!1,v)};function fe(y,p,m,v,T){return p=+p,m=m>>>0,T||Ee(y,p,m,8),t.write(y,p,m,v,52,8),m+8}a.prototype.writeDoubleLE=function(p,m,v){return fe(this,p,m,!0,v)},a.prototype.writeDoubleBE=function(p,m,v){return fe(this,p,m,!1,v)},a.prototype.copy=function(p,m,v,T){if(!a.isBuffer(p))throw new TypeError("argument should be a Buffer");if(v||(v=0),!T&&T!==0&&(T=this.length),m>=p.length&&(m=p.length),m||(m=0),T>0&&T<v&&(T=v),T===v||p.length===0||this.length===0)return 0;if(m<0)throw new RangeError("targetStart out of bounds");if(v<0||v>=this.length)throw new RangeError("Index out of range");if(T<0)throw new RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),p.length-m<T-v&&(T=p.length-m+v);const I=T-v;return this===p&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(m,v,T):Uint8Array.prototype.set.call(p,this.subarray(v,T),m),I},a.prototype.fill=function(p,m,v,T){if(typeof p=="string"){if(typeof m=="string"?(T=m,m=0,v=this.length):typeof v=="string"&&(T=v,v=this.length),T!==void 0&&typeof T!="string")throw new TypeError("encoding must be a string");if(typeof T=="string"&&!a.isEncoding(T))throw new TypeError("Unknown encoding: "+T);if(p.length===1){const P=p.charCodeAt(0);(T==="utf8"&&P<128||T==="latin1")&&(p=P)}}else typeof p=="number"?p=p&255:typeof p=="boolean"&&(p=Number(p));if(m<0||this.length<m||this.length<v)throw new RangeError("Out of range index");if(v<=m)return this;m=m>>>0,v=v===void 0?this.length:v>>>0,p||(p=0);let I;if(typeof p=="number")for(I=m;I<v;++I)this[I]=p;else{const P=a.isBuffer(p)?p:a.from(p,T),J=P.length;if(J===0)throw new TypeError('The value "'+p+'" is invalid for argument "value"');for(I=0;I<v-m;++I)this[I+m]=P[I%J]}return this};const le={};function L(y,p,m){le[y]=class extends m{constructor(){super(),Object.defineProperty(this,"message",{value:p.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${y}]`,this.stack,delete this.name}get code(){return y}set code(T){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:T,writable:!0})}toString(){return`${this.name} [${y}]: ${this.message}`}}}L("ERR_BUFFER_OUT_OF_BOUNDS",function(y){return y?`${y} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(y,p){return`The "${y}" argument must be of type number. Received type ${typeof p}`},TypeError),L("ERR_OUT_OF_RANGE",function(y,p,m){let v=`The value of "${y}" is out of range.`,T=m;return Number.isInteger(m)&&Math.abs(m)>2**32?T=me(String(m)):typeof m=="bigint"&&(T=String(m),(m>BigInt(2)**BigInt(32)||m<-(BigInt(2)**BigInt(32)))&&(T=me(T)),T+="n"),v+=` It must be ${p}. Received ${T}`,v},RangeError);function me(y){let p="",m=y.length;const v=y[0]==="-"?1:0;for(;m>=v+4;m-=3)p=`_${y.slice(m-3,m)}${p}`;return`${y.slice(0,m)}${p}`}function Y(y,p,m){we(p,"offset"),(y[p]===void 0||y[p+m]===void 0)&&ce(p,y.length-(m+1))}function ie(y,p,m,v,T,I){if(y>m||y<p){const P=typeof p=="bigint"?"n":"";let J;throw p===0||p===BigInt(0)?J=`>= 0${P} and < 2${P} ** ${(I+1)*8}${P}`:J=`>= -(2${P} ** ${(I+1)*8-1}${P}) and < 2 ** ${(I+1)*8-1}${P}`,new le.ERR_OUT_OF_RANGE("value",J,y)}Y(v,T,I)}function we(y,p){if(typeof y!="number")throw new le.ERR_INVALID_ARG_TYPE(p,"number",y)}function ce(y,p,m){throw Math.floor(y)!==y?(we(y,m),new le.ERR_OUT_OF_RANGE("offset","an integer",y)):p<0?new le.ERR_BUFFER_OUT_OF_BOUNDS:new le.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${p}`,y)}const He=/[^+/0-9A-Za-z-_]/g;function Qt(y){if(y=y.split("=")[0],y=y.trim().replace(He,""),y.length<2)return"";for(;y.length%4!==0;)y=y+"=";return y}function Et(y,p){p=p||1/0;let m;const v=y.length;let T=null;const I=[];for(let P=0;P<v;++P){if(m=y.charCodeAt(P),m>55295&&m<57344){if(!T){if(m>56319){(p-=3)>-1&&I.push(239,191,189);continue}else if(P+1===v){(p-=3)>-1&&I.push(239,191,189);continue}T=m;continue}if(m<56320){(p-=3)>-1&&I.push(239,191,189),T=m;continue}m=(T-55296<<10|m-56320)+65536}else T&&(p-=3)>-1&&I.push(239,191,189);if(T=null,m<128){if((p-=1)<0)break;I.push(m)}else if(m<2048){if((p-=2)<0)break;I.push(m>>6|192,m&63|128)}else if(m<65536){if((p-=3)<0)break;I.push(m>>12|224,m>>6&63|128,m&63|128)}else if(m<1114112){if((p-=4)<0)break;I.push(m>>18|240,m>>12&63|128,m>>6&63|128,m&63|128)}else throw new Error("Invalid code point")}return I}function ui(y){const p=[];for(let m=0;m<y.length;++m)p.push(y.charCodeAt(m)&255);return p}function ji(y,p){let m,v,T;const I=[];for(let P=0;P<y.length&&!((p-=2)<0);++P)m=y.charCodeAt(P),v=m>>8,T=m%256,I.push(T),I.push(v);return I}function Ut(y){return e.toByteArray(Qt(y))}function pt(y,p,m,v){let T;for(T=0;T<v&&!(T+m>=p.length||T>=y.length);++T)p[T+m]=y[T];return T}function tt(y,p){return y instanceof p||y!=null&&y.constructor!=null&&y.constructor.name!=null&&y.constructor.name===p.name}function Xi(y){return y!==y}const Or=(function(){const y="0123456789abcdef",p=new Array(256);for(let m=0;m<16;++m){const v=m*16;for(let T=0;T<16;++T)p[v+T]=y[m]+y[T]}return p})();function mt(y){return typeof BigInt>"u"?Br:y}function Br(){throw new Error("BigInt not supported")}})(Bo)),Bo}var Tx=Ex();const Ax="https://api.anam.ai",wx="/v1",Bu={client:"js-sdk",version:"4.12.0"};var Ix=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Du="https://api.anam.ai",Do="/v1";var Dt;(function(s){s.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",s.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",s.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(Dt||(Dt={}));let No=Du,Nu=Do,zt,Uu=!1;const Rx=(s,e=Do)=>{No=s,Nu=e},Mx=s=>{zt=s},Px=s=>{Uu=s};let $t={sessionId:null,organizationId:null,attemptCorrelationId:null};const Di=s=>{$t=Object.assign(Object.assign({},$t),s)},li=(s,e,t)=>Ix(void 0,void 0,void 0,function*(){if(!Uu)try{const i=Object.assign(Object.assign({},Bu),t);$t.sessionId&&(i.sessionId=$t.sessionId),$t.organizationId&&(i.organizationId=$t.organizationId),$t.attemptCorrelationId&&(i.attemptCorrelationId=$t.attemptCorrelationId);const r=`${Nu}/metrics/client`;let n,o={"Content-Type":"application/json"};zt!=null&&zt.enabled&&(zt!=null&&zt.baseUrl)?(n=`${zt.baseUrl}${r}`,o["X-Anam-Target-Url"]=`${No}${r}`):n=`${No}${r}`,yield fetch(n,{method:"POST",headers:o,body:JSON.stringify({name:s,value:e,tags:i})})}catch(i){console.error("Failed to send error metric:",i)}}),kx=(s,e="console")=>{var t,i,r;const n={};s.forEach(u=>{n[u.type]||(n[u.type]=[]),n[u.type].push(u)});const o={issues:[]},a=((t=n["inbound-rtp"])===null||t===void 0?void 0:t.filter(u=>u.kind==="video"))||[];a.length>0&&(o.personaVideoStream=[],a.forEach(u=>{var f,d,g,_,b;const x={framesReceived:(f=u.framesReceived)!==null&&f!==void 0?f:"unknown",framesDropped:(d=u.framesDropped)!==null&&d!==void 0?d:"unknown",framesPerSecond:(g=u.framesPerSecond)!==null&&g!==void 0?g:"unknown",packetsReceived:(_=u.packetsReceived)!==null&&_!==void 0?_:"unknown",packetsLost:(b=u.packetsLost)!==null&&b!==void 0?b:"unknown",resolution:u.frameWidth&&u.frameHeight?`${u.frameWidth}x${u.frameHeight}`:void 0,jitter:u.jitter!==void 0?u.jitter:void 0};o.personaVideoStream.push(x)}));const l=((i=n["inbound-rtp"])===null||i===void 0?void 0:i.filter(u=>u.kind==="audio"))||[];l.length>0&&(o.personaAudioStream=[],l.forEach(u=>{var f,d,g;const _={packetsReceived:(f=u.packetsReceived)!==null&&f!==void 0?f:"unknown",packetsLost:(d=u.packetsLost)!==null&&d!==void 0?d:"unknown",audioLevel:(g=u.audioLevel)!==null&&g!==void 0?g:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};o.personaAudioStream.push(_)}));const c=((r=n["outbound-rtp"])===null||r===void 0?void 0:r.filter(u=>u.kind==="audio"))||[];c.length>0&&(o.userAudioInput=[],c.forEach(u=>{var f,d;const g={packetsSent:(f=u.packetsSent)!==null&&f!==void 0?f:"unknown",retransmittedPackets:(d=u.retransmittedPacketsSent)!==null&&d!==void 0?d:void 0,avgPacketSendDelay:u.totalPacketSendDelay!==void 0?u.totalPacketSendDelay/(u.packetsSent||1)*1e3:void 0};o.userAudioInput.push(g)})),n.codec&&(o.codecs=[],n.codec.forEach(u=>{const f={status:u.payloadType?"Active":"Available",mimeType:u.mimeType||"Unknown",payloadType:u.payloadType||"N/A",clockRate:u.clockRate||void 0,channels:u.channels||void 0};o.codecs.push(f)})),n.transport&&(o.transportLayer=[],n.transport.forEach(u=>{const f={dtlsState:u.dtlsState||"unknown",iceState:u.iceState||"unknown",bytesSent:u.bytesSent||void 0,bytesReceived:u.bytesReceived||void 0};o.transportLayer.push(f)}));const h=[];if(a.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&h.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&h.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),l.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&h.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),o.issues=h,e==="json")return o;console.group("📊 WebRTC Session Statistics Report"),o.personaVideoStream&&o.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),o.personaVideoStream.forEach(u=>{console.log(`Frames Received: ${u.framesReceived}`),console.log(`Frames Dropped: ${u.framesDropped}`),console.log(`Frames Per Second: ${u.framesPerSecond}`),console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),u.resolution&&console.log(`Resolution: ${u.resolution}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`)}),console.groupEnd()),o.personaAudioStream&&o.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),o.personaAudioStream.forEach(u=>{console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),console.log(`Audio Level: ${u.audioLevel}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`),u.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${u.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),o.userAudioInput&&o.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),o.userAudioInput.forEach(u=>{console.log(`Packets Sent: ${typeof u.packetsSent=="number"?u.packetsSent.toLocaleString():u.packetsSent}`),u.retransmittedPackets&&console.log(`Retransmitted Packets: ${u.retransmittedPackets}`),u.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${u.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),o.codecs&&o.codecs.length>0&&(console.group("🔧 Codecs Used"),o.codecs.forEach(u=>{console.log(`${u.status} ${u.mimeType} - Payload Type: ${u.payloadType}`),u.clockRate&&console.log(` Clock Rate: ${u.clockRate}Hz`),u.channels&&console.log(` Channels: ${u.channels}`)}),console.groupEnd()),o.transportLayer&&o.transportLayer.length>0&&(console.group("🚚 Transport Layer"),o.transportLayer.forEach(u=>{console.log(`DTLS State: ${u.dtlsState}`),console.log(`ICE State: ${u.iceState}`),(u.bytesReceived||u.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(u.bytesSent||0).toLocaleString()}, Received: ${(u.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),o.issues.length>0?(console.group("⚠️ Potential Issues Detected"),o.issues.forEach(u=>console.warn(u)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var ze;(function(s){s.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",s.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",s.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",s.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",s.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",s.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",s.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",s.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",s.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",s.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})(ze||(ze={}));class Ne extends Error{constructor(e,t,i=500,r){super(e),this.name="ClientError",this.code=t,this.statusCode=i,this.details=r,Object.setPrototypeOf(this,Ne.prototype),li(Dt.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:r,statusCode:i})}}function Fu(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function Ox(s){if(!(!s||!s.enabled)){if(!s.baseUrl)return"API Gateway baseUrl is required when enabled";try{const e=new URL(s.baseUrl);if(!["http:","https:","ws:","wss:"].includes(e.protocol))return`Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${s.baseUrl}`}if(s.wsPath&&!s.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var Xe;(function(s){s.OFFER="offer",s.ANSWER="answer",s.ICE_CANDIDATE="icecandidate",s.END_SESSION="endsession",s.HEARTBEAT="heartbeat",s.WARNING="warning",s.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",s.TALK_STREAM_INPUT="talkstream",s.SESSION_READY="sessionready",s.AGENT_AUDIO_INPUT="agentaudioinput",s.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(Xe||(Xe={}));var xt;(function(s){s.SPEECH_TEXT="speechText",s.CLIENT_TOOL_EVENT="clientToolEvent",s.TOOL_CALL_STARTED_EVENT="toolCallStarted",s.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",s.TOOL_CALL_FAILED_EVENT="toolCallFailed",s.REASONING_TEXT="reasoningText",s.USER_SPEECH_STARTED="userSpeechStarted",s.USER_SPEECH_ENDED="userSpeechEnded"})(xt||(xt={}));var jt;(function(s){s.PENDING="pending",s.GRANTED="granted",s.DENIED="denied",s.NOT_REQUESTED="not_requested"})(jt||(jt={}));var yr;(function(s){s.USER="user",s.PERSONA="persona"})(yr||(yr={}));var te;(function(s){s.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",s.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",s.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",s.CONNECTION_CLOSED="CONNECTION_CLOSED",s.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",s.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",s.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",s.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",s.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",s.SESSION_READY="SESSION_READY",s.SERVER_WARNING="SERVER_WARNING",s.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",s.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",s.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",s.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",s.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",s.TOOL_CALL_STARTED="TOOL_CALL_STARTED",s.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",s.TOOL_CALL_FAILED="TOOL_CALL_FAILED",s.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",s.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",s.USER_SPEECH_STARTED="USER_SPEECH_STARTED",s.USER_SPEECH_ENDED="USER_SPEECH_ENDED"})(te||(te={}));var Ue;(function(s){s.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",s.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",s.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",s.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",s.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(Ue||(Ue={}));var Xt;(function(s){s.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",s.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",s.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",s.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",s.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(Xt||(Xt={}));class Bx{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){const i={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(i)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),i=Array.from(t,r=>String.fromCharCode(r)).join("");return btoa(i)}}var Ni=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Dx=5,Nx=5;class Ux{constructor(e,t,i,r,n){var o,a,l,c,h;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.apiGatewayConfig=n,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:f,url:d}=t;if(this.heartbeatIntervalSeconds=u||Dx,this.maxWsReconnectionAttempts=f||Nx,!d.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const g=new URL(this.apiGatewayConfig.baseUrl),_=(l=this.apiGatewayConfig.wsPath)!==null&&l!==void 0?l:"/ws";g.protocol=g.protocol.replace("http","ws"),g.pathname=_,this.url=g;const b=d.protocol||"https",x=b==="http"?"ws":"wss",C=`${b}://${d.baseUrl}`,S=(c=d.signallingPath)!==null&&c!==void 0?c:"/ws",E=new URL(C);E.protocol=x==="ws"?"ws:":"wss:",d.port&&(E.port=d.port),E.pathname=S,E.searchParams.append("session_id",e),this.url.searchParams.append("target_url",E.href)}else{const _=`${d.protocol||"https"}://${d.baseUrl}`;this.url=new URL(_),this.url.protocol=d.protocol==="http"?"ws:":"wss:",d.port&&(this.url.port=d.port),this.url.pathname=(h=d.signallingPath)!==null&&h!==void 0?h:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return Ni(this,void 0,void 0,function*(){const t={connectionDescription:e,userUid:this.sessionId},i={actionType:Xe.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(i)})}sendIceCandidate(e){return Ni(this,void 0,void 0,function*(){const t={actionType:Xe.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if(((t=this.socket)===null||t===void 0?void 0:t.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(i){console.error("SignallingClient - sendSignalMessage: error sending message",i)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Ni(this,void 0,void 0,function*(){const t={actionType:Xe.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){const t={actionType:Xe.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){const e={actionType:Xe.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Ni(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(Ue.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Ni(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var i;((i=this.socket)===null||i===void 0?void 0:i.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return Ni(this,void 0,void 0,function*(){const t=JSON.parse(e.data);this.internalEventEmitter.emit(Ue.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,t={actionType:Xe.HEARTBEAT,sessionId:this.sessionId,payload:""},i=JSON.stringify(t);this.heartBeatIntervalRef=setInterval(()=>{var r;this.stopSignal||((r=this.socket)===null||r===void 0?void 0:r.readyState)===WebSocket.OPEN&&this.socket.send(i)},e)}}function Fx(s){return"brainType"in s||"llmId"in s}var Gu=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Gx{constructor(e,t,i){if(!e&&!t)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(i==null?void 0:i.baseUrl)||Ax,this.apiVersion=(i==null?void 0:i.apiVersion)||wx,this.apiGatewayConfig=(i==null?void 0:i.apiGateway)||void 0}buildGatewayUrlAndHeaders(e,t){var i,r;if(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.enabled&&(!((r=this.apiGatewayConfig)===null||r===void 0)&&r.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${e}`,o=new URL(`${this.baseUrl}${e}`),a=Object.assign(Object.assign({},t),{"X-Anam-Target-Url":o.href});return{url:n,headers:a}}else return{url:`${this.baseUrl}${e}`,headers:t}}startSession(e,t){return Gu(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new Ne("Persona configuration must be provided when using apiKey",ze.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const i=`${this.apiVersion}/engine/session`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),o=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:Bu})}),a=yield o.json(),l=a.error;switch(o.status){case 200:case 201:return a;case 400:throw new Ne("Invalid request to start session",ze.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:a.message});case 401:throw new Ne("Authentication failed when starting session",ze.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:a.message});case 402:throw new Ne("Please sign up for a plan to start a session",ze.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:a.message});case 403:throw new Ne("Authentication failed when starting session",ze.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:a.message});case 429:throw l==="Concurrent session limit reached"?new Ne("Concurrency limit reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:a.message}):l==="Spend cap reached"?new Ne("Spend cap reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:a.message}):new Ne("Usage limit reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:a.message});case 503:throw new Ne("There are no available personas, please try again later",ze.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:a.message});default:throw new Ne("Unknown error when starting session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a.message})}}catch(i){throw i instanceof Ne?i:new Ne("Failed to start session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:i instanceof Error?i.message:String(i)})}})}unsafe_getSessionToken(e){return Gu(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};Fx(e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{const i=`${this.apiVersion}/auth/session-token`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(r,{method:"POST",headers:n,body:JSON.stringify(t)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var Lx=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Wx{constructor(e,t,i){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=i}sendTalkCommand(e){return Lx(this,void 0,void 0,function*(){var t,i;try{let r,n={"Content-Type":"application/json"};const o="/talk",a=`?session_id=${this.sessionId}`;if(!((t=this.apiGatewayConfig)===null||t===void 0)&&t.enabled&&(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.baseUrl)){r=`${this.apiGatewayConfig.baseUrl}${o}${a}`;const c=new URL(`${this.baseUrl}${o}${a}`);n["X-Anam-Target-Url"]=c.href}else r=`${this.baseUrl}${o}${a}`;const l=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({content:e})});if(!l.ok)throw new Error(`Failed to send talk command: ${l.status} ${l.statusText}`)}catch(r){throw console.error(r),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class Hx{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(i=>{i(...t)})}}class Vx{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Ue.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){const t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},i=this.messages.findIndex(r=>r.id===t.id);if(i!==-1){const r=this.messages[i];this.messages[i]=Object.assign(Object.assign({},r),{content:r.content+t.content,interrupted:r.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){const t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(te.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case yr.USER:this.processUserMessage(t);break;case yr.PERSONA:this.processPersonaMessage(t);break}t.endOfSpeech&&this.publicEventEmitter.emit(te.MESSAGE_HISTORY_UPDATED,this.messages)}}class zx{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){if(e===te.CONNECTION_ESTABLISHED&&li(Dt.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===te.CONNECTION_CLOSED){const[i,r]=t;li(Dt.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,i,r?{details:r}:void 0)}this.listeners[e]&&this.listeners[e].forEach(i=>{i(...t)})}}var Ke;(function(s){s[s.UNSTARTED=0]="UNSTARTED",s[s.STREAMING=1]="STREAMING",s[s.INTERRUPTED=2]="INTERRUPTED",s[s.ENDED=3]="ENDED"})(Ke||(Ke={}));var Uo=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class $x{constructor(e,t,i){this.state=Ke.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=i,this.internalEventEmitter.addListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return Uo(this,void 0,void 0,function*(){e.actionType===Xe.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=Ke.INTERRUPTED,this.onDeactivate())})}endMessage(){return Uo(this,void 0,void 0,function*(){if(this.state===Ke.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==Ke.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=Ke.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return Uo(this,void 0,void 0,function*(){if(this.state!==Ke.STREAMING&&this.state!==Ke.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const i={content:e,startOfSpeech:this.state===Ke.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?Ke.ENDED:Ke.STREAMING,this.state===Ke.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(i)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===Ke.STREAMING||this.state===Ke.UNSTARTED}getState(){return this.state}}var Fo=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Lu=(s,e)=>{if(isNaN(s)||isNaN(e))return 0;const t=e-s;return t>0?t:0};class Wu{constructor(e){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.publicEventEmitter=e}clearPendingCalls(){this.pendingCalls=Object.create(null)}registerHandler(e,t){return this.handlers[e]=t,()=>{delete this.handlers[e]}}processToolCallStartedEvent(e){return Fo(this,void 0,void 0,function*(){const{tool_name:t,timestamp:i}=e,r=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),n=new Date(i);if(this.pendingCalls[e.tool_call_id]={payload:r,timestamp:n.getTime()},!(t in this.handlers))return;const o=this.handlers[t];if(o.onStart)try{let a=yield o.onStart(r);if(e.tool_type==="client"){yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:a,timestamp:new Date().toISOString()}));return}}catch(a){a instanceof Error?yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${a.message}`,timestamp:new Date().toISOString()})):yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${String(a)}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(e){return Fo(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:i,timestamp:r}=e,n=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;const o=this.handlers[t];if(o.onComplete){e.tool_type==="client"&&this.publicEventEmitter.emit(te.TOOL_CALL_COMPLETED,n);try{yield o.onComplete(n)}catch(a){console.error(`Error in onComplete handler for tool ${t}:`,a);return}}})}processToolCallFailedEvent(e){return Fo(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:i,timestamp:r}=e,n=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;const o=this.handlers[t];if(o.onFail){e.tool_type==="client"&&this.publicEventEmitter.emit(te.TOOL_CALL_FAILED,n);try{yield o.onFail(n)}catch(a){console.error(`Error in onFail handler for tool ${t}:`,a);return}}})}static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}static WebRTCToolCallStartedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(e){return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(e){const t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],r=i?Lu(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:r>0?r:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],r=i?Lu(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,errorMessage:e.error_message,executionTime:r>0?r:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}var st=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const jx=15e3,Xx=5e3,Yx=2;class qx{constructor(e,t,i,r,n){var o,a,l,c;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:jt.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.toolCallManager=n,this.apiGatewayConfig=t.apiGateway;const{inputAudio:h}=t;this.inputAudioState=h.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=t.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(Ue.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.iceServers=t.iceServers,this.signallingClient=new Ux(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new Wx(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(a=(o=t.metrics)===null||o===void 0?void 0:o.showPeerConnectionStatsReport)!==null&&a!==void 0?a:!1,this.peerConnectionStatsReportOutputFormat=(c=(l=t.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&c!==void 0?c:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>st(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),Xx))}sendClientSideMetrics(e){e.forEach(t=>{if(t.type==="inbound-rtp"){const i={message_type:"remote_rtp_stats",data:t};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(i))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},jx);this.successMetricPoller=setInterval(()=>st(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const t=yield this.peerConnection.getStats();let i=!1,r=null;t.forEach(n=>{n.type==="inbound-rtp"&&n.kind==="video"&&(n.framesDecoded!==void 0&&n.framesDecoded>0?(i=!0,r="framesDecoded"):n.framesReceived!==void 0&&n.framesReceived>0?(i=!0,r="framesReceived"):n.bytesReceived>0&&n.packetsReceived>0&&n.bytesReceived>1e5&&(i=!0,r="bytesReceived"))}),i&&!this.successMetricFired&&(this.successMetricFired=!0,li(Dt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",r?{detectionMethod:r}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(e==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(r=>{r.stop()});const i={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:i}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(te.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(i){throw console.error("Failed to change audio input device:",i),new Error(`StreamingClient - changeAudioInputDevice: ${i instanceof Error?i.message:String(i)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const t=document.getElementById(e);if(!t)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return st(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new $x(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new Bx(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return st(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:Yx}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case Xe.ANSWER:const t=e.payload;yield this.peerConnection.setRemoteDescription(t),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case Xe.ICE_CANDIDATE:const i=e.payload,r=new RTCIceCandidate(i);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(r):this.remoteIceCandidateBuffer.push(r);break;case Xe.END_SESSION:const n=e.payload;this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.SERVER_CLOSED_CONNECTION,n),this.shutdown();break;case Xe.WARNING:const o=e.payload;console.warn("Warning received from server: "+o),this.publicEventEmitter.emit(te.SERVER_WARNING,o);break;case Xe.TALK_STREAM_INTERRUPTED:const a=e.payload;this.publicEventEmitter.emit(te.TALK_STREAM_INTERRUPTED,a.correlationId);break;case Xe.SESSION_READY:const l=e.sessionId;this.publicEventEmitter.emit(te.SESSION_READY,l);break;case Xe.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}})}onSignallingClientConnected(){return st(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var t;(t=this.peerConnection)===null||t===void 0||t.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,t;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((t=this.peerConnection)===null||t===void 0?void 0:t.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(te.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;((e=this.peerConnection)===null||e===void 0?void 0:e.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.WEBRTC_FAILURE);try{this.stopConnection()}catch(t){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",t)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(te.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const t=this.videoElement.requestVideoFrameCallback(()=>{var i;(i=this.videoElement)===null||i===void 0||i.cancelVideoFrameCallback(t),this.publicEventEmitter.emit(te.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,li(Dt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(te.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return st(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=e??null},e.onclose=()=>{},e.onmessage=t=>{var i,r,n,o;try{const a=JSON.parse(t.data);switch(a.messageType){case xt.SPEECH_TEXT:this.internalEventEmitter.emit(Ue.WEBRTC_CHAT_MESSAGE_RECEIVED,a.data);break;case xt.CLIENT_TOOL_EVENT:const l=a.data;this.internalEventEmitter.emit(Ue.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,l);const c=Wu.WebRTCClientToolEventToClientToolEvent(l);this.publicEventEmitter.emit(te.CLIENT_TOOL_EVENT_RECEIVED,c);break;case xt.TOOL_CALL_STARTED_EVENT:const h=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(h)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,h);break;case xt.TOOL_CALL_COMPLETED_EVENT:const u=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(u)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,u);break;case xt.TOOL_CALL_FAILED_EVENT:const f=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(f)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,f);break;case xt.REASONING_TEXT:this.internalEventEmitter.emit(Ue.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,a.data);break;case xt.USER_SPEECH_STARTED:this.publicEventEmitter.emit(te.USER_SPEECH_STARTED,(r=(i=a.data)===null||i===void 0?void 0:i.user_action_correlation_id)!==null&&r!==void 0?r:"unknown");break;case xt.USER_SPEECH_ENDED:this.publicEventEmitter.emit(te.USER_SPEECH_ENDED,(o=(n=a.data)===null||n===void 0?void 0:n.user_action_correlation_id)!==null&&o!==void 0?o:"unknown");break;default:break}}catch(a){console.error("Failed to parse data channel message:",a)}}})}requestMicrophonePermissionAsync(){return st(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==jt.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:jt.PENDING}),this.publicEventEmitter.emit(te.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:jt.GRANTED}),this.publicEventEmitter.emit(te.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:jt.DENIED});const t=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(te.MIC_PERMISSION_DENIED,t)}}})}setupAudioTrack(){return st(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],i=this.peerConnection.getSenders().find(r=>{var n;return((n=r.track)===null||n===void 0?void 0:n.kind)==="audio"||r.track===null&&r.dtmf!==null});if(i)try{yield i.replaceTrack(e)}catch(r){console.error("Failed to replace audio track:",r),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(te.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return st(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return st(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const t=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(t){const i=kx(t,this.peerConnectionStatsReportOutputFormat);i&&console.log(i,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(t=>{t.stop()}),this.inputAudioStream=null}catch(t){console.error("StreamingClient - shutdown: error stopping input audio stream",t)}try{this.signallingClient.stop()}catch(t){console.error("StreamingClient - shutdown: error stopping signallilng",t)}this.toolCallManager.clearPendingCalls();try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(t){console.error("StreamingClient - shutdown: error closing peer connection",t)}})}}class Kx{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Ue.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(te.REASONING_STREAM_EVENT_RECEIVED,t);const i={id:t.id,content:t.content,role:t.role},r=this.reasoning_messages.findIndex(n=>n.id===i.id);if(r!==-1){const n=this.reasoning_messages[r];n.content+=i.content,this.reasoning_messages[r]=n}else this.reasoning_messages.push(i);t.endOfThought&&this.publicEventEmitter.emit(te.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var Yt=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Zx{constructor(e,t,i){var r,n,o,a,l;this.inputAudioState={isMuted:!1,permissionState:jt.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const c=this.validateClientConfig(e,t,i);if(c)throw new Ne(c,ze.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=i,(!((r=i==null?void 0:i.api)===null||r===void 0)&&r.baseUrl||!((n=i==null?void 0:i.api)===null||n===void 0)&&n.apiVersion)&&Rx(i.api.baseUrl||Du,i.api.apiVersion||Do),!((a=(o=i==null?void 0:i.api)===null||o===void 0?void 0:o.apiGateway)===null||a===void 0)&&a.enabled&&Mx(i.api.apiGateway),!((l=i==null?void 0:i.metrics)===null||l===void 0)&&l.disableClientMetrics&&Px(!0),this.publicEventEmitter=new zx,this.internalEventEmitter=new Hx,this.toolCallManager=new Wu(this.publicEventEmitter),this.apiClient=new Gx(e,i==null?void 0:i.apiKey,i==null?void 0:i.api),this.messageHistoryClient=new Vx(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Kx(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const t=e.split(".")[1],i=Tx.Buffer.from(t,"base64").toString("utf8");return JSON.parse(i)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,t,i){var r,n;if(!e&&!(i!=null&&i.apiKey))return"Either sessionToken or apiKey must be provided";if(i!=null&&i.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const o=Ox((r=i==null?void 0:i.api)===null||r===void 0?void 0:r.apiGateway);if(o)return o;if(e){const a=this.decodeJwt(e);this.organizationId=a.accountId,Di({organizationId:this.organizationId});const l=(n=a.type)===null||n===void 0?void 0:n.toLowerCase();if(l==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((l==="ephemeral"||l==="stateful")&&t)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!t)return"Missing persona config. Persona configuration must be provided when using apiKey";if(i!=null&&i.voiceDetection){if(i.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(i.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof i.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(i.voiceDetection.endOfSpeechSensitivity<0||i.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const t={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(t.voiceDetection=this.clientOptions.voiceDetection),Object.keys(t).length!==0)return t}startSession(e){return Yt(this,void 0,void 0,function*(){var t,i,r,n,o,a,l,c,h,u,f,d;const g=this.personaConfig,_=this.buildStartSessionOptionsForClient(),b=yield this.apiClient.startSession(g,_),{sessionId:x,clientConfig:C,engineHost:S,engineProtocol:E,signallingEndpoint:w}=b,{heartbeatIntervalSeconds:R,maxWsReconnectionAttempts:M,iceServers:D}=C;this.sessionId=x,Di({sessionId:this.sessionId});const F=!((t=this.clientOptions)===null||t===void 0)&&t.iceServers?this.clientOptions.iceServers:D;try{this.streamingClient=new qx(x,{engine:{baseUrl:`${E}://${S}`},signalling:{heartbeatIntervalSeconds:R,maxWsReconnectionAttempts:M,url:{baseUrl:S,protocol:E,signallingPath:w}},iceServers:F,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio?void 0:e,audioDeviceId:(r=this.clientOptions)===null||r===void 0?void 0:r.audioDeviceId,disableInputAudio:(n=this.clientOptions)===null||n===void 0?void 0:n.disableInputAudio},apiGateway:(a=(o=this.clientOptions)===null||o===void 0?void 0:o.api)===null||a===void 0?void 0:a.apiGateway,metrics:{showPeerConnectionStatsReport:(h=(c=(l=this.clientOptions)===null||l===void 0?void 0:l.metrics)===null||c===void 0?void 0:c.showPeerConnectionStatsReport)!==null&&h!==void 0?h:!1,peerConnectionStatsReportOutputFormat:(d=(f=(u=this.clientOptions)===null||u===void 0?void 0:u.metrics)===null||f===void 0?void 0:f.peerConnectionStatsReportOutputFormat)!==null&&d!==void 0?d:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(k){throw Di({sessionId:null}),new Ne("Failed to initialize streaming client",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:k instanceof Error?k.message:String(k),sessionId:x})}return x})}startSessionIfNeeded(e){return Yt(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new Ne("Session ID or streaming client is not available after starting session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return Yt(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw new Error("Already streaming");const i=Fu();return Di({attemptCorrelationId:i,sessionId:null}),li(Dt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(r=>{var n;const o=[];let a=!1,l=!1;this.publicEventEmitter.addListener(te.VIDEO_STREAM_STARTED,c=>{o.push(c),a=!0,l&&r(o)}),this.publicEventEmitter.addListener(te.AUDIO_STREAM_STARTED,c=>{o.push(c),l=!0,a&&r(o)}),(n=this.streamingClient)===null||n===void 0||n.startConnection()})})}streamToVideoAndAudioElements(e,t,i){return Yt(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,i)})}streamToVideoElement(e,t){return Yt(this,void 0,void 0,function*(){var i;const r=Fu();Di({attemptCorrelationId:r,sessionId:null}),li(Dt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio&&t&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t)}catch(n){throw n instanceof Ne?n:new Ne("Failed to start session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:n instanceof Error?n.message:String(n),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return Yt(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send user message: no active session");const i=new Date().toISOString().replace("Z",""),r=JSON.stringify({content:e,timestamp:i,session_id:t,message_type:"speech"});this.sendDataMessage(r)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(t)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to add context: no active session");const i=JSON.stringify({message_type:"context",session_id:t,content:e});this.sendDataMessage(i)}stopStreaming(){return Yt(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Di({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return Yt(this,void 0,void 0,function*(){var t;if(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,t){this.publicEventEmitter.addListener(e,t)}removeListener(e,t){this.publicEventEmitter.removeListener(e,t)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,t){return this.toolCallManager.registerHandler(e,t)}}const Jx=(s,e)=>new Zx(s,void 0,e);let Qx=0;class ev{constructor(e){this.onVideoReady=null,this.onConnected=null,this.onDisconnected=null,this.onTalkStreamInterrupted=null,this.onError=null,this.audioInputStream=null,this.videoElement=null,this._connected=!1,this._closing=!1,this.inlineMode=e.inlineMode??!1,this.client=Jx(e.sessionToken,{disableInputAudio:!0,metrics:{disableClientMetrics:!0}})}get isConnected(){return this._connected}get videoEl(){return this.videoElement}async connect(){var e;try{const t=`anam-avatar-video-${++Qx}`;this.videoElement=document.createElement("video"),this.videoElement.id=t,this.videoElement.autoplay=!0,this.videoElement.playsInline=!0,this.inlineMode?this.videoElement.style.cssText=`
940
+ */var Ou;function Tx(){return Ou||(Ou=1,(function(s){const e=Sx(),t=Ex(),i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;s.Buffer=a,s.SlowBuffer=C,s.INSPECT_MAX_BYTES=50;const r=2147483647;s.kMaxLength=r,a.TYPED_ARRAY_SUPPORT=n(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function n(){try{const b=new Uint8Array(1),p={foo:function(){return 42}};return Object.setPrototypeOf(p,Uint8Array.prototype),Object.setPrototypeOf(b,p),b.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(b){if(b>r)throw new RangeError('The value "'+b+'" is invalid for option "size"');const p=new Uint8Array(b);return Object.setPrototypeOf(p,a.prototype),p}function a(b,p,m){if(typeof b=="number"){if(typeof p=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(b)}return l(b,p,m)}a.poolSize=8192;function l(b,p,m){if(typeof b=="string")return f(b,p);if(ArrayBuffer.isView(b))return g(b);if(b==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b);if(tt(b,ArrayBuffer)||b&&tt(b.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(tt(b,SharedArrayBuffer)||b&&tt(b.buffer,SharedArrayBuffer)))return _(b,p,m);if(typeof b=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const v=b.valueOf&&b.valueOf();if(v!=null&&v!==b)return a.from(v,p,m);const T=y(b);if(T)return T;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof b[Symbol.toPrimitive]=="function")return a.from(b[Symbol.toPrimitive]("string"),p,m);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b)}a.from=function(b,p,m){return l(b,p,m)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function c(b){if(typeof b!="number")throw new TypeError('"size" argument must be of type number');if(b<0)throw new RangeError('The value "'+b+'" is invalid for option "size"')}function h(b,p,m){return c(b),b<=0?o(b):p!==void 0?typeof m=="string"?o(b).fill(p,m):o(b).fill(p):o(b)}a.alloc=function(b,p,m){return h(b,p,m)};function u(b){return c(b),o(b<0?0:x(b)|0)}a.allocUnsafe=function(b){return u(b)},a.allocUnsafeSlow=function(b){return u(b)};function f(b,p){if((typeof p!="string"||p==="")&&(p="utf8"),!a.isEncoding(p))throw new TypeError("Unknown encoding: "+p);const m=S(b,p)|0;let v=o(m);const T=v.write(b,p);return T!==m&&(v=v.slice(0,T)),v}function d(b){const p=b.length<0?0:x(b.length)|0,m=o(p);for(let v=0;v<p;v+=1)m[v]=b[v]&255;return m}function g(b){if(tt(b,Uint8Array)){const p=new Uint8Array(b);return _(p.buffer,p.byteOffset,p.byteLength)}return d(b)}function _(b,p,m){if(p<0||b.byteLength<p)throw new RangeError('"offset" is outside of buffer bounds');if(b.byteLength<p+(m||0))throw new RangeError('"length" is outside of buffer bounds');let v;return p===void 0&&m===void 0?v=new Uint8Array(b):m===void 0?v=new Uint8Array(b,p):v=new Uint8Array(b,p,m),Object.setPrototypeOf(v,a.prototype),v}function y(b){if(a.isBuffer(b)){const p=x(b.length)|0,m=o(p);return m.length===0||b.copy(m,0,0,p),m}if(b.length!==void 0)return typeof b.length!="number"||Xi(b.length)?o(0):d(b);if(b.type==="Buffer"&&Array.isArray(b.data))return d(b.data)}function x(b){if(b>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return b|0}function C(b){return+b!=b&&(b=0),a.alloc(+b)}a.isBuffer=function(p){return p!=null&&p._isBuffer===!0&&p!==a.prototype},a.compare=function(p,m){if(tt(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),tt(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),!a.isBuffer(p)||!a.isBuffer(m))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(p===m)return 0;let v=p.length,T=m.length;for(let I=0,P=Math.min(v,T);I<P;++I)if(p[I]!==m[I]){v=p[I],T=m[I];break}return v<T?-1:T<v?1:0},a.isEncoding=function(p){switch(String(p).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(p,m){if(!Array.isArray(p))throw new TypeError('"list" argument must be an Array of Buffers');if(p.length===0)return a.alloc(0);let v;if(m===void 0)for(m=0,v=0;v<p.length;++v)m+=p[v].length;const T=a.allocUnsafe(m);let I=0;for(v=0;v<p.length;++v){let P=p[v];if(tt(P,Uint8Array))I+P.length>T.length?(a.isBuffer(P)||(P=a.from(P)),P.copy(T,I)):Uint8Array.prototype.set.call(T,P,I);else if(a.isBuffer(P))P.copy(T,I);else throw new TypeError('"list" argument must be an Array of Buffers');I+=P.length}return T};function S(b,p){if(a.isBuffer(b))return b.length;if(ArrayBuffer.isView(b)||tt(b,ArrayBuffer))return b.byteLength;if(typeof b!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof b);const m=b.length,v=arguments.length>2&&arguments[2]===!0;if(!v&&m===0)return 0;let T=!1;for(;;)switch(p){case"ascii":case"latin1":case"binary":return m;case"utf8":case"utf-8":return Et(b).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return m*2;case"hex":return m>>>1;case"base64":return Ut(b).length;default:if(T)return v?-1:Et(b).length;p=(""+p).toLowerCase(),T=!0}}a.byteLength=S;function E(b,p,m){let v=!1;if((p===void 0||p<0)&&(p=0),p>this.length||((m===void 0||m>this.length)&&(m=this.length),m<=0)||(m>>>=0,p>>>=0,m<=p))return"";for(b||(b="utf8");;)switch(b){case"hex":return N(this,p,m);case"utf8":case"utf-8":return z(this,p,m);case"ascii":return U(this,p,m);case"latin1":case"binary":return q(this,p,m);case"base64":return X(this,p,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K(this,p,m);default:if(v)throw new TypeError("Unknown encoding: "+b);b=(b+"").toLowerCase(),v=!0}}a.prototype._isBuffer=!0;function w(b,p,m){const v=b[p];b[p]=b[m],b[m]=v}a.prototype.swap16=function(){const p=this.length;if(p%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let m=0;m<p;m+=2)w(this,m,m+1);return this},a.prototype.swap32=function(){const p=this.length;if(p%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let m=0;m<p;m+=4)w(this,m,m+3),w(this,m+1,m+2);return this},a.prototype.swap64=function(){const p=this.length;if(p%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let m=0;m<p;m+=8)w(this,m,m+7),w(this,m+1,m+6),w(this,m+2,m+5),w(this,m+3,m+4);return this},a.prototype.toString=function(){const p=this.length;return p===0?"":arguments.length===0?z(this,0,p):E.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(p){if(!a.isBuffer(p))throw new TypeError("Argument must be a Buffer");return this===p?!0:a.compare(this,p)===0},a.prototype.inspect=function(){let p="";const m=s.INSPECT_MAX_BYTES;return p=this.toString("hex",0,m).replace(/(.{2})/g,"$1 ").trim(),this.length>m&&(p+=" ... "),"<Buffer "+p+">"},i&&(a.prototype[i]=a.prototype.inspect),a.prototype.compare=function(p,m,v,T,I){if(tt(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),!a.isBuffer(p))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof p);if(m===void 0&&(m=0),v===void 0&&(v=p?p.length:0),T===void 0&&(T=0),I===void 0&&(I=this.length),m<0||v>p.length||T<0||I>this.length)throw new RangeError("out of range index");if(T>=I&&m>=v)return 0;if(T>=I)return-1;if(m>=v)return 1;if(m>>>=0,v>>>=0,T>>>=0,I>>>=0,this===p)return 0;let P=I-T,J=v-m;const Re=Math.min(P,J),Te=this.slice(T,I),Me=p.slice(m,v);for(let ye=0;ye<Re;++ye)if(Te[ye]!==Me[ye]){P=Te[ye],J=Me[ye];break}return P<J?-1:J<P?1:0};function R(b,p,m,v,T){if(b.length===0)return-1;if(typeof m=="string"?(v=m,m=0):m>2147483647?m=2147483647:m<-2147483648&&(m=-2147483648),m=+m,Xi(m)&&(m=T?0:b.length-1),m<0&&(m=b.length+m),m>=b.length){if(T)return-1;m=b.length-1}else if(m<0)if(T)m=0;else return-1;if(typeof p=="string"&&(p=a.from(p,v)),a.isBuffer(p))return p.length===0?-1:M(b,p,m,v,T);if(typeof p=="number")return p=p&255,typeof Uint8Array.prototype.indexOf=="function"?T?Uint8Array.prototype.indexOf.call(b,p,m):Uint8Array.prototype.lastIndexOf.call(b,p,m):M(b,[p],m,v,T);throw new TypeError("val must be string, number or Buffer")}function M(b,p,m,v,T){let I=1,P=b.length,J=p.length;if(v!==void 0&&(v=String(v).toLowerCase(),v==="ucs2"||v==="ucs-2"||v==="utf16le"||v==="utf-16le")){if(b.length<2||p.length<2)return-1;I=2,P/=2,J/=2,m/=2}function Re(Me,ye){return I===1?Me[ye]:Me.readUInt16BE(ye*I)}let Te;if(T){let Me=-1;for(Te=m;Te<P;Te++)if(Re(b,Te)===Re(p,Me===-1?0:Te-Me)){if(Me===-1&&(Me=Te),Te-Me+1===J)return Me*I}else Me!==-1&&(Te-=Te-Me),Me=-1}else for(m+J>P&&(m=P-J),Te=m;Te>=0;Te--){let Me=!0;for(let ye=0;ye<J;ye++)if(Re(b,Te+ye)!==Re(p,ye)){Me=!1;break}if(Me)return Te}return-1}a.prototype.includes=function(p,m,v){return this.indexOf(p,m,v)!==-1},a.prototype.indexOf=function(p,m,v){return R(this,p,m,v,!0)},a.prototype.lastIndexOf=function(p,m,v){return R(this,p,m,v,!1)};function D(b,p,m,v){m=Number(m)||0;const T=b.length-m;v?(v=Number(v),v>T&&(v=T)):v=T;const I=p.length;v>I/2&&(v=I/2);let P;for(P=0;P<v;++P){const J=parseInt(p.substr(P*2,2),16);if(Xi(J))return P;b[m+P]=J}return P}function F(b,p,m,v){return pt(Et(p,b.length-m),b,m,v)}function k(b,p,m,v){return pt(ui(p),b,m,v)}function O(b,p,m,v){return pt(Ut(p),b,m,v)}function V(b,p,m,v){return pt(ji(p,b.length-m),b,m,v)}a.prototype.write=function(p,m,v,T){if(m===void 0)T="utf8",v=this.length,m=0;else if(v===void 0&&typeof m=="string")T=m,v=this.length,m=0;else if(isFinite(m))m=m>>>0,isFinite(v)?(v=v>>>0,T===void 0&&(T="utf8")):(T=v,v=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const I=this.length-m;if((v===void 0||v>I)&&(v=I),p.length>0&&(v<0||m<0)||m>this.length)throw new RangeError("Attempt to write outside buffer bounds");T||(T="utf8");let P=!1;for(;;)switch(T){case"hex":return D(this,p,m,v);case"utf8":case"utf-8":return F(this,p,m,v);case"ascii":case"latin1":case"binary":return k(this,p,m,v);case"base64":return O(this,p,m,v);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,p,m,v);default:if(P)throw new TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),P=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function X(b,p,m){return p===0&&m===b.length?e.fromByteArray(b):e.fromByteArray(b.slice(p,m))}function z(b,p,m){m=Math.min(b.length,m);const v=[];let T=p;for(;T<m;){const I=b[T];let P=null,J=I>239?4:I>223?3:I>191?2:1;if(T+J<=m){let Re,Te,Me,ye;switch(J){case 1:I<128&&(P=I);break;case 2:Re=b[T+1],(Re&192)===128&&(ye=(I&31)<<6|Re&63,ye>127&&(P=ye));break;case 3:Re=b[T+1],Te=b[T+2],(Re&192)===128&&(Te&192)===128&&(ye=(I&15)<<12|(Re&63)<<6|Te&63,ye>2047&&(ye<55296||ye>57343)&&(P=ye));break;case 4:Re=b[T+1],Te=b[T+2],Me=b[T+3],(Re&192)===128&&(Te&192)===128&&(Me&192)===128&&(ye=(I&15)<<18|(Re&63)<<12|(Te&63)<<6|Me&63,ye>65535&&ye<1114112&&(P=ye))}}P===null?(P=65533,J=1):P>65535&&(P-=65536,v.push(P>>>10&1023|55296),P=56320|P&1023),v.push(P),T+=J}return B(v)}const de=4096;function B(b){const p=b.length;if(p<=de)return String.fromCharCode.apply(String,b);let m="",v=0;for(;v<p;)m+=String.fromCharCode.apply(String,b.slice(v,v+=de));return m}function U(b,p,m){let v="";m=Math.min(b.length,m);for(let T=p;T<m;++T)v+=String.fromCharCode(b[T]&127);return v}function q(b,p,m){let v="";m=Math.min(b.length,m);for(let T=p;T<m;++T)v+=String.fromCharCode(b[T]);return v}function N(b,p,m){const v=b.length;(!p||p<0)&&(p=0),(!m||m<0||m>v)&&(m=v);let T="";for(let I=p;I<m;++I)T+=Br[b[I]];return T}function K(b,p,m){const v=b.slice(p,m);let T="";for(let I=0;I<v.length-1;I+=2)T+=String.fromCharCode(v[I]+v[I+1]*256);return T}a.prototype.slice=function(p,m){const v=this.length;p=~~p,m=m===void 0?v:~~m,p<0?(p+=v,p<0&&(p=0)):p>v&&(p=v),m<0?(m+=v,m<0&&(m=0)):m>v&&(m=v),m<p&&(m=p);const T=this.subarray(p,m);return Object.setPrototypeOf(T,a.prototype),T};function Z(b,p,m){if(b%1!==0||b<0)throw new RangeError("offset is not uint");if(b+p>m)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(p,m,v){p=p>>>0,m=m>>>0,v||Z(p,m,this.length);let T=this[p],I=1,P=0;for(;++P<m&&(I*=256);)T+=this[p+P]*I;return T},a.prototype.readUintBE=a.prototype.readUIntBE=function(p,m,v){p=p>>>0,m=m>>>0,v||Z(p,m,this.length);let T=this[p+--m],I=1;for(;m>0&&(I*=256);)T+=this[p+--m]*I;return T},a.prototype.readUint8=a.prototype.readUInt8=function(p,m){return p=p>>>0,m||Z(p,1,this.length),this[p]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(p,m){return p=p>>>0,m||Z(p,2,this.length),this[p]|this[p+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(p,m){return p=p>>>0,m||Z(p,2,this.length),this[p]<<8|this[p+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),(this[p]|this[p+1]<<8|this[p+2]<<16)+this[p+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),this[p]*16777216+(this[p+1]<<16|this[p+2]<<8|this[p+3])},a.prototype.readBigUInt64LE=mt(function(p){p=p>>>0,we(p,"offset");const m=this[p],v=this[p+7];(m===void 0||v===void 0)&&ce(p,this.length-8);const T=m+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,I=this[++p]+this[++p]*2**8+this[++p]*2**16+v*2**24;return BigInt(T)+(BigInt(I)<<BigInt(32))}),a.prototype.readBigUInt64BE=mt(function(p){p=p>>>0,we(p,"offset");const m=this[p],v=this[p+7];(m===void 0||v===void 0)&&ce(p,this.length-8);const T=m*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],I=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+v;return(BigInt(T)<<BigInt(32))+BigInt(I)}),a.prototype.readIntLE=function(p,m,v){p=p>>>0,m=m>>>0,v||Z(p,m,this.length);let T=this[p],I=1,P=0;for(;++P<m&&(I*=256);)T+=this[p+P]*I;return I*=128,T>=I&&(T-=Math.pow(2,8*m)),T},a.prototype.readIntBE=function(p,m,v){p=p>>>0,m=m>>>0,v||Z(p,m,this.length);let T=m,I=1,P=this[p+--T];for(;T>0&&(I*=256);)P+=this[p+--T]*I;return I*=128,P>=I&&(P-=Math.pow(2,8*m)),P},a.prototype.readInt8=function(p,m){return p=p>>>0,m||Z(p,1,this.length),this[p]&128?(255-this[p]+1)*-1:this[p]},a.prototype.readInt16LE=function(p,m){p=p>>>0,m||Z(p,2,this.length);const v=this[p]|this[p+1]<<8;return v&32768?v|4294901760:v},a.prototype.readInt16BE=function(p,m){p=p>>>0,m||Z(p,2,this.length);const v=this[p+1]|this[p]<<8;return v&32768?v|4294901760:v},a.prototype.readInt32LE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),this[p]|this[p+1]<<8|this[p+2]<<16|this[p+3]<<24},a.prototype.readInt32BE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),this[p]<<24|this[p+1]<<16|this[p+2]<<8|this[p+3]},a.prototype.readBigInt64LE=mt(function(p){p=p>>>0,we(p,"offset");const m=this[p],v=this[p+7];(m===void 0||v===void 0)&&ce(p,this.length-8);const T=this[p+4]+this[p+5]*2**8+this[p+6]*2**16+(v<<24);return(BigInt(T)<<BigInt(32))+BigInt(m+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24)}),a.prototype.readBigInt64BE=mt(function(p){p=p>>>0,we(p,"offset");const m=this[p],v=this[p+7];(m===void 0||v===void 0)&&ce(p,this.length-8);const T=(m<<24)+this[++p]*2**16+this[++p]*2**8+this[++p];return(BigInt(T)<<BigInt(32))+BigInt(this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+v)}),a.prototype.readFloatLE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),t.read(this,p,!0,23,4)},a.prototype.readFloatBE=function(p,m){return p=p>>>0,m||Z(p,4,this.length),t.read(this,p,!1,23,4)},a.prototype.readDoubleLE=function(p,m){return p=p>>>0,m||Z(p,8,this.length),t.read(this,p,!0,52,8)},a.prototype.readDoubleBE=function(p,m){return p=p>>>0,m||Z(p,8,this.length),t.read(this,p,!1,52,8)};function $(b,p,m,v,T,I){if(!a.isBuffer(b))throw new TypeError('"buffer" argument must be a Buffer instance');if(p>T||p<I)throw new RangeError('"value" argument is out of bounds');if(m+v>b.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(p,m,v,T){if(p=+p,m=m>>>0,v=v>>>0,!T){const J=Math.pow(2,8*v)-1;$(this,p,m,v,J,0)}let I=1,P=0;for(this[m]=p&255;++P<v&&(I*=256);)this[m+P]=p/I&255;return m+v},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(p,m,v,T){if(p=+p,m=m>>>0,v=v>>>0,!T){const J=Math.pow(2,8*v)-1;$(this,p,m,v,J,0)}let I=v-1,P=1;for(this[m+I]=p&255;--I>=0&&(P*=256);)this[m+I]=p/P&255;return m+v},a.prototype.writeUint8=a.prototype.writeUInt8=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,1,255,0),this[m]=p&255,m+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,2,65535,0),this[m]=p&255,this[m+1]=p>>>8,m+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,2,65535,0),this[m]=p>>>8,this[m+1]=p&255,m+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,4,4294967295,0),this[m+3]=p>>>24,this[m+2]=p>>>16,this[m+1]=p>>>8,this[m]=p&255,m+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,4,4294967295,0),this[m]=p>>>24,this[m+1]=p>>>16,this[m+2]=p>>>8,this[m+3]=p&255,m+4};function ae(b,p,m,v,T){ie(p,v,T,b,m,7);let I=Number(p&BigInt(4294967295));b[m++]=I,I=I>>8,b[m++]=I,I=I>>8,b[m++]=I,I=I>>8,b[m++]=I;let P=Number(p>>BigInt(32)&BigInt(4294967295));return b[m++]=P,P=P>>8,b[m++]=P,P=P>>8,b[m++]=P,P=P>>8,b[m++]=P,m}function Ce(b,p,m,v,T){ie(p,v,T,b,m,7);let I=Number(p&BigInt(4294967295));b[m+7]=I,I=I>>8,b[m+6]=I,I=I>>8,b[m+5]=I,I=I>>8,b[m+4]=I;let P=Number(p>>BigInt(32)&BigInt(4294967295));return b[m+3]=P,P=P>>8,b[m+2]=P,P=P>>8,b[m+1]=P,P=P>>8,b[m]=P,m+8}a.prototype.writeBigUInt64LE=mt(function(p,m=0){return ae(this,p,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=mt(function(p,m=0){return Ce(this,p,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(p,m,v,T){if(p=+p,m=m>>>0,!T){const Re=Math.pow(2,8*v-1);$(this,p,m,v,Re-1,-Re)}let I=0,P=1,J=0;for(this[m]=p&255;++I<v&&(P*=256);)p<0&&J===0&&this[m+I-1]!==0&&(J=1),this[m+I]=(p/P>>0)-J&255;return m+v},a.prototype.writeIntBE=function(p,m,v,T){if(p=+p,m=m>>>0,!T){const Re=Math.pow(2,8*v-1);$(this,p,m,v,Re-1,-Re)}let I=v-1,P=1,J=0;for(this[m+I]=p&255;--I>=0&&(P*=256);)p<0&&J===0&&this[m+I+1]!==0&&(J=1),this[m+I]=(p/P>>0)-J&255;return m+v},a.prototype.writeInt8=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,1,127,-128),p<0&&(p=255+p+1),this[m]=p&255,m+1},a.prototype.writeInt16LE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,2,32767,-32768),this[m]=p&255,this[m+1]=p>>>8,m+2},a.prototype.writeInt16BE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,2,32767,-32768),this[m]=p>>>8,this[m+1]=p&255,m+2},a.prototype.writeInt32LE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,4,2147483647,-2147483648),this[m]=p&255,this[m+1]=p>>>8,this[m+2]=p>>>16,this[m+3]=p>>>24,m+4},a.prototype.writeInt32BE=function(p,m,v){return p=+p,m=m>>>0,v||$(this,p,m,4,2147483647,-2147483648),p<0&&(p=4294967295+p+1),this[m]=p>>>24,this[m+1]=p>>>16,this[m+2]=p>>>8,this[m+3]=p&255,m+4},a.prototype.writeBigInt64LE=mt(function(p,m=0){return ae(this,p,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=mt(function(p,m=0){return Ce(this,p,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Ee(b,p,m,v,T,I){if(m+v>b.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("Index out of range")}function G(b,p,m,v,T){return p=+p,m=m>>>0,T||Ee(b,p,m,4),t.write(b,p,m,v,23,4),m+4}a.prototype.writeFloatLE=function(p,m,v){return G(this,p,m,!0,v)},a.prototype.writeFloatBE=function(p,m,v){return G(this,p,m,!1,v)};function fe(b,p,m,v,T){return p=+p,m=m>>>0,T||Ee(b,p,m,8),t.write(b,p,m,v,52,8),m+8}a.prototype.writeDoubleLE=function(p,m,v){return fe(this,p,m,!0,v)},a.prototype.writeDoubleBE=function(p,m,v){return fe(this,p,m,!1,v)},a.prototype.copy=function(p,m,v,T){if(!a.isBuffer(p))throw new TypeError("argument should be a Buffer");if(v||(v=0),!T&&T!==0&&(T=this.length),m>=p.length&&(m=p.length),m||(m=0),T>0&&T<v&&(T=v),T===v||p.length===0||this.length===0)return 0;if(m<0)throw new RangeError("targetStart out of bounds");if(v<0||v>=this.length)throw new RangeError("Index out of range");if(T<0)throw new RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),p.length-m<T-v&&(T=p.length-m+v);const I=T-v;return this===p&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(m,v,T):Uint8Array.prototype.set.call(p,this.subarray(v,T),m),I},a.prototype.fill=function(p,m,v,T){if(typeof p=="string"){if(typeof m=="string"?(T=m,m=0,v=this.length):typeof v=="string"&&(T=v,v=this.length),T!==void 0&&typeof T!="string")throw new TypeError("encoding must be a string");if(typeof T=="string"&&!a.isEncoding(T))throw new TypeError("Unknown encoding: "+T);if(p.length===1){const P=p.charCodeAt(0);(T==="utf8"&&P<128||T==="latin1")&&(p=P)}}else typeof p=="number"?p=p&255:typeof p=="boolean"&&(p=Number(p));if(m<0||this.length<m||this.length<v)throw new RangeError("Out of range index");if(v<=m)return this;m=m>>>0,v=v===void 0?this.length:v>>>0,p||(p=0);let I;if(typeof p=="number")for(I=m;I<v;++I)this[I]=p;else{const P=a.isBuffer(p)?p:a.from(p,T),J=P.length;if(J===0)throw new TypeError('The value "'+p+'" is invalid for argument "value"');for(I=0;I<v-m;++I)this[I+m]=P[I%J]}return this};const le={};function L(b,p,m){le[b]=class extends m{constructor(){super(),Object.defineProperty(this,"message",{value:p.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${b}]`,this.stack,delete this.name}get code(){return b}set code(T){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:T,writable:!0})}toString(){return`${this.name} [${b}]: ${this.message}`}}}L("ERR_BUFFER_OUT_OF_BOUNDS",function(b){return b?`${b} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(b,p){return`The "${b}" argument must be of type number. Received type ${typeof p}`},TypeError),L("ERR_OUT_OF_RANGE",function(b,p,m){let v=`The value of "${b}" is out of range.`,T=m;return Number.isInteger(m)&&Math.abs(m)>2**32?T=me(String(m)):typeof m=="bigint"&&(T=String(m),(m>BigInt(2)**BigInt(32)||m<-(BigInt(2)**BigInt(32)))&&(T=me(T)),T+="n"),v+=` It must be ${p}. Received ${T}`,v},RangeError);function me(b){let p="",m=b.length;const v=b[0]==="-"?1:0;for(;m>=v+4;m-=3)p=`_${b.slice(m-3,m)}${p}`;return`${b.slice(0,m)}${p}`}function Y(b,p,m){we(p,"offset"),(b[p]===void 0||b[p+m]===void 0)&&ce(p,b.length-(m+1))}function ie(b,p,m,v,T,I){if(b>m||b<p){const P=typeof p=="bigint"?"n":"";let J;throw p===0||p===BigInt(0)?J=`>= 0${P} and < 2${P} ** ${(I+1)*8}${P}`:J=`>= -(2${P} ** ${(I+1)*8-1}${P}) and < 2 ** ${(I+1)*8-1}${P}`,new le.ERR_OUT_OF_RANGE("value",J,b)}Y(v,T,I)}function we(b,p){if(typeof b!="number")throw new le.ERR_INVALID_ARG_TYPE(p,"number",b)}function ce(b,p,m){throw Math.floor(b)!==b?(we(b,m),new le.ERR_OUT_OF_RANGE("offset","an integer",b)):p<0?new le.ERR_BUFFER_OUT_OF_BOUNDS:new le.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${p}`,b)}const He=/[^+/0-9A-Za-z-_]/g;function Qt(b){if(b=b.split("=")[0],b=b.trim().replace(He,""),b.length<2)return"";for(;b.length%4!==0;)b=b+"=";return b}function Et(b,p){p=p||1/0;let m;const v=b.length;let T=null;const I=[];for(let P=0;P<v;++P){if(m=b.charCodeAt(P),m>55295&&m<57344){if(!T){if(m>56319){(p-=3)>-1&&I.push(239,191,189);continue}else if(P+1===v){(p-=3)>-1&&I.push(239,191,189);continue}T=m;continue}if(m<56320){(p-=3)>-1&&I.push(239,191,189),T=m;continue}m=(T-55296<<10|m-56320)+65536}else T&&(p-=3)>-1&&I.push(239,191,189);if(T=null,m<128){if((p-=1)<0)break;I.push(m)}else if(m<2048){if((p-=2)<0)break;I.push(m>>6|192,m&63|128)}else if(m<65536){if((p-=3)<0)break;I.push(m>>12|224,m>>6&63|128,m&63|128)}else if(m<1114112){if((p-=4)<0)break;I.push(m>>18|240,m>>12&63|128,m>>6&63|128,m&63|128)}else throw new Error("Invalid code point")}return I}function ui(b){const p=[];for(let m=0;m<b.length;++m)p.push(b.charCodeAt(m)&255);return p}function ji(b,p){let m,v,T;const I=[];for(let P=0;P<b.length&&!((p-=2)<0);++P)m=b.charCodeAt(P),v=m>>8,T=m%256,I.push(T),I.push(v);return I}function Ut(b){return e.toByteArray(Qt(b))}function pt(b,p,m,v){let T;for(T=0;T<v&&!(T+m>=p.length||T>=b.length);++T)p[T+m]=b[T];return T}function tt(b,p){return b instanceof p||b!=null&&b.constructor!=null&&b.constructor.name!=null&&b.constructor.name===p.name}function Xi(b){return b!==b}const Br=(function(){const b="0123456789abcdef",p=new Array(256);for(let m=0;m<16;++m){const v=m*16;for(let T=0;T<16;++T)p[v+T]=b[m]+b[T]}return p})();function mt(b){return typeof BigInt>"u"?Dr:b}function Dr(){throw new Error("BigInt not supported")}})(Bo)),Bo}var Ax=Tx();const wx="https://api.anam.ai",Ix="/v1",Bu={client:"js-sdk",version:"4.12.0"};var Rx=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Du="https://api.anam.ai",Do="/v1";var Dt;(function(s){s.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",s.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",s.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(Dt||(Dt={}));let No=Du,Nu=Do,zt,Uu=!1;const Mx=(s,e=Do)=>{No=s,Nu=e},Px=s=>{zt=s},kx=s=>{Uu=s};let $t={sessionId:null,organizationId:null,attemptCorrelationId:null};const Di=s=>{$t=Object.assign(Object.assign({},$t),s)},li=(s,e,t)=>Rx(void 0,void 0,void 0,function*(){if(!Uu)try{const i=Object.assign(Object.assign({},Bu),t);$t.sessionId&&(i.sessionId=$t.sessionId),$t.organizationId&&(i.organizationId=$t.organizationId),$t.attemptCorrelationId&&(i.attemptCorrelationId=$t.attemptCorrelationId);const r=`${Nu}/metrics/client`;let n,o={"Content-Type":"application/json"};zt!=null&&zt.enabled&&(zt!=null&&zt.baseUrl)?(n=`${zt.baseUrl}${r}`,o["X-Anam-Target-Url"]=`${No}${r}`):n=`${No}${r}`,yield fetch(n,{method:"POST",headers:o,body:JSON.stringify({name:s,value:e,tags:i})})}catch(i){console.error("Failed to send error metric:",i)}}),Ox=(s,e="console")=>{var t,i,r;const n={};s.forEach(u=>{n[u.type]||(n[u.type]=[]),n[u.type].push(u)});const o={issues:[]},a=((t=n["inbound-rtp"])===null||t===void 0?void 0:t.filter(u=>u.kind==="video"))||[];a.length>0&&(o.personaVideoStream=[],a.forEach(u=>{var f,d,g,_,y;const x={framesReceived:(f=u.framesReceived)!==null&&f!==void 0?f:"unknown",framesDropped:(d=u.framesDropped)!==null&&d!==void 0?d:"unknown",framesPerSecond:(g=u.framesPerSecond)!==null&&g!==void 0?g:"unknown",packetsReceived:(_=u.packetsReceived)!==null&&_!==void 0?_:"unknown",packetsLost:(y=u.packetsLost)!==null&&y!==void 0?y:"unknown",resolution:u.frameWidth&&u.frameHeight?`${u.frameWidth}x${u.frameHeight}`:void 0,jitter:u.jitter!==void 0?u.jitter:void 0};o.personaVideoStream.push(x)}));const l=((i=n["inbound-rtp"])===null||i===void 0?void 0:i.filter(u=>u.kind==="audio"))||[];l.length>0&&(o.personaAudioStream=[],l.forEach(u=>{var f,d,g;const _={packetsReceived:(f=u.packetsReceived)!==null&&f!==void 0?f:"unknown",packetsLost:(d=u.packetsLost)!==null&&d!==void 0?d:"unknown",audioLevel:(g=u.audioLevel)!==null&&g!==void 0?g:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};o.personaAudioStream.push(_)}));const c=((r=n["outbound-rtp"])===null||r===void 0?void 0:r.filter(u=>u.kind==="audio"))||[];c.length>0&&(o.userAudioInput=[],c.forEach(u=>{var f,d;const g={packetsSent:(f=u.packetsSent)!==null&&f!==void 0?f:"unknown",retransmittedPackets:(d=u.retransmittedPacketsSent)!==null&&d!==void 0?d:void 0,avgPacketSendDelay:u.totalPacketSendDelay!==void 0?u.totalPacketSendDelay/(u.packetsSent||1)*1e3:void 0};o.userAudioInput.push(g)})),n.codec&&(o.codecs=[],n.codec.forEach(u=>{const f={status:u.payloadType?"Active":"Available",mimeType:u.mimeType||"Unknown",payloadType:u.payloadType||"N/A",clockRate:u.clockRate||void 0,channels:u.channels||void 0};o.codecs.push(f)})),n.transport&&(o.transportLayer=[],n.transport.forEach(u=>{const f={dtlsState:u.dtlsState||"unknown",iceState:u.iceState||"unknown",bytesSent:u.bytesSent||void 0,bytesReceived:u.bytesReceived||void 0};o.transportLayer.push(f)}));const h=[];if(a.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&h.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&h.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),l.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&h.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),o.issues=h,e==="json")return o;console.group("📊 WebRTC Session Statistics Report"),o.personaVideoStream&&o.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),o.personaVideoStream.forEach(u=>{console.log(`Frames Received: ${u.framesReceived}`),console.log(`Frames Dropped: ${u.framesDropped}`),console.log(`Frames Per Second: ${u.framesPerSecond}`),console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),u.resolution&&console.log(`Resolution: ${u.resolution}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`)}),console.groupEnd()),o.personaAudioStream&&o.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),o.personaAudioStream.forEach(u=>{console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),console.log(`Audio Level: ${u.audioLevel}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`),u.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${u.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),o.userAudioInput&&o.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),o.userAudioInput.forEach(u=>{console.log(`Packets Sent: ${typeof u.packetsSent=="number"?u.packetsSent.toLocaleString():u.packetsSent}`),u.retransmittedPackets&&console.log(`Retransmitted Packets: ${u.retransmittedPackets}`),u.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${u.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),o.codecs&&o.codecs.length>0&&(console.group("🔧 Codecs Used"),o.codecs.forEach(u=>{console.log(`${u.status} ${u.mimeType} - Payload Type: ${u.payloadType}`),u.clockRate&&console.log(` Clock Rate: ${u.clockRate}Hz`),u.channels&&console.log(` Channels: ${u.channels}`)}),console.groupEnd()),o.transportLayer&&o.transportLayer.length>0&&(console.group("🚚 Transport Layer"),o.transportLayer.forEach(u=>{console.log(`DTLS State: ${u.dtlsState}`),console.log(`ICE State: ${u.iceState}`),(u.bytesReceived||u.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(u.bytesSent||0).toLocaleString()}, Received: ${(u.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),o.issues.length>0?(console.group("⚠️ Potential Issues Detected"),o.issues.forEach(u=>console.warn(u)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var ze;(function(s){s.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",s.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",s.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",s.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",s.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",s.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",s.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",s.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",s.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",s.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})(ze||(ze={}));class Ne extends Error{constructor(e,t,i=500,r){super(e),this.name="ClientError",this.code=t,this.statusCode=i,this.details=r,Object.setPrototypeOf(this,Ne.prototype),li(Dt.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:r,statusCode:i})}}function Fu(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function Bx(s){if(!(!s||!s.enabled)){if(!s.baseUrl)return"API Gateway baseUrl is required when enabled";try{const e=new URL(s.baseUrl);if(!["http:","https:","ws:","wss:"].includes(e.protocol))return`Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${s.baseUrl}`}if(s.wsPath&&!s.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var Xe;(function(s){s.OFFER="offer",s.ANSWER="answer",s.ICE_CANDIDATE="icecandidate",s.END_SESSION="endsession",s.HEARTBEAT="heartbeat",s.WARNING="warning",s.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",s.TALK_STREAM_INPUT="talkstream",s.SESSION_READY="sessionready",s.AGENT_AUDIO_INPUT="agentaudioinput",s.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(Xe||(Xe={}));var xt;(function(s){s.SPEECH_TEXT="speechText",s.CLIENT_TOOL_EVENT="clientToolEvent",s.TOOL_CALL_STARTED_EVENT="toolCallStarted",s.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",s.TOOL_CALL_FAILED_EVENT="toolCallFailed",s.REASONING_TEXT="reasoningText",s.USER_SPEECH_STARTED="userSpeechStarted",s.USER_SPEECH_ENDED="userSpeechEnded"})(xt||(xt={}));var jt;(function(s){s.PENDING="pending",s.GRANTED="granted",s.DENIED="denied",s.NOT_REQUESTED="not_requested"})(jt||(jt={}));var br;(function(s){s.USER="user",s.PERSONA="persona"})(br||(br={}));var te;(function(s){s.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",s.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",s.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",s.CONNECTION_CLOSED="CONNECTION_CLOSED",s.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",s.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",s.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",s.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",s.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",s.SESSION_READY="SESSION_READY",s.SERVER_WARNING="SERVER_WARNING",s.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",s.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",s.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",s.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",s.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",s.TOOL_CALL_STARTED="TOOL_CALL_STARTED",s.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",s.TOOL_CALL_FAILED="TOOL_CALL_FAILED",s.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",s.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",s.USER_SPEECH_STARTED="USER_SPEECH_STARTED",s.USER_SPEECH_ENDED="USER_SPEECH_ENDED"})(te||(te={}));var Ue;(function(s){s.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",s.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",s.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",s.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",s.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(Ue||(Ue={}));var Xt;(function(s){s.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",s.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",s.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",s.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",s.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(Xt||(Xt={}));class Dx{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){const i={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(i)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),i=Array.from(t,r=>String.fromCharCode(r)).join("");return btoa(i)}}var Ni=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Nx=5,Ux=5;class Fx{constructor(e,t,i,r,n){var o,a,l,c,h;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.apiGatewayConfig=n,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:f,url:d}=t;if(this.heartbeatIntervalSeconds=u||Nx,this.maxWsReconnectionAttempts=f||Ux,!d.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const g=new URL(this.apiGatewayConfig.baseUrl),_=(l=this.apiGatewayConfig.wsPath)!==null&&l!==void 0?l:"/ws";g.protocol=g.protocol.replace("http","ws"),g.pathname=_,this.url=g;const y=d.protocol||"https",x=y==="http"?"ws":"wss",C=`${y}://${d.baseUrl}`,S=(c=d.signallingPath)!==null&&c!==void 0?c:"/ws",E=new URL(C);E.protocol=x==="ws"?"ws:":"wss:",d.port&&(E.port=d.port),E.pathname=S,E.searchParams.append("session_id",e),this.url.searchParams.append("target_url",E.href)}else{const _=`${d.protocol||"https"}://${d.baseUrl}`;this.url=new URL(_),this.url.protocol=d.protocol==="http"?"ws:":"wss:",d.port&&(this.url.port=d.port),this.url.pathname=(h=d.signallingPath)!==null&&h!==void 0?h:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return Ni(this,void 0,void 0,function*(){const t={connectionDescription:e,userUid:this.sessionId},i={actionType:Xe.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(i)})}sendIceCandidate(e){return Ni(this,void 0,void 0,function*(){const t={actionType:Xe.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if(((t=this.socket)===null||t===void 0?void 0:t.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(i){console.error("SignallingClient - sendSignalMessage: error sending message",i)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Ni(this,void 0,void 0,function*(){const t={actionType:Xe.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){const t={actionType:Xe.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){const e={actionType:Xe.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Ni(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(Ue.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Ni(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var i;((i=this.socket)===null||i===void 0?void 0:i.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return Ni(this,void 0,void 0,function*(){const t=JSON.parse(e.data);this.internalEventEmitter.emit(Ue.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,t={actionType:Xe.HEARTBEAT,sessionId:this.sessionId,payload:""},i=JSON.stringify(t);this.heartBeatIntervalRef=setInterval(()=>{var r;this.stopSignal||((r=this.socket)===null||r===void 0?void 0:r.readyState)===WebSocket.OPEN&&this.socket.send(i)},e)}}function Gx(s){return"brainType"in s||"llmId"in s}var Gu=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Lx{constructor(e,t,i){if(!e&&!t)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(i==null?void 0:i.baseUrl)||wx,this.apiVersion=(i==null?void 0:i.apiVersion)||Ix,this.apiGatewayConfig=(i==null?void 0:i.apiGateway)||void 0}buildGatewayUrlAndHeaders(e,t){var i,r;if(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.enabled&&(!((r=this.apiGatewayConfig)===null||r===void 0)&&r.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${e}`,o=new URL(`${this.baseUrl}${e}`),a=Object.assign(Object.assign({},t),{"X-Anam-Target-Url":o.href});return{url:n,headers:a}}else return{url:`${this.baseUrl}${e}`,headers:t}}startSession(e,t){return Gu(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new Ne("Persona configuration must be provided when using apiKey",ze.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const i=`${this.apiVersion}/engine/session`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),o=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:Bu})}),a=yield o.json(),l=a.error;switch(o.status){case 200:case 201:return a;case 400:throw new Ne("Invalid request to start session",ze.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:a.message});case 401:throw new Ne("Authentication failed when starting session",ze.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:a.message});case 402:throw new Ne("Please sign up for a plan to start a session",ze.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:a.message});case 403:throw new Ne("Authentication failed when starting session",ze.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:a.message});case 429:throw l==="Concurrent session limit reached"?new Ne("Concurrency limit reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:a.message}):l==="Spend cap reached"?new Ne("Spend cap reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:a.message}):new Ne("Usage limit reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:a.message});case 503:throw new Ne("There are no available personas, please try again later",ze.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:a.message});default:throw new Ne("Unknown error when starting session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a.message})}}catch(i){throw i instanceof Ne?i:new Ne("Failed to start session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:i instanceof Error?i.message:String(i)})}})}unsafe_getSessionToken(e){return Gu(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};Gx(e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{const i=`${this.apiVersion}/auth/session-token`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(r,{method:"POST",headers:n,body:JSON.stringify(t)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var Wx=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Hx{constructor(e,t,i){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=i}sendTalkCommand(e){return Wx(this,void 0,void 0,function*(){var t,i;try{let r,n={"Content-Type":"application/json"};const o="/talk",a=`?session_id=${this.sessionId}`;if(!((t=this.apiGatewayConfig)===null||t===void 0)&&t.enabled&&(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.baseUrl)){r=`${this.apiGatewayConfig.baseUrl}${o}${a}`;const c=new URL(`${this.baseUrl}${o}${a}`);n["X-Anam-Target-Url"]=c.href}else r=`${this.baseUrl}${o}${a}`;const l=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({content:e})});if(!l.ok)throw new Error(`Failed to send talk command: ${l.status} ${l.statusText}`)}catch(r){throw console.error(r),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class Vx{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(i=>{i(...t)})}}class zx{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Ue.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){const t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},i=this.messages.findIndex(r=>r.id===t.id);if(i!==-1){const r=this.messages[i];this.messages[i]=Object.assign(Object.assign({},r),{content:r.content+t.content,interrupted:r.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){const t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(te.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case br.USER:this.processUserMessage(t);break;case br.PERSONA:this.processPersonaMessage(t);break}t.endOfSpeech&&this.publicEventEmitter.emit(te.MESSAGE_HISTORY_UPDATED,this.messages)}}class $x{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){if(e===te.CONNECTION_ESTABLISHED&&li(Dt.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===te.CONNECTION_CLOSED){const[i,r]=t;li(Dt.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,i,r?{details:r}:void 0)}this.listeners[e]&&this.listeners[e].forEach(i=>{i(...t)})}}var Ke;(function(s){s[s.UNSTARTED=0]="UNSTARTED",s[s.STREAMING=1]="STREAMING",s[s.INTERRUPTED=2]="INTERRUPTED",s[s.ENDED=3]="ENDED"})(Ke||(Ke={}));var Uo=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class jx{constructor(e,t,i){this.state=Ke.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=i,this.internalEventEmitter.addListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return Uo(this,void 0,void 0,function*(){e.actionType===Xe.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=Ke.INTERRUPTED,this.onDeactivate())})}endMessage(){return Uo(this,void 0,void 0,function*(){if(this.state===Ke.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==Ke.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=Ke.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return Uo(this,void 0,void 0,function*(){if(this.state!==Ke.STREAMING&&this.state!==Ke.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const i={content:e,startOfSpeech:this.state===Ke.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?Ke.ENDED:Ke.STREAMING,this.state===Ke.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(i)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===Ke.STREAMING||this.state===Ke.UNSTARTED}getState(){return this.state}}var Fo=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Lu=(s,e)=>{if(isNaN(s)||isNaN(e))return 0;const t=e-s;return t>0?t:0};class Wu{constructor(e){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.publicEventEmitter=e}clearPendingCalls(){this.pendingCalls=Object.create(null)}registerHandler(e,t){return this.handlers[e]=t,()=>{delete this.handlers[e]}}processToolCallStartedEvent(e){return Fo(this,void 0,void 0,function*(){const{tool_name:t,timestamp:i}=e,r=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),n=new Date(i);if(this.pendingCalls[e.tool_call_id]={payload:r,timestamp:n.getTime()},!(t in this.handlers))return;const o=this.handlers[t];if(o.onStart)try{let a=yield o.onStart(r);if(e.tool_type==="client"){yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:a,timestamp:new Date().toISOString()}));return}}catch(a){a instanceof Error?yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${a.message}`,timestamp:new Date().toISOString()})):yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${String(a)}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(e){return Fo(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:i,timestamp:r}=e,n=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;const o=this.handlers[t];if(o.onComplete){e.tool_type==="client"&&this.publicEventEmitter.emit(te.TOOL_CALL_COMPLETED,n);try{yield o.onComplete(n)}catch(a){console.error(`Error in onComplete handler for tool ${t}:`,a);return}}})}processToolCallFailedEvent(e){return Fo(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:i,timestamp:r}=e,n=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;const o=this.handlers[t];if(o.onFail){e.tool_type==="client"&&this.publicEventEmitter.emit(te.TOOL_CALL_FAILED,n);try{yield o.onFail(n)}catch(a){console.error(`Error in onFail handler for tool ${t}:`,a);return}}})}static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}static WebRTCToolCallStartedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(e){return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(e){const t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],r=i?Lu(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:r>0?r:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],r=i?Lu(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,errorMessage:e.error_message,executionTime:r>0?r:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}var st=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Xx=15e3,Yx=5e3,qx=2;class Kx{constructor(e,t,i,r,n){var o,a,l,c;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:jt.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.toolCallManager=n,this.apiGatewayConfig=t.apiGateway;const{inputAudio:h}=t;this.inputAudioState=h.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=t.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(Ue.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.iceServers=t.iceServers,this.signallingClient=new Fx(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new Hx(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(a=(o=t.metrics)===null||o===void 0?void 0:o.showPeerConnectionStatsReport)!==null&&a!==void 0?a:!1,this.peerConnectionStatsReportOutputFormat=(c=(l=t.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&c!==void 0?c:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>st(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),Yx))}sendClientSideMetrics(e){e.forEach(t=>{if(t.type==="inbound-rtp"){const i={message_type:"remote_rtp_stats",data:t};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(i))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},Xx);this.successMetricPoller=setInterval(()=>st(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const t=yield this.peerConnection.getStats();let i=!1,r=null;t.forEach(n=>{n.type==="inbound-rtp"&&n.kind==="video"&&(n.framesDecoded!==void 0&&n.framesDecoded>0?(i=!0,r="framesDecoded"):n.framesReceived!==void 0&&n.framesReceived>0?(i=!0,r="framesReceived"):n.bytesReceived>0&&n.packetsReceived>0&&n.bytesReceived>1e5&&(i=!0,r="bytesReceived"))}),i&&!this.successMetricFired&&(this.successMetricFired=!0,li(Dt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",r?{detectionMethod:r}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(e==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(r=>{r.stop()});const i={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:i}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(te.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(i){throw console.error("Failed to change audio input device:",i),new Error(`StreamingClient - changeAudioInputDevice: ${i instanceof Error?i.message:String(i)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const t=document.getElementById(e);if(!t)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return st(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new jx(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new Dx(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return st(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:qx}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case Xe.ANSWER:const t=e.payload;yield this.peerConnection.setRemoteDescription(t),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case Xe.ICE_CANDIDATE:const i=e.payload,r=new RTCIceCandidate(i);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(r):this.remoteIceCandidateBuffer.push(r);break;case Xe.END_SESSION:const n=e.payload;this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.SERVER_CLOSED_CONNECTION,n),this.shutdown();break;case Xe.WARNING:const o=e.payload;console.warn("Warning received from server: "+o),this.publicEventEmitter.emit(te.SERVER_WARNING,o);break;case Xe.TALK_STREAM_INTERRUPTED:const a=e.payload;this.publicEventEmitter.emit(te.TALK_STREAM_INTERRUPTED,a.correlationId);break;case Xe.SESSION_READY:const l=e.sessionId;this.publicEventEmitter.emit(te.SESSION_READY,l);break;case Xe.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}})}onSignallingClientConnected(){return st(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var t;(t=this.peerConnection)===null||t===void 0||t.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,t;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((t=this.peerConnection)===null||t===void 0?void 0:t.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(te.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;((e=this.peerConnection)===null||e===void 0?void 0:e.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.WEBRTC_FAILURE);try{this.stopConnection()}catch(t){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",t)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(te.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const t=this.videoElement.requestVideoFrameCallback(()=>{var i;(i=this.videoElement)===null||i===void 0||i.cancelVideoFrameCallback(t),this.publicEventEmitter.emit(te.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,li(Dt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(te.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return st(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=e??null},e.onclose=()=>{},e.onmessage=t=>{var i,r,n,o;try{const a=JSON.parse(t.data);switch(a.messageType){case xt.SPEECH_TEXT:this.internalEventEmitter.emit(Ue.WEBRTC_CHAT_MESSAGE_RECEIVED,a.data);break;case xt.CLIENT_TOOL_EVENT:const l=a.data;this.internalEventEmitter.emit(Ue.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,l);const c=Wu.WebRTCClientToolEventToClientToolEvent(l);this.publicEventEmitter.emit(te.CLIENT_TOOL_EVENT_RECEIVED,c);break;case xt.TOOL_CALL_STARTED_EVENT:const h=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(h)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,h);break;case xt.TOOL_CALL_COMPLETED_EVENT:const u=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(u)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,u);break;case xt.TOOL_CALL_FAILED_EVENT:const f=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(f)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,f);break;case xt.REASONING_TEXT:this.internalEventEmitter.emit(Ue.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,a.data);break;case xt.USER_SPEECH_STARTED:this.publicEventEmitter.emit(te.USER_SPEECH_STARTED,(r=(i=a.data)===null||i===void 0?void 0:i.user_action_correlation_id)!==null&&r!==void 0?r:"unknown");break;case xt.USER_SPEECH_ENDED:this.publicEventEmitter.emit(te.USER_SPEECH_ENDED,(o=(n=a.data)===null||n===void 0?void 0:n.user_action_correlation_id)!==null&&o!==void 0?o:"unknown");break;default:break}}catch(a){console.error("Failed to parse data channel message:",a)}}})}requestMicrophonePermissionAsync(){return st(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==jt.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:jt.PENDING}),this.publicEventEmitter.emit(te.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:jt.GRANTED}),this.publicEventEmitter.emit(te.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:jt.DENIED});const t=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(te.MIC_PERMISSION_DENIED,t)}}})}setupAudioTrack(){return st(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],i=this.peerConnection.getSenders().find(r=>{var n;return((n=r.track)===null||n===void 0?void 0:n.kind)==="audio"||r.track===null&&r.dtmf!==null});if(i)try{yield i.replaceTrack(e)}catch(r){console.error("Failed to replace audio track:",r),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(te.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return st(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return st(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const t=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(t){const i=Ox(t,this.peerConnectionStatsReportOutputFormat);i&&console.log(i,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(t=>{t.stop()}),this.inputAudioStream=null}catch(t){console.error("StreamingClient - shutdown: error stopping input audio stream",t)}try{this.signallingClient.stop()}catch(t){console.error("StreamingClient - shutdown: error stopping signallilng",t)}this.toolCallManager.clearPendingCalls();try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(t){console.error("StreamingClient - shutdown: error closing peer connection",t)}})}}class Zx{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Ue.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(te.REASONING_STREAM_EVENT_RECEIVED,t);const i={id:t.id,content:t.content,role:t.role},r=this.reasoning_messages.findIndex(n=>n.id===i.id);if(r!==-1){const n=this.reasoning_messages[r];n.content+=i.content,this.reasoning_messages[r]=n}else this.reasoning_messages.push(i);t.endOfThought&&this.publicEventEmitter.emit(te.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var Yt=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Jx{constructor(e,t,i){var r,n,o,a,l;this.inputAudioState={isMuted:!1,permissionState:jt.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const c=this.validateClientConfig(e,t,i);if(c)throw new Ne(c,ze.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=i,(!((r=i==null?void 0:i.api)===null||r===void 0)&&r.baseUrl||!((n=i==null?void 0:i.api)===null||n===void 0)&&n.apiVersion)&&Mx(i.api.baseUrl||Du,i.api.apiVersion||Do),!((a=(o=i==null?void 0:i.api)===null||o===void 0?void 0:o.apiGateway)===null||a===void 0)&&a.enabled&&Px(i.api.apiGateway),!((l=i==null?void 0:i.metrics)===null||l===void 0)&&l.disableClientMetrics&&kx(!0),this.publicEventEmitter=new $x,this.internalEventEmitter=new Vx,this.toolCallManager=new Wu(this.publicEventEmitter),this.apiClient=new Lx(e,i==null?void 0:i.apiKey,i==null?void 0:i.api),this.messageHistoryClient=new zx(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Zx(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const t=e.split(".")[1],i=Ax.Buffer.from(t,"base64").toString("utf8");return JSON.parse(i)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,t,i){var r,n;if(!e&&!(i!=null&&i.apiKey))return"Either sessionToken or apiKey must be provided";if(i!=null&&i.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const o=Bx((r=i==null?void 0:i.api)===null||r===void 0?void 0:r.apiGateway);if(o)return o;if(e){const a=this.decodeJwt(e);this.organizationId=a.accountId,Di({organizationId:this.organizationId});const l=(n=a.type)===null||n===void 0?void 0:n.toLowerCase();if(l==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((l==="ephemeral"||l==="stateful")&&t)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!t)return"Missing persona config. Persona configuration must be provided when using apiKey";if(i!=null&&i.voiceDetection){if(i.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(i.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof i.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(i.voiceDetection.endOfSpeechSensitivity<0||i.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const t={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(t.voiceDetection=this.clientOptions.voiceDetection),Object.keys(t).length!==0)return t}startSession(e){return Yt(this,void 0,void 0,function*(){var t,i,r,n,o,a,l,c,h,u,f,d;const g=this.personaConfig,_=this.buildStartSessionOptionsForClient(),y=yield this.apiClient.startSession(g,_),{sessionId:x,clientConfig:C,engineHost:S,engineProtocol:E,signallingEndpoint:w}=y,{heartbeatIntervalSeconds:R,maxWsReconnectionAttempts:M,iceServers:D}=C;this.sessionId=x,Di({sessionId:this.sessionId});const F=!((t=this.clientOptions)===null||t===void 0)&&t.iceServers?this.clientOptions.iceServers:D;try{this.streamingClient=new Kx(x,{engine:{baseUrl:`${E}://${S}`},signalling:{heartbeatIntervalSeconds:R,maxWsReconnectionAttempts:M,url:{baseUrl:S,protocol:E,signallingPath:w}},iceServers:F,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio?void 0:e,audioDeviceId:(r=this.clientOptions)===null||r===void 0?void 0:r.audioDeviceId,disableInputAudio:(n=this.clientOptions)===null||n===void 0?void 0:n.disableInputAudio},apiGateway:(a=(o=this.clientOptions)===null||o===void 0?void 0:o.api)===null||a===void 0?void 0:a.apiGateway,metrics:{showPeerConnectionStatsReport:(h=(c=(l=this.clientOptions)===null||l===void 0?void 0:l.metrics)===null||c===void 0?void 0:c.showPeerConnectionStatsReport)!==null&&h!==void 0?h:!1,peerConnectionStatsReportOutputFormat:(d=(f=(u=this.clientOptions)===null||u===void 0?void 0:u.metrics)===null||f===void 0?void 0:f.peerConnectionStatsReportOutputFormat)!==null&&d!==void 0?d:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(k){throw Di({sessionId:null}),new Ne("Failed to initialize streaming client",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:k instanceof Error?k.message:String(k),sessionId:x})}return x})}startSessionIfNeeded(e){return Yt(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new Ne("Session ID or streaming client is not available after starting session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return Yt(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw new Error("Already streaming");const i=Fu();return Di({attemptCorrelationId:i,sessionId:null}),li(Dt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(r=>{var n;const o=[];let a=!1,l=!1;this.publicEventEmitter.addListener(te.VIDEO_STREAM_STARTED,c=>{o.push(c),a=!0,l&&r(o)}),this.publicEventEmitter.addListener(te.AUDIO_STREAM_STARTED,c=>{o.push(c),l=!0,a&&r(o)}),(n=this.streamingClient)===null||n===void 0||n.startConnection()})})}streamToVideoAndAudioElements(e,t,i){return Yt(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,i)})}streamToVideoElement(e,t){return Yt(this,void 0,void 0,function*(){var i;const r=Fu();Di({attemptCorrelationId:r,sessionId:null}),li(Dt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio&&t&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t)}catch(n){throw n instanceof Ne?n:new Ne("Failed to start session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:n instanceof Error?n.message:String(n),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return Yt(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send user message: no active session");const i=new Date().toISOString().replace("Z",""),r=JSON.stringify({content:e,timestamp:i,session_id:t,message_type:"speech"});this.sendDataMessage(r)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(t)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to add context: no active session");const i=JSON.stringify({message_type:"context",session_id:t,content:e});this.sendDataMessage(i)}stopStreaming(){return Yt(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(te.CONNECTION_CLOSED,Xt.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Di({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return Yt(this,void 0,void 0,function*(){var t;if(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,t){this.publicEventEmitter.addListener(e,t)}removeListener(e,t){this.publicEventEmitter.removeListener(e,t)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,t){return this.toolCallManager.registerHandler(e,t)}}const Qx=(s,e)=>new Jx(s,void 0,e);let ev=0;class tv{constructor(e){this.onVideoReady=null,this.onConnected=null,this.onDisconnected=null,this.onTalkStreamInterrupted=null,this.onError=null,this.audioInputStream=null,this.videoElement=null,this._connected=!1,this._closing=!1,this.inlineMode=e.inlineMode??!1,this.client=Qx(e.sessionToken,{disableInputAudio:!0,metrics:{disableClientMetrics:!0}})}get isConnected(){return this._connected}get videoEl(){return this.videoElement}async connect(){var e;try{const t=`anam-avatar-video-${++ev}`;this.videoElement=document.createElement("video"),this.videoElement.id=t,this.videoElement.autoplay=!0,this.videoElement.playsInline=!0,this.inlineMode?this.videoElement.style.cssText=`
941
941
  width: 100%;
942
942
  height: 100%;
943
943
  object-fit: cover;
@@ -952,10 +952,10 @@ registerProcessor('pcm-buffer-processor', PcmBufferProcessor)
952
952
  z-index: 2147483646;
953
953
  pointer-events: none;
954
954
  display: none;
955
- `,document.body.appendChild(this.videoElement),this.client.addListener(te.CONNECTION_ESTABLISHED,()=>{var i;console.log("[AnamSession] Connection established"),this._connected=!0,(i=this.onConnected)==null||i.call(this)}),this.client.addListener(te.VIDEO_PLAY_STARTED,()=>{var i;console.log("[AnamSession] Video playing"),this.videoElement&&(this.videoElement.style.display="",(i=this.onVideoReady)==null||i.call(this,this.videoElement))}),this.client.addListener(te.TALK_STREAM_INTERRUPTED,()=>{var i;console.log("[AnamSession] Talk stream interrupted"),(i=this.onTalkStreamInterrupted)==null||i.call(this)}),this.client.addListener(te.CONNECTION_CLOSED,i=>{var r;console.log("[AnamSession] Connection closed:",i),this._connected=!1,(r=this.onDisconnected)==null||r.call(this,String(i))}),await this.client.streamToVideoElement(t),this.audioInputStream=this.client.createAgentAudioInputStream({encoding:"pcm_s16le",sampleRate:24e3,channels:1}),console.log("[AnamSession] BYO audio input stream ready")}catch(t){const i=t instanceof Error?t:new Error(String(t));throw console.error("[AnamSession] Connection failed:",i.message),(e=this.onError)==null||e.call(this,i),this.close(),i}}sendAudioChunk(e){var t;(t=this.audioInputStream)==null||t.sendAudioChunk(e)}endSequence(){var e;(e=this.audioInputStream)==null||e.endSequence()}interrupt(){this.client.interruptPersona()}close(){if(!this._closing){this._closing=!0,console.log("[AnamSession] Closing...");try{this.client.stopStreaming()}catch{}this.videoElement&&(this.videoElement.pause(),this.videoElement.srcObject=null,this.videoElement.remove(),this.videoElement=null),document.querySelectorAll('video[id^="anam-avatar-video"]').forEach(e=>{e.pause(),e.remove()}),this.audioInputStream=null,this._connected=!1}}}const tv=new Set(["a","button","input","select","textarea","details","summary","label","option"]),iv=new Set(["button","link","menuitem","menuitemcheckbox","menuitemradio","tab","switch","slider","combobox","listbox","option","radio","checkbox","textbox","searchbox","scrollbar"]),sv=new Set(["h1","h2","h3","h4","h5","h6"]),rv=["type","role","aria-label","placeholder","value","href","alt","title","name","checked","aria-expanded"];class nv{constructor(){this.elementMap=new Map}analyze(){this.elementMap.clear();let e=0;const t=[];t.push(`Page: ${document.title}`),t.push(`URL: ${location.href}`),t.push("");const i=r=>{if(r.nodeType===Node.TEXT_NODE){const c=(r.textContent??"").trim();c&&c.length>1&&t.push(c);return}if(r.nodeType!==Node.ELEMENT_NODE)return;const n=r,o=n.tagName.toLowerCase();if(!this.isVisible(n)||["script","style","svg","noscript","link","meta"].includes(o)||n.id==="holostaff-widget-root"||n.closest("#holostaff-widget-root"))return;const a=this.isInteractive(n),l=sv.has(o);if(a||l){const c=e++;this.elementMap.set(c,n);const h=this.getUsefulAttrs(n),u=h?" "+h:"",f=this.getDirectText(n).slice(0,200);if(l){const d=parseInt(o[1]),g="#".repeat(d);t.push(""),t.push(`${g} [${c}]${f}`)}else t.push(`[${c}]<${o}${u}>${f}</${o}>`);return}for(const c of n.childNodes)i(c)};return i(document.body),{text:t.join(`
956
- `),elementMap:this.elementMap}}getElementByIndex(e){return this.elementMap.get(e)??null}isVisible(e){const t=getComputedStyle(e);return!(t.display==="none"||t.visibility==="hidden")}isInteractive(e){const t=e.tagName.toLowerCase();if(tv.has(t))return!e.disabled;const i=e.getAttribute("role");if(i&&iv.has(i))return!0;try{if(getComputedStyle(e).cursor==="pointer")return!0}catch{}return!!(e.hasAttribute("tabindex")&&e.getAttribute("tabindex")!=="-1"||e.isContentEditable&&e.getAttribute("contenteditable")!=="false")}getDirectText(e){return(e.textContent??"").replace(/\s+/g," ").trim()}getUsefulAttrs(e){const t=[];for(const i of rv){const r=e.getAttribute(i);r&&r.length>0&&r.length<100&&t.push(`${i}="${r}"`)}return t.join(" ")}}const ov=new Set(["scroll_to","click","highlight"]);class av{constructor(e){this.onToolCall=null,this.fnArgBufs=new Map,this.fnNames=new Map,this.fnCallIds=new Map,this.realtimeSession=e.realtimeSession,this.domAnalyzer=e.domAnalyzer,this.pageActions=e.pageActions,this.overlayActions=e.overlayActions,this.confirmationPrompt=e.confirmationPrompt,this.staffId=e.staffId,this.backendUrl=e.backendUrl,this.skills=e.skills??{}}handleMessage(e){var i;switch(e.type){case"response.output_item.added":if(((i=e.item)==null?void 0:i.type)==="function_call"){const r=e.item.id,n=e.item.name,o=e.item.call_id||e.item.id;return this.fnNames.set(r,n),this.fnCallIds.set(r,o),this.fnArgBufs.set(r,""),console.log(`[ToolHandler] Function call started: ${n} (${r})`),!0}return!1;case"response.function_call_arguments.delta":if(e.item_id&&this.fnArgBufs.has(e.item_id)){const r=this.fnArgBufs.get(e.item_id)??"";return this.fnArgBufs.set(e.item_id,r+(e.delta??"")),!0}return!1;case"response.function_call_arguments.done":return e.item_id&&this.fnArgBufs.has(e.item_id)?(this.handleFunctionCallDone(e.item_id),!0):!1;default:return!1}}async handleFunctionCallDone(e){var a;const t=this.fnNames.get(e)??"unknown",i=this.fnCallIds.get(e)??e,r=this.fnArgBufs.get(e)??"{}";this.fnArgBufs.delete(e),this.fnNames.delete(e),this.fnCallIds.delete(e);let n;try{n=JSON.parse(r)}catch{console.warn(`[ToolHandler] Failed to parse args for ${t}:`,r),this.sendToolResult(i,{error:"Malformed JSON in function call arguments"});return}console.log(`[ToolHandler] Executing: ${t}`,n),(a=this.onToolCall)==null||a.call(this,t,n);let o=null;switch(t){case"page_action":await this.handlePageAction(i,n.instruction??"");return;case"show_text_card":o=this.overlayActions.showTextCard(n.title??"",n.body??"");break;case"show_image_card":o=this.overlayActions.showImageCard(n.image_url??"",n.caption);break;case"show_bullet_list":o=this.overlayActions.showBulletList(n.title??"",n.items??[]);break;case"dismiss_overlays":o=this.overlayActions.dismissAll();break;case"get_skill_instructions":{const l=n.skill_name??"",c=this.skills[l];c?(console.log(`[ToolHandler] Serving skill instructions for "${l}" (${c.length} chars)`),o={instructions:c}):(console.warn(`[ToolHandler] Skill not found: "${l}". Available: ${Object.keys(this.skills).join(", ")}`),o={error:`No skill found with name "${l}". Available skills: ${Object.keys(this.skills).join(", ")}`});break}default:console.warn(`[ToolHandler] Unknown tool: ${t}`),o={error:`Unknown tool: ${t}`}}this.sendToolResult(i,o)}async handlePageAction(e,t){try{const i=t.toLowerCase();if(i.includes("scroll")&&(i.includes("top")||i.includes("beginning"))){const l=this.pageActions.scrollTo(-1);this.sendToolResult(e,{results:[{action:"scroll_to",...l}]});return}if(i.includes("scroll")&&(i.includes("bottom")||i.includes("end"))){const l=this.pageActions.scrollTo(-2);this.sendToolResult(e,{results:[{action:"scroll_to",...l}]});return}const{text:r}=this.domAnalyzer.analyze();console.log(`[ToolHandler] DOM snapshot: ${r.length} chars, instruction: "${t}"`);const o=(await Uf(this.staffId,r,t,this.backendUrl)).actions??[];console.log(`[ToolHandler] Page agent returned ${o.length} actions:`,o);const a=[];for(const l of o){if(l.action==="describe"){a.push({action:"describe",status:"ok",description:l.description});continue}if(ov.has(l.action)&&!await this.confirmationPrompt.ask(`${l.description}?`)){a.push({action:l.action,status:"declined",description:"Visitor declined"});continue}let c;switch(l.action){case"scroll_to":c=this.pageActions.scrollTo(l.index);break;case"highlight":c=this.pageActions.highlight(l.index);break;case"click":c=this.pageActions.click(l.index);break;case"fill":c=this.pageActions.fill(l.index,l.value??"");break;default:c={status:"error",description:`Unknown action: ${l.action}`}}a.push({action:l.action,...c})}this.sendToolResult(e,{results:a})}catch(i){const r=i instanceof Error?i.message:String(i);console.error("[ToolHandler] Page action failed:",r),this.sendToolResult(e,{error:r})}}sendToolResult(e,t){this.realtimeSession.sendJSON({type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(t)}}),this.realtimeSession.sendJSON({type:"response.create"})}}class lv{constructor(e,t){this.analyzer=e,this.highlightRenderer=t}scrollTo(e){if(e===-1)return window.scrollTo({top:0,behavior:"smooth"}),document.documentElement.scrollTop=0,document.body.scrollTop=0,console.log("[PageActions] Scrolled to top"),{status:"scrolled",description:"Top of page"};if(e===-2)return window.scrollTo({top:document.body.scrollHeight,behavior:"smooth"}),console.log("[PageActions] Scrolled to bottom"),{status:"scrolled",description:"Bottom of page"};const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.scrollIntoView({behavior:"smooth",block:"center"});let i=t.parentElement;for(;i;){const n=getComputedStyle(i).overflowY;if(n==="auto"||n==="scroll"){const o=t.getBoundingClientRect().top-i.getBoundingClientRect().top+i.scrollTop;i.scrollTo({top:o-i.clientHeight/2,behavior:"smooth"});break}i=i.parentElement}const r=this.describeElement(t);return console.log(`[PageActions] Scrolled to [${e}] ${r}`),{status:"scrolled",description:r}}highlight(e,t=3e3){const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};this.highlightRenderer.highlight(i,t);const r=this.describeElement(i);return console.log(`[PageActions] Highlighting [${e}] ${r} for ${t}ms`),{status:"highlighted",description:r}}click(e){const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.click();const i=this.describeElement(t);return console.log(`[PageActions] Clicked [${e}] ${i}`),{status:"clicked",description:i}}fill(e,t){var a,l;const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};const r=i.tagName.toLowerCase(),n=(a=i.type)==null?void 0:a.toLowerCase();if(r==="select"){const c=i,h=Array.from(c.options).find(u=>u.text.toLowerCase().includes(t.toLowerCase())||u.value.toLowerCase()===t.toLowerCase());if(h)c.value=h.value,c.dispatchEvent(new Event("change",{bubbles:!0}));else return{status:"error",description:`No option matching "${t}"`}}else if(n==="checkbox"||n==="radio"){const c=i;c.checked=t==="true"||t==="1",c.dispatchEvent(new Event("change",{bubbles:!0}))}else{const c=(l=Object.getOwnPropertyDescriptor(r==="textarea"?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value"))==null?void 0:l.set;c?c.call(i,t):i.value=t,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0}))}const o=this.describeElement(i);return console.log(`[PageActions] Filled [${e}] ${o} with "${t}"`),{status:"filled",description:`${o} = "${t}"`}}describeElement(e){const t=e.tagName.toLowerCase(),i=(e.textContent??"").trim().slice(0,50),r=e.getAttribute("aria-label")||e.getAttribute("placeholder")||i;return`<${t}>${r}</${t}>`}}class cv{constructor(e){this.renderer=e}showTextCard(e,t){return this.renderer.showTextCard(e,t),console.log(`[OverlayActions] Showing text card: "${e}"`),{status:"shown"}}showImageCard(e,t){return this.renderer.showImageCard(e,t),console.log(`[OverlayActions] Showing image card: "${t??e}"`),{status:"shown"}}showBulletList(e,t){return this.renderer.showBulletList(e,t),console.log(`[OverlayActions] Showing bullet list: "${e}" (${t.length} items)`),{status:"shown"}}dismissAll(){return this.renderer.dismissAll(),console.log("[OverlayActions] Dismissed all overlays"),{status:"dismissed"}}}const hv="https://us-central1-holostaff-ai.cloudfunctions.net";class uv{constructor(e){this.messages={},this.actions=[],this.msgCounter=0,this.staffId=e.staffId,this.staffName=e.staffName,this.backendUrl=e.backendUrl??hv,this.startTime=new Date().toISOString(),this.userId=`visitor_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}addUserMessage(e){if(!e.trim())return;const t=`msg_${this.msgCounter++}`;this.messages[t]={sender:"user",text:e.trim(),timestamp:new Date().toISOString()}}addStaffMessage(e){if(!e.trim())return;const t=`msg_${this.msgCounter++}`;this.messages[t]={sender:"staff",text:e.trim(),timestamp:new Date().toISOString()}}addAction(e,t){this.actions.push({tool:e,args:t,timestamp:new Date().toISOString()})}getSummary(){const e=Object.values(this.messages);return e.length===0?"No conversation took place.":e.slice(-6).map(i=>`${i.sender==="user"?"User":"Agent"}: ${i.text.slice(0,80)}`).join(" | ")}async flush(){if(Object.keys(this.messages).length===0){console.log("[Logger] No messages to log, skipping");return}const e=Object.values(this.messages).pop(),t={staffId:this.staffId,staffName:this.staffName,userId:this.userId,startTime:this.startTime,lastMessageAt:(e==null?void 0:e.timestamp)??this.startTime,messages:this.messages,actions:this.actions,source:"widget_v2"};console.log("[Logger] Flushing conversation log:",{messages:Object.keys(this.messages).length,actions:this.actions.length});const i=`${this.backendUrl}/logConversation`,r=JSON.stringify(t);try{const n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!0});if(n.ok){const o=await n.json();console.log("[Logger] Conversation logged:",o.id)}else console.warn("[Logger] Failed to log conversation:",n.status)}catch(n){console.warn("[Logger] Error logging conversation:",n)}}}var We;(function(s){s[s.Document=0]="Document",s[s.DocumentType=1]="DocumentType",s[s.Element=2]="Element",s[s.Text=3]="Text",s[s.CDATA=4]="CDATA",s[s.Comment=5]="Comment"})(We||(We={}));function dv(s){return s.nodeType===s.ELEMENT_NODE}function Es(s){var e=s==null?void 0:s.host;return(e==null?void 0:e.shadowRoot)===s}function Ts(s){return Object.prototype.toString.call(s)==="[object ShadowRoot]"}function fv(s){return s.includes(" background-clip: text;")&&!s.includes(" -webkit-background-clip: text;")&&(s=s.replace(" background-clip: text;"," -webkit-background-clip: text; background-clip: text;")),s}function Go(s){try{var e=s.rules||s.cssRules;return e?fv(Array.from(e).map(Hu).join("")):null}catch{return null}}function Hu(s){var e=s.cssText;if(pv(s))try{e=Go(s.styleSheet)||e}catch{}return e}function pv(s){return"styleSheet"in s}var Vu=(function(){function s(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}return s.prototype.getId=function(e){var t;if(!e)return-1;var i=(t=this.getMeta(e))===null||t===void 0?void 0:t.id;return i??-1},s.prototype.getNode=function(e){return this.idNodeMap.get(e)||null},s.prototype.getIds=function(){return Array.from(this.idNodeMap.keys())},s.prototype.getMeta=function(e){return this.nodeMetaMap.get(e)||null},s.prototype.removeNodeFromMap=function(e){var t=this,i=this.getId(e);this.idNodeMap.delete(i),e.childNodes&&e.childNodes.forEach(function(r){return t.removeNodeFromMap(r)})},s.prototype.has=function(e){return this.idNodeMap.has(e)},s.prototype.hasNode=function(e){return this.nodeMetaMap.has(e)},s.prototype.add=function(e,t){var i=t.id;this.idNodeMap.set(i,e),this.nodeMetaMap.set(e,t)},s.prototype.replace=function(e,t){var i=this.getNode(e);if(i){var r=this.nodeMetaMap.get(i);r&&this.nodeMetaMap.set(t,r)}this.idNodeMap.set(e,t)},s.prototype.reset=function(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap},s})();function mv(){return new Vu}function Lo(s){var e=s.maskInputOptions,t=s.tagName,i=s.type,r=s.value,n=s.maskInputFn,o=r||"";return(e[t.toLowerCase()]||e[i])&&(n?o=n(o):o="*".repeat(o.length)),o}var zu="__rrweb_original__";function gv(s){var e=s.getContext("2d");if(!e)return!0;for(var t=50,i=0;i<s.width;i+=t)for(var r=0;r<s.height;r+=t){var n=e.getImageData,o=zu in n?n[zu]:n,a=new Uint32Array(o.call(e,i,r,Math.min(t,s.width-i),Math.min(t,s.height-r)).data.buffer);if(a.some(function(l){return l!==0}))return!1}return!0}var _v=1,yv=new RegExp("[^a-z0-9-_:]"),As=-2;function $u(){return _v++}function bv(s){if(s instanceof HTMLFormElement)return"form";var e=s.tagName.toLowerCase().trim();return yv.test(e)?"div":e}function xv(s){return s.cssRules?Array.from(s.cssRules).map(function(e){return e.cssText||""}).join(""):""}function vv(s){var e="";return s.indexOf("//")>-1?e=s.split("/").slice(0,3).join("/"):e=s.split("/")[0],e=e.split("?")[0],e}var Ui,ju,Cv=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,Sv=/^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/,Ev=/^(data:)([^,]*),(.*)/i;function br(s,e){return(s||"").replace(Cv,function(t,i,r,n,o,a){var l=r||o||a,c=i||n||"";if(!l)return t;if(!Sv.test(l)||Ev.test(l))return"url(".concat(c).concat(l).concat(c,")");if(l[0]==="/")return"url(".concat(c).concat(vv(e)+l).concat(c,")");var h=e.split("/"),u=l.split("/");h.pop();for(var f=0,d=u;f<d.length;f++){var g=d[f];g!=="."&&(g===".."?h.pop():h.push(g))}return"url(".concat(c).concat(h.join("/")).concat(c,")")})}var Tv=/^[^ \t\n\r\u000c]+/,Av=/^[, \t\n\r\u000c]+/;function wv(s,e){if(e.trim()==="")return e;var t=0;function i(c){var h,u=c.exec(e.substring(t));return u?(h=u[0],t+=h.length,h):""}for(var r=[];i(Av),!(t>=e.length);){var n=i(Tv);if(n.slice(-1)===",")n=Fi(s,n.substring(0,n.length-1)),r.push(n);else{var o="";n=Fi(s,n);for(var a=!1;;){var l=e.charAt(t);if(l===""){r.push((n+o).trim());break}else if(a)l===")"&&(a=!1);else if(l===","){t+=1,r.push((n+o).trim());break}else l==="("&&(a=!0);o+=l,t+=1}}}return r.join(", ")}function Fi(s,e){if(!e||e.trim()==="")return e;var t=s.createElement("a");return t.href=e,t.href}function Iv(s){return!!(s.tagName==="svg"||s.ownerSVGElement)}function Wo(){var s=document.createElement("a");return s.href="",s.href}function Xu(s,e,t,i){return t==="src"||t==="href"&&i&&!(e==="use"&&i[0]==="#")||t==="xlink:href"&&i&&i[0]!=="#"||t==="background"&&i&&(e==="table"||e==="td"||e==="th")?Fi(s,i):t==="srcset"&&i?wv(s,i):t==="style"&&i?br(i,Wo()):e==="object"&&t==="data"&&i?Fi(s,i):i}function Rv(s,e,t){if(typeof e=="string"){if(s.classList.contains(e))return!0}else for(var i=s.classList.length;i--;){var r=s.classList[i];if(e.test(r))return!0}return t?s.matches(t):!1}function xr(s,e,t){if(!s)return!1;if(s.nodeType!==s.ELEMENT_NODE)return t?xr(s.parentNode,e,t):!1;for(var i=s.classList.length;i--;){var r=s.classList[i];if(e.test(r))return!0}return t?xr(s.parentNode,e,t):!1}function Yu(s,e,t){var i=s.nodeType===s.ELEMENT_NODE?s:s.parentElement;if(i===null)return!1;if(typeof e=="string"){if(i.classList.contains(e)||i.closest(".".concat(e)))return!0}else if(xr(i,e,!0))return!0;return!!(t&&(i.matches(t)||i.closest(t)))}function Mv(s,e,t){var i=s.contentWindow;if(i){var r=!1,n;try{n=i.document.readyState}catch{return}if(n!=="complete"){var o=setTimeout(function(){r||(e(),r=!0)},t);s.addEventListener("load",function(){clearTimeout(o),r=!0,e()});return}var a="about:blank";if(i.location.href!==a||s.src===a||s.src==="")return setTimeout(e,0),s.addEventListener("load",e);s.addEventListener("load",e)}}function Pv(s,e,t){var i=!1,r;try{r=s.sheet}catch{return}if(!r){var n=setTimeout(function(){i||(e(),i=!0)},t);s.addEventListener("load",function(){clearTimeout(n),i=!0,e()})}}function kv(s,e){var t=e.doc,i=e.mirror,r=e.blockClass,n=e.blockSelector,o=e.maskTextClass,a=e.maskTextSelector,l=e.inlineStylesheet,c=e.maskInputOptions,h=c===void 0?{}:c,u=e.maskTextFn,f=e.maskInputFn,d=e.dataURLOptions,g=d===void 0?{}:d,_=e.inlineImages,b=e.recordCanvas,x=e.keepIframeSrcFn,C=e.newlyAddedElement,S=C===void 0?!1:C,E=Ov(t,i);switch(s.nodeType){case s.DOCUMENT_NODE:return s.compatMode!=="CSS1Compat"?{type:We.Document,childNodes:[],compatMode:s.compatMode}:{type:We.Document,childNodes:[]};case s.DOCUMENT_TYPE_NODE:return{type:We.DocumentType,name:s.name,publicId:s.publicId,systemId:s.systemId,rootId:E};case s.ELEMENT_NODE:return Dv(s,{doc:t,blockClass:r,blockSelector:n,inlineStylesheet:l,maskInputOptions:h,maskInputFn:f,dataURLOptions:g,inlineImages:_,recordCanvas:b,keepIframeSrcFn:x,newlyAddedElement:S,rootId:E});case s.TEXT_NODE:return Bv(s,{maskTextClass:o,maskTextSelector:a,maskTextFn:u,rootId:E});case s.CDATA_SECTION_NODE:return{type:We.CDATA,textContent:"",rootId:E};case s.COMMENT_NODE:return{type:We.Comment,textContent:s.textContent||"",rootId:E};default:return!1}}function Ov(s,e){if(e.hasNode(s)){var t=e.getId(s);return t===1?void 0:t}}function Bv(s,e){var t,i=e.maskTextClass,r=e.maskTextSelector,n=e.maskTextFn,o=e.rootId,a=s.parentNode&&s.parentNode.tagName,l=s.textContent,c=a==="STYLE"?!0:void 0,h=a==="SCRIPT"?!0:void 0;if(c&&l){try{s.nextSibling||s.previousSibling||!((t=s.parentNode.sheet)===null||t===void 0)&&t.cssRules&&(l=xv(s.parentNode.sheet))}catch(u){console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(u),s)}l=br(l,Wo())}return h&&(l="SCRIPT_PLACEHOLDER"),!c&&!h&&l&&Yu(s,i,r)&&(l=n?n(l):l.replace(/[\S]/g,"*")),{type:We.Text,textContent:l||"",isStyle:c,rootId:o}}function Dv(s,e){for(var t=e.doc,i=e.blockClass,r=e.blockSelector,n=e.inlineStylesheet,o=e.maskInputOptions,a=o===void 0?{}:o,l=e.maskInputFn,c=e.dataURLOptions,h=c===void 0?{}:c,u=e.inlineImages,f=e.recordCanvas,d=e.keepIframeSrcFn,g=e.newlyAddedElement,_=g===void 0?!1:g,b=e.rootId,x=Rv(s,i,r),C=bv(s),S={},E=s.attributes.length,w=0;w<E;w++){var R=s.attributes[w];S[R.name]=Xu(t,C,R.name,R.value)}if(C==="link"&&n){var M=Array.from(t.styleSheets).find(function(K){return K.href===s.href}),D=null;M&&(D=Go(M)),D&&(delete S.rel,delete S.href,S._cssText=br(D,M.href))}if(C==="style"&&s.sheet&&!(s.innerText||s.textContent||"").trim().length){var D=Go(s.sheet);D&&(S._cssText=br(D,Wo()))}if(C==="input"||C==="textarea"||C==="select"){var F=s.value,k=s.checked;S.type!=="radio"&&S.type!=="checkbox"&&S.type!=="submit"&&S.type!=="button"&&F?S.value=Lo({type:S.type,tagName:C,value:F,maskInputOptions:a,maskInputFn:l}):k&&(S.checked=k)}if(C==="option"&&(s.selected&&!a.select?S.selected=!0:delete S.selected),C==="canvas"&&f){if(s.__context==="2d")gv(s)||(S.rr_dataURL=s.toDataURL(h.type,h.quality));else if(!("__context"in s)){var O=s.toDataURL(h.type,h.quality),V=document.createElement("canvas");V.width=s.width,V.height=s.height;var X=V.toDataURL(h.type,h.quality);O!==X&&(S.rr_dataURL=O)}}if(C==="img"&&u){Ui||(Ui=t.createElement("canvas"),ju=Ui.getContext("2d"));var z=s,de=z.crossOrigin;z.crossOrigin="anonymous";var B=function(){try{Ui.width=z.naturalWidth,Ui.height=z.naturalHeight,ju.drawImage(z,0,0),S.rr_dataURL=Ui.toDataURL(h.type,h.quality)}catch(K){console.warn("Cannot inline img src=".concat(z.currentSrc,"! Error: ").concat(K))}de?S.crossOrigin=de:z.removeAttribute("crossorigin")};z.complete&&z.naturalWidth!==0?B():z.onload=B}if((C==="audio"||C==="video")&&(S.rr_mediaState=s.paused?"paused":"played",S.rr_mediaCurrentTime=s.currentTime),_||(s.scrollLeft&&(S.rr_scrollLeft=s.scrollLeft),s.scrollTop&&(S.rr_scrollTop=s.scrollTop)),x){var U=s.getBoundingClientRect(),q=U.width,N=U.height;S={class:S.class,rr_width:"".concat(q,"px"),rr_height:"".concat(N,"px")}}return C==="iframe"&&!d(S.src)&&(s.contentDocument||(S.rr_src=S.src),delete S.src),{type:We.Element,tagName:C,attributes:S,childNodes:[],isSVG:Iv(s)||void 0,needBlock:x,rootId:b}}function ve(s){return s===void 0?"":s.toLowerCase()}function Nv(s,e){if(e.comment&&s.type===We.Comment)return!0;if(s.type===We.Element){if(e.script&&(s.tagName==="script"||s.tagName==="link"&&s.attributes.rel==="preload"&&s.attributes.as==="script"||s.tagName==="link"&&s.attributes.rel==="prefetch"&&typeof s.attributes.href=="string"&&s.attributes.href.endsWith(".js")))return!0;if(e.headFavicon&&(s.tagName==="link"&&s.attributes.rel==="shortcut icon"||s.tagName==="meta"&&(ve(s.attributes.name).match(/^msapplication-tile(image|color)$/)||ve(s.attributes.name)==="application-name"||ve(s.attributes.rel)==="icon"||ve(s.attributes.rel)==="apple-touch-icon"||ve(s.attributes.rel)==="shortcut icon")))return!0;if(s.tagName==="meta"){if(e.headMetaDescKeywords&&ve(s.attributes.name).match(/^description|keywords$/))return!0;if(e.headMetaSocial&&(ve(s.attributes.property).match(/^(og|twitter|fb):/)||ve(s.attributes.name).match(/^(og|twitter):/)||ve(s.attributes.name)==="pinterest"))return!0;if(e.headMetaRobots&&(ve(s.attributes.name)==="robots"||ve(s.attributes.name)==="googlebot"||ve(s.attributes.name)==="bingbot"))return!0;if(e.headMetaHttpEquiv&&s.attributes["http-equiv"]!==void 0)return!0;if(e.headMetaAuthorship&&(ve(s.attributes.name)==="author"||ve(s.attributes.name)==="generator"||ve(s.attributes.name)==="framework"||ve(s.attributes.name)==="publisher"||ve(s.attributes.name)==="progid"||ve(s.attributes.property).match(/^article:/)||ve(s.attributes.property).match(/^product:/)))return!0;if(e.headMetaVerification&&(ve(s.attributes.name)==="google-site-verification"||ve(s.attributes.name)==="yandex-verification"||ve(s.attributes.name)==="csrf-token"||ve(s.attributes.name)==="p:domain_verify"||ve(s.attributes.name)==="verify-v1"||ve(s.attributes.name)==="verification"||ve(s.attributes.name)==="shopify-checkout-api-token"))return!0}}return!1}function Gi(s,e){var t=e.doc,i=e.mirror,r=e.blockClass,n=e.blockSelector,o=e.maskTextClass,a=e.maskTextSelector,l=e.skipChild,c=l===void 0?!1:l,h=e.inlineStylesheet,u=h===void 0?!0:h,f=e.maskInputOptions,d=f===void 0?{}:f,g=e.maskTextFn,_=e.maskInputFn,b=e.slimDOMOptions,x=e.dataURLOptions,C=x===void 0?{}:x,S=e.inlineImages,E=S===void 0?!1:S,w=e.recordCanvas,R=w===void 0?!1:w,M=e.onSerialize,D=e.onIframeLoad,F=e.iframeLoadTimeout,k=F===void 0?5e3:F,O=e.onStylesheetLoad,V=e.stylesheetLoadTimeout,X=V===void 0?5e3:V,z=e.keepIframeSrcFn,de=z===void 0?function(){return!1}:z,B=e.newlyAddedElement,U=B===void 0?!1:B,q=e.preserveWhiteSpace,N=q===void 0?!0:q,K=kv(s,{doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,dataURLOptions:C,inlineImages:E,recordCanvas:R,keepIframeSrcFn:de,newlyAddedElement:U});if(!K)return console.warn(s,"not serialized"),null;var Z;i.hasNode(s)?Z=i.getId(s):Nv(K,b)||!N&&K.type===We.Text&&!K.isStyle&&!K.textContent.replace(/^\s+|\s+$/gm,"").length?Z=As:Z=$u();var $=Object.assign(K,{id:Z});if(i.add(s,$),Z===As)return null;M&&M(s);var ae=!c;if($.type===We.Element){ae=ae&&!$.needBlock,delete $.needBlock;var Ce=s.shadowRoot;Ce&&Ts(Ce)&&($.isShadowHost=!0)}if(($.type===We.Document||$.type===We.Element)&&ae){b.headWhitespace&&$.type===We.Element&&$.tagName==="head"&&(N=!1);for(var Ee={doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:c,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de},G=0,fe=Array.from(s.childNodes);G<fe.length;G++){var le=fe[G],L=Gi(le,Ee);L&&$.childNodes.push(L)}if(dv(s)&&s.shadowRoot)for(var me=0,Y=Array.from(s.shadowRoot.childNodes);me<Y.length;me++){var le=Y[me],L=Gi(le,Ee);L&&(Ts(s.shadowRoot)&&(L.isShadow=!0),$.childNodes.push(L))}}return s.parentNode&&Es(s.parentNode)&&Ts(s.parentNode)&&($.isShadow=!0),$.type===We.Element&&$.tagName==="iframe"&&Mv(s,function(){var ie=s.contentDocument;if(ie&&D){var we=Gi(ie,{doc:ie,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});we&&D(s,we)}},k),$.type===We.Element&&$.tagName==="link"&&$.attributes.rel==="stylesheet"&&Pv(s,function(){if(O){var ie=Gi(s,{doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});ie&&O(s,ie)}},X),$}function Uv(s,e){var t=e||{},i=t.mirror,r=i===void 0?new Vu:i,n=t.blockClass,o=n===void 0?"rr-block":n,a=t.blockSelector,l=a===void 0?null:a,c=t.maskTextClass,h=c===void 0?"rr-mask":c,u=t.maskTextSelector,f=u===void 0?null:u,d=t.inlineStylesheet,g=d===void 0?!0:d,_=t.inlineImages,b=_===void 0?!1:_,x=t.recordCanvas,C=x===void 0?!1:x,S=t.maskAllInputs,E=S===void 0?!1:S,w=t.maskTextFn,R=t.maskInputFn,M=t.slimDOM,D=M===void 0?!1:M,F=t.dataURLOptions,k=t.preserveWhiteSpace,O=t.onSerialize,V=t.onIframeLoad,X=t.iframeLoadTimeout,z=t.onStylesheetLoad,de=t.stylesheetLoadTimeout,B=t.keepIframeSrcFn,U=B===void 0?function(){return!1}:B,q=E===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:E===!1?{password:!0}:E,N=D===!0||D==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:D==="all",headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:D===!1?{}:D;return Gi(s,{doc:s,mirror:r,blockClass:o,blockSelector:l,maskTextClass:h,maskTextSelector:f,skipChild:!1,inlineStylesheet:g,maskInputOptions:q,maskTextFn:w,maskInputFn:R,slimDOMOptions:N,dataURLOptions:F,inlineImages:b,recordCanvas:C,preserveWhiteSpace:k,onSerialize:O,onIframeLoad:V,iframeLoadTimeout:X,onStylesheetLoad:z,stylesheetLoadTimeout:de,keepIframeSrcFn:U,newlyAddedElement:!1})}function Ze(s,e,t=document){const i={capture:!0,passive:!0};return t.addEventListener(s,e,i),()=>t.removeEventListener(s,e,i)}const Li=`Please stop import mirror directly. Instead of that,\r
955
+ `,document.body.appendChild(this.videoElement),this.client.addListener(te.CONNECTION_ESTABLISHED,()=>{var i;console.log("[AnamSession] Connection established"),this._connected=!0,(i=this.onConnected)==null||i.call(this)}),this.client.addListener(te.VIDEO_PLAY_STARTED,()=>{var i;console.log("[AnamSession] Video playing"),this.videoElement&&(this.videoElement.style.display="",(i=this.onVideoReady)==null||i.call(this,this.videoElement))}),this.client.addListener(te.TALK_STREAM_INTERRUPTED,()=>{var i;console.log("[AnamSession] Talk stream interrupted"),(i=this.onTalkStreamInterrupted)==null||i.call(this)}),this.client.addListener(te.CONNECTION_CLOSED,i=>{var r;console.log("[AnamSession] Connection closed:",i),this._connected=!1,(r=this.onDisconnected)==null||r.call(this,String(i))}),await this.client.streamToVideoElement(t),this.audioInputStream=this.client.createAgentAudioInputStream({encoding:"pcm_s16le",sampleRate:24e3,channels:1}),console.log("[AnamSession] BYO audio input stream ready")}catch(t){const i=t instanceof Error?t:new Error(String(t));throw console.error("[AnamSession] Connection failed:",i.message),(e=this.onError)==null||e.call(this,i),this.close(),i}}sendAudioChunk(e){var t;(t=this.audioInputStream)==null||t.sendAudioChunk(e)}endSequence(){var e;(e=this.audioInputStream)==null||e.endSequence()}interrupt(){this.client.interruptPersona()}close(){if(!this._closing){this._closing=!0,console.log("[AnamSession] Closing...");try{this.client.stopStreaming()}catch{}this.videoElement&&(this.videoElement.pause(),this.videoElement.srcObject=null,this.videoElement.remove(),this.videoElement=null),document.querySelectorAll('video[id^="anam-avatar-video"]').forEach(e=>{e.pause(),e.remove()}),this.audioInputStream=null,this._connected=!1}}}const iv=new Set(["a","button","input","select","textarea","details","summary","label","option"]),sv=new Set(["button","link","menuitem","menuitemcheckbox","menuitemradio","tab","switch","slider","combobox","listbox","option","radio","checkbox","textbox","searchbox","scrollbar"]),rv=new Set(["h1","h2","h3","h4","h5","h6"]),nv=["type","role","aria-label","placeholder","value","href","alt","title","name","checked","aria-expanded"];class ov{constructor(){this.elementMap=new Map}analyze(){this.elementMap.clear();let e=0;const t=[];t.push(`Page: ${document.title}`),t.push(`URL: ${location.href}`),t.push("");const i=r=>{if(r.nodeType===Node.TEXT_NODE){const c=(r.textContent??"").trim();c&&c.length>1&&t.push(c);return}if(r.nodeType!==Node.ELEMENT_NODE)return;const n=r,o=n.tagName.toLowerCase();if(!this.isVisible(n)||["script","style","svg","noscript","link","meta"].includes(o)||n.id==="holostaff-widget-root"||n.closest("#holostaff-widget-root"))return;const a=this.isInteractive(n),l=rv.has(o);if(a||l){const c=e++;this.elementMap.set(c,n);const h=this.getUsefulAttrs(n),u=h?" "+h:"",f=this.getDirectText(n).slice(0,200);if(l){const d=parseInt(o[1]),g="#".repeat(d);t.push(""),t.push(`${g} [${c}]${f}`)}else t.push(`[${c}]<${o}${u}>${f}</${o}>`);return}for(const c of n.childNodes)i(c)};return i(document.body),{text:t.join(`
956
+ `),elementMap:this.elementMap}}getElementByIndex(e){return this.elementMap.get(e)??null}isVisible(e){const t=getComputedStyle(e);return!(t.display==="none"||t.visibility==="hidden")}isInteractive(e){const t=e.tagName.toLowerCase();if(iv.has(t))return!e.disabled;const i=e.getAttribute("role");if(i&&sv.has(i))return!0;try{if(getComputedStyle(e).cursor==="pointer")return!0}catch{}return!!(e.hasAttribute("tabindex")&&e.getAttribute("tabindex")!=="-1"||e.isContentEditable&&e.getAttribute("contenteditable")!=="false")}getDirectText(e){return(e.textContent??"").replace(/\s+/g," ").trim()}getUsefulAttrs(e){const t=[];for(const i of nv){const r=e.getAttribute(i);r&&r.length>0&&r.length<100&&t.push(`${i}="${r}"`)}return t.join(" ")}}const av=new Set(["scroll_to","click","highlight"]);class lv{constructor(e){this.onToolCall=null,this.onEndConversation=null,this.fnArgBufs=new Map,this.fnNames=new Map,this.fnCallIds=new Map,this.realtimeSession=e.realtimeSession,this.domAnalyzer=e.domAnalyzer,this.pageActions=e.pageActions,this.overlayActions=e.overlayActions,this.confirmationPrompt=e.confirmationPrompt,this.staffId=e.staffId,this.backendUrl=e.backendUrl,this.skills=e.skills??{}}handleMessage(e){var i;switch(e.type){case"response.output_item.added":if(((i=e.item)==null?void 0:i.type)==="function_call"){const r=e.item.id,n=e.item.name,o=e.item.call_id||e.item.id;return this.fnNames.set(r,n),this.fnCallIds.set(r,o),this.fnArgBufs.set(r,""),console.log(`[ToolHandler] Function call started: ${n} (${r})`),!0}return!1;case"response.function_call_arguments.delta":if(e.item_id&&this.fnArgBufs.has(e.item_id)){const r=this.fnArgBufs.get(e.item_id)??"";return this.fnArgBufs.set(e.item_id,r+(e.delta??"")),!0}return!1;case"response.function_call_arguments.done":return e.item_id&&this.fnArgBufs.has(e.item_id)?(this.handleFunctionCallDone(e.item_id),!0):!1;default:return!1}}async handleFunctionCallDone(e){var a;const t=this.fnNames.get(e)??"unknown",i=this.fnCallIds.get(e)??e,r=this.fnArgBufs.get(e)??"{}";this.fnArgBufs.delete(e),this.fnNames.delete(e),this.fnCallIds.delete(e);let n;try{n=JSON.parse(r)}catch{console.warn(`[ToolHandler] Failed to parse args for ${t}:`,r),this.sendToolResult(i,{error:"Malformed JSON in function call arguments"});return}console.log(`[ToolHandler] Executing: ${t}`,n),(a=this.onToolCall)==null||a.call(this,t,n);let o=null;switch(t){case"page_action":await this.handlePageAction(i,n.instruction??"");return;case"show_text_card":o=this.overlayActions.showTextCard(n.title??"",n.body??"");break;case"show_image_card":o=this.overlayActions.showImageCard(n.image_url??"",n.caption);break;case"show_bullet_list":o=this.overlayActions.showBulletList(n.title??"",n.items??[]);break;case"dismiss_overlays":o=this.overlayActions.dismissAll();break;case"get_skill_instructions":{const l=n.skill_name??"",c=this.skills[l];c?(console.log(`[ToolHandler] Serving skill instructions for "${l}" (${c.length} chars)`),o={instructions:c}):(console.warn(`[ToolHandler] Skill not found: "${l}". Available: ${Object.keys(this.skills).join(", ")}`),o={error:`No skill found with name "${l}". Available skills: ${Object.keys(this.skills).join(", ")}`});break}case"end_conversation":{const l=n.flag===!0,c=n.reason??"non_serious";console.log(`[ToolHandler] end_conversation requested (flag=${l}, reason="${c}")`),o={acknowledged:!0},setTimeout(()=>{var h;return(h=this.onEndConversation)==null?void 0:h.call(this,l,c)},0);break}default:console.warn(`[ToolHandler] Unknown tool: ${t}`),o={error:`Unknown tool: ${t}`}}this.sendToolResult(i,o)}async handlePageAction(e,t){try{const i=t.toLowerCase();if(i.includes("scroll")&&(i.includes("top")||i.includes("beginning"))){const l=this.pageActions.scrollTo(-1);this.sendToolResult(e,{results:[{action:"scroll_to",...l}]});return}if(i.includes("scroll")&&(i.includes("bottom")||i.includes("end"))){const l=this.pageActions.scrollTo(-2);this.sendToolResult(e,{results:[{action:"scroll_to",...l}]});return}const{text:r}=this.domAnalyzer.analyze();console.log(`[ToolHandler] DOM snapshot: ${r.length} chars, instruction: "${t}"`);const o=(await Ff(this.staffId,r,t,this.backendUrl)).actions??[];console.log(`[ToolHandler] Page agent returned ${o.length} actions:`,o);const a=[];for(const l of o){if(l.action==="describe"){a.push({action:"describe",status:"ok",description:l.description});continue}if(av.has(l.action)&&!await this.confirmationPrompt.ask(`${l.description}?`)){a.push({action:l.action,status:"declined",description:"Visitor declined"});continue}let c;switch(l.action){case"scroll_to":c=this.pageActions.scrollTo(l.index);break;case"highlight":c=this.pageActions.highlight(l.index);break;case"click":c=this.pageActions.click(l.index);break;case"fill":c=this.pageActions.fill(l.index,l.value??"");break;default:c={status:"error",description:`Unknown action: ${l.action}`}}a.push({action:l.action,...c})}this.sendToolResult(e,{results:a})}catch(i){const r=i instanceof Error?i.message:String(i);console.error("[ToolHandler] Page action failed:",r),this.sendToolResult(e,{error:r})}}sendToolResult(e,t){this.realtimeSession.sendJSON({type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(t)}}),this.realtimeSession.sendJSON({type:"response.create"})}}class cv{constructor(e,t){this.analyzer=e,this.highlightRenderer=t}scrollTo(e){if(e===-1)return window.scrollTo({top:0,behavior:"smooth"}),document.documentElement.scrollTop=0,document.body.scrollTop=0,console.log("[PageActions] Scrolled to top"),{status:"scrolled",description:"Top of page"};if(e===-2)return window.scrollTo({top:document.body.scrollHeight,behavior:"smooth"}),console.log("[PageActions] Scrolled to bottom"),{status:"scrolled",description:"Bottom of page"};const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.scrollIntoView({behavior:"smooth",block:"center"});let i=t.parentElement;for(;i;){const n=getComputedStyle(i).overflowY;if(n==="auto"||n==="scroll"){const o=t.getBoundingClientRect().top-i.getBoundingClientRect().top+i.scrollTop;i.scrollTo({top:o-i.clientHeight/2,behavior:"smooth"});break}i=i.parentElement}const r=this.describeElement(t);return console.log(`[PageActions] Scrolled to [${e}] ${r}`),{status:"scrolled",description:r}}highlight(e,t=3e3){const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};this.highlightRenderer.highlight(i,t);const r=this.describeElement(i);return console.log(`[PageActions] Highlighting [${e}] ${r} for ${t}ms`),{status:"highlighted",description:r}}click(e){const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.click();const i=this.describeElement(t);return console.log(`[PageActions] Clicked [${e}] ${i}`),{status:"clicked",description:i}}fill(e,t){var a,l;const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};const r=i.tagName.toLowerCase(),n=(a=i.type)==null?void 0:a.toLowerCase();if(r==="select"){const c=i,h=Array.from(c.options).find(u=>u.text.toLowerCase().includes(t.toLowerCase())||u.value.toLowerCase()===t.toLowerCase());if(h)c.value=h.value,c.dispatchEvent(new Event("change",{bubbles:!0}));else return{status:"error",description:`No option matching "${t}"`}}else if(n==="checkbox"||n==="radio"){const c=i;c.checked=t==="true"||t==="1",c.dispatchEvent(new Event("change",{bubbles:!0}))}else{const c=(l=Object.getOwnPropertyDescriptor(r==="textarea"?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value"))==null?void 0:l.set;c?c.call(i,t):i.value=t,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0}))}const o=this.describeElement(i);return console.log(`[PageActions] Filled [${e}] ${o} with "${t}"`),{status:"filled",description:`${o} = "${t}"`}}describeElement(e){const t=e.tagName.toLowerCase(),i=(e.textContent??"").trim().slice(0,50),r=e.getAttribute("aria-label")||e.getAttribute("placeholder")||i;return`<${t}>${r}</${t}>`}}class hv{constructor(e){this.renderer=e}showTextCard(e,t){return this.renderer.showTextCard(e,t),console.log(`[OverlayActions] Showing text card: "${e}"`),{status:"shown"}}showImageCard(e,t){return this.renderer.showImageCard(e,t),console.log(`[OverlayActions] Showing image card: "${t??e}"`),{status:"shown"}}showBulletList(e,t){return this.renderer.showBulletList(e,t),console.log(`[OverlayActions] Showing bullet list: "${e}" (${t.length} items)`),{status:"shown"}}dismissAll(){return this.renderer.dismissAll(),console.log("[OverlayActions] Dismissed all overlays"),{status:"dismissed"}}}const uv="https://us-central1-holostaff-ai.cloudfunctions.net";class dv{constructor(e){this.messages={},this.actions=[],this.msgCounter=0,this.staffId=e.staffId,this.staffName=e.staffName,this.backendUrl=e.backendUrl??uv,this.startTime=new Date().toISOString(),this.userId=`visitor_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}addUserMessage(e){if(!e.trim())return;const t=`msg_${this.msgCounter++}`;this.messages[t]={sender:"user",text:e.trim(),timestamp:new Date().toISOString()}}addStaffMessage(e){if(!e.trim())return;const t=`msg_${this.msgCounter++}`;this.messages[t]={sender:"staff",text:e.trim(),timestamp:new Date().toISOString()}}addAction(e,t){this.actions.push({tool:e,args:t,timestamp:new Date().toISOString()})}getSummary(){const e=Object.values(this.messages);return e.length===0?"No conversation took place.":e.slice(-6).map(i=>`${i.sender==="user"?"User":"Agent"}: ${i.text.slice(0,80)}`).join(" | ")}async flush(){if(Object.keys(this.messages).length===0){console.log("[Logger] No messages to log, skipping");return}const e=Object.values(this.messages).pop(),t={staffId:this.staffId,staffName:this.staffName,userId:this.userId,startTime:this.startTime,lastMessageAt:(e==null?void 0:e.timestamp)??this.startTime,messages:this.messages,actions:this.actions,source:"widget_v2"};console.log("[Logger] Flushing conversation log:",{messages:Object.keys(this.messages).length,actions:this.actions.length});const i=`${this.backendUrl}/logConversation`,r=JSON.stringify(t);try{const n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!0});if(n.ok){const o=await n.json();console.log("[Logger] Conversation logged:",o.id)}else console.warn("[Logger] Failed to log conversation:",n.status)}catch(n){console.warn("[Logger] Error logging conversation:",n)}}}var We;(function(s){s[s.Document=0]="Document",s[s.DocumentType=1]="DocumentType",s[s.Element=2]="Element",s[s.Text=3]="Text",s[s.CDATA=4]="CDATA",s[s.Comment=5]="Comment"})(We||(We={}));function fv(s){return s.nodeType===s.ELEMENT_NODE}function Es(s){var e=s==null?void 0:s.host;return(e==null?void 0:e.shadowRoot)===s}function Ts(s){return Object.prototype.toString.call(s)==="[object ShadowRoot]"}function pv(s){return s.includes(" background-clip: text;")&&!s.includes(" -webkit-background-clip: text;")&&(s=s.replace(" background-clip: text;"," -webkit-background-clip: text; background-clip: text;")),s}function Go(s){try{var e=s.rules||s.cssRules;return e?pv(Array.from(e).map(Hu).join("")):null}catch{return null}}function Hu(s){var e=s.cssText;if(mv(s))try{e=Go(s.styleSheet)||e}catch{}return e}function mv(s){return"styleSheet"in s}var Vu=(function(){function s(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}return s.prototype.getId=function(e){var t;if(!e)return-1;var i=(t=this.getMeta(e))===null||t===void 0?void 0:t.id;return i??-1},s.prototype.getNode=function(e){return this.idNodeMap.get(e)||null},s.prototype.getIds=function(){return Array.from(this.idNodeMap.keys())},s.prototype.getMeta=function(e){return this.nodeMetaMap.get(e)||null},s.prototype.removeNodeFromMap=function(e){var t=this,i=this.getId(e);this.idNodeMap.delete(i),e.childNodes&&e.childNodes.forEach(function(r){return t.removeNodeFromMap(r)})},s.prototype.has=function(e){return this.idNodeMap.has(e)},s.prototype.hasNode=function(e){return this.nodeMetaMap.has(e)},s.prototype.add=function(e,t){var i=t.id;this.idNodeMap.set(i,e),this.nodeMetaMap.set(e,t)},s.prototype.replace=function(e,t){var i=this.getNode(e);if(i){var r=this.nodeMetaMap.get(i);r&&this.nodeMetaMap.set(t,r)}this.idNodeMap.set(e,t)},s.prototype.reset=function(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap},s})();function gv(){return new Vu}function Lo(s){var e=s.maskInputOptions,t=s.tagName,i=s.type,r=s.value,n=s.maskInputFn,o=r||"";return(e[t.toLowerCase()]||e[i])&&(n?o=n(o):o="*".repeat(o.length)),o}var zu="__rrweb_original__";function _v(s){var e=s.getContext("2d");if(!e)return!0;for(var t=50,i=0;i<s.width;i+=t)for(var r=0;r<s.height;r+=t){var n=e.getImageData,o=zu in n?n[zu]:n,a=new Uint32Array(o.call(e,i,r,Math.min(t,s.width-i),Math.min(t,s.height-r)).data.buffer);if(a.some(function(l){return l!==0}))return!1}return!0}var yv=1,bv=new RegExp("[^a-z0-9-_:]"),As=-2;function $u(){return yv++}function xv(s){if(s instanceof HTMLFormElement)return"form";var e=s.tagName.toLowerCase().trim();return bv.test(e)?"div":e}function vv(s){return s.cssRules?Array.from(s.cssRules).map(function(e){return e.cssText||""}).join(""):""}function Cv(s){var e="";return s.indexOf("//")>-1?e=s.split("/").slice(0,3).join("/"):e=s.split("/")[0],e=e.split("?")[0],e}var Ui,ju,Sv=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,Ev=/^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/,Tv=/^(data:)([^,]*),(.*)/i;function xr(s,e){return(s||"").replace(Sv,function(t,i,r,n,o,a){var l=r||o||a,c=i||n||"";if(!l)return t;if(!Ev.test(l)||Tv.test(l))return"url(".concat(c).concat(l).concat(c,")");if(l[0]==="/")return"url(".concat(c).concat(Cv(e)+l).concat(c,")");var h=e.split("/"),u=l.split("/");h.pop();for(var f=0,d=u;f<d.length;f++){var g=d[f];g!=="."&&(g===".."?h.pop():h.push(g))}return"url(".concat(c).concat(h.join("/")).concat(c,")")})}var Av=/^[^ \t\n\r\u000c]+/,wv=/^[, \t\n\r\u000c]+/;function Iv(s,e){if(e.trim()==="")return e;var t=0;function i(c){var h,u=c.exec(e.substring(t));return u?(h=u[0],t+=h.length,h):""}for(var r=[];i(wv),!(t>=e.length);){var n=i(Av);if(n.slice(-1)===",")n=Fi(s,n.substring(0,n.length-1)),r.push(n);else{var o="";n=Fi(s,n);for(var a=!1;;){var l=e.charAt(t);if(l===""){r.push((n+o).trim());break}else if(a)l===")"&&(a=!1);else if(l===","){t+=1,r.push((n+o).trim());break}else l==="("&&(a=!0);o+=l,t+=1}}}return r.join(", ")}function Fi(s,e){if(!e||e.trim()==="")return e;var t=s.createElement("a");return t.href=e,t.href}function Rv(s){return!!(s.tagName==="svg"||s.ownerSVGElement)}function Wo(){var s=document.createElement("a");return s.href="",s.href}function Xu(s,e,t,i){return t==="src"||t==="href"&&i&&!(e==="use"&&i[0]==="#")||t==="xlink:href"&&i&&i[0]!=="#"||t==="background"&&i&&(e==="table"||e==="td"||e==="th")?Fi(s,i):t==="srcset"&&i?Iv(s,i):t==="style"&&i?xr(i,Wo()):e==="object"&&t==="data"&&i?Fi(s,i):i}function Mv(s,e,t){if(typeof e=="string"){if(s.classList.contains(e))return!0}else for(var i=s.classList.length;i--;){var r=s.classList[i];if(e.test(r))return!0}return t?s.matches(t):!1}function vr(s,e,t){if(!s)return!1;if(s.nodeType!==s.ELEMENT_NODE)return t?vr(s.parentNode,e,t):!1;for(var i=s.classList.length;i--;){var r=s.classList[i];if(e.test(r))return!0}return t?vr(s.parentNode,e,t):!1}function Yu(s,e,t){var i=s.nodeType===s.ELEMENT_NODE?s:s.parentElement;if(i===null)return!1;if(typeof e=="string"){if(i.classList.contains(e)||i.closest(".".concat(e)))return!0}else if(vr(i,e,!0))return!0;return!!(t&&(i.matches(t)||i.closest(t)))}function Pv(s,e,t){var i=s.contentWindow;if(i){var r=!1,n;try{n=i.document.readyState}catch{return}if(n!=="complete"){var o=setTimeout(function(){r||(e(),r=!0)},t);s.addEventListener("load",function(){clearTimeout(o),r=!0,e()});return}var a="about:blank";if(i.location.href!==a||s.src===a||s.src==="")return setTimeout(e,0),s.addEventListener("load",e);s.addEventListener("load",e)}}function kv(s,e,t){var i=!1,r;try{r=s.sheet}catch{return}if(!r){var n=setTimeout(function(){i||(e(),i=!0)},t);s.addEventListener("load",function(){clearTimeout(n),i=!0,e()})}}function Ov(s,e){var t=e.doc,i=e.mirror,r=e.blockClass,n=e.blockSelector,o=e.maskTextClass,a=e.maskTextSelector,l=e.inlineStylesheet,c=e.maskInputOptions,h=c===void 0?{}:c,u=e.maskTextFn,f=e.maskInputFn,d=e.dataURLOptions,g=d===void 0?{}:d,_=e.inlineImages,y=e.recordCanvas,x=e.keepIframeSrcFn,C=e.newlyAddedElement,S=C===void 0?!1:C,E=Bv(t,i);switch(s.nodeType){case s.DOCUMENT_NODE:return s.compatMode!=="CSS1Compat"?{type:We.Document,childNodes:[],compatMode:s.compatMode}:{type:We.Document,childNodes:[]};case s.DOCUMENT_TYPE_NODE:return{type:We.DocumentType,name:s.name,publicId:s.publicId,systemId:s.systemId,rootId:E};case s.ELEMENT_NODE:return Nv(s,{doc:t,blockClass:r,blockSelector:n,inlineStylesheet:l,maskInputOptions:h,maskInputFn:f,dataURLOptions:g,inlineImages:_,recordCanvas:y,keepIframeSrcFn:x,newlyAddedElement:S,rootId:E});case s.TEXT_NODE:return Dv(s,{maskTextClass:o,maskTextSelector:a,maskTextFn:u,rootId:E});case s.CDATA_SECTION_NODE:return{type:We.CDATA,textContent:"",rootId:E};case s.COMMENT_NODE:return{type:We.Comment,textContent:s.textContent||"",rootId:E};default:return!1}}function Bv(s,e){if(e.hasNode(s)){var t=e.getId(s);return t===1?void 0:t}}function Dv(s,e){var t,i=e.maskTextClass,r=e.maskTextSelector,n=e.maskTextFn,o=e.rootId,a=s.parentNode&&s.parentNode.tagName,l=s.textContent,c=a==="STYLE"?!0:void 0,h=a==="SCRIPT"?!0:void 0;if(c&&l){try{s.nextSibling||s.previousSibling||!((t=s.parentNode.sheet)===null||t===void 0)&&t.cssRules&&(l=vv(s.parentNode.sheet))}catch(u){console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(u),s)}l=xr(l,Wo())}return h&&(l="SCRIPT_PLACEHOLDER"),!c&&!h&&l&&Yu(s,i,r)&&(l=n?n(l):l.replace(/[\S]/g,"*")),{type:We.Text,textContent:l||"",isStyle:c,rootId:o}}function Nv(s,e){for(var t=e.doc,i=e.blockClass,r=e.blockSelector,n=e.inlineStylesheet,o=e.maskInputOptions,a=o===void 0?{}:o,l=e.maskInputFn,c=e.dataURLOptions,h=c===void 0?{}:c,u=e.inlineImages,f=e.recordCanvas,d=e.keepIframeSrcFn,g=e.newlyAddedElement,_=g===void 0?!1:g,y=e.rootId,x=Mv(s,i,r),C=xv(s),S={},E=s.attributes.length,w=0;w<E;w++){var R=s.attributes[w];S[R.name]=Xu(t,C,R.name,R.value)}if(C==="link"&&n){var M=Array.from(t.styleSheets).find(function(K){return K.href===s.href}),D=null;M&&(D=Go(M)),D&&(delete S.rel,delete S.href,S._cssText=xr(D,M.href))}if(C==="style"&&s.sheet&&!(s.innerText||s.textContent||"").trim().length){var D=Go(s.sheet);D&&(S._cssText=xr(D,Wo()))}if(C==="input"||C==="textarea"||C==="select"){var F=s.value,k=s.checked;S.type!=="radio"&&S.type!=="checkbox"&&S.type!=="submit"&&S.type!=="button"&&F?S.value=Lo({type:S.type,tagName:C,value:F,maskInputOptions:a,maskInputFn:l}):k&&(S.checked=k)}if(C==="option"&&(s.selected&&!a.select?S.selected=!0:delete S.selected),C==="canvas"&&f){if(s.__context==="2d")_v(s)||(S.rr_dataURL=s.toDataURL(h.type,h.quality));else if(!("__context"in s)){var O=s.toDataURL(h.type,h.quality),V=document.createElement("canvas");V.width=s.width,V.height=s.height;var X=V.toDataURL(h.type,h.quality);O!==X&&(S.rr_dataURL=O)}}if(C==="img"&&u){Ui||(Ui=t.createElement("canvas"),ju=Ui.getContext("2d"));var z=s,de=z.crossOrigin;z.crossOrigin="anonymous";var B=function(){try{Ui.width=z.naturalWidth,Ui.height=z.naturalHeight,ju.drawImage(z,0,0),S.rr_dataURL=Ui.toDataURL(h.type,h.quality)}catch(K){console.warn("Cannot inline img src=".concat(z.currentSrc,"! Error: ").concat(K))}de?S.crossOrigin=de:z.removeAttribute("crossorigin")};z.complete&&z.naturalWidth!==0?B():z.onload=B}if((C==="audio"||C==="video")&&(S.rr_mediaState=s.paused?"paused":"played",S.rr_mediaCurrentTime=s.currentTime),_||(s.scrollLeft&&(S.rr_scrollLeft=s.scrollLeft),s.scrollTop&&(S.rr_scrollTop=s.scrollTop)),x){var U=s.getBoundingClientRect(),q=U.width,N=U.height;S={class:S.class,rr_width:"".concat(q,"px"),rr_height:"".concat(N,"px")}}return C==="iframe"&&!d(S.src)&&(s.contentDocument||(S.rr_src=S.src),delete S.src),{type:We.Element,tagName:C,attributes:S,childNodes:[],isSVG:Rv(s)||void 0,needBlock:x,rootId:y}}function ve(s){return s===void 0?"":s.toLowerCase()}function Uv(s,e){if(e.comment&&s.type===We.Comment)return!0;if(s.type===We.Element){if(e.script&&(s.tagName==="script"||s.tagName==="link"&&s.attributes.rel==="preload"&&s.attributes.as==="script"||s.tagName==="link"&&s.attributes.rel==="prefetch"&&typeof s.attributes.href=="string"&&s.attributes.href.endsWith(".js")))return!0;if(e.headFavicon&&(s.tagName==="link"&&s.attributes.rel==="shortcut icon"||s.tagName==="meta"&&(ve(s.attributes.name).match(/^msapplication-tile(image|color)$/)||ve(s.attributes.name)==="application-name"||ve(s.attributes.rel)==="icon"||ve(s.attributes.rel)==="apple-touch-icon"||ve(s.attributes.rel)==="shortcut icon")))return!0;if(s.tagName==="meta"){if(e.headMetaDescKeywords&&ve(s.attributes.name).match(/^description|keywords$/))return!0;if(e.headMetaSocial&&(ve(s.attributes.property).match(/^(og|twitter|fb):/)||ve(s.attributes.name).match(/^(og|twitter):/)||ve(s.attributes.name)==="pinterest"))return!0;if(e.headMetaRobots&&(ve(s.attributes.name)==="robots"||ve(s.attributes.name)==="googlebot"||ve(s.attributes.name)==="bingbot"))return!0;if(e.headMetaHttpEquiv&&s.attributes["http-equiv"]!==void 0)return!0;if(e.headMetaAuthorship&&(ve(s.attributes.name)==="author"||ve(s.attributes.name)==="generator"||ve(s.attributes.name)==="framework"||ve(s.attributes.name)==="publisher"||ve(s.attributes.name)==="progid"||ve(s.attributes.property).match(/^article:/)||ve(s.attributes.property).match(/^product:/)))return!0;if(e.headMetaVerification&&(ve(s.attributes.name)==="google-site-verification"||ve(s.attributes.name)==="yandex-verification"||ve(s.attributes.name)==="csrf-token"||ve(s.attributes.name)==="p:domain_verify"||ve(s.attributes.name)==="verify-v1"||ve(s.attributes.name)==="verification"||ve(s.attributes.name)==="shopify-checkout-api-token"))return!0}}return!1}function Gi(s,e){var t=e.doc,i=e.mirror,r=e.blockClass,n=e.blockSelector,o=e.maskTextClass,a=e.maskTextSelector,l=e.skipChild,c=l===void 0?!1:l,h=e.inlineStylesheet,u=h===void 0?!0:h,f=e.maskInputOptions,d=f===void 0?{}:f,g=e.maskTextFn,_=e.maskInputFn,y=e.slimDOMOptions,x=e.dataURLOptions,C=x===void 0?{}:x,S=e.inlineImages,E=S===void 0?!1:S,w=e.recordCanvas,R=w===void 0?!1:w,M=e.onSerialize,D=e.onIframeLoad,F=e.iframeLoadTimeout,k=F===void 0?5e3:F,O=e.onStylesheetLoad,V=e.stylesheetLoadTimeout,X=V===void 0?5e3:V,z=e.keepIframeSrcFn,de=z===void 0?function(){return!1}:z,B=e.newlyAddedElement,U=B===void 0?!1:B,q=e.preserveWhiteSpace,N=q===void 0?!0:q,K=Ov(s,{doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,dataURLOptions:C,inlineImages:E,recordCanvas:R,keepIframeSrcFn:de,newlyAddedElement:U});if(!K)return console.warn(s,"not serialized"),null;var Z;i.hasNode(s)?Z=i.getId(s):Uv(K,y)||!N&&K.type===We.Text&&!K.isStyle&&!K.textContent.replace(/^\s+|\s+$/gm,"").length?Z=As:Z=$u();var $=Object.assign(K,{id:Z});if(i.add(s,$),Z===As)return null;M&&M(s);var ae=!c;if($.type===We.Element){ae=ae&&!$.needBlock,delete $.needBlock;var Ce=s.shadowRoot;Ce&&Ts(Ce)&&($.isShadowHost=!0)}if(($.type===We.Document||$.type===We.Element)&&ae){y.headWhitespace&&$.type===We.Element&&$.tagName==="head"&&(N=!1);for(var Ee={doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:c,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:y,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de},G=0,fe=Array.from(s.childNodes);G<fe.length;G++){var le=fe[G],L=Gi(le,Ee);L&&$.childNodes.push(L)}if(fv(s)&&s.shadowRoot)for(var me=0,Y=Array.from(s.shadowRoot.childNodes);me<Y.length;me++){var le=Y[me],L=Gi(le,Ee);L&&(Ts(s.shadowRoot)&&(L.isShadow=!0),$.childNodes.push(L))}}return s.parentNode&&Es(s.parentNode)&&Ts(s.parentNode)&&($.isShadow=!0),$.type===We.Element&&$.tagName==="iframe"&&Pv(s,function(){var ie=s.contentDocument;if(ie&&D){var we=Gi(ie,{doc:ie,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:y,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});we&&D(s,we)}},k),$.type===We.Element&&$.tagName==="link"&&$.attributes.rel==="stylesheet"&&kv(s,function(){if(O){var ie=Gi(s,{doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:y,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});ie&&O(s,ie)}},X),$}function Fv(s,e){var t=e||{},i=t.mirror,r=i===void 0?new Vu:i,n=t.blockClass,o=n===void 0?"rr-block":n,a=t.blockSelector,l=a===void 0?null:a,c=t.maskTextClass,h=c===void 0?"rr-mask":c,u=t.maskTextSelector,f=u===void 0?null:u,d=t.inlineStylesheet,g=d===void 0?!0:d,_=t.inlineImages,y=_===void 0?!1:_,x=t.recordCanvas,C=x===void 0?!1:x,S=t.maskAllInputs,E=S===void 0?!1:S,w=t.maskTextFn,R=t.maskInputFn,M=t.slimDOM,D=M===void 0?!1:M,F=t.dataURLOptions,k=t.preserveWhiteSpace,O=t.onSerialize,V=t.onIframeLoad,X=t.iframeLoadTimeout,z=t.onStylesheetLoad,de=t.stylesheetLoadTimeout,B=t.keepIframeSrcFn,U=B===void 0?function(){return!1}:B,q=E===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:E===!1?{password:!0}:E,N=D===!0||D==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:D==="all",headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:D===!1?{}:D;return Gi(s,{doc:s,mirror:r,blockClass:o,blockSelector:l,maskTextClass:h,maskTextSelector:f,skipChild:!1,inlineStylesheet:g,maskInputOptions:q,maskTextFn:w,maskInputFn:R,slimDOMOptions:N,dataURLOptions:F,inlineImages:y,recordCanvas:C,preserveWhiteSpace:k,onSerialize:O,onIframeLoad:V,iframeLoadTimeout:X,onStylesheetLoad:z,stylesheetLoadTimeout:de,keepIframeSrcFn:U,newlyAddedElement:!1})}function Ze(s,e,t=document){const i={capture:!0,passive:!0};return t.addEventListener(s,e,i),()=>t.removeEventListener(s,e,i)}const Li=`Please stop import mirror directly. Instead of that,\r
957
957
  now you can use replayer.getMirror() to access the mirror instance of a replayer,\r
958
- or you can use record.mirror to access the mirror instance during recording.`;let qu={map:{},getId(){return console.error(Li),-1},getNode(){return console.error(Li),null},removeNodeFromMap(){console.error(Li)},has(){return console.error(Li),!1},reset(){console.error(Li)}};typeof window<"u"&&window.Proxy&&window.Reflect&&(qu=new Proxy(qu,{get(s,e,t){return e==="map"&&console.error(Li),Reflect.get(s,e,t)}}));function ws(s,e,t={}){let i=null,r=0;return function(...n){const o=Date.now();!r&&t.leading===!1&&(r=o);const a=e-(o-r),l=this;a<=0||a>e?(i&&(clearTimeout(i),i=null),r=o,s.apply(l,n)):!i&&t.trailing!==!1&&(i=setTimeout(()=>{r=t.leading===!1?0:Date.now(),i=null,s.apply(l,n)},a))}}function vr(s,e,t,i,r=window){const n=r.Object.getOwnPropertyDescriptor(s,e);return r.Object.defineProperty(s,e,i?t:{set(o){setTimeout(()=>{t.set.call(this,o)},0),n&&n.set&&n.set.call(this,o)}}),()=>vr(s,e,n||{},!0)}function Wi(s,e,t){try{if(!(e in s))return()=>{};const i=s[e],r=t(i);return typeof r=="function"&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__rrweb_original__:{enumerable:!1,value:i}})),s[e]=r,()=>{s[e]=i}}catch{return()=>{}}}function Ku(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Zu(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Je(s,e,t,i){if(!s)return!1;const r=s.nodeType===s.ELEMENT_NODE?s:s.parentElement;if(!r)return!1;if(typeof e=="string"){if(r.classList.contains(e)||i&&r.closest("."+e)!==null)return!0}else if(xr(r,e,i))return!0;return!!(t&&(s.matches(t)||i&&r.closest(t)!==null))}function Fv(s,e){return e.getId(s)!==-1}function Ho(s,e){return e.getId(s)===As}function Ju(s,e){if(Es(s))return!1;const t=e.getId(s);return e.has(t)?s.parentNode&&s.parentNode.nodeType===s.DOCUMENT_NODE?!1:s.parentNode?Ju(s.parentNode,e):!0:!0}function Qu(s){return!!s.changedTouches}function Gv(s=window){"NodeList"in s&&!s.NodeList.prototype.forEach&&(s.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in s&&!s.DOMTokenList.prototype.forEach&&(s.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=(...e)=>{let t=e[0];if(!(0 in e))throw new TypeError("1 argument is required");do if(this===t)return!0;while(t=t&&t.parentNode);return!1})}function ed(s,e){return!!(s.nodeName==="IFRAME"&&e.getMeta(s))}function td(s,e){return!!(s.nodeName==="LINK"&&s.nodeType===s.ELEMENT_NODE&&s.getAttribute&&s.getAttribute("rel")==="stylesheet"&&e.getMeta(s))}function id(s){return!!(s!=null&&s.shadowRoot)}class Lv{constructor(){this.id=1,this.styleIDMap=new WeakMap,this.idStyleMap=new Map}getId(e){var t;return(t=this.styleIDMap.get(e))!==null&&t!==void 0?t:-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let i;return t===void 0?i=this.id++:i=t,this.styleIDMap.set(e,i),this.idStyleMap.set(i,e),i}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}var ue=(s=>(s[s.DomContentLoaded=0]="DomContentLoaded",s[s.Load=1]="Load",s[s.FullSnapshot=2]="FullSnapshot",s[s.IncrementalSnapshot=3]="IncrementalSnapshot",s[s.Meta=4]="Meta",s[s.Custom=5]="Custom",s[s.Plugin=6]="Plugin",s))(ue||{}),oe=(s=>(s[s.Mutation=0]="Mutation",s[s.MouseMove=1]="MouseMove",s[s.MouseInteraction=2]="MouseInteraction",s[s.Scroll=3]="Scroll",s[s.ViewportResize=4]="ViewportResize",s[s.Input=5]="Input",s[s.TouchMove=6]="TouchMove",s[s.MediaInteraction=7]="MediaInteraction",s[s.StyleSheetRule=8]="StyleSheetRule",s[s.CanvasMutation=9]="CanvasMutation",s[s.Font=10]="Font",s[s.Log=11]="Log",s[s.Drag=12]="Drag",s[s.StyleDeclaration=13]="StyleDeclaration",s[s.Selection=14]="Selection",s[s.AdoptedStyleSheet=15]="AdoptedStyleSheet",s))(oe||{}),Vo=(s=>(s[s.MouseUp=0]="MouseUp",s[s.MouseDown=1]="MouseDown",s[s.Click=2]="Click",s[s.ContextMenu=3]="ContextMenu",s[s.DblClick=4]="DblClick",s[s.Focus=5]="Focus",s[s.Blur=6]="Blur",s[s.TouchStart=7]="TouchStart",s[s.TouchMove_Departed=8]="TouchMove_Departed",s[s.TouchEnd=9]="TouchEnd",s[s.TouchCancel=10]="TouchCancel",s))(Vo||{}),Hi=(s=>(s[s["2D"]=0]="2D",s[s.WebGL=1]="WebGL",s[s.WebGL2=2]="WebGL2",s))(Hi||{});function sd(s){return"__ln"in s}class Wv{constructor(){this.length=0,this.head=null}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let i=0;i<e;i++)t=(t==null?void 0:t.next)||null;return t}addNode(e){const t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&sd(e.previousSibling)){const i=e.previousSibling.__ln.next;t.next=i,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,i&&(i.previous=t)}else if(e.nextSibling&&sd(e.nextSibling)&&e.nextSibling.__ln.previous){const i=e.nextSibling.__ln.previous;t.previous=i,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,i&&(i.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;this.length++}removeNode(e){const t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next&&(t.next.previous=t.previous)):(this.head=t.next,this.head&&(this.head.previous=null)),e.__ln&&delete e.__ln,this.length--)}}const rd=(s,e)=>`${s}@${e}`;class Hv{constructor(){this.frozen=!1,this.locked=!1,this.texts=[],this.attributes=[],this.removes=[],this.mapRemoves=[],this.movedMap={},this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.processMutations=e=>{e.forEach(this.processMutation),this.emit()},this.emit=()=>{if(this.frozen||this.locked)return;const e=[],t=new Wv,i=a=>{let l=a,c=As;for(;c===As;)l=l&&l.nextSibling,c=l&&this.mirror.getId(l);return c},r=a=>{var l,c,h,u;let f=null;((c=(l=a.getRootNode)===null||l===void 0?void 0:l.call(a))===null||c===void 0?void 0:c.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&a.getRootNode().host&&(f=a.getRootNode().host);let d=f;for(;((u=(h=d==null?void 0:d.getRootNode)===null||h===void 0?void 0:h.call(d))===null||u===void 0?void 0:u.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&d.getRootNode().host;)d=d.getRootNode().host;const g=!this.doc.contains(a)&&(!d||!this.doc.contains(d));if(!a.parentNode||g)return;const _=Es(a.parentNode)?this.mirror.getId(f):this.mirror.getId(a.parentNode),b=i(a);if(_===-1||b===-1)return t.addNode(a);const x=Gi(a,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:C=>{ed(C,this.mirror)&&this.iframeManager.addIframe(C),td(C,this.mirror)&&this.stylesheetManager.trackLinkElement(C),id(a)&&this.shadowDomManager.addShadowRoot(a.shadowRoot,this.doc)},onIframeLoad:(C,S)=>{this.iframeManager.attachIframe(C,S),this.shadowDomManager.observeAttachShadow(C)},onStylesheetLoad:(C,S)=>{this.stylesheetManager.attachLinkElement(C,S)}});x&&e.push({parentId:_,nextId:b,node:x})};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const a of Array.from(this.movedSet.values()))nd(this.removes,a,this.mirror)&&!this.movedSet.has(a.parentNode)||r(a);for(const a of Array.from(this.addedSet.values()))!ad(this.droppedSet,a)&&!nd(this.removes,a,this.mirror)||ad(this.movedSet,a)?r(a):this.droppedSet.add(a);let n=null;for(;t.length;){let a=null;if(n){const l=this.mirror.getId(n.value.parentNode),c=i(n.value);l!==-1&&c!==-1&&(a=n)}if(!a)for(let l=t.length-1;l>=0;l--){const c=t.get(l);if(c){const h=this.mirror.getId(c.value.parentNode);if(i(c.value)===-1)continue;if(h!==-1){a=c;break}else{const f=c.value;if(f.parentNode&&f.parentNode.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const d=f.parentNode.host;if(this.mirror.getId(d)!==-1){a=c;break}}}}}if(!a){for(;t.head;)t.removeNode(t.head.value);break}n=a.previous,t.removeNode(a.value),r(a.value)}const o={texts:this.texts.map(a=>({id:this.mirror.getId(a.node),value:a.value})).filter(a=>this.mirror.has(a.id)),attributes:this.attributes.map(a=>({id:this.mirror.getId(a.node),attributes:a.attributes})).filter(a=>this.mirror.has(a.id)),removes:this.removes,adds:e};!o.texts.length&&!o.attributes.length&&!o.removes.length&&!o.adds.length||(this.texts=[],this.attributes=[],this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.movedMap={},this.mutationCb(o))},this.processMutation=e=>{if(!Ho(e.target,this.mirror))switch(e.type){case"characterData":{const t=e.target.textContent;!Je(e.target,this.blockClass,this.blockSelector,!1)&&t!==e.oldValue&&this.texts.push({value:Yu(e.target,this.maskTextClass,this.maskTextSelector)&&t?this.maskTextFn?this.maskTextFn(t):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{const t=e.target;let i=e.target.getAttribute(e.attributeName);if(e.attributeName==="value"&&(i=Lo({maskInputOptions:this.maskInputOptions,tagName:e.target.tagName,type:e.target.getAttribute("type"),value:i,maskInputFn:this.maskInputFn})),Je(e.target,this.blockClass,this.blockSelector,!1)||i===e.oldValue)return;let r=this.attributes.find(n=>n.node===e.target);if(t.tagName==="IFRAME"&&e.attributeName==="src"&&!this.keepIframeSrcFn(i))if(!t.contentDocument)e.attributeName="rr_src";else return;if(r||(r={node:e.target,attributes:{}},this.attributes.push(r)),e.attributeName==="style"){const n=this.doc.createElement("span");e.oldValue&&n.setAttribute("style",e.oldValue),(r.attributes.style===void 0||r.attributes.style===null)&&(r.attributes.style={});const o=r.attributes.style;for(const a of Array.from(t.style)){const l=t.style.getPropertyValue(a),c=t.style.getPropertyPriority(a);(l!==n.style.getPropertyValue(a)||c!==n.style.getPropertyPriority(a))&&(c===""?o[a]=l:o[a]=[l,c])}for(const a of Array.from(n.style))t.style.getPropertyValue(a)===""&&(o[a]=!1)}else r.attributes[e.attributeName]=Xu(this.doc,t.tagName,e.attributeName,i);break}case"childList":{if(Je(e.target,this.blockClass,this.blockSelector,!0))return;e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{const i=this.mirror.getId(t),r=Es(e.target)?this.mirror.getId(e.target.host):this.mirror.getId(e.target);Je(e.target,this.blockClass,this.blockSelector,!1)||Ho(t,this.mirror)||!Fv(t,this.mirror)||(this.addedSet.has(t)?(zo(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&i===-1||Ju(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[rd(i,r)]?zo(this.movedSet,t):this.removes.push({parentId:r,id:i,isShadow:Es(e.target)&&Ts(e.target)?!0:void 0})),this.mapRemoves.push(t))});break}}},this.genAdds=(e,t)=>{if(this.mirror.hasNode(e)){if(Ho(e,this.mirror))return;this.movedSet.add(e);let i=null;t&&this.mirror.hasNode(t)&&(i=this.mirror.getId(t)),i&&i!==-1&&(this.movedMap[rd(this.mirror.getId(e),i)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);Je(e,this.blockClass,this.blockSelector,!1)||e.childNodes.forEach(i=>this.genAdds(i))}}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function zo(s,e){s.delete(e),e.childNodes.forEach(t=>zo(s,t))}function nd(s,e,t){return s.length===0?!1:od(s,e,t)}function od(s,e,t){const{parentNode:i}=e;if(!i)return!1;const r=t.getId(i);return s.some(n=>n.id===r)?!0:od(s,i,t)}function ad(s,e){return s.size===0?!1:ld(s,e)}function ld(s,e){const{parentNode:t}=e;return t?s.has(t)?!0:ld(s,t):!1}const ci=[],cd=typeof CSSGroupingRule<"u",hd=typeof CSSMediaRule<"u",ud=typeof CSSSupportsRule<"u",dd=typeof CSSConditionRule<"u";function Is(s){try{if("composedPath"in s){const e=s.composedPath();if(e.length)return e[0]}else if("path"in s&&s.path.length)return s.path[0];return s.target}catch{return s.target}}function fd(s,e){var t,i;const r=new Hv;ci.push(r),r.init(s);let n=window.MutationObserver||window.__rrMutationObserver;const o=(i=(t=window==null?void 0:window.Zone)===null||t===void 0?void 0:t.__symbol__)===null||i===void 0?void 0:i.call(t,"MutationObserver");o&&window[o]&&(n=window[o]);const a=new n(r.processMutations.bind(r));return a.observe(e,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),a}function Vv({mousemoveCb:s,sampling:e,doc:t,mirror:i}){if(e.mousemove===!1)return()=>{};const r=typeof e.mousemove=="number"?e.mousemove:50,n=typeof e.mousemoveCallback=="number"?e.mousemoveCallback:500;let o=[],a;const l=ws(u=>{const f=Date.now()-a;s(o.map(d=>(d.timeOffset-=f,d)),u),o=[],a=null},n),c=ws(u=>{const f=Is(u),{clientX:d,clientY:g}=Qu(u)?u.changedTouches[0]:u;a||(a=Date.now()),o.push({x:d,y:g,id:i.getId(f),timeOffset:Date.now()-a}),l(typeof DragEvent<"u"&&u instanceof DragEvent?oe.Drag:u instanceof MouseEvent?oe.MouseMove:oe.TouchMove)},r,{trailing:!1}),h=[Ze("mousemove",c,t),Ze("touchmove",c,t),Ze("drag",c,t)];return()=>{h.forEach(u=>u())}}function zv({mouseInteractionCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,sampling:n}){if(n.mouseInteraction===!1)return()=>{};const o=n.mouseInteraction===!0||n.mouseInteraction===void 0?{}:n.mouseInteraction,a=[],l=c=>h=>{const u=Is(h);if(Je(u,i,r,!0))return;const f=Qu(h)?h.changedTouches[0]:h;if(!f)return;const d=t.getId(u),{clientX:g,clientY:_}=f;s({type:Vo[c],id:d,x:g,y:_})};return Object.keys(Vo).filter(c=>Number.isNaN(Number(c))&&!c.endsWith("_Departed")&&o[c]!==!1).forEach(c=>{const h=c.toLowerCase(),u=l(c);a.push(Ze(h,u,e))}),()=>{a.forEach(c=>c())}}function pd({scrollCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,sampling:n}){const o=ws(a=>{const l=Is(a);if(!l||Je(l,i,r,!0))return;const c=t.getId(l);if(l===e){const h=e.scrollingElement||e.documentElement;s({id:c,x:h.scrollLeft,y:h.scrollTop})}else s({id:c,x:l.scrollLeft,y:l.scrollTop})},n.scroll||100);return Ze("scroll",o,e)}function $v({viewportResizeCb:s}){let e=-1,t=-1;const i=ws(()=>{const r=Ku(),n=Zu();(e!==r||t!==n)&&(s({width:Number(n),height:Number(r)}),e=r,t=n)},200);return Ze("resize",i,window)}function md(s,e){const t=Object.assign({},s);return e||delete t.userTriggered,t}const jv=["INPUT","TEXTAREA","SELECT"],gd=new WeakMap;function Xv({inputCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,ignoreClass:n,maskInputOptions:o,maskInputFn:a,sampling:l,userTriggeredOnInput:c}){function h(x){let C=Is(x);const S=x.isTrusted;if(C&&C.tagName==="OPTION"&&(C=C.parentElement),!C||!C.tagName||jv.indexOf(C.tagName)<0||Je(C,i,r,!0))return;const E=C.type;if(C.classList.contains(n))return;let w=C.value,R=!1;E==="radio"||E==="checkbox"?R=C.checked:(o[C.tagName.toLowerCase()]||o[E])&&(w=Lo({maskInputOptions:o,tagName:C.tagName,type:E,value:w,maskInputFn:a})),u(C,md({text:w,isChecked:R,userTriggered:S},c));const M=C.name;E==="radio"&&M&&R&&e.querySelectorAll(`input[type="radio"][name="${M}"]`).forEach(D=>{D!==C&&u(D,md({text:D.value,isChecked:!R,userTriggered:!1},c))})}function u(x,C){const S=gd.get(x);if(!S||S.text!==C.text||S.isChecked!==C.isChecked){gd.set(x,C);const E=t.getId(x);s(Object.assign(Object.assign({},C),{id:E}))}}const d=(l.input==="last"?["change"]:["input","change"]).map(x=>Ze(x,h,e)),g=e.defaultView;if(!g)return()=>{d.forEach(x=>x())};const _=g.Object.getOwnPropertyDescriptor(g.HTMLInputElement.prototype,"value"),b=[[g.HTMLInputElement.prototype,"value"],[g.HTMLInputElement.prototype,"checked"],[g.HTMLSelectElement.prototype,"value"],[g.HTMLTextAreaElement.prototype,"value"],[g.HTMLSelectElement.prototype,"selectedIndex"],[g.HTMLOptionElement.prototype,"selected"]];return _&&_.set&&d.push(...b.map(x=>vr(x[0],x[1],{set(){h({target:this})}},!1,g))),()=>{d.forEach(x=>x())}}function Cr(s){const e=[];function t(i,r){if(cd&&i.parentRule instanceof CSSGroupingRule||hd&&i.parentRule instanceof CSSMediaRule||ud&&i.parentRule instanceof CSSSupportsRule||dd&&i.parentRule instanceof CSSConditionRule){const o=Array.from(i.parentRule.cssRules).indexOf(i);r.unshift(o)}else if(i.parentStyleSheet){const o=Array.from(i.parentStyleSheet.cssRules).indexOf(i);r.unshift(o)}return r}return t(s,e)}function qt(s,e,t){let i,r;return s?(s.ownerNode?i=e.getId(s.ownerNode):r=t.getId(s),{styleId:r,id:i}):{}}function Yv({styleSheetRuleCb:s,mirror:e,stylesheetManager:t},{win:i}){const r=i.CSSStyleSheet.prototype.insertRule;i.CSSStyleSheet.prototype.insertRule=function(h,u){const{id:f,styleId:d}=qt(this,e,t.styleMirror);return(f&&f!==-1||d&&d!==-1)&&s({id:f,styleId:d,adds:[{rule:h,index:u}]}),r.apply(this,[h,u])};const n=i.CSSStyleSheet.prototype.deleteRule;i.CSSStyleSheet.prototype.deleteRule=function(h){const{id:u,styleId:f}=qt(this,e,t.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,removes:[{index:h}]}),n.apply(this,[h])};let o;i.CSSStyleSheet.prototype.replace&&(o=i.CSSStyleSheet.prototype.replace,i.CSSStyleSheet.prototype.replace=function(h){const{id:u,styleId:f}=qt(this,e,t.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,replace:h}),o.apply(this,[h])});let a;i.CSSStyleSheet.prototype.replaceSync&&(a=i.CSSStyleSheet.prototype.replaceSync,i.CSSStyleSheet.prototype.replaceSync=function(h){const{id:u,styleId:f}=qt(this,e,t.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,replaceSync:h}),a.apply(this,[h])});const l={};cd?l.CSSGroupingRule=i.CSSGroupingRule:(hd&&(l.CSSMediaRule=i.CSSMediaRule),dd&&(l.CSSConditionRule=i.CSSConditionRule),ud&&(l.CSSSupportsRule=i.CSSSupportsRule));const c={};return Object.entries(l).forEach(([h,u])=>{c[h]={insertRule:u.prototype.insertRule,deleteRule:u.prototype.deleteRule},u.prototype.insertRule=function(f,d){const{id:g,styleId:_}=qt(this.parentStyleSheet,e,t.styleMirror);return(g&&g!==-1||_&&_!==-1)&&s({id:g,styleId:_,adds:[{rule:f,index:[...Cr(this),d||0]}]}),c[h].insertRule.apply(this,[f,d])},u.prototype.deleteRule=function(f){const{id:d,styleId:g}=qt(this.parentStyleSheet,e,t.styleMirror);return(d&&d!==-1||g&&g!==-1)&&s({id:d,styleId:g,removes:[{index:[...Cr(this),f]}]}),c[h].deleteRule.apply(this,[f])}}),()=>{i.CSSStyleSheet.prototype.insertRule=r,i.CSSStyleSheet.prototype.deleteRule=n,o&&(i.CSSStyleSheet.prototype.replace=o),a&&(i.CSSStyleSheet.prototype.replaceSync=a),Object.entries(l).forEach(([h,u])=>{u.prototype.insertRule=c[h].insertRule,u.prototype.deleteRule=c[h].deleteRule})}}function _d({mirror:s,stylesheetManager:e},t){var i,r,n;let o=null;t.nodeName==="#document"?o=s.getId(t):o=s.getId(t.host);const a=t.nodeName==="#document"?(i=t.defaultView)===null||i===void 0?void 0:i.Document:(n=(r=t.ownerDocument)===null||r===void 0?void 0:r.defaultView)===null||n===void 0?void 0:n.ShadowRoot,l=Object.getOwnPropertyDescriptor(a==null?void 0:a.prototype,"adoptedStyleSheets");return o===null||o===-1||!a||!l?()=>{}:(Object.defineProperty(t,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get(){var c;return(c=l.get)===null||c===void 0?void 0:c.call(this)},set(c){var h;const u=(h=l.set)===null||h===void 0?void 0:h.call(this,c);if(o!==null&&o!==-1)try{e.adoptStyleSheets(c,o)}catch{}return u}}),()=>{Object.defineProperty(t,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get:l.get,set:l.set})})}function qv({styleDeclarationCb:s,mirror:e,ignoreCSSAttributes:t,stylesheetManager:i},{win:r}){const n=r.CSSStyleDeclaration.prototype.setProperty;r.CSSStyleDeclaration.prototype.setProperty=function(a,l,c){var h;if(t.has(a))return n.apply(this,[a,l,c]);const{id:u,styleId:f}=qt((h=this.parentRule)===null||h===void 0?void 0:h.parentStyleSheet,e,i.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,set:{property:a,value:l,priority:c},index:Cr(this.parentRule)}),n.apply(this,[a,l,c])};const o=r.CSSStyleDeclaration.prototype.removeProperty;return r.CSSStyleDeclaration.prototype.removeProperty=function(a){var l;if(t.has(a))return o.apply(this,[a]);const{id:c,styleId:h}=qt((l=this.parentRule)===null||l===void 0?void 0:l.parentStyleSheet,e,i.styleMirror);return(c&&c!==-1||h&&h!==-1)&&s({id:c,styleId:h,remove:{property:a},index:Cr(this.parentRule)}),o.apply(this,[a])},()=>{r.CSSStyleDeclaration.prototype.setProperty=n,r.CSSStyleDeclaration.prototype.removeProperty=o}}function Kv({mediaInteractionCb:s,blockClass:e,blockSelector:t,mirror:i,sampling:r}){const n=a=>ws(l=>{const c=Is(l);if(!c||Je(c,e,t,!0))return;const{currentTime:h,volume:u,muted:f,playbackRate:d}=c;s({type:a,id:i.getId(c),currentTime:h,volume:u,muted:f,playbackRate:d})},r.media||500),o=[Ze("play",n(0)),Ze("pause",n(1)),Ze("seeked",n(2)),Ze("volumechange",n(3)),Ze("ratechange",n(4))];return()=>{o.forEach(a=>a())}}function Zv({fontCb:s,doc:e}){const t=e.defaultView;if(!t)return()=>{};const i=[],r=new WeakMap,n=t.FontFace;t.FontFace=function(l,c,h){const u=new n(l,c,h);return r.set(u,{family:l,buffer:typeof c!="string",descriptors:h,fontSource:typeof c=="string"?c:JSON.stringify(Array.from(new Uint8Array(c)))}),u};const o=Wi(e.fonts,"add",function(a){return function(l){return setTimeout(()=>{const c=r.get(l);c&&(s(c),r.delete(l))},0),a.apply(this,[l])}});return i.push(()=>{t.FontFace=n}),i.push(o),()=>{i.forEach(a=>a())}}function Jv(s){const{doc:e,mirror:t,blockClass:i,blockSelector:r,selectionCb:n}=s;let o=!0;const a=()=>{const l=e.getSelection();if(!l||o&&(l!=null&&l.isCollapsed))return;o=l.isCollapsed||!1;const c=[],h=l.rangeCount||0;for(let u=0;u<h;u++){const f=l.getRangeAt(u),{startContainer:d,startOffset:g,endContainer:_,endOffset:b}=f;Je(d,i,r,!0)||Je(_,i,r,!0)||c.push({start:t.getId(d),startOffset:g,end:t.getId(_),endOffset:b})}n({ranges:c})};return a(),Ze("selectionchange",a)}function Qv(s,e){const{mutationCb:t,mousemoveCb:i,mouseInteractionCb:r,scrollCb:n,viewportResizeCb:o,inputCb:a,mediaInteractionCb:l,styleSheetRuleCb:c,styleDeclarationCb:h,canvasMutationCb:u,fontCb:f,selectionCb:d}=s;s.mutationCb=(...g)=>{e.mutation&&e.mutation(...g),t(...g)},s.mousemoveCb=(...g)=>{e.mousemove&&e.mousemove(...g),i(...g)},s.mouseInteractionCb=(...g)=>{e.mouseInteraction&&e.mouseInteraction(...g),r(...g)},s.scrollCb=(...g)=>{e.scroll&&e.scroll(...g),n(...g)},s.viewportResizeCb=(...g)=>{e.viewportResize&&e.viewportResize(...g),o(...g)},s.inputCb=(...g)=>{e.input&&e.input(...g),a(...g)},s.mediaInteractionCb=(...g)=>{e.mediaInteaction&&e.mediaInteaction(...g),l(...g)},s.styleSheetRuleCb=(...g)=>{e.styleSheetRule&&e.styleSheetRule(...g),c(...g)},s.styleDeclarationCb=(...g)=>{e.styleDeclaration&&e.styleDeclaration(...g),h(...g)},s.canvasMutationCb=(...g)=>{e.canvasMutation&&e.canvasMutation(...g),u(...g)},s.fontCb=(...g)=>{e.font&&e.font(...g),f(...g)},s.selectionCb=(...g)=>{e.selection&&e.selection(...g),d(...g)}}function e0(s,e={}){const t=s.doc.defaultView;if(!t)return()=>{};Qv(s,e);const i=fd(s,s.doc),r=Vv(s),n=zv(s),o=pd(s),a=$v(s),l=Xv(s),c=Kv(s),h=Yv(s,{win:t}),u=_d(s,s.doc),f=qv(s,{win:t}),d=s.collectFonts?Zv(s):()=>{},g=Jv(s),_=[];for(const b of s.plugins)_.push(b.observer(b.callback,t,b.options));return()=>{ci.forEach(b=>b.reset()),i.disconnect(),r(),n(),o(),a(),l(),c(),h(),u(),f(),d(),g(),_.forEach(b=>b())}}class yd{constructor(e){this.generateIdFn=e,this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap}getId(e,t,i,r){const n=i||this.getIdToRemoteIdMap(e),o=r||this.getRemoteIdToIdMap(e);let a=n.get(t);return a||(a=this.generateIdFn(),n.set(t,a),o.set(a,t)),a}getIds(e,t){const i=this.getIdToRemoteIdMap(e),r=this.getRemoteIdToIdMap(e);return t.map(n=>this.getId(e,n,i,r))}getRemoteId(e,t,i){const r=i||this.getRemoteIdToIdMap(e);if(typeof t!="number")return t;const n=r.get(t);return n||-1}getRemoteIds(e,t){const i=this.getRemoteIdToIdMap(e);return t.map(r=>this.getRemoteId(e,r,i))}reset(e){if(!e){this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap;return}this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}}class t0{constructor(e){this.iframes=new WeakMap,this.crossOriginIframeMap=new WeakMap,this.crossOriginIframeMirror=new yd($u),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new yd(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var i;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),(i=this.loadListener)===null||i===void 0||i.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){if(e.data.type==="rrweb"){if(!e.source)return;const i=this.crossOriginIframeMap.get(e.source);if(!i)return;const r=this.transformCrossOriginEvent(i,e.data.event);r&&this.wrappedEmit(r,e.data.isCheckout)}}transformCrossOriginEvent(e,t){var i;switch(t.type){case ue.FullSnapshot:return this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e),{timestamp:t.timestamp,type:ue.IncrementalSnapshot,data:{source:oe.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}};case ue.Meta:case ue.Load:case ue.DomContentLoaded:return!1;case ue.Plugin:return t;case ue.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case ue.IncrementalSnapshot:switch(t.data.source){case oe.Mutation:return t.data.adds.forEach(r=>{this.replaceIds(r,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(r.node,e)}),t.data.removes.forEach(r=>{this.replaceIds(r,e,["parentId","id"])}),t.data.attributes.forEach(r=>{this.replaceIds(r,e,["id"])}),t.data.texts.forEach(r=>{this.replaceIds(r,e,["id"])}),t;case oe.Drag:case oe.TouchMove:case oe.MouseMove:return t.data.positions.forEach(r=>{this.replaceIds(r,e,["id"])}),t;case oe.ViewportResize:return!1;case oe.MediaInteraction:case oe.MouseInteraction:case oe.Scroll:case oe.CanvasMutation:case oe.Input:return this.replaceIds(t.data,e,["id"]),t;case oe.StyleSheetRule:case oe.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case oe.Font:return t;case oe.Selection:return t.data.ranges.forEach(r=>{this.replaceIds(r,e,["start","end"])}),t;case oe.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),(i=t.data.styles)===null||i===void 0||i.forEach(r=>{this.replaceStyleIds(r,e,["styleId"])}),t}}}replace(e,t,i,r){for(const n of r)!Array.isArray(t[n])&&typeof t[n]!="number"||(Array.isArray(t[n])?t[n]=e.getIds(i,t[n]):t[n]=e.getId(i,t[n]));return t}replaceIds(e,t,i){return this.replace(this.crossOriginIframeMirror,e,t,i)}replaceStyleIds(e,t,i){return this.replace(this.crossOriginIframeStyleMirror,e,t,i)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id"]),"childNodes"in e&&e.childNodes.forEach(i=>{this.replaceIdOnNode(i,t)})}}class i0{constructor(e){this.shadowDoms=new WeakSet,this.restorePatches=[],this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror;const t=this;this.restorePatches.push(Wi(Element.prototype,"attachShadow",function(i){return function(r){const n=i.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,this.ownerDocument),n}}))}addShadowRoot(e,t){Ts(e)&&(this.shadowDoms.has(e)||(this.shadowDoms.add(e),fd(Object.assign(Object.assign({},this.bypassOptions),{doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this}),e),pd(Object.assign(Object.assign({},this.bypassOptions),{scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(e.host)),_d({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e)},0)))}observeAttachShadow(e){if(e.contentWindow){const t=this;this.restorePatches.push(Wi(e.contentWindow.HTMLElement.prototype,"attachShadow",function(i){return function(r){const n=i.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,e.contentDocument),n}}))}}reset(){this.restorePatches.forEach(e=>e()),this.shadowDoms=new WeakSet}}/*! *****************************************************************************
958
+ or you can use record.mirror to access the mirror instance during recording.`;let qu={map:{},getId(){return console.error(Li),-1},getNode(){return console.error(Li),null},removeNodeFromMap(){console.error(Li)},has(){return console.error(Li),!1},reset(){console.error(Li)}};typeof window<"u"&&window.Proxy&&window.Reflect&&(qu=new Proxy(qu,{get(s,e,t){return e==="map"&&console.error(Li),Reflect.get(s,e,t)}}));function ws(s,e,t={}){let i=null,r=0;return function(...n){const o=Date.now();!r&&t.leading===!1&&(r=o);const a=e-(o-r),l=this;a<=0||a>e?(i&&(clearTimeout(i),i=null),r=o,s.apply(l,n)):!i&&t.trailing!==!1&&(i=setTimeout(()=>{r=t.leading===!1?0:Date.now(),i=null,s.apply(l,n)},a))}}function Cr(s,e,t,i,r=window){const n=r.Object.getOwnPropertyDescriptor(s,e);return r.Object.defineProperty(s,e,i?t:{set(o){setTimeout(()=>{t.set.call(this,o)},0),n&&n.set&&n.set.call(this,o)}}),()=>Cr(s,e,n||{},!0)}function Wi(s,e,t){try{if(!(e in s))return()=>{};const i=s[e],r=t(i);return typeof r=="function"&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__rrweb_original__:{enumerable:!1,value:i}})),s[e]=r,()=>{s[e]=i}}catch{return()=>{}}}function Ku(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Zu(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Je(s,e,t,i){if(!s)return!1;const r=s.nodeType===s.ELEMENT_NODE?s:s.parentElement;if(!r)return!1;if(typeof e=="string"){if(r.classList.contains(e)||i&&r.closest("."+e)!==null)return!0}else if(vr(r,e,i))return!0;return!!(t&&(s.matches(t)||i&&r.closest(t)!==null))}function Gv(s,e){return e.getId(s)!==-1}function Ho(s,e){return e.getId(s)===As}function Ju(s,e){if(Es(s))return!1;const t=e.getId(s);return e.has(t)?s.parentNode&&s.parentNode.nodeType===s.DOCUMENT_NODE?!1:s.parentNode?Ju(s.parentNode,e):!0:!0}function Qu(s){return!!s.changedTouches}function Lv(s=window){"NodeList"in s&&!s.NodeList.prototype.forEach&&(s.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in s&&!s.DOMTokenList.prototype.forEach&&(s.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=(...e)=>{let t=e[0];if(!(0 in e))throw new TypeError("1 argument is required");do if(this===t)return!0;while(t=t&&t.parentNode);return!1})}function ed(s,e){return!!(s.nodeName==="IFRAME"&&e.getMeta(s))}function td(s,e){return!!(s.nodeName==="LINK"&&s.nodeType===s.ELEMENT_NODE&&s.getAttribute&&s.getAttribute("rel")==="stylesheet"&&e.getMeta(s))}function id(s){return!!(s!=null&&s.shadowRoot)}class Wv{constructor(){this.id=1,this.styleIDMap=new WeakMap,this.idStyleMap=new Map}getId(e){var t;return(t=this.styleIDMap.get(e))!==null&&t!==void 0?t:-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let i;return t===void 0?i=this.id++:i=t,this.styleIDMap.set(e,i),this.idStyleMap.set(i,e),i}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}var ue=(s=>(s[s.DomContentLoaded=0]="DomContentLoaded",s[s.Load=1]="Load",s[s.FullSnapshot=2]="FullSnapshot",s[s.IncrementalSnapshot=3]="IncrementalSnapshot",s[s.Meta=4]="Meta",s[s.Custom=5]="Custom",s[s.Plugin=6]="Plugin",s))(ue||{}),oe=(s=>(s[s.Mutation=0]="Mutation",s[s.MouseMove=1]="MouseMove",s[s.MouseInteraction=2]="MouseInteraction",s[s.Scroll=3]="Scroll",s[s.ViewportResize=4]="ViewportResize",s[s.Input=5]="Input",s[s.TouchMove=6]="TouchMove",s[s.MediaInteraction=7]="MediaInteraction",s[s.StyleSheetRule=8]="StyleSheetRule",s[s.CanvasMutation=9]="CanvasMutation",s[s.Font=10]="Font",s[s.Log=11]="Log",s[s.Drag=12]="Drag",s[s.StyleDeclaration=13]="StyleDeclaration",s[s.Selection=14]="Selection",s[s.AdoptedStyleSheet=15]="AdoptedStyleSheet",s))(oe||{}),Vo=(s=>(s[s.MouseUp=0]="MouseUp",s[s.MouseDown=1]="MouseDown",s[s.Click=2]="Click",s[s.ContextMenu=3]="ContextMenu",s[s.DblClick=4]="DblClick",s[s.Focus=5]="Focus",s[s.Blur=6]="Blur",s[s.TouchStart=7]="TouchStart",s[s.TouchMove_Departed=8]="TouchMove_Departed",s[s.TouchEnd=9]="TouchEnd",s[s.TouchCancel=10]="TouchCancel",s))(Vo||{}),Hi=(s=>(s[s["2D"]=0]="2D",s[s.WebGL=1]="WebGL",s[s.WebGL2=2]="WebGL2",s))(Hi||{});function sd(s){return"__ln"in s}class Hv{constructor(){this.length=0,this.head=null}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let i=0;i<e;i++)t=(t==null?void 0:t.next)||null;return t}addNode(e){const t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&sd(e.previousSibling)){const i=e.previousSibling.__ln.next;t.next=i,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,i&&(i.previous=t)}else if(e.nextSibling&&sd(e.nextSibling)&&e.nextSibling.__ln.previous){const i=e.nextSibling.__ln.previous;t.previous=i,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,i&&(i.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;this.length++}removeNode(e){const t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next&&(t.next.previous=t.previous)):(this.head=t.next,this.head&&(this.head.previous=null)),e.__ln&&delete e.__ln,this.length--)}}const rd=(s,e)=>`${s}@${e}`;class Vv{constructor(){this.frozen=!1,this.locked=!1,this.texts=[],this.attributes=[],this.removes=[],this.mapRemoves=[],this.movedMap={},this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.processMutations=e=>{e.forEach(this.processMutation),this.emit()},this.emit=()=>{if(this.frozen||this.locked)return;const e=[],t=new Hv,i=a=>{let l=a,c=As;for(;c===As;)l=l&&l.nextSibling,c=l&&this.mirror.getId(l);return c},r=a=>{var l,c,h,u;let f=null;((c=(l=a.getRootNode)===null||l===void 0?void 0:l.call(a))===null||c===void 0?void 0:c.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&a.getRootNode().host&&(f=a.getRootNode().host);let d=f;for(;((u=(h=d==null?void 0:d.getRootNode)===null||h===void 0?void 0:h.call(d))===null||u===void 0?void 0:u.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&d.getRootNode().host;)d=d.getRootNode().host;const g=!this.doc.contains(a)&&(!d||!this.doc.contains(d));if(!a.parentNode||g)return;const _=Es(a.parentNode)?this.mirror.getId(f):this.mirror.getId(a.parentNode),y=i(a);if(_===-1||y===-1)return t.addNode(a);const x=Gi(a,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:C=>{ed(C,this.mirror)&&this.iframeManager.addIframe(C),td(C,this.mirror)&&this.stylesheetManager.trackLinkElement(C),id(a)&&this.shadowDomManager.addShadowRoot(a.shadowRoot,this.doc)},onIframeLoad:(C,S)=>{this.iframeManager.attachIframe(C,S),this.shadowDomManager.observeAttachShadow(C)},onStylesheetLoad:(C,S)=>{this.stylesheetManager.attachLinkElement(C,S)}});x&&e.push({parentId:_,nextId:y,node:x})};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const a of Array.from(this.movedSet.values()))nd(this.removes,a,this.mirror)&&!this.movedSet.has(a.parentNode)||r(a);for(const a of Array.from(this.addedSet.values()))!ad(this.droppedSet,a)&&!nd(this.removes,a,this.mirror)||ad(this.movedSet,a)?r(a):this.droppedSet.add(a);let n=null;for(;t.length;){let a=null;if(n){const l=this.mirror.getId(n.value.parentNode),c=i(n.value);l!==-1&&c!==-1&&(a=n)}if(!a)for(let l=t.length-1;l>=0;l--){const c=t.get(l);if(c){const h=this.mirror.getId(c.value.parentNode);if(i(c.value)===-1)continue;if(h!==-1){a=c;break}else{const f=c.value;if(f.parentNode&&f.parentNode.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const d=f.parentNode.host;if(this.mirror.getId(d)!==-1){a=c;break}}}}}if(!a){for(;t.head;)t.removeNode(t.head.value);break}n=a.previous,t.removeNode(a.value),r(a.value)}const o={texts:this.texts.map(a=>({id:this.mirror.getId(a.node),value:a.value})).filter(a=>this.mirror.has(a.id)),attributes:this.attributes.map(a=>({id:this.mirror.getId(a.node),attributes:a.attributes})).filter(a=>this.mirror.has(a.id)),removes:this.removes,adds:e};!o.texts.length&&!o.attributes.length&&!o.removes.length&&!o.adds.length||(this.texts=[],this.attributes=[],this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.movedMap={},this.mutationCb(o))},this.processMutation=e=>{if(!Ho(e.target,this.mirror))switch(e.type){case"characterData":{const t=e.target.textContent;!Je(e.target,this.blockClass,this.blockSelector,!1)&&t!==e.oldValue&&this.texts.push({value:Yu(e.target,this.maskTextClass,this.maskTextSelector)&&t?this.maskTextFn?this.maskTextFn(t):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{const t=e.target;let i=e.target.getAttribute(e.attributeName);if(e.attributeName==="value"&&(i=Lo({maskInputOptions:this.maskInputOptions,tagName:e.target.tagName,type:e.target.getAttribute("type"),value:i,maskInputFn:this.maskInputFn})),Je(e.target,this.blockClass,this.blockSelector,!1)||i===e.oldValue)return;let r=this.attributes.find(n=>n.node===e.target);if(t.tagName==="IFRAME"&&e.attributeName==="src"&&!this.keepIframeSrcFn(i))if(!t.contentDocument)e.attributeName="rr_src";else return;if(r||(r={node:e.target,attributes:{}},this.attributes.push(r)),e.attributeName==="style"){const n=this.doc.createElement("span");e.oldValue&&n.setAttribute("style",e.oldValue),(r.attributes.style===void 0||r.attributes.style===null)&&(r.attributes.style={});const o=r.attributes.style;for(const a of Array.from(t.style)){const l=t.style.getPropertyValue(a),c=t.style.getPropertyPriority(a);(l!==n.style.getPropertyValue(a)||c!==n.style.getPropertyPriority(a))&&(c===""?o[a]=l:o[a]=[l,c])}for(const a of Array.from(n.style))t.style.getPropertyValue(a)===""&&(o[a]=!1)}else r.attributes[e.attributeName]=Xu(this.doc,t.tagName,e.attributeName,i);break}case"childList":{if(Je(e.target,this.blockClass,this.blockSelector,!0))return;e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{const i=this.mirror.getId(t),r=Es(e.target)?this.mirror.getId(e.target.host):this.mirror.getId(e.target);Je(e.target,this.blockClass,this.blockSelector,!1)||Ho(t,this.mirror)||!Gv(t,this.mirror)||(this.addedSet.has(t)?(zo(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&i===-1||Ju(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[rd(i,r)]?zo(this.movedSet,t):this.removes.push({parentId:r,id:i,isShadow:Es(e.target)&&Ts(e.target)?!0:void 0})),this.mapRemoves.push(t))});break}}},this.genAdds=(e,t)=>{if(this.mirror.hasNode(e)){if(Ho(e,this.mirror))return;this.movedSet.add(e);let i=null;t&&this.mirror.hasNode(t)&&(i=this.mirror.getId(t)),i&&i!==-1&&(this.movedMap[rd(this.mirror.getId(e),i)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);Je(e,this.blockClass,this.blockSelector,!1)||e.childNodes.forEach(i=>this.genAdds(i))}}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function zo(s,e){s.delete(e),e.childNodes.forEach(t=>zo(s,t))}function nd(s,e,t){return s.length===0?!1:od(s,e,t)}function od(s,e,t){const{parentNode:i}=e;if(!i)return!1;const r=t.getId(i);return s.some(n=>n.id===r)?!0:od(s,i,t)}function ad(s,e){return s.size===0?!1:ld(s,e)}function ld(s,e){const{parentNode:t}=e;return t?s.has(t)?!0:ld(s,t):!1}const ci=[],cd=typeof CSSGroupingRule<"u",hd=typeof CSSMediaRule<"u",ud=typeof CSSSupportsRule<"u",dd=typeof CSSConditionRule<"u";function Is(s){try{if("composedPath"in s){const e=s.composedPath();if(e.length)return e[0]}else if("path"in s&&s.path.length)return s.path[0];return s.target}catch{return s.target}}function fd(s,e){var t,i;const r=new Vv;ci.push(r),r.init(s);let n=window.MutationObserver||window.__rrMutationObserver;const o=(i=(t=window==null?void 0:window.Zone)===null||t===void 0?void 0:t.__symbol__)===null||i===void 0?void 0:i.call(t,"MutationObserver");o&&window[o]&&(n=window[o]);const a=new n(r.processMutations.bind(r));return a.observe(e,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),a}function zv({mousemoveCb:s,sampling:e,doc:t,mirror:i}){if(e.mousemove===!1)return()=>{};const r=typeof e.mousemove=="number"?e.mousemove:50,n=typeof e.mousemoveCallback=="number"?e.mousemoveCallback:500;let o=[],a;const l=ws(u=>{const f=Date.now()-a;s(o.map(d=>(d.timeOffset-=f,d)),u),o=[],a=null},n),c=ws(u=>{const f=Is(u),{clientX:d,clientY:g}=Qu(u)?u.changedTouches[0]:u;a||(a=Date.now()),o.push({x:d,y:g,id:i.getId(f),timeOffset:Date.now()-a}),l(typeof DragEvent<"u"&&u instanceof DragEvent?oe.Drag:u instanceof MouseEvent?oe.MouseMove:oe.TouchMove)},r,{trailing:!1}),h=[Ze("mousemove",c,t),Ze("touchmove",c,t),Ze("drag",c,t)];return()=>{h.forEach(u=>u())}}function $v({mouseInteractionCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,sampling:n}){if(n.mouseInteraction===!1)return()=>{};const o=n.mouseInteraction===!0||n.mouseInteraction===void 0?{}:n.mouseInteraction,a=[],l=c=>h=>{const u=Is(h);if(Je(u,i,r,!0))return;const f=Qu(h)?h.changedTouches[0]:h;if(!f)return;const d=t.getId(u),{clientX:g,clientY:_}=f;s({type:Vo[c],id:d,x:g,y:_})};return Object.keys(Vo).filter(c=>Number.isNaN(Number(c))&&!c.endsWith("_Departed")&&o[c]!==!1).forEach(c=>{const h=c.toLowerCase(),u=l(c);a.push(Ze(h,u,e))}),()=>{a.forEach(c=>c())}}function pd({scrollCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,sampling:n}){const o=ws(a=>{const l=Is(a);if(!l||Je(l,i,r,!0))return;const c=t.getId(l);if(l===e){const h=e.scrollingElement||e.documentElement;s({id:c,x:h.scrollLeft,y:h.scrollTop})}else s({id:c,x:l.scrollLeft,y:l.scrollTop})},n.scroll||100);return Ze("scroll",o,e)}function jv({viewportResizeCb:s}){let e=-1,t=-1;const i=ws(()=>{const r=Ku(),n=Zu();(e!==r||t!==n)&&(s({width:Number(n),height:Number(r)}),e=r,t=n)},200);return Ze("resize",i,window)}function md(s,e){const t=Object.assign({},s);return e||delete t.userTriggered,t}const Xv=["INPUT","TEXTAREA","SELECT"],gd=new WeakMap;function Yv({inputCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,ignoreClass:n,maskInputOptions:o,maskInputFn:a,sampling:l,userTriggeredOnInput:c}){function h(x){let C=Is(x);const S=x.isTrusted;if(C&&C.tagName==="OPTION"&&(C=C.parentElement),!C||!C.tagName||Xv.indexOf(C.tagName)<0||Je(C,i,r,!0))return;const E=C.type;if(C.classList.contains(n))return;let w=C.value,R=!1;E==="radio"||E==="checkbox"?R=C.checked:(o[C.tagName.toLowerCase()]||o[E])&&(w=Lo({maskInputOptions:o,tagName:C.tagName,type:E,value:w,maskInputFn:a})),u(C,md({text:w,isChecked:R,userTriggered:S},c));const M=C.name;E==="radio"&&M&&R&&e.querySelectorAll(`input[type="radio"][name="${M}"]`).forEach(D=>{D!==C&&u(D,md({text:D.value,isChecked:!R,userTriggered:!1},c))})}function u(x,C){const S=gd.get(x);if(!S||S.text!==C.text||S.isChecked!==C.isChecked){gd.set(x,C);const E=t.getId(x);s(Object.assign(Object.assign({},C),{id:E}))}}const d=(l.input==="last"?["change"]:["input","change"]).map(x=>Ze(x,h,e)),g=e.defaultView;if(!g)return()=>{d.forEach(x=>x())};const _=g.Object.getOwnPropertyDescriptor(g.HTMLInputElement.prototype,"value"),y=[[g.HTMLInputElement.prototype,"value"],[g.HTMLInputElement.prototype,"checked"],[g.HTMLSelectElement.prototype,"value"],[g.HTMLTextAreaElement.prototype,"value"],[g.HTMLSelectElement.prototype,"selectedIndex"],[g.HTMLOptionElement.prototype,"selected"]];return _&&_.set&&d.push(...y.map(x=>Cr(x[0],x[1],{set(){h({target:this})}},!1,g))),()=>{d.forEach(x=>x())}}function Sr(s){const e=[];function t(i,r){if(cd&&i.parentRule instanceof CSSGroupingRule||hd&&i.parentRule instanceof CSSMediaRule||ud&&i.parentRule instanceof CSSSupportsRule||dd&&i.parentRule instanceof CSSConditionRule){const o=Array.from(i.parentRule.cssRules).indexOf(i);r.unshift(o)}else if(i.parentStyleSheet){const o=Array.from(i.parentStyleSheet.cssRules).indexOf(i);r.unshift(o)}return r}return t(s,e)}function qt(s,e,t){let i,r;return s?(s.ownerNode?i=e.getId(s.ownerNode):r=t.getId(s),{styleId:r,id:i}):{}}function qv({styleSheetRuleCb:s,mirror:e,stylesheetManager:t},{win:i}){const r=i.CSSStyleSheet.prototype.insertRule;i.CSSStyleSheet.prototype.insertRule=function(h,u){const{id:f,styleId:d}=qt(this,e,t.styleMirror);return(f&&f!==-1||d&&d!==-1)&&s({id:f,styleId:d,adds:[{rule:h,index:u}]}),r.apply(this,[h,u])};const n=i.CSSStyleSheet.prototype.deleteRule;i.CSSStyleSheet.prototype.deleteRule=function(h){const{id:u,styleId:f}=qt(this,e,t.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,removes:[{index:h}]}),n.apply(this,[h])};let o;i.CSSStyleSheet.prototype.replace&&(o=i.CSSStyleSheet.prototype.replace,i.CSSStyleSheet.prototype.replace=function(h){const{id:u,styleId:f}=qt(this,e,t.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,replace:h}),o.apply(this,[h])});let a;i.CSSStyleSheet.prototype.replaceSync&&(a=i.CSSStyleSheet.prototype.replaceSync,i.CSSStyleSheet.prototype.replaceSync=function(h){const{id:u,styleId:f}=qt(this,e,t.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,replaceSync:h}),a.apply(this,[h])});const l={};cd?l.CSSGroupingRule=i.CSSGroupingRule:(hd&&(l.CSSMediaRule=i.CSSMediaRule),dd&&(l.CSSConditionRule=i.CSSConditionRule),ud&&(l.CSSSupportsRule=i.CSSSupportsRule));const c={};return Object.entries(l).forEach(([h,u])=>{c[h]={insertRule:u.prototype.insertRule,deleteRule:u.prototype.deleteRule},u.prototype.insertRule=function(f,d){const{id:g,styleId:_}=qt(this.parentStyleSheet,e,t.styleMirror);return(g&&g!==-1||_&&_!==-1)&&s({id:g,styleId:_,adds:[{rule:f,index:[...Sr(this),d||0]}]}),c[h].insertRule.apply(this,[f,d])},u.prototype.deleteRule=function(f){const{id:d,styleId:g}=qt(this.parentStyleSheet,e,t.styleMirror);return(d&&d!==-1||g&&g!==-1)&&s({id:d,styleId:g,removes:[{index:[...Sr(this),f]}]}),c[h].deleteRule.apply(this,[f])}}),()=>{i.CSSStyleSheet.prototype.insertRule=r,i.CSSStyleSheet.prototype.deleteRule=n,o&&(i.CSSStyleSheet.prototype.replace=o),a&&(i.CSSStyleSheet.prototype.replaceSync=a),Object.entries(l).forEach(([h,u])=>{u.prototype.insertRule=c[h].insertRule,u.prototype.deleteRule=c[h].deleteRule})}}function _d({mirror:s,stylesheetManager:e},t){var i,r,n;let o=null;t.nodeName==="#document"?o=s.getId(t):o=s.getId(t.host);const a=t.nodeName==="#document"?(i=t.defaultView)===null||i===void 0?void 0:i.Document:(n=(r=t.ownerDocument)===null||r===void 0?void 0:r.defaultView)===null||n===void 0?void 0:n.ShadowRoot,l=Object.getOwnPropertyDescriptor(a==null?void 0:a.prototype,"adoptedStyleSheets");return o===null||o===-1||!a||!l?()=>{}:(Object.defineProperty(t,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get(){var c;return(c=l.get)===null||c===void 0?void 0:c.call(this)},set(c){var h;const u=(h=l.set)===null||h===void 0?void 0:h.call(this,c);if(o!==null&&o!==-1)try{e.adoptStyleSheets(c,o)}catch{}return u}}),()=>{Object.defineProperty(t,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get:l.get,set:l.set})})}function Kv({styleDeclarationCb:s,mirror:e,ignoreCSSAttributes:t,stylesheetManager:i},{win:r}){const n=r.CSSStyleDeclaration.prototype.setProperty;r.CSSStyleDeclaration.prototype.setProperty=function(a,l,c){var h;if(t.has(a))return n.apply(this,[a,l,c]);const{id:u,styleId:f}=qt((h=this.parentRule)===null||h===void 0?void 0:h.parentStyleSheet,e,i.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,set:{property:a,value:l,priority:c},index:Sr(this.parentRule)}),n.apply(this,[a,l,c])};const o=r.CSSStyleDeclaration.prototype.removeProperty;return r.CSSStyleDeclaration.prototype.removeProperty=function(a){var l;if(t.has(a))return o.apply(this,[a]);const{id:c,styleId:h}=qt((l=this.parentRule)===null||l===void 0?void 0:l.parentStyleSheet,e,i.styleMirror);return(c&&c!==-1||h&&h!==-1)&&s({id:c,styleId:h,remove:{property:a},index:Sr(this.parentRule)}),o.apply(this,[a])},()=>{r.CSSStyleDeclaration.prototype.setProperty=n,r.CSSStyleDeclaration.prototype.removeProperty=o}}function Zv({mediaInteractionCb:s,blockClass:e,blockSelector:t,mirror:i,sampling:r}){const n=a=>ws(l=>{const c=Is(l);if(!c||Je(c,e,t,!0))return;const{currentTime:h,volume:u,muted:f,playbackRate:d}=c;s({type:a,id:i.getId(c),currentTime:h,volume:u,muted:f,playbackRate:d})},r.media||500),o=[Ze("play",n(0)),Ze("pause",n(1)),Ze("seeked",n(2)),Ze("volumechange",n(3)),Ze("ratechange",n(4))];return()=>{o.forEach(a=>a())}}function Jv({fontCb:s,doc:e}){const t=e.defaultView;if(!t)return()=>{};const i=[],r=new WeakMap,n=t.FontFace;t.FontFace=function(l,c,h){const u=new n(l,c,h);return r.set(u,{family:l,buffer:typeof c!="string",descriptors:h,fontSource:typeof c=="string"?c:JSON.stringify(Array.from(new Uint8Array(c)))}),u};const o=Wi(e.fonts,"add",function(a){return function(l){return setTimeout(()=>{const c=r.get(l);c&&(s(c),r.delete(l))},0),a.apply(this,[l])}});return i.push(()=>{t.FontFace=n}),i.push(o),()=>{i.forEach(a=>a())}}function Qv(s){const{doc:e,mirror:t,blockClass:i,blockSelector:r,selectionCb:n}=s;let o=!0;const a=()=>{const l=e.getSelection();if(!l||o&&(l!=null&&l.isCollapsed))return;o=l.isCollapsed||!1;const c=[],h=l.rangeCount||0;for(let u=0;u<h;u++){const f=l.getRangeAt(u),{startContainer:d,startOffset:g,endContainer:_,endOffset:y}=f;Je(d,i,r,!0)||Je(_,i,r,!0)||c.push({start:t.getId(d),startOffset:g,end:t.getId(_),endOffset:y})}n({ranges:c})};return a(),Ze("selectionchange",a)}function e0(s,e){const{mutationCb:t,mousemoveCb:i,mouseInteractionCb:r,scrollCb:n,viewportResizeCb:o,inputCb:a,mediaInteractionCb:l,styleSheetRuleCb:c,styleDeclarationCb:h,canvasMutationCb:u,fontCb:f,selectionCb:d}=s;s.mutationCb=(...g)=>{e.mutation&&e.mutation(...g),t(...g)},s.mousemoveCb=(...g)=>{e.mousemove&&e.mousemove(...g),i(...g)},s.mouseInteractionCb=(...g)=>{e.mouseInteraction&&e.mouseInteraction(...g),r(...g)},s.scrollCb=(...g)=>{e.scroll&&e.scroll(...g),n(...g)},s.viewportResizeCb=(...g)=>{e.viewportResize&&e.viewportResize(...g),o(...g)},s.inputCb=(...g)=>{e.input&&e.input(...g),a(...g)},s.mediaInteractionCb=(...g)=>{e.mediaInteaction&&e.mediaInteaction(...g),l(...g)},s.styleSheetRuleCb=(...g)=>{e.styleSheetRule&&e.styleSheetRule(...g),c(...g)},s.styleDeclarationCb=(...g)=>{e.styleDeclaration&&e.styleDeclaration(...g),h(...g)},s.canvasMutationCb=(...g)=>{e.canvasMutation&&e.canvasMutation(...g),u(...g)},s.fontCb=(...g)=>{e.font&&e.font(...g),f(...g)},s.selectionCb=(...g)=>{e.selection&&e.selection(...g),d(...g)}}function t0(s,e={}){const t=s.doc.defaultView;if(!t)return()=>{};e0(s,e);const i=fd(s,s.doc),r=zv(s),n=$v(s),o=pd(s),a=jv(s),l=Yv(s),c=Zv(s),h=qv(s,{win:t}),u=_d(s,s.doc),f=Kv(s,{win:t}),d=s.collectFonts?Jv(s):()=>{},g=Qv(s),_=[];for(const y of s.plugins)_.push(y.observer(y.callback,t,y.options));return()=>{ci.forEach(y=>y.reset()),i.disconnect(),r(),n(),o(),a(),l(),c(),h(),u(),f(),d(),g(),_.forEach(y=>y())}}class yd{constructor(e){this.generateIdFn=e,this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap}getId(e,t,i,r){const n=i||this.getIdToRemoteIdMap(e),o=r||this.getRemoteIdToIdMap(e);let a=n.get(t);return a||(a=this.generateIdFn(),n.set(t,a),o.set(a,t)),a}getIds(e,t){const i=this.getIdToRemoteIdMap(e),r=this.getRemoteIdToIdMap(e);return t.map(n=>this.getId(e,n,i,r))}getRemoteId(e,t,i){const r=i||this.getRemoteIdToIdMap(e);if(typeof t!="number")return t;const n=r.get(t);return n||-1}getRemoteIds(e,t){const i=this.getRemoteIdToIdMap(e);return t.map(r=>this.getRemoteId(e,r,i))}reset(e){if(!e){this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap;return}this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}}class i0{constructor(e){this.iframes=new WeakMap,this.crossOriginIframeMap=new WeakMap,this.crossOriginIframeMirror=new yd($u),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new yd(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var i;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),(i=this.loadListener)===null||i===void 0||i.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){if(e.data.type==="rrweb"){if(!e.source)return;const i=this.crossOriginIframeMap.get(e.source);if(!i)return;const r=this.transformCrossOriginEvent(i,e.data.event);r&&this.wrappedEmit(r,e.data.isCheckout)}}transformCrossOriginEvent(e,t){var i;switch(t.type){case ue.FullSnapshot:return this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e),{timestamp:t.timestamp,type:ue.IncrementalSnapshot,data:{source:oe.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}};case ue.Meta:case ue.Load:case ue.DomContentLoaded:return!1;case ue.Plugin:return t;case ue.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case ue.IncrementalSnapshot:switch(t.data.source){case oe.Mutation:return t.data.adds.forEach(r=>{this.replaceIds(r,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(r.node,e)}),t.data.removes.forEach(r=>{this.replaceIds(r,e,["parentId","id"])}),t.data.attributes.forEach(r=>{this.replaceIds(r,e,["id"])}),t.data.texts.forEach(r=>{this.replaceIds(r,e,["id"])}),t;case oe.Drag:case oe.TouchMove:case oe.MouseMove:return t.data.positions.forEach(r=>{this.replaceIds(r,e,["id"])}),t;case oe.ViewportResize:return!1;case oe.MediaInteraction:case oe.MouseInteraction:case oe.Scroll:case oe.CanvasMutation:case oe.Input:return this.replaceIds(t.data,e,["id"]),t;case oe.StyleSheetRule:case oe.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case oe.Font:return t;case oe.Selection:return t.data.ranges.forEach(r=>{this.replaceIds(r,e,["start","end"])}),t;case oe.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),(i=t.data.styles)===null||i===void 0||i.forEach(r=>{this.replaceStyleIds(r,e,["styleId"])}),t}}}replace(e,t,i,r){for(const n of r)!Array.isArray(t[n])&&typeof t[n]!="number"||(Array.isArray(t[n])?t[n]=e.getIds(i,t[n]):t[n]=e.getId(i,t[n]));return t}replaceIds(e,t,i){return this.replace(this.crossOriginIframeMirror,e,t,i)}replaceStyleIds(e,t,i){return this.replace(this.crossOriginIframeStyleMirror,e,t,i)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id"]),"childNodes"in e&&e.childNodes.forEach(i=>{this.replaceIdOnNode(i,t)})}}class s0{constructor(e){this.shadowDoms=new WeakSet,this.restorePatches=[],this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror;const t=this;this.restorePatches.push(Wi(Element.prototype,"attachShadow",function(i){return function(r){const n=i.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,this.ownerDocument),n}}))}addShadowRoot(e,t){Ts(e)&&(this.shadowDoms.has(e)||(this.shadowDoms.add(e),fd(Object.assign(Object.assign({},this.bypassOptions),{doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this}),e),pd(Object.assign(Object.assign({},this.bypassOptions),{scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(e.host)),_d({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e)},0)))}observeAttachShadow(e){if(e.contentWindow){const t=this;this.restorePatches.push(Wi(e.contentWindow.HTMLElement.prototype,"attachShadow",function(i){return function(r){const n=i.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,e.contentDocument),n}}))}}reset(){this.restorePatches.forEach(e=>e()),this.shadowDoms=new WeakSet}}/*! *****************************************************************************
959
959
  Copyright (c) Microsoft Corporation.
960
960
 
961
961
  Permission to use, copy, modify, and/or distribute this software for any
@@ -968,10 +968,10 @@ or you can use record.mirror to access the mirror instance during recording.`;le
968
968
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
969
969
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
970
970
  PERFORMANCE OF THIS SOFTWARE.
971
- ***************************************************************************** */function s0(s,e){var t={};for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(s);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(s,i[r])&&(t[i[r]]=s[i[r]]);return t}function r0(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,[])).next())})}for(var Vi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n0=typeof Uint8Array>"u"?[]:new Uint8Array(256),Sr=0;Sr<Vi.length;Sr++)n0[Vi.charCodeAt(Sr)]=Sr;var o0=function(s){var e=new Uint8Array(s),t,i=e.length,r="";for(t=0;t<i;t+=3)r+=Vi[e[t]>>2],r+=Vi[(e[t]&3)<<4|e[t+1]>>4],r+=Vi[(e[t+1]&15)<<2|e[t+2]>>6],r+=Vi[e[t+2]&63];return i%3===2?r=r.substring(0,r.length-1)+"=":i%3===1&&(r=r.substring(0,r.length-2)+"=="),r};const bd=new Map;function a0(s,e){let t=bd.get(s);return t||(t=new Map,bd.set(s,t)),t.has(e)||t.set(e,[]),t.get(e)}const xd=(s,e,t)=>{if(!s||!(Cd(s,e)||typeof s=="object"))return;const i=s.constructor.name,r=a0(t,i);let n=r.indexOf(s);return n===-1&&(n=r.length,r.push(s)),n};function Er(s,e,t){if(s instanceof Array)return s.map(i=>Er(i,e,t));if(s===null)return s;if(s instanceof Float32Array||s instanceof Float64Array||s instanceof Int32Array||s instanceof Uint32Array||s instanceof Uint8Array||s instanceof Uint16Array||s instanceof Int16Array||s instanceof Int8Array||s instanceof Uint8ClampedArray)return{rr_type:s.constructor.name,args:[Object.values(s)]};if(s instanceof ArrayBuffer){const i=s.constructor.name,r=o0(s);return{rr_type:i,base64:r}}else{if(s instanceof DataView)return{rr_type:s.constructor.name,args:[Er(s.buffer,e,t),s.byteOffset,s.byteLength]};if(s instanceof HTMLImageElement){const i=s.constructor.name,{src:r}=s;return{rr_type:i,src:r}}else if(s instanceof HTMLCanvasElement){const i="HTMLImageElement",r=s.toDataURL();return{rr_type:i,src:r}}else{if(s instanceof ImageData)return{rr_type:s.constructor.name,args:[Er(s.data,e,t),s.width,s.height]};if(Cd(s,e)||typeof s=="object"){const i=s.constructor.name,r=xd(s,e,t);return{rr_type:i,index:r}}}}return s}const vd=(s,e,t)=>[...s].map(i=>Er(i,e,t)),Cd=(s,e)=>!!["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(r=>typeof e[r]=="function").find(r=>s instanceof e[r]);function l0(s,e,t,i){const r=[],n=Object.getOwnPropertyNames(e.CanvasRenderingContext2D.prototype);for(const o of n)try{if(typeof e.CanvasRenderingContext2D.prototype[o]!="function")continue;const a=Wi(e.CanvasRenderingContext2D.prototype,o,function(l){return function(...c){return Je(this.canvas,t,i,!0)||setTimeout(()=>{const h=vd([...c],e,this);s(this.canvas,{type:Hi["2D"],property:o,args:h})},0),l.apply(this,c)}});r.push(a)}catch{const l=vr(e.CanvasRenderingContext2D.prototype,o,{set(c){s(this.canvas,{type:Hi["2D"],property:o,args:[c],setter:!0})}});r.push(l)}return()=>{r.forEach(o=>o())}}function Sd(s,e,t){const i=[];try{const r=Wi(s.HTMLCanvasElement.prototype,"getContext",function(n){return function(o,...a){return Je(this,e,t,!0)||"__context"in this||(this.__context=o),n.apply(this,[o,...a])}});i.push(r)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{i.forEach(r=>r())}}function Ed(s,e,t,i,r,n,o){const a=[],l=Object.getOwnPropertyNames(s);for(const c of l)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(c))try{if(typeof s[c]!="function")continue;const h=Wi(s,c,function(u){return function(...f){const d=u.apply(this,f);if(xd(d,o,this),!Je(this.canvas,i,r,!0)){const g=vd([...f],o,this),_={type:e,property:c,args:g};t(this.canvas,_)}return d}});a.push(h)}catch{const u=vr(s,c,{set(f){t(this.canvas,{type:e,property:c,args:[f],setter:!0})}});a.push(u)}return a}function c0(s,e,t,i,r){const n=[];return n.push(...Ed(e.WebGLRenderingContext.prototype,Hi.WebGL,s,t,i,r,e)),typeof e.WebGL2RenderingContext<"u"&&n.push(...Ed(e.WebGL2RenderingContext.prototype,Hi.WebGL2,s,t,i,r,e)),()=>{n.forEach(o=>o())}}var Td=null;try{var h0=typeof module<"u"&&typeof module.require=="function"&&module.require("worker_threads")||typeof __non_webpack_require__=="function"&&__non_webpack_require__("worker_threads")||typeof require=="function"&&require("worker_threads");Td=h0.Worker}catch{}function u0(s,e){return Buffer.from(s,"base64").toString("utf8")}function d0(s,e,t){var i=u0(s),r=i.indexOf(`
972
- `,10)+1,n=i.substring(r)+"";return function(a){return new Td(n,Object.assign({},a,{eval:!0}))}}function f0(s,e){var t=atob(s);return t}function p0(s,e,t){var i=f0(s),r=i.indexOf(`
973
- `,10)+1,n=i.substring(r)+"",o=new Blob([n],{type:"application/javascript"});return URL.createObjectURL(o)}function m0(s,e,t){var i;return function(n){return i=i||p0(s),new Worker(i,n)}}var g0=Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";function _0(){return g0}function y0(s,e,t){return _0()?d0(s):m0(s)}var b0=y0("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qISAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KICAgIENvcHlyaWdodCAoYykgTWljcm9zb2Z0IENvcnBvcmF0aW9uLg0KDQogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55DQogICAgcHVycG9zZSB3aXRoIG9yIHdpdGhvdXQgZmVlIGlzIGhlcmVieSBncmFudGVkLg0KDQogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTIFdJVEgNCiAgICBSRUdBUkQgVE8gVEhJUyBTT0ZUV0FSRSBJTkNMVURJTkcgQUxMIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkNCiAgICBBTkQgRklUTkVTUy4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIEFVVEhPUiBCRSBMSUFCTEUgRk9SIEFOWSBTUEVDSUFMLCBESVJFQ1QsDQogICAgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUyBXSEFUU09FVkVSIFJFU1VMVElORyBGUk9NDQogICAgTE9TUyBPRiBVU0UsIERBVEEgT1IgUFJPRklUUywgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1INCiAgICBPVEhFUiBUT1JUSU9VUyBBQ1RJT04sIEFSSVNJTkcgT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgVVNFIE9SDQogICAgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4NCiAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiAqLw0KDQogICAgZnVuY3Rpb24gX19hd2FpdGVyKHRoaXNBcmcsIF9hcmd1bWVudHMsIFAsIGdlbmVyYXRvcikgew0KICAgICAgICBmdW5jdGlvbiBhZG9wdCh2YWx1ZSkgeyByZXR1cm4gdmFsdWUgaW5zdGFuY2VvZiBQID8gdmFsdWUgOiBuZXcgUChmdW5jdGlvbiAocmVzb2x2ZSkgeyByZXNvbHZlKHZhbHVlKTsgfSk7IH0NCiAgICAgICAgcmV0dXJuIG5ldyAoUCB8fCAoUCA9IFByb21pc2UpKShmdW5jdGlvbiAocmVzb2x2ZSwgcmVqZWN0KSB7DQogICAgICAgICAgICBmdW5jdGlvbiBmdWxmaWxsZWQodmFsdWUpIHsgdHJ5IHsgc3RlcChnZW5lcmF0b3IubmV4dCh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiByZWplY3RlZCh2YWx1ZSkgeyB0cnkgeyBzdGVwKGdlbmVyYXRvclsidGhyb3ciXSh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiBzdGVwKHJlc3VsdCkgeyByZXN1bHQuZG9uZSA/IHJlc29sdmUocmVzdWx0LnZhbHVlKSA6IGFkb3B0KHJlc3VsdC52YWx1ZSkudGhlbihmdWxmaWxsZWQsIHJlamVjdGVkKTsgfQ0KICAgICAgICAgICAgc3RlcCgoZ2VuZXJhdG9yID0gZ2VuZXJhdG9yLmFwcGx5KHRoaXNBcmcsIF9hcmd1bWVudHMgfHwgW10pKS5uZXh0KCkpOw0KICAgICAgICB9KTsNCiAgICB9CgogICAgLyoKICAgICAqIGJhc2U2NC1hcnJheWJ1ZmZlciAxLjAuMSA8aHR0cHM6Ly9naXRodWIuY29tL25pa2xhc3ZoL2Jhc2U2NC1hcnJheWJ1ZmZlcj4KICAgICAqIENvcHlyaWdodCAoYykgMjAyMSBOaWtsYXMgdm9uIEhlcnR6ZW4gPGh0dHBzOi8vaGVydHplbi5jb20+CiAgICAgKiBSZWxlYXNlZCB1bmRlciBNSVQgTGljZW5zZQogICAgICovCiAgICB2YXIgY2hhcnMgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyc7CiAgICAvLyBVc2UgYSBsb29rdXAgdGFibGUgdG8gZmluZCB0aGUgaW5kZXguCiAgICB2YXIgbG9va3VwID0gdHlwZW9mIFVpbnQ4QXJyYXkgPT09ICd1bmRlZmluZWQnID8gW10gOiBuZXcgVWludDhBcnJheSgyNTYpOwogICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjaGFycy5sZW5ndGg7IGkrKykgewogICAgICAgIGxvb2t1cFtjaGFycy5jaGFyQ29kZUF0KGkpXSA9IGk7CiAgICB9CiAgICB2YXIgZW5jb2RlID0gZnVuY3Rpb24gKGFycmF5YnVmZmVyKSB7CiAgICAgICAgdmFyIGJ5dGVzID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlidWZmZXIpLCBpLCBsZW4gPSBieXRlcy5sZW5ndGgsIGJhc2U2NCA9ICcnOwogICAgICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkgKz0gMykgewogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaV0gPj4gMl07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2ldICYgMykgPDwgNCkgfCAoYnl0ZXNbaSArIDFdID4+IDQpXTsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzWygoYnl0ZXNbaSArIDFdICYgMTUpIDw8IDIpIHwgKGJ5dGVzW2kgKyAyXSA+PiA2KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1tieXRlc1tpICsgMl0gJiA2M107CiAgICAgICAgfQogICAgICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgJz0nOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgJz09JzsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGJhc2U2NDsKICAgIH07CgogICAgY29uc3QgbGFzdEJsb2JNYXAgPSBuZXcgTWFwKCk7DQogICAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gbmV3IE1hcCgpOw0KICAgIGZ1bmN0aW9uIGdldFRyYW5zcGFyZW50QmxvYkZvcih3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucykgew0KICAgICAgICByZXR1cm4gX19hd2FpdGVyKHRoaXMsIHZvaWQgMCwgdm9pZCAwLCBmdW5jdGlvbiogKCkgew0KICAgICAgICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgaWYgKHRyYW5zcGFyZW50QmxvYk1hcC5oYXMoaWQpKQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7DQogICAgICAgICAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsNCiAgICAgICAgICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgnMmQnKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0geWllbGQgYmxvYi5hcnJheUJ1ZmZlcigpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7DQogICAgICAgICAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICByZXR1cm4gYmFzZTY0Ow0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgZWxzZSB7DQogICAgICAgICAgICAgICAgcmV0dXJuICcnOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICB9DQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsNCiAgICB3b3JrZXIub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsNCiAgICAgICAgcmV0dXJuIF9fYXdhaXRlcih0aGlzLCB2b2lkIDAsIHZvaWQgMCwgZnVuY3Rpb24qICgpIHsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOw0KICAgICAgICAgICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsNCiAgICAgICAgICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCcyZCcpOw0KICAgICAgICAgICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsNCiAgICAgICAgICAgICAgICBiaXRtYXAuY2xvc2UoKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7DQogICAgICAgICAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSB5aWVsZCBibG9iLmFycmF5QnVmZmVyKCk7DQogICAgICAgICAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsNCiAgICAgICAgICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgKHlpZWxkIHRyYW5zcGFyZW50QmFzZTY0KSA9PT0gYmFzZTY0KSB7DQogICAgICAgICAgICAgICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7DQogICAgICAgICAgICAgICAgd29ya2VyLnBvc3RNZXNzYWdlKHsNCiAgICAgICAgICAgICAgICAgICAgaWQsDQogICAgICAgICAgICAgICAgICAgIHR5cGUsDQogICAgICAgICAgICAgICAgICAgIGJhc2U2NCwNCiAgICAgICAgICAgICAgICAgICAgd2lkdGgsDQogICAgICAgICAgICAgICAgICAgIGhlaWdodCwNCiAgICAgICAgICAgICAgICB9KTsNCiAgICAgICAgICAgICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBlbHNlIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfTsKCn0pKCk7Cgo=");class x0{constructor(e){this.pendingCanvasMutations=new Map,this.rafStamps={latestId:0,invokeId:null},this.frozen=!1,this.locked=!1,this.processMutation=(l,c)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(l)||this.pendingCanvasMutations.set(l,[]),this.pendingCanvasMutations.get(l).push(c)};const{sampling:t="all",win:i,blockClass:r,blockSelector:n,recordCanvas:o,dataURLOptions:a}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,o&&t==="all"&&this.initCanvasMutationObserver(i,r,n),o&&typeof t=="number"&&this.initCanvasFPSObserver(t,i,r,n,{dataURLOptions:a})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,i,r,n){const o=Sd(t,i,r),a=new Map,l=new b0;l.onmessage=g=>{const{id:_}=g.data;if(a.set(_,!1),!("base64"in g.data))return;const{base64:b,type:x,width:C,height:S}=g.data;this.mutationCb({id:_,type:Hi["2D"],commands:[{property:"clearRect",args:[0,0,C,S]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:b}],type:x}]},0,0]}]})};const c=1e3/e;let h=0,u;const f=()=>{const g=[];return t.document.querySelectorAll("canvas").forEach(_=>{Je(_,i,r,!0)||g.push(_)}),g},d=g=>{if(h&&g-h<c){u=requestAnimationFrame(d);return}h=g,f().forEach(_=>r0(this,void 0,void 0,function*(){var b;const x=this.mirror.getId(_);if(a.get(x))return;if(a.set(x,!0),["webgl","webgl2"].includes(_.__context)){const S=_.getContext(_.__context);((b=S==null?void 0:S.getContextAttributes())===null||b===void 0?void 0:b.preserveDrawingBuffer)===!1&&(S==null||S.clear(S.COLOR_BUFFER_BIT))}const C=yield createImageBitmap(_);l.postMessage({id:x,bitmap:C,width:_.width,height:_.height,dataURLOptions:n.dataURLOptions},[C])})),u=requestAnimationFrame(d)};u=requestAnimationFrame(d),this.resetObservers=()=>{o(),cancelAnimationFrame(u)}}initCanvasMutationObserver(e,t,i){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const r=Sd(e,t,i),n=l0(this.processMutation.bind(this),e,t,i),o=c0(this.processMutation.bind(this),e,t,i,this.mirror);this.resetObservers=()=>{r(),n(),o()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const i=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,i)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const i=this.pendingCanvasMutations.get(e);if(!i||t===-1)return;const r=i.map(o=>s0(o,["type"])),{type:n}=i[0];this.mutationCb({id:t,type:n,commands:r}),this.pendingCanvasMutations.delete(e)}}class v0{constructor(e){this.trackedLinkElements=new WeakSet,this.styleMirror=new Lv,this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(e.length===0)return;const i={id:t,styleIds:[]},r=[];for(const n of e){let o;if(this.styleMirror.has(n))o=this.styleMirror.getId(n);else{o=this.styleMirror.add(n);const a=Array.from(n.rules||CSSRule);r.push({styleId:o,rules:a.map((l,c)=>({rule:Hu(l),index:c}))})}i.styleIds.push(o)}r.length>0&&(i.styles=r),this.adoptedStyleSheetCb(i)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(e){}}function Fe(s){return Object.assign(Object.assign({},s),{timestamp:Date.now()})}let Oe,Tr,$o,Ar=!1;const ft=mv();function zi(s={}){const{emit:e,checkoutEveryNms:t,checkoutEveryNth:i,blockClass:r="rr-block",blockSelector:n=null,ignoreClass:o="rr-ignore",maskTextClass:a="rr-mask",maskTextSelector:l=null,inlineStylesheet:c=!0,maskAllInputs:h,maskInputOptions:u,slimDOMOptions:f,maskInputFn:d,maskTextFn:g,hooks:_,packFn:b,sampling:x={},dataURLOptions:C={},mousemoveWait:S,recordCanvas:E=!1,recordCrossOriginIframes:w=!1,userTriggeredOnInput:R=!1,collectFonts:M=!1,inlineImages:D=!1,plugins:F,keepIframeSrcFn:k=()=>!1,ignoreCSSAttributes:O=new Set([])}=s,V=w?window.parent===window:!0;let X=!1;if(!V)try{window.parent.document,X=!1}catch{X=!0}if(V&&!e)throw new Error("emit function is required");S!==void 0&&x.mousemove===void 0&&(x.mousemove=S),ft.reset();const z=h===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:u!==void 0?u:{password:!0},de=f===!0||f==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:f==="all",headMetaDescKeywords:f==="all"}:f||{};Gv();let B,U=0;const q=G=>{for(const fe of F||[])fe.eventProcessor&&(G=fe.eventProcessor(G));return b&&(G=b(G)),G};Oe=(G,fe)=>{var le;if(!((le=ci[0])===null||le===void 0)&&le.isFrozen()&&G.type!==ue.FullSnapshot&&!(G.type===ue.IncrementalSnapshot&&G.data.source===oe.Mutation)&&ci.forEach(L=>L.unfreeze()),V)e==null||e(q(G),fe);else if(X){const L={type:"rrweb",event:q(G),isCheckout:fe};window.parent.postMessage(L,"*")}if(G.type===ue.FullSnapshot)B=G,U=0;else if(G.type===ue.IncrementalSnapshot){if(G.data.source===oe.Mutation&&G.data.isAttachIframe)return;U++;const L=i&&U>=i,me=t&&G.timestamp-B.timestamp>t;(L||me)&&Tr(!0)}};const N=G=>{Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Mutation},G)}))},K=G=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Scroll},G)})),Z=G=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.CanvasMutation},G)})),$=G=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.AdoptedStyleSheet},G)})),ae=new v0({mutationCb:N,adoptedStyleSheetCb:$}),Ce=new t0({mirror:ft,mutationCb:N,stylesheetManager:ae,recordCrossOriginIframes:w,wrappedEmit:Oe});for(const G of F||[])G.getMirror&&G.getMirror({nodeMirror:ft,crossOriginIframeMirror:Ce.crossOriginIframeMirror,crossOriginIframeStyleMirror:Ce.crossOriginIframeStyleMirror});$o=new x0({recordCanvas:E,mutationCb:Z,win:window,blockClass:r,blockSelector:n,mirror:ft,sampling:x.canvas,dataURLOptions:C});const Ee=new i0({mutationCb:N,scrollCb:K,bypassOptions:{blockClass:r,blockSelector:n,maskTextClass:a,maskTextSelector:l,inlineStylesheet:c,maskInputOptions:z,dataURLOptions:C,maskTextFn:g,maskInputFn:d,recordCanvas:E,inlineImages:D,sampling:x,slimDOMOptions:de,iframeManager:Ce,stylesheetManager:ae,canvasManager:$o,keepIframeSrcFn:k},mirror:ft});Tr=(G=!1)=>{var fe,le,L,me,Y,ie;Oe(Fe({type:ue.Meta,data:{href:window.location.href,width:Zu(),height:Ku()}}),G),ae.reset(),ci.forEach(ce=>ce.lock());const we=Uv(document,{mirror:ft,blockClass:r,blockSelector:n,maskTextClass:a,maskTextSelector:l,inlineStylesheet:c,maskAllInputs:z,maskTextFn:g,slimDOM:de,dataURLOptions:C,recordCanvas:E,inlineImages:D,onSerialize:ce=>{ed(ce,ft)&&Ce.addIframe(ce),td(ce,ft)&&ae.trackLinkElement(ce),id(ce)&&Ee.addShadowRoot(ce.shadowRoot,document)},onIframeLoad:(ce,He)=>{Ce.attachIframe(ce,He),Ee.observeAttachShadow(ce)},onStylesheetLoad:(ce,He)=>{ae.attachLinkElement(ce,He)},keepIframeSrcFn:k});if(!we)return console.warn("Failed to snapshot the document");Oe(Fe({type:ue.FullSnapshot,data:{node:we,initialOffset:{left:window.pageXOffset!==void 0?window.pageXOffset:(document==null?void 0:document.documentElement.scrollLeft)||((le=(fe=document==null?void 0:document.body)===null||fe===void 0?void 0:fe.parentElement)===null||le===void 0?void 0:le.scrollLeft)||((L=document==null?void 0:document.body)===null||L===void 0?void 0:L.scrollLeft)||0,top:window.pageYOffset!==void 0?window.pageYOffset:(document==null?void 0:document.documentElement.scrollTop)||((Y=(me=document==null?void 0:document.body)===null||me===void 0?void 0:me.parentElement)===null||Y===void 0?void 0:Y.scrollTop)||((ie=document==null?void 0:document.body)===null||ie===void 0?void 0:ie.scrollTop)||0}}})),ci.forEach(ce=>ce.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ae.adoptStyleSheets(document.adoptedStyleSheets,ft.getId(document))};try{const G=[];G.push(Ze("DOMContentLoaded",()=>{Oe(Fe({type:ue.DomContentLoaded,data:{}}))}));const fe=L=>{var me;return e0({mutationCb:N,mousemoveCb:(Y,ie)=>Oe(Fe({type:ue.IncrementalSnapshot,data:{source:ie,positions:Y}})),mouseInteractionCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.MouseInteraction},Y)})),scrollCb:K,viewportResizeCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.ViewportResize},Y)})),inputCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Input},Y)})),mediaInteractionCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.MediaInteraction},Y)})),styleSheetRuleCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.StyleSheetRule},Y)})),styleDeclarationCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.StyleDeclaration},Y)})),canvasMutationCb:Z,fontCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Font},Y)})),selectionCb:Y=>{Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Selection},Y)}))},blockClass:r,ignoreClass:o,maskTextClass:a,maskTextSelector:l,maskInputOptions:z,inlineStylesheet:c,sampling:x,recordCanvas:E,inlineImages:D,userTriggeredOnInput:R,collectFonts:M,doc:L,maskInputFn:d,maskTextFn:g,keepIframeSrcFn:k,blockSelector:n,slimDOMOptions:de,dataURLOptions:C,mirror:ft,iframeManager:Ce,stylesheetManager:ae,shadowDomManager:Ee,canvasManager:$o,ignoreCSSAttributes:O,plugins:((me=F==null?void 0:F.filter(Y=>Y.observer))===null||me===void 0?void 0:me.map(Y=>({observer:Y.observer,options:Y.options,callback:ie=>Oe(Fe({type:ue.Plugin,data:{plugin:Y.name,payload:ie}}))})))||[]},_)};Ce.addLoadListener(L=>{G.push(fe(L.contentDocument))});const le=()=>{Tr(),G.push(fe(document)),Ar=!0};return document.readyState==="interactive"||document.readyState==="complete"?le():G.push(Ze("load",()=>{Oe(Fe({type:ue.Load,data:{}})),le()},window)),()=>{G.forEach(L=>L()),Ar=!1}}catch(G){console.warn(G)}}zi.addCustomEvent=(s,e)=>{if(!Ar)throw new Error("please add custom event after start recording");Oe(Fe({type:ue.Custom,data:{tag:s,payload:e}}))},zi.freezePage=()=>{ci.forEach(s=>s.freeze())},zi.takeFullSnapshot=s=>{if(!Ar)throw new Error("please take full snapshot after start recording");Tr(s)},zi.mirror=ft;const C0=3e4,S0=3,E0=0;function T0(s){if(s.type!==S0)return!1;const e=s.data;if(!e||e.source!==E0)return!1;const{adds:t,removes:i,texts:r,attributes:n}=e;return t&&t.length||i&&i.length||r&&r.length?!1:n&&n.length>0?n.every(o=>o.attributes&&Object.keys(o.attributes).length===1&&"style"in o.attributes):!0}function A0(){for(const s of[Text,Comment,CDATASection,ProcessingInstruction])s.prototype.matches||(s.prototype.matches=function(){return!1})}class Ad{constructor(){this.onEvent=null,this.stopFn=null,this._recording=!1,this._paused=!1}get isRecording(){return this._recording}get isPaused(){return this._paused}start(){if(this._recording)return;A0();const e=zi({emit:t=>{var i;this._paused||T0(t)||(i=this.onEvent)==null||i.call(this,t)},checkoutEveryNms:C0,blockClass:"hs-no-record",blockSelector:'#holostaff-widget-root, #holostaff-agent, [id^="anam-avatar"], video, [autocomplete^="cc-"], [data-hs-no-record]',maskAllInputs:!1,maskInputOptions:{password:!0,email:!0,tel:!0},maskTextSelector:"[data-hs-mask]",sampling:{mousemove:100,scroll:150,input:"last"}});e?(this.stopFn=e,this._recording=!0,this._paused=!1,console.log("[RRWebRecorder] Started recording")):console.warn("[RRWebRecorder] record() returned undefined — recording may have failed")}stop(){var e;this._recording&&((e=this.stopFn)==null||e.call(this),this.stopFn=null,this._recording=!1,this._paused=!1,console.log("[RRWebRecorder] Stopped recording"))}pause(){!this._recording||this._paused||(this._paused=!0,console.log("[RRWebRecorder] Paused"))}resume(){!this._recording||!this._paused||(this._paused=!1,zi.takeFullSnapshot(),console.log("[RRWebRecorder] Resumed (full snapshot taken)"))}}function w0(s){return s.startsWith("ws://")||s.startsWith("wss://")?s:`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}${s.startsWith("/")?"":"/"}${s}`}const wd=1e3,I0=3e4,R0=500;class Id{constructor(e,t){this.onIntervention=null,this.onStatus=null,this.onConnected=null,this.onDisconnected=null,this.ws=null,this.eventBuffer=[],this.reconnectDelay=wd,this.reconnectTimer=null,this._connected=!1,this._closed=!1,this.url=w0(e),this.initPayload={type:"init",...t}}get isConnected(){return this._connected}connect(){this._closed||this.doConnect()}close(){if(this._closed=!0,this.clearReconnectTimer(),this.ws){try{this.ws.close()}catch{}this.ws=null}this._connected=!1}sendRRWebEvent(e){this.send({type:"rrweb",event:e})}sendActionComplete(e,t){this.send({type:"action_complete",actionId:e,result:t})}sendConversationStarted(){this.send({type:"conversation_started"})}sendConversationEnded(e){this.send({type:"conversation_ended",summary:e})}sendPageChanged(e,t,i){this.send({type:"page_changed",url:e,pathname:t,title:i})}doConnect(){if(!this._closed){try{this.ws=new WebSocket(this.url)}catch(e){console.warn("[VisionWS] Failed to create WebSocket:",e),this.scheduleReconnect();return}this.ws.onopen=()=>{var e;console.log("[VisionWS] Connected"),this._connected=!0,this.reconnectDelay=wd,this.ws.send(JSON.stringify(this.initPayload)),this.flushBuffer(),(e=this.onConnected)==null||e.call(this)},this.ws.onmessage=e=>{const t=e.data;typeof t=="string"?this.parseAndHandle(t):t instanceof Blob?t.text().then(i=>this.parseAndHandle(i)):t instanceof ArrayBuffer?this.parseAndHandle(new TextDecoder().decode(t)):console.warn("[VisionWS] Unknown message data type:",typeof t)},this.ws.onclose=()=>{var t;const e=this._connected;this._connected=!1,this.ws=null,e&&(console.log("[VisionWS] Disconnected"),(t=this.onDisconnected)==null||t.call(this)),this._closed||this.scheduleReconnect()},this.ws.onerror=e=>{console.warn("[VisionWS] Error:",e)}}}parseAndHandle(e){var t,i;try{const r=JSON.parse(e);switch(r.type){case"suggest_intervention":(t=this.onIntervention)==null||t.call(this,r);break;case"status":(i=this.onStatus)==null||i.call(this,r);break;default:console.log("[VisionWS] Unknown message type:",r.type)}}catch(r){console.warn("[VisionWS] Failed to parse message:",r)}}send(e){var t;this._connected&&((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?this.ws.send(JSON.stringify(e)):(this.eventBuffer.length>=R0&&this.eventBuffer.shift(),this.eventBuffer.push(e))}flushBuffer(){if(!(!this._connected||!this.ws)){for(const e of this.eventBuffer)this.ws.send(JSON.stringify(e));this.eventBuffer.length>0&&console.log(`[VisionWS] Flushed ${this.eventBuffer.length} buffered messages`),this.eventBuffer=[]}}scheduleReconnect(){if(this._closed||this.reconnectTimer)return;const e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*2,I0),console.log(`[VisionWS] Reconnecting in ${e}ms...`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}}const M0={sm:"var(--hs-radius-sm)",md:"var(--hs-radius-md)",lg:"var(--hs-radius-lg)",pill:"var(--hs-radius-pill)"},P0={base:"var(--hs-glass-bg)",elevated:"var(--hs-glass-bg-elevated)",solid:"var(--hs-glass-bg-solid)"};function Kt(s={}){const{tag:e="div",radius:t="md",elevation:i="base",interactive:r=!1,className:n,role:o}=s,a=document.createElement(e);return n&&(a.className=n),o&&a.setAttribute("role",o),Object.assign(a.style,{background:P0[i],backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",border:"1px solid var(--hs-glass-border)",borderRadius:M0[t],boxShadow:i==="elevated"?"var(--hs-glass-shadow-elevated)":"var(--hs-glass-shadow)",color:"var(--hs-text-primary)",fontFamily:"var(--hs-font)",fontSize:"var(--hs-text-base)",lineHeight:"var(--hs-line-height)",boxSizing:"border-box"}),r&&(a.style.transition=`border-color var(--hs-fade-duration) var(--hs-ease-fast),
974
- box-shadow var(--hs-fade-duration) var(--hs-ease-fast)`,a.style.cursor="pointer",a.addEventListener("mouseenter",()=>{a.style.borderColor="var(--hs-glass-border-hover)"}),a.addEventListener("mouseleave",()=>{a.style.borderColor="var(--hs-glass-border)"})),a}function vt(s,e="primary",t="base",i="normal"){const r={primary:"var(--hs-text-primary)",secondary:"var(--hs-text-secondary)",tertiary:"var(--hs-text-tertiary)"},n={xs:"var(--hs-text-xs)",sm:"var(--hs-text-sm)",base:"var(--hs-text-base)",lg:"var(--hs-text-lg)",xl:"var(--hs-text-xl)"},o={normal:"var(--hs-weight-normal)",medium:"var(--hs-weight-medium)",semibold:"var(--hs-weight-semibold)"};return Object.assign(s.style,{color:r[e],fontSize:n[t],fontWeight:o[i],fontFamily:"var(--hs-font)",lineHeight:"var(--hs-line-height)",margin:"0"}),s}function Ct(s){const{label:e,variant:t="default",size:i="md",icon:r,onClick:n}=s,o=document.createElement("button");o.textContent=r?`${r} ${e}`:e;const a=i==="sm"?"4px 10px":"8px 16px",l=i==="sm"?"var(--hs-text-sm)":"var(--hs-text-base)";switch(Object.assign(o.style,{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"var(--hs-space-1)",padding:a,fontSize:l,fontWeight:"var(--hs-weight-medium)",fontFamily:"var(--hs-font)",lineHeight:"1",border:"none",borderRadius:"var(--hs-radius-pill)",cursor:"pointer",transition:"all var(--hs-fade-duration) var(--hs-ease-fast)",outline:"none",whiteSpace:"nowrap"}),t){case"accent":Object.assign(o.style,{background:"var(--hs-accent)",color:"var(--hs-accent-text)",boxShadow:"0 2px 12px var(--hs-accent-glow)"}),o.addEventListener("mouseenter",()=>{o.style.filter="brightness(1.12)",o.style.transform="scale(1.03)"}),o.addEventListener("mouseleave",()=>{o.style.filter="",o.style.transform=""});break;case"ghost":Object.assign(o.style,{background:"transparent",color:"var(--hs-text-secondary)"}),o.addEventListener("mouseenter",()=>{o.style.background="var(--hs-glass-bg)",o.style.color="var(--hs-text-primary)"}),o.addEventListener("mouseleave",()=>{o.style.background="transparent",o.style.color="var(--hs-text-secondary)"});break;default:Object.assign(o.style,{background:"var(--hs-glass-bg-elevated)",color:"var(--hs-text-primary)",backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",border:"1px solid var(--hs-glass-border)"}),o.addEventListener("mouseenter",()=>{o.style.borderColor="var(--hs-glass-border-hover)",o.style.transform="scale(1.03)"}),o.addEventListener("mouseleave",()=>{o.style.borderColor="var(--hs-glass-border)",o.style.transform=""});break}return n&&o.addEventListener("click",c=>{c.stopPropagation(),n(c)}),o}function Rd(s,e){var t={};for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(s);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(s,i[r])&&(t[i[r]]=s[i[r]]);return t}var Md=function(){};const jo=(s,e,t)=>Math.min(Math.max(t,s),e),Xo=.001,k0=.01,O0=10,B0=.05,D0=1;function N0({duration:s=800,bounce:e=.25,velocity:t=0,mass:i=1}){let r,n,o=1-e;o=jo(B0,D0,o),s=jo(k0,O0,s/1e3),o<1?(r=c=>{const h=c*o,u=h*s,f=h-t,d=Yo(c,o),g=Math.exp(-u);return Xo-f/d*g},n=c=>{const u=c*o*s,f=u*t+t,d=Math.pow(o,2)*Math.pow(c,2)*s,g=Math.exp(-u),_=Yo(Math.pow(c,2),o);return(-r(c)+Xo>0?-1:1)*((f-d)*g)/_}):(r=c=>{const h=Math.exp(-c*s),u=(c-t)*s+1;return-Xo+h*u},n=c=>{const h=Math.exp(-c*s),u=(t-c)*(s*s);return h*u});const a=5/s,l=F0(r,n,a);if(s=s*1e3,isNaN(l))return{stiffness:100,damping:10,duration:s};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:o*2*Math.sqrt(i*c),duration:s}}}const U0=12;function F0(s,e,t){let i=t;for(let r=1;r<U0;r++)i=i-s(i)/e(i);return i}function Yo(s,e){return s*Math.sqrt(1-e*e)}const G0=["duration","bounce"],L0=["stiffness","damping","mass"];function Pd(s,e){return e.some(t=>s[t]!==void 0)}function W0(s){let e=Object.assign({velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1},s);if(!Pd(s,L0)&&Pd(s,G0)){const t=N0(s);e=Object.assign(Object.assign(Object.assign({},e),t),{velocity:0,mass:1}),e.isResolvedFromDuration=!0}return e}function qo(s){var{from:e=0,to:t=1,restSpeed:i=2,restDelta:r}=s,n=Rd(s,["from","to","restSpeed","restDelta"]);const o={done:!1,value:e};let{stiffness:a,damping:l,mass:c,velocity:h,duration:u,isResolvedFromDuration:f}=W0(n),d=kd,g=kd;function _(){const b=h?-(h/1e3):0,x=t-e,C=l/(2*Math.sqrt(a*c)),S=Math.sqrt(a/c)/1e3;if(r===void 0&&(r=Math.min(Math.abs(t-e)/100,.4)),C<1){const E=Yo(S,C);d=w=>{const R=Math.exp(-C*S*w);return t-R*((b+C*S*x)/E*Math.sin(E*w)+x*Math.cos(E*w))},g=w=>{const R=Math.exp(-C*S*w);return C*S*R*(Math.sin(E*w)*(b+C*S*x)/E+x*Math.cos(E*w))-R*(Math.cos(E*w)*(b+C*S*x)-E*x*Math.sin(E*w))}}else if(C===1)d=E=>t-Math.exp(-S*E)*(x+(b+S*x)*E);else{const E=S*Math.sqrt(C*C-1);d=w=>{const R=Math.exp(-C*S*w),M=Math.min(E*w,300);return t-R*((b+C*S*x)*Math.sinh(M)+E*x*Math.cosh(M))/E}}}return _(),{next:b=>{const x=d(b);if(f)o.done=b>=u;else{const C=g(b)*1e3,S=Math.abs(C)<=i,E=Math.abs(t-x)<=r;o.done=S&&E}return o.value=o.done?t:x,o},flipTarget:()=>{h=-h,[e,t]=[t,e],_()}}}qo.needsInterpolation=(s,e)=>typeof s=="string"||typeof e=="string";const kd=s=>0,Od=(s,e,t)=>{const i=e-s;return i===0?1:(t-s)/i},Ko=(s,e,t)=>-t*s+t*e+s,Bd=(s,e)=>t=>Math.max(Math.min(t,e),s),Rs=s=>s%1?Number(s.toFixed(5)):s,wr=/(-)?([\d]*\.?[\d])+/g,Zo=/(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi,H0=/^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;function Ms(s){return typeof s=="string"}const Ir={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},Dd=Object.assign(Object.assign({},Ir),{transform:Bd(0,1)});Object.assign(Object.assign({},Ir),{default:1});const Ps=(s=>({test:e=>Ms(e)&&e.endsWith(s)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${s}`}))("%");Object.assign(Object.assign({},Ps),{parse:s=>Ps.parse(s)/100,transform:s=>Ps.transform(s*100)});const Jo=(s,e)=>t=>!!(Ms(t)&&H0.test(t)&&t.startsWith(s)||e&&Object.prototype.hasOwnProperty.call(t,e)),Nd=(s,e,t)=>i=>{if(!Ms(i))return i;const[r,n,o,a]=i.match(wr);return{[s]:parseFloat(r),[e]:parseFloat(n),[t]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},hi={test:Jo("hsl","hue"),parse:Nd("hue","saturation","lightness"),transform:({hue:s,saturation:e,lightness:t,alpha:i=1})=>"hsla("+Math.round(s)+", "+Ps.transform(Rs(e))+", "+Ps.transform(Rs(t))+", "+Rs(Dd.transform(i))+")"},V0=Bd(0,255),Qo=Object.assign(Object.assign({},Ir),{transform:s=>Math.round(V0(s))}),Zt={test:Jo("rgb","red"),parse:Nd("red","green","blue"),transform:({red:s,green:e,blue:t,alpha:i=1})=>"rgba("+Qo.transform(s)+", "+Qo.transform(e)+", "+Qo.transform(t)+", "+Rs(Dd.transform(i))+")"};function z0(s){let e="",t="",i="",r="";return s.length>5?(e=s.substr(1,2),t=s.substr(3,2),i=s.substr(5,2),r=s.substr(7,2)):(e=s.substr(1,1),t=s.substr(2,1),i=s.substr(3,1),r=s.substr(4,1),e+=e,t+=t,i+=i,r+=r),{red:parseInt(e,16),green:parseInt(t,16),blue:parseInt(i,16),alpha:r?parseInt(r,16)/255:1}}const ea={test:Jo("#"),parse:z0,transform:Zt.transform},Rr={test:s=>Zt.test(s)||ea.test(s)||hi.test(s),parse:s=>Zt.test(s)?Zt.parse(s):hi.test(s)?hi.parse(s):ea.parse(s),transform:s=>Ms(s)?s:s.hasOwnProperty("red")?Zt.transform(s):hi.transform(s)},Ud="${c}",Fd="${n}";function $0(s){var e,t,i,r;return isNaN(s)&&Ms(s)&&((t=(e=s.match(wr))===null||e===void 0?void 0:e.length)!==null&&t!==void 0?t:0)+((r=(i=s.match(Zo))===null||i===void 0?void 0:i.length)!==null&&r!==void 0?r:0)>0}function Gd(s){typeof s=="number"&&(s=`${s}`);const e=[];let t=0;const i=s.match(Zo);i&&(t=i.length,s=s.replace(Zo,Ud),e.push(...i.map(Rr.parse)));const r=s.match(wr);return r&&(s=s.replace(wr,Fd),e.push(...r.map(Ir.parse))),{values:e,numColors:t,tokenised:s}}function Ld(s){return Gd(s).values}function Wd(s){const{values:e,numColors:t,tokenised:i}=Gd(s),r=e.length;return n=>{let o=i;for(let a=0;a<r;a++)o=o.replace(a<t?Ud:Fd,a<t?Rr.transform(n[a]):Rs(n[a]));return o}}const j0=s=>typeof s=="number"?0:s;function X0(s){const e=Ld(s);return Wd(s)(e.map(j0))}const Hd={test:$0,parse:Ld,createTransformer:Wd,getAnimatableNone:X0};function ta(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?s+(e-s)*6*t:t<1/2?e:t<2/3?s+(e-s)*(2/3-t)*6:s}function Vd({hue:s,saturation:e,lightness:t,alpha:i}){s/=360,e/=100,t/=100;let r=0,n=0,o=0;if(!e)r=n=o=t;else{const a=t<.5?t*(1+e):t+e-t*e,l=2*t-a;r=ta(l,a,s+1/3),n=ta(l,a,s),o=ta(l,a,s-1/3)}return{red:Math.round(r*255),green:Math.round(n*255),blue:Math.round(o*255),alpha:i}}const Y0=(s,e,t)=>{const i=s*s,r=e*e;return Math.sqrt(Math.max(0,t*(r-i)+i))},q0=[ea,Zt,hi],zd=s=>q0.find(e=>e.test(s)),$d=(s,e)=>{let t=zd(s),i=zd(e),r=t.parse(s),n=i.parse(e);t===hi&&(r=Vd(r),t=Zt),i===hi&&(n=Vd(n),i=Zt);const o=Object.assign({},r);return a=>{for(const l in o)l!=="alpha"&&(o[l]=Y0(r[l],n[l],a));return o.alpha=Ko(r.alpha,n.alpha,a),t.transform(o)}},K0=s=>typeof s=="number",Z0=(s,e)=>t=>e(s(t)),jd=(...s)=>s.reduce(Z0);function Xd(s,e){return K0(s)?t=>Ko(s,e,t):Rr.test(s)?$d(s,e):Kd(s,e)}const Yd=(s,e)=>{const t=[...s],i=t.length,r=s.map((n,o)=>Xd(n,e[o]));return n=>{for(let o=0;o<i;o++)t[o]=r[o](n);return t}},J0=(s,e)=>{const t=Object.assign(Object.assign({},s),e),i={};for(const r in t)s[r]!==void 0&&e[r]!==void 0&&(i[r]=Xd(s[r],e[r]));return r=>{for(const n in i)t[n]=i[n](r);return t}};function qd(s){const e=Hd.parse(s),t=e.length;let i=0,r=0,n=0;for(let o=0;o<t;o++)i||typeof e[o]=="number"?i++:e[o].hue!==void 0?n++:r++;return{parsed:e,numNumbers:i,numRGB:r,numHSL:n}}const Kd=(s,e)=>{const t=Hd.createTransformer(e),i=qd(s),r=qd(e);return i.numHSL===r.numHSL&&i.numRGB===r.numRGB&&i.numNumbers>=r.numNumbers?jd(Yd(i.parsed,r.parsed),t):o=>`${o>0?e:s}`},Q0=(s,e)=>t=>Ko(s,e,t);function eC(s){if(typeof s=="number")return Q0;if(typeof s=="string")return Rr.test(s)?$d:Kd;if(Array.isArray(s))return Yd;if(typeof s=="object")return J0}function tC(s,e,t){const i=[],r=t||eC(s[0]),n=s.length-1;for(let o=0;o<n;o++){let a=r(s[o],s[o+1]);if(e){const l=Array.isArray(e)?e[o]:e;a=jd(l,a)}i.push(a)}return i}function iC([s,e],[t]){return i=>t(Od(s,e,i))}function sC(s,e){const t=s.length,i=t-1;return r=>{let n=0,o=!1;if(r<=s[0]?o=!0:r>=s[i]&&(n=i-1,o=!0),!o){let l=1;for(;l<t&&!(s[l]>r||l===i);l++);n=l-1}const a=Od(s[n],s[n+1],r);return e[n](a)}}function Zd(s,e,{clamp:t=!0,ease:i,mixer:r}={}){const n=s.length;Md(n===e.length),Md(!i||!Array.isArray(i)||i.length===n-1),s[0]>s[n-1]&&(s=[].concat(s),e=[].concat(e),s.reverse(),e.reverse());const o=tC(e,i,r),a=n===2?iC(s,o):sC(s,o);return t?l=>a(jo(s[0],s[n-1],l)):a}const rC=s=>e=>e<=.5?s(2*e)/2:(2-s(2*(1-e)))/2,nC=(s=>e=>Math.pow(e,s))(2),oC=rC(nC);function aC(s,e){return s.map(()=>e||oC).splice(0,s.length-1)}function lC(s){const e=s.length;return s.map((t,i)=>i!==0?i/(e-1):0)}function cC(s,e){return s.map(t=>t*e)}function Mr({from:s=0,to:e=1,ease:t,offset:i,duration:r=300}){const n={done:!1,value:s},o=Array.isArray(e)?e:[s,e],a=cC(i&&i.length===o.length?i:lC(o),r);function l(){return Zd(a,o,{ease:Array.isArray(t)?t:aC(o,t)})}let c=l();return{next:h=>(n.value=c(h),n.done=h>=r,n),flipTarget:()=>{o.reverse(),c=l()}}}function hC({velocity:s=0,from:e=0,power:t=.8,timeConstant:i=350,restDelta:r=.5,modifyTarget:n}){const o={done:!1,value:e};let a=t*s;const l=e+a,c=n===void 0?l:n(l);return c!==l&&(a=c-e),{next:h=>{const u=-a*Math.exp(-h/i);return o.done=!(u>r||u<-r),o.value=o.done?c:c+u,o},flipTarget:()=>{}}}const Jd={keyframes:Mr,spring:qo,decay:hC};function uC(s){if(Array.isArray(s.to))return Mr;if(Jd[s.type])return Jd[s.type];const e=new Set(Object.keys(s));return e.has("ease")||e.has("duration")&&!e.has("dampingRatio")?Mr:e.has("dampingRatio")||e.has("stiffness")||e.has("mass")||e.has("damping")||e.has("restSpeed")||e.has("restDelta")?qo:Mr}const Qd=1/60*1e3,dC=typeof performance<"u"?()=>performance.now():()=>Date.now(),ef=typeof window<"u"?s=>window.requestAnimationFrame(s):s=>setTimeout(()=>s(dC()),Qd);function fC(s){let e=[],t=[],i=0,r=!1,n=!1;const o=new WeakSet,a={schedule:(l,c=!1,h=!1)=>{const u=h&&r,f=u?e:t;return c&&o.add(l),f.indexOf(l)===-1&&(f.push(l),u&&r&&(i=e.length)),l},cancel:l=>{const c=t.indexOf(l);c!==-1&&t.splice(c,1),o.delete(l)},process:l=>{if(r){n=!0;return}if(r=!0,[e,t]=[t,e],t.length=0,i=e.length,i)for(let c=0;c<i;c++){const h=e[c];h(l),o.has(h)&&(a.schedule(h),s())}r=!1,n&&(n=!1,a.process(l))}};return a}const pC=40;let ia=!0,ks=!1,sa=!1;const Os={delta:0,timestamp:0},Bs=["read","update","preRender","render","postRender"],Pr=Bs.reduce((s,e)=>(s[e]=fC(()=>ks=!0),s),{}),mC=Bs.reduce((s,e)=>{const t=Pr[e];return s[e]=(i,r=!1,n=!1)=>(ks||yC(),t.schedule(i,r,n)),s},{}),gC=Bs.reduce((s,e)=>(s[e]=Pr[e].cancel,s),{});Bs.reduce((s,e)=>(s[e]=()=>Pr[e].process(Os),s),{});const _C=s=>Pr[s].process(Os),tf=s=>{ks=!1,Os.delta=ia?Qd:Math.max(Math.min(s-Os.timestamp,pC),1),Os.timestamp=s,sa=!0,Bs.forEach(_C),sa=!1,ks&&(ia=!1,ef(tf))},yC=()=>{ks=!0,ia=!0,sa||ef(tf)};function sf(s,e,t=0){return s-e-t}function bC(s,e,t=0,i=!0){return i?sf(e+-s,e,t):e-(s-e)+t}function xC(s,e,t,i){return i?s>=e+t:s<=-t}const vC=s=>{const e=({delta:t})=>s(t);return{start:()=>mC.update(e,!0),stop:()=>gC.update(e)}};function CC(s){var e,t,{from:i,autoplay:r=!0,driver:n=vC,elapsed:o=0,repeat:a=0,repeatType:l="loop",repeatDelay:c=0,onPlay:h,onStop:u,onComplete:f,onRepeat:d,onUpdate:g}=s,_=Rd(s,["from","autoplay","driver","elapsed","repeat","repeatType","repeatDelay","onPlay","onStop","onComplete","onRepeat","onUpdate"]);let{to:b}=_,x,C=0,S=_.duration,E,w=!1,R=!0,M;const D=uC(_);!((t=(e=D).needsInterpolation)===null||t===void 0)&&t.call(e,i,b)&&(M=Zd([0,100],[i,b],{clamp:!1}),i=0,b=100);const F=D(Object.assign(Object.assign({},_),{from:i,to:b}));function k(){C++,l==="reverse"?(R=C%2===0,o=bC(o,S,c,R)):(o=sf(o,S,c),l==="mirror"&&F.flipTarget()),w=!1,d&&d()}function O(){x.stop(),f&&f()}function V(z){if(R||(z=-z),o+=z,!w){const de=F.next(Math.max(0,o));E=de.value,M&&(E=M(E)),w=R?de.done:o<=0}g==null||g(E),w&&(C===0&&(S??(S=o)),C<a?xC(o,S,c,R)&&k():O())}function X(){h==null||h(),x=n(V),x.start()}return r&&X(),{stop:()=>{u==null||u(),x.stop()}}}const SC={snappy:{stiffness:300,damping:28,mass:.8},gentle:{stiffness:170,damping:26,mass:1},bouncy:{stiffness:400,damping:20,mass:.6},smooth:{stiffness:200,damping:30,mass:1}};function Jt(s){const e=s.preset?SC[s.preset]:void 0,t=CC({from:s.from,to:s.to,type:"spring",stiffness:s.stiffness??(e==null?void 0:e.stiffness)??170,damping:s.damping??(e==null?void 0:e.damping)??26,mass:s.mass??(e==null?void 0:e.mass)??1,onUpdate:s.onUpdate,onComplete:s.onComplete});return{stop:()=>t.stop()}}function EC(s,e,t,i="smooth",r){return Jt({from:e,to:t,preset:i,onUpdate:n=>{s.style.opacity=String(n)},onComplete:r})}function rt(s,e={}){const{from:t={},preset:i="snappy",onComplete:r}=e,n=t.opacity??0,o=t.scale??.92,a=t.y??8;s.style.opacity=String(n),s.style.transform=`scale(${o}) translateY(${a}px)`;const l=[];let c=0;const h=3,u=()=>{++c>=h&&(r==null||r())};return l.push(Jt({from:n,to:1,preset:i,onUpdate:f=>{s.style.opacity=String(f)},onComplete:u})),l.push(Jt({from:o,to:1,preset:i,onUpdate:f=>{var g;const d=parseFloat(((g=s.style.transform.match(/translateY\(([^)]+)\)/))==null?void 0:g[1])??"0");s.style.transform=`scale(${f}) translateY(${d}px)`},onComplete:u})),l.push(Jt({from:a,to:0,preset:i,onUpdate:f=>{var g;const d=parseFloat(((g=s.style.transform.match(/scale\(([^)]+)\)/))==null?void 0:g[1])??"1");s.style.transform=`scale(${d}) translateY(${f}px)`},onComplete:u})),{stop:()=>l.forEach(f=>f.stop())}}function Nt(s,e={}){const{to:t={},preset:i="smooth",remove:r=!0,onComplete:n}=e,o=t.opacity??0,a=t.scale??.92,l=t.y??8,c=[];let h=0;const u=3,f=()=>{++h>=u&&(r&&s.remove(),n==null||n())};return c.push(Jt({from:parseFloat(s.style.opacity||"1"),to:o,preset:i,onUpdate:d=>{s.style.opacity=String(d)},onComplete:f})),c.push(Jt({from:1,to:a,preset:i,onUpdate:d=>{var _;const g=parseFloat(((_=s.style.transform.match(/translateY\(([^)]+)\)/))==null?void 0:_[1])??"0");s.style.transform=`scale(${d}) translateY(${g}px)`},onComplete:f})),c.push(Jt({from:0,to:l,preset:i,onUpdate:d=>{var _;const g=parseFloat(((_=s.style.transform.match(/scale\(([^)]+)\)/))==null?void 0:_[1])??"1");s.style.transform=`scale(${g}) translateY(${d}px)`},onComplete:f})),{stop:()=>c.forEach(d=>d.stop())}}const rf="holostaff-liquid-tokens",W={glassBlur:"20px",glassSaturate:"180%",dark:{glassBg:"rgba(255, 255, 255, 0.10)",glassBgElevated:"rgba(255, 255, 255, 0.16)",glassBgSolid:"rgba(30, 30, 40, 0.85)",glassBorder:"rgba(255, 255, 255, 0.14)",glassBorderHover:"rgba(255, 255, 255, 0.28)",glassShadow:"0 8px 32px rgba(0, 0, 0, 0.24)",glassShadowElevated:"0 12px 48px rgba(0, 0, 0, 0.32)",textPrimary:"rgba(255, 255, 255, 0.92)",textSecondary:"rgba(255, 255, 255, 0.56)",textTertiary:"rgba(255, 255, 255, 0.32)",divider:"rgba(255, 255, 255, 0.08)"},light:{glassBg:"rgba(255, 255, 255, 0.55)",glassBgElevated:"rgba(255, 255, 255, 0.72)",glassBgSolid:"rgba(255, 255, 255, 0.92)",glassBorder:"rgba(0, 0, 0, 0.06)",glassBorderHover:"rgba(0, 0, 0, 0.12)",glassShadow:"0 8px 32px rgba(0, 0, 0, 0.08)",glassShadowElevated:"0 12px 48px rgba(0, 0, 0, 0.12)",textPrimary:"rgba(0, 0, 0, 0.85)",textSecondary:"rgba(0, 0, 0, 0.50)",textTertiary:"rgba(0, 0, 0, 0.28)",divider:"rgba(0, 0, 0, 0.06)"},radiusSm:"10px",radiusMd:"16px",radiusLg:"24px",radiusPill:"9999px",font:"-apple-system, 'Inter', 'Segoe UI', system-ui, sans-serif",textXs:"11px",textSm:"12px",textBase:"14px",textLg:"16px",textXl:"20px",weightNormal:"400",weightMedium:"500",weightSemibold:"600",lineHeight:"1.45",springDuration:"500ms",springEasing:"cubic-bezier(0.34, 1.56, 0.64, 1)",easeFast:"cubic-bezier(0.25, 0.1, 0.25, 1)",fadeDuration:"200ms",accent:"#7C5CFF",accentGlow:"rgba(124, 92, 255, 0.35)",accentText:"#ffffff",space1:"4px",space2:"8px",space3:"12px",space4:"16px",space5:"20px",space6:"24px",space8:"32px",zOverlay:"2147483644",zControls:"2147483646",zTop:"2147483647"};function St(){if(document.getElementById(rf))return;const s=document.createElement("style");s.id=rf,s.textContent=`
971
+ ***************************************************************************** */function r0(s,e){var t={};for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(s);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(s,i[r])&&(t[i[r]]=s[i[r]]);return t}function n0(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,[])).next())})}for(var Vi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o0=typeof Uint8Array>"u"?[]:new Uint8Array(256),Er=0;Er<Vi.length;Er++)o0[Vi.charCodeAt(Er)]=Er;var a0=function(s){var e=new Uint8Array(s),t,i=e.length,r="";for(t=0;t<i;t+=3)r+=Vi[e[t]>>2],r+=Vi[(e[t]&3)<<4|e[t+1]>>4],r+=Vi[(e[t+1]&15)<<2|e[t+2]>>6],r+=Vi[e[t+2]&63];return i%3===2?r=r.substring(0,r.length-1)+"=":i%3===1&&(r=r.substring(0,r.length-2)+"=="),r};const bd=new Map;function l0(s,e){let t=bd.get(s);return t||(t=new Map,bd.set(s,t)),t.has(e)||t.set(e,[]),t.get(e)}const xd=(s,e,t)=>{if(!s||!(Cd(s,e)||typeof s=="object"))return;const i=s.constructor.name,r=l0(t,i);let n=r.indexOf(s);return n===-1&&(n=r.length,r.push(s)),n};function Tr(s,e,t){if(s instanceof Array)return s.map(i=>Tr(i,e,t));if(s===null)return s;if(s instanceof Float32Array||s instanceof Float64Array||s instanceof Int32Array||s instanceof Uint32Array||s instanceof Uint8Array||s instanceof Uint16Array||s instanceof Int16Array||s instanceof Int8Array||s instanceof Uint8ClampedArray)return{rr_type:s.constructor.name,args:[Object.values(s)]};if(s instanceof ArrayBuffer){const i=s.constructor.name,r=a0(s);return{rr_type:i,base64:r}}else{if(s instanceof DataView)return{rr_type:s.constructor.name,args:[Tr(s.buffer,e,t),s.byteOffset,s.byteLength]};if(s instanceof HTMLImageElement){const i=s.constructor.name,{src:r}=s;return{rr_type:i,src:r}}else if(s instanceof HTMLCanvasElement){const i="HTMLImageElement",r=s.toDataURL();return{rr_type:i,src:r}}else{if(s instanceof ImageData)return{rr_type:s.constructor.name,args:[Tr(s.data,e,t),s.width,s.height]};if(Cd(s,e)||typeof s=="object"){const i=s.constructor.name,r=xd(s,e,t);return{rr_type:i,index:r}}}}return s}const vd=(s,e,t)=>[...s].map(i=>Tr(i,e,t)),Cd=(s,e)=>!!["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(r=>typeof e[r]=="function").find(r=>s instanceof e[r]);function c0(s,e,t,i){const r=[],n=Object.getOwnPropertyNames(e.CanvasRenderingContext2D.prototype);for(const o of n)try{if(typeof e.CanvasRenderingContext2D.prototype[o]!="function")continue;const a=Wi(e.CanvasRenderingContext2D.prototype,o,function(l){return function(...c){return Je(this.canvas,t,i,!0)||setTimeout(()=>{const h=vd([...c],e,this);s(this.canvas,{type:Hi["2D"],property:o,args:h})},0),l.apply(this,c)}});r.push(a)}catch{const l=Cr(e.CanvasRenderingContext2D.prototype,o,{set(c){s(this.canvas,{type:Hi["2D"],property:o,args:[c],setter:!0})}});r.push(l)}return()=>{r.forEach(o=>o())}}function Sd(s,e,t){const i=[];try{const r=Wi(s.HTMLCanvasElement.prototype,"getContext",function(n){return function(o,...a){return Je(this,e,t,!0)||"__context"in this||(this.__context=o),n.apply(this,[o,...a])}});i.push(r)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{i.forEach(r=>r())}}function Ed(s,e,t,i,r,n,o){const a=[],l=Object.getOwnPropertyNames(s);for(const c of l)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(c))try{if(typeof s[c]!="function")continue;const h=Wi(s,c,function(u){return function(...f){const d=u.apply(this,f);if(xd(d,o,this),!Je(this.canvas,i,r,!0)){const g=vd([...f],o,this),_={type:e,property:c,args:g};t(this.canvas,_)}return d}});a.push(h)}catch{const u=Cr(s,c,{set(f){t(this.canvas,{type:e,property:c,args:[f],setter:!0})}});a.push(u)}return a}function h0(s,e,t,i,r){const n=[];return n.push(...Ed(e.WebGLRenderingContext.prototype,Hi.WebGL,s,t,i,r,e)),typeof e.WebGL2RenderingContext<"u"&&n.push(...Ed(e.WebGL2RenderingContext.prototype,Hi.WebGL2,s,t,i,r,e)),()=>{n.forEach(o=>o())}}var Td=null;try{var u0=typeof module<"u"&&typeof module.require=="function"&&module.require("worker_threads")||typeof __non_webpack_require__=="function"&&__non_webpack_require__("worker_threads")||typeof require=="function"&&require("worker_threads");Td=u0.Worker}catch{}function d0(s,e){return Buffer.from(s,"base64").toString("utf8")}function f0(s,e,t){var i=d0(s),r=i.indexOf(`
972
+ `,10)+1,n=i.substring(r)+"";return function(a){return new Td(n,Object.assign({},a,{eval:!0}))}}function p0(s,e){var t=atob(s);return t}function m0(s,e,t){var i=p0(s),r=i.indexOf(`
973
+ `,10)+1,n=i.substring(r)+"",o=new Blob([n],{type:"application/javascript"});return URL.createObjectURL(o)}function g0(s,e,t){var i;return function(n){return i=i||m0(s),new Worker(i,n)}}var _0=Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";function y0(){return _0}function b0(s,e,t){return y0()?f0(s):g0(s)}var x0=b0("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qISAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KICAgIENvcHlyaWdodCAoYykgTWljcm9zb2Z0IENvcnBvcmF0aW9uLg0KDQogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55DQogICAgcHVycG9zZSB3aXRoIG9yIHdpdGhvdXQgZmVlIGlzIGhlcmVieSBncmFudGVkLg0KDQogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTIFdJVEgNCiAgICBSRUdBUkQgVE8gVEhJUyBTT0ZUV0FSRSBJTkNMVURJTkcgQUxMIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkNCiAgICBBTkQgRklUTkVTUy4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIEFVVEhPUiBCRSBMSUFCTEUgRk9SIEFOWSBTUEVDSUFMLCBESVJFQ1QsDQogICAgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUyBXSEFUU09FVkVSIFJFU1VMVElORyBGUk9NDQogICAgTE9TUyBPRiBVU0UsIERBVEEgT1IgUFJPRklUUywgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1INCiAgICBPVEhFUiBUT1JUSU9VUyBBQ1RJT04sIEFSSVNJTkcgT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgVVNFIE9SDQogICAgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4NCiAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiAqLw0KDQogICAgZnVuY3Rpb24gX19hd2FpdGVyKHRoaXNBcmcsIF9hcmd1bWVudHMsIFAsIGdlbmVyYXRvcikgew0KICAgICAgICBmdW5jdGlvbiBhZG9wdCh2YWx1ZSkgeyByZXR1cm4gdmFsdWUgaW5zdGFuY2VvZiBQID8gdmFsdWUgOiBuZXcgUChmdW5jdGlvbiAocmVzb2x2ZSkgeyByZXNvbHZlKHZhbHVlKTsgfSk7IH0NCiAgICAgICAgcmV0dXJuIG5ldyAoUCB8fCAoUCA9IFByb21pc2UpKShmdW5jdGlvbiAocmVzb2x2ZSwgcmVqZWN0KSB7DQogICAgICAgICAgICBmdW5jdGlvbiBmdWxmaWxsZWQodmFsdWUpIHsgdHJ5IHsgc3RlcChnZW5lcmF0b3IubmV4dCh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiByZWplY3RlZCh2YWx1ZSkgeyB0cnkgeyBzdGVwKGdlbmVyYXRvclsidGhyb3ciXSh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiBzdGVwKHJlc3VsdCkgeyByZXN1bHQuZG9uZSA/IHJlc29sdmUocmVzdWx0LnZhbHVlKSA6IGFkb3B0KHJlc3VsdC52YWx1ZSkudGhlbihmdWxmaWxsZWQsIHJlamVjdGVkKTsgfQ0KICAgICAgICAgICAgc3RlcCgoZ2VuZXJhdG9yID0gZ2VuZXJhdG9yLmFwcGx5KHRoaXNBcmcsIF9hcmd1bWVudHMgfHwgW10pKS5uZXh0KCkpOw0KICAgICAgICB9KTsNCiAgICB9CgogICAgLyoKICAgICAqIGJhc2U2NC1hcnJheWJ1ZmZlciAxLjAuMSA8aHR0cHM6Ly9naXRodWIuY29tL25pa2xhc3ZoL2Jhc2U2NC1hcnJheWJ1ZmZlcj4KICAgICAqIENvcHlyaWdodCAoYykgMjAyMSBOaWtsYXMgdm9uIEhlcnR6ZW4gPGh0dHBzOi8vaGVydHplbi5jb20+CiAgICAgKiBSZWxlYXNlZCB1bmRlciBNSVQgTGljZW5zZQogICAgICovCiAgICB2YXIgY2hhcnMgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyc7CiAgICAvLyBVc2UgYSBsb29rdXAgdGFibGUgdG8gZmluZCB0aGUgaW5kZXguCiAgICB2YXIgbG9va3VwID0gdHlwZW9mIFVpbnQ4QXJyYXkgPT09ICd1bmRlZmluZWQnID8gW10gOiBuZXcgVWludDhBcnJheSgyNTYpOwogICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjaGFycy5sZW5ndGg7IGkrKykgewogICAgICAgIGxvb2t1cFtjaGFycy5jaGFyQ29kZUF0KGkpXSA9IGk7CiAgICB9CiAgICB2YXIgZW5jb2RlID0gZnVuY3Rpb24gKGFycmF5YnVmZmVyKSB7CiAgICAgICAgdmFyIGJ5dGVzID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlidWZmZXIpLCBpLCBsZW4gPSBieXRlcy5sZW5ndGgsIGJhc2U2NCA9ICcnOwogICAgICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkgKz0gMykgewogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaV0gPj4gMl07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2ldICYgMykgPDwgNCkgfCAoYnl0ZXNbaSArIDFdID4+IDQpXTsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzWygoYnl0ZXNbaSArIDFdICYgMTUpIDw8IDIpIHwgKGJ5dGVzW2kgKyAyXSA+PiA2KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1tieXRlc1tpICsgMl0gJiA2M107CiAgICAgICAgfQogICAgICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgJz0nOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgJz09JzsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGJhc2U2NDsKICAgIH07CgogICAgY29uc3QgbGFzdEJsb2JNYXAgPSBuZXcgTWFwKCk7DQogICAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gbmV3IE1hcCgpOw0KICAgIGZ1bmN0aW9uIGdldFRyYW5zcGFyZW50QmxvYkZvcih3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucykgew0KICAgICAgICByZXR1cm4gX19hd2FpdGVyKHRoaXMsIHZvaWQgMCwgdm9pZCAwLCBmdW5jdGlvbiogKCkgew0KICAgICAgICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgaWYgKHRyYW5zcGFyZW50QmxvYk1hcC5oYXMoaWQpKQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7DQogICAgICAgICAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsNCiAgICAgICAgICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgnMmQnKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0geWllbGQgYmxvYi5hcnJheUJ1ZmZlcigpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7DQogICAgICAgICAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICByZXR1cm4gYmFzZTY0Ow0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgZWxzZSB7DQogICAgICAgICAgICAgICAgcmV0dXJuICcnOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICB9DQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsNCiAgICB3b3JrZXIub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsNCiAgICAgICAgcmV0dXJuIF9fYXdhaXRlcih0aGlzLCB2b2lkIDAsIHZvaWQgMCwgZnVuY3Rpb24qICgpIHsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOw0KICAgICAgICAgICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsNCiAgICAgICAgICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCcyZCcpOw0KICAgICAgICAgICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsNCiAgICAgICAgICAgICAgICBiaXRtYXAuY2xvc2UoKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7DQogICAgICAgICAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSB5aWVsZCBibG9iLmFycmF5QnVmZmVyKCk7DQogICAgICAgICAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsNCiAgICAgICAgICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgKHlpZWxkIHRyYW5zcGFyZW50QmFzZTY0KSA9PT0gYmFzZTY0KSB7DQogICAgICAgICAgICAgICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7DQogICAgICAgICAgICAgICAgd29ya2VyLnBvc3RNZXNzYWdlKHsNCiAgICAgICAgICAgICAgICAgICAgaWQsDQogICAgICAgICAgICAgICAgICAgIHR5cGUsDQogICAgICAgICAgICAgICAgICAgIGJhc2U2NCwNCiAgICAgICAgICAgICAgICAgICAgd2lkdGgsDQogICAgICAgICAgICAgICAgICAgIGhlaWdodCwNCiAgICAgICAgICAgICAgICB9KTsNCiAgICAgICAgICAgICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBlbHNlIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfTsKCn0pKCk7Cgo=");class v0{constructor(e){this.pendingCanvasMutations=new Map,this.rafStamps={latestId:0,invokeId:null},this.frozen=!1,this.locked=!1,this.processMutation=(l,c)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(l)||this.pendingCanvasMutations.set(l,[]),this.pendingCanvasMutations.get(l).push(c)};const{sampling:t="all",win:i,blockClass:r,blockSelector:n,recordCanvas:o,dataURLOptions:a}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,o&&t==="all"&&this.initCanvasMutationObserver(i,r,n),o&&typeof t=="number"&&this.initCanvasFPSObserver(t,i,r,n,{dataURLOptions:a})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,i,r,n){const o=Sd(t,i,r),a=new Map,l=new x0;l.onmessage=g=>{const{id:_}=g.data;if(a.set(_,!1),!("base64"in g.data))return;const{base64:y,type:x,width:C,height:S}=g.data;this.mutationCb({id:_,type:Hi["2D"],commands:[{property:"clearRect",args:[0,0,C,S]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:y}],type:x}]},0,0]}]})};const c=1e3/e;let h=0,u;const f=()=>{const g=[];return t.document.querySelectorAll("canvas").forEach(_=>{Je(_,i,r,!0)||g.push(_)}),g},d=g=>{if(h&&g-h<c){u=requestAnimationFrame(d);return}h=g,f().forEach(_=>n0(this,void 0,void 0,function*(){var y;const x=this.mirror.getId(_);if(a.get(x))return;if(a.set(x,!0),["webgl","webgl2"].includes(_.__context)){const S=_.getContext(_.__context);((y=S==null?void 0:S.getContextAttributes())===null||y===void 0?void 0:y.preserveDrawingBuffer)===!1&&(S==null||S.clear(S.COLOR_BUFFER_BIT))}const C=yield createImageBitmap(_);l.postMessage({id:x,bitmap:C,width:_.width,height:_.height,dataURLOptions:n.dataURLOptions},[C])})),u=requestAnimationFrame(d)};u=requestAnimationFrame(d),this.resetObservers=()=>{o(),cancelAnimationFrame(u)}}initCanvasMutationObserver(e,t,i){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const r=Sd(e,t,i),n=c0(this.processMutation.bind(this),e,t,i),o=h0(this.processMutation.bind(this),e,t,i,this.mirror);this.resetObservers=()=>{r(),n(),o()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const i=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,i)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const i=this.pendingCanvasMutations.get(e);if(!i||t===-1)return;const r=i.map(o=>r0(o,["type"])),{type:n}=i[0];this.mutationCb({id:t,type:n,commands:r}),this.pendingCanvasMutations.delete(e)}}class C0{constructor(e){this.trackedLinkElements=new WeakSet,this.styleMirror=new Wv,this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(e.length===0)return;const i={id:t,styleIds:[]},r=[];for(const n of e){let o;if(this.styleMirror.has(n))o=this.styleMirror.getId(n);else{o=this.styleMirror.add(n);const a=Array.from(n.rules||CSSRule);r.push({styleId:o,rules:a.map((l,c)=>({rule:Hu(l),index:c}))})}i.styleIds.push(o)}r.length>0&&(i.styles=r),this.adoptedStyleSheetCb(i)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(e){}}function Fe(s){return Object.assign(Object.assign({},s),{timestamp:Date.now()})}let Oe,Ar,$o,wr=!1;const ft=gv();function zi(s={}){const{emit:e,checkoutEveryNms:t,checkoutEveryNth:i,blockClass:r="rr-block",blockSelector:n=null,ignoreClass:o="rr-ignore",maskTextClass:a="rr-mask",maskTextSelector:l=null,inlineStylesheet:c=!0,maskAllInputs:h,maskInputOptions:u,slimDOMOptions:f,maskInputFn:d,maskTextFn:g,hooks:_,packFn:y,sampling:x={},dataURLOptions:C={},mousemoveWait:S,recordCanvas:E=!1,recordCrossOriginIframes:w=!1,userTriggeredOnInput:R=!1,collectFonts:M=!1,inlineImages:D=!1,plugins:F,keepIframeSrcFn:k=()=>!1,ignoreCSSAttributes:O=new Set([])}=s,V=w?window.parent===window:!0;let X=!1;if(!V)try{window.parent.document,X=!1}catch{X=!0}if(V&&!e)throw new Error("emit function is required");S!==void 0&&x.mousemove===void 0&&(x.mousemove=S),ft.reset();const z=h===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:u!==void 0?u:{password:!0},de=f===!0||f==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:f==="all",headMetaDescKeywords:f==="all"}:f||{};Lv();let B,U=0;const q=G=>{for(const fe of F||[])fe.eventProcessor&&(G=fe.eventProcessor(G));return y&&(G=y(G)),G};Oe=(G,fe)=>{var le;if(!((le=ci[0])===null||le===void 0)&&le.isFrozen()&&G.type!==ue.FullSnapshot&&!(G.type===ue.IncrementalSnapshot&&G.data.source===oe.Mutation)&&ci.forEach(L=>L.unfreeze()),V)e==null||e(q(G),fe);else if(X){const L={type:"rrweb",event:q(G),isCheckout:fe};window.parent.postMessage(L,"*")}if(G.type===ue.FullSnapshot)B=G,U=0;else if(G.type===ue.IncrementalSnapshot){if(G.data.source===oe.Mutation&&G.data.isAttachIframe)return;U++;const L=i&&U>=i,me=t&&G.timestamp-B.timestamp>t;(L||me)&&Ar(!0)}};const N=G=>{Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Mutation},G)}))},K=G=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Scroll},G)})),Z=G=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.CanvasMutation},G)})),$=G=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.AdoptedStyleSheet},G)})),ae=new C0({mutationCb:N,adoptedStyleSheetCb:$}),Ce=new i0({mirror:ft,mutationCb:N,stylesheetManager:ae,recordCrossOriginIframes:w,wrappedEmit:Oe});for(const G of F||[])G.getMirror&&G.getMirror({nodeMirror:ft,crossOriginIframeMirror:Ce.crossOriginIframeMirror,crossOriginIframeStyleMirror:Ce.crossOriginIframeStyleMirror});$o=new v0({recordCanvas:E,mutationCb:Z,win:window,blockClass:r,blockSelector:n,mirror:ft,sampling:x.canvas,dataURLOptions:C});const Ee=new s0({mutationCb:N,scrollCb:K,bypassOptions:{blockClass:r,blockSelector:n,maskTextClass:a,maskTextSelector:l,inlineStylesheet:c,maskInputOptions:z,dataURLOptions:C,maskTextFn:g,maskInputFn:d,recordCanvas:E,inlineImages:D,sampling:x,slimDOMOptions:de,iframeManager:Ce,stylesheetManager:ae,canvasManager:$o,keepIframeSrcFn:k},mirror:ft});Ar=(G=!1)=>{var fe,le,L,me,Y,ie;Oe(Fe({type:ue.Meta,data:{href:window.location.href,width:Zu(),height:Ku()}}),G),ae.reset(),ci.forEach(ce=>ce.lock());const we=Fv(document,{mirror:ft,blockClass:r,blockSelector:n,maskTextClass:a,maskTextSelector:l,inlineStylesheet:c,maskAllInputs:z,maskTextFn:g,slimDOM:de,dataURLOptions:C,recordCanvas:E,inlineImages:D,onSerialize:ce=>{ed(ce,ft)&&Ce.addIframe(ce),td(ce,ft)&&ae.trackLinkElement(ce),id(ce)&&Ee.addShadowRoot(ce.shadowRoot,document)},onIframeLoad:(ce,He)=>{Ce.attachIframe(ce,He),Ee.observeAttachShadow(ce)},onStylesheetLoad:(ce,He)=>{ae.attachLinkElement(ce,He)},keepIframeSrcFn:k});if(!we)return console.warn("Failed to snapshot the document");Oe(Fe({type:ue.FullSnapshot,data:{node:we,initialOffset:{left:window.pageXOffset!==void 0?window.pageXOffset:(document==null?void 0:document.documentElement.scrollLeft)||((le=(fe=document==null?void 0:document.body)===null||fe===void 0?void 0:fe.parentElement)===null||le===void 0?void 0:le.scrollLeft)||((L=document==null?void 0:document.body)===null||L===void 0?void 0:L.scrollLeft)||0,top:window.pageYOffset!==void 0?window.pageYOffset:(document==null?void 0:document.documentElement.scrollTop)||((Y=(me=document==null?void 0:document.body)===null||me===void 0?void 0:me.parentElement)===null||Y===void 0?void 0:Y.scrollTop)||((ie=document==null?void 0:document.body)===null||ie===void 0?void 0:ie.scrollTop)||0}}})),ci.forEach(ce=>ce.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ae.adoptStyleSheets(document.adoptedStyleSheets,ft.getId(document))};try{const G=[];G.push(Ze("DOMContentLoaded",()=>{Oe(Fe({type:ue.DomContentLoaded,data:{}}))}));const fe=L=>{var me;return t0({mutationCb:N,mousemoveCb:(Y,ie)=>Oe(Fe({type:ue.IncrementalSnapshot,data:{source:ie,positions:Y}})),mouseInteractionCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.MouseInteraction},Y)})),scrollCb:K,viewportResizeCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.ViewportResize},Y)})),inputCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Input},Y)})),mediaInteractionCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.MediaInteraction},Y)})),styleSheetRuleCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.StyleSheetRule},Y)})),styleDeclarationCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.StyleDeclaration},Y)})),canvasMutationCb:Z,fontCb:Y=>Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Font},Y)})),selectionCb:Y=>{Oe(Fe({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Selection},Y)}))},blockClass:r,ignoreClass:o,maskTextClass:a,maskTextSelector:l,maskInputOptions:z,inlineStylesheet:c,sampling:x,recordCanvas:E,inlineImages:D,userTriggeredOnInput:R,collectFonts:M,doc:L,maskInputFn:d,maskTextFn:g,keepIframeSrcFn:k,blockSelector:n,slimDOMOptions:de,dataURLOptions:C,mirror:ft,iframeManager:Ce,stylesheetManager:ae,shadowDomManager:Ee,canvasManager:$o,ignoreCSSAttributes:O,plugins:((me=F==null?void 0:F.filter(Y=>Y.observer))===null||me===void 0?void 0:me.map(Y=>({observer:Y.observer,options:Y.options,callback:ie=>Oe(Fe({type:ue.Plugin,data:{plugin:Y.name,payload:ie}}))})))||[]},_)};Ce.addLoadListener(L=>{G.push(fe(L.contentDocument))});const le=()=>{Ar(),G.push(fe(document)),wr=!0};return document.readyState==="interactive"||document.readyState==="complete"?le():G.push(Ze("load",()=>{Oe(Fe({type:ue.Load,data:{}})),le()},window)),()=>{G.forEach(L=>L()),wr=!1}}catch(G){console.warn(G)}}zi.addCustomEvent=(s,e)=>{if(!wr)throw new Error("please add custom event after start recording");Oe(Fe({type:ue.Custom,data:{tag:s,payload:e}}))},zi.freezePage=()=>{ci.forEach(s=>s.freeze())},zi.takeFullSnapshot=s=>{if(!wr)throw new Error("please take full snapshot after start recording");Ar(s)},zi.mirror=ft;const S0=3e4,E0=3,T0=0;function A0(s){if(s.type!==E0)return!1;const e=s.data;if(!e||e.source!==T0)return!1;const{adds:t,removes:i,texts:r,attributes:n}=e;return t&&t.length||i&&i.length||r&&r.length?!1:n&&n.length>0?n.every(o=>o.attributes&&Object.keys(o.attributes).length===1&&"style"in o.attributes):!0}function w0(){for(const s of[Text,Comment,CDATASection,ProcessingInstruction])s.prototype.matches||(s.prototype.matches=function(){return!1})}class Ad{constructor(){this.onEvent=null,this.stopFn=null,this._recording=!1,this._paused=!1}get isRecording(){return this._recording}get isPaused(){return this._paused}start(){if(this._recording)return;w0();const e=zi({emit:t=>{var i;this._paused||A0(t)||(i=this.onEvent)==null||i.call(this,t)},checkoutEveryNms:S0,blockClass:"hs-no-record",blockSelector:'#holostaff-widget-root, #holostaff-agent, [id^="anam-avatar"], video, [autocomplete^="cc-"], [data-hs-no-record]',maskAllInputs:!1,maskInputOptions:{password:!0,email:!0,tel:!0},maskTextSelector:"[data-hs-mask]",sampling:{mousemove:100,scroll:150,input:"last"}});e?(this.stopFn=e,this._recording=!0,this._paused=!1,console.log("[RRWebRecorder] Started recording")):console.warn("[RRWebRecorder] record() returned undefined — recording may have failed")}stop(){var e;this._recording&&((e=this.stopFn)==null||e.call(this),this.stopFn=null,this._recording=!1,this._paused=!1,console.log("[RRWebRecorder] Stopped recording"))}pause(){!this._recording||this._paused||(this._paused=!0,console.log("[RRWebRecorder] Paused"))}resume(){!this._recording||!this._paused||(this._paused=!1,zi.takeFullSnapshot(),console.log("[RRWebRecorder] Resumed (full snapshot taken)"))}}function I0(s){return s.startsWith("ws://")||s.startsWith("wss://")?s:`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}${s.startsWith("/")?"":"/"}${s}`}const wd=1e3,R0=3e4,M0=500;class Id{constructor(e,t){this.onIntervention=null,this.onStatus=null,this.onConnected=null,this.onDisconnected=null,this.ws=null,this.eventBuffer=[],this.reconnectDelay=wd,this.reconnectTimer=null,this._connected=!1,this._closed=!1,this.url=I0(e),this.initPayload={type:"init",...t}}get isConnected(){return this._connected}connect(){this._closed||this.doConnect()}close(){if(this._closed=!0,this.clearReconnectTimer(),this.ws){try{this.ws.close()}catch{}this.ws=null}this._connected=!1}sendRRWebEvent(e){this.send({type:"rrweb",event:e})}sendActionComplete(e,t){this.send({type:"action_complete",actionId:e,result:t})}sendConversationStarted(){this.send({type:"conversation_started"})}sendConversationEnded(e){this.send({type:"conversation_ended",summary:e})}sendPageChanged(e,t,i){this.send({type:"page_changed",url:e,pathname:t,title:i})}doConnect(){if(!this._closed){try{this.ws=new WebSocket(this.url)}catch(e){console.warn("[VisionWS] Failed to create WebSocket:",e),this.scheduleReconnect();return}this.ws.onopen=()=>{var e;console.log("[VisionWS] Connected"),this._connected=!0,this.reconnectDelay=wd,this.ws.send(JSON.stringify(this.initPayload)),this.flushBuffer(),(e=this.onConnected)==null||e.call(this)},this.ws.onmessage=e=>{const t=e.data;typeof t=="string"?this.parseAndHandle(t):t instanceof Blob?t.text().then(i=>this.parseAndHandle(i)):t instanceof ArrayBuffer?this.parseAndHandle(new TextDecoder().decode(t)):console.warn("[VisionWS] Unknown message data type:",typeof t)},this.ws.onclose=()=>{var t;const e=this._connected;this._connected=!1,this.ws=null,e&&(console.log("[VisionWS] Disconnected"),(t=this.onDisconnected)==null||t.call(this)),this._closed||this.scheduleReconnect()},this.ws.onerror=e=>{console.warn("[VisionWS] Error:",e)}}}parseAndHandle(e){var t,i;try{const r=JSON.parse(e);switch(r.type){case"suggest_intervention":(t=this.onIntervention)==null||t.call(this,r);break;case"status":(i=this.onStatus)==null||i.call(this,r);break;default:console.log("[VisionWS] Unknown message type:",r.type)}}catch(r){console.warn("[VisionWS] Failed to parse message:",r)}}send(e){var t;this._connected&&((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?this.ws.send(JSON.stringify(e)):(this.eventBuffer.length>=M0&&this.eventBuffer.shift(),this.eventBuffer.push(e))}flushBuffer(){if(!(!this._connected||!this.ws)){for(const e of this.eventBuffer)this.ws.send(JSON.stringify(e));this.eventBuffer.length>0&&console.log(`[VisionWS] Flushed ${this.eventBuffer.length} buffered messages`),this.eventBuffer=[]}}scheduleReconnect(){if(this._closed||this.reconnectTimer)return;const e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*2,R0),console.log(`[VisionWS] Reconnecting in ${e}ms...`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}}const P0={sm:"var(--hs-radius-sm)",md:"var(--hs-radius-md)",lg:"var(--hs-radius-lg)",pill:"var(--hs-radius-pill)"},k0={base:"var(--hs-glass-bg)",elevated:"var(--hs-glass-bg-elevated)",solid:"var(--hs-glass-bg-solid)"};function Kt(s={}){const{tag:e="div",radius:t="md",elevation:i="base",interactive:r=!1,className:n,role:o}=s,a=document.createElement(e);return n&&(a.className=n),o&&a.setAttribute("role",o),Object.assign(a.style,{background:k0[i],backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",border:"1px solid var(--hs-glass-border)",borderRadius:P0[t],boxShadow:i==="elevated"?"var(--hs-glass-shadow-elevated)":"var(--hs-glass-shadow)",color:"var(--hs-text-primary)",fontFamily:"var(--hs-font)",fontSize:"var(--hs-text-base)",lineHeight:"var(--hs-line-height)",boxSizing:"border-box"}),r&&(a.style.transition=`border-color var(--hs-fade-duration) var(--hs-ease-fast),
974
+ box-shadow var(--hs-fade-duration) var(--hs-ease-fast)`,a.style.cursor="pointer",a.addEventListener("mouseenter",()=>{a.style.borderColor="var(--hs-glass-border-hover)"}),a.addEventListener("mouseleave",()=>{a.style.borderColor="var(--hs-glass-border)"})),a}function vt(s,e="primary",t="base",i="normal"){const r={primary:"var(--hs-text-primary)",secondary:"var(--hs-text-secondary)",tertiary:"var(--hs-text-tertiary)"},n={xs:"var(--hs-text-xs)",sm:"var(--hs-text-sm)",base:"var(--hs-text-base)",lg:"var(--hs-text-lg)",xl:"var(--hs-text-xl)"},o={normal:"var(--hs-weight-normal)",medium:"var(--hs-weight-medium)",semibold:"var(--hs-weight-semibold)"};return Object.assign(s.style,{color:r[e],fontSize:n[t],fontWeight:o[i],fontFamily:"var(--hs-font)",lineHeight:"var(--hs-line-height)",margin:"0"}),s}function Ct(s){const{label:e,variant:t="default",size:i="md",icon:r,onClick:n}=s,o=document.createElement("button");o.textContent=r?`${r} ${e}`:e;const a=i==="sm"?"4px 10px":"8px 16px",l=i==="sm"?"var(--hs-text-sm)":"var(--hs-text-base)";switch(Object.assign(o.style,{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"var(--hs-space-1)",padding:a,fontSize:l,fontWeight:"var(--hs-weight-medium)",fontFamily:"var(--hs-font)",lineHeight:"1",border:"none",borderRadius:"var(--hs-radius-pill)",cursor:"pointer",transition:"all var(--hs-fade-duration) var(--hs-ease-fast)",outline:"none",whiteSpace:"nowrap"}),t){case"accent":Object.assign(o.style,{background:"var(--hs-accent)",color:"var(--hs-accent-text)",boxShadow:"0 2px 12px var(--hs-accent-glow)"}),o.addEventListener("mouseenter",()=>{o.style.filter="brightness(1.12)",o.style.transform="scale(1.03)"}),o.addEventListener("mouseleave",()=>{o.style.filter="",o.style.transform=""});break;case"ghost":Object.assign(o.style,{background:"transparent",color:"var(--hs-text-secondary)"}),o.addEventListener("mouseenter",()=>{o.style.background="var(--hs-glass-bg)",o.style.color="var(--hs-text-primary)"}),o.addEventListener("mouseleave",()=>{o.style.background="transparent",o.style.color="var(--hs-text-secondary)"});break;default:Object.assign(o.style,{background:"var(--hs-glass-bg-elevated)",color:"var(--hs-text-primary)",backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",border:"1px solid var(--hs-glass-border)"}),o.addEventListener("mouseenter",()=>{o.style.borderColor="var(--hs-glass-border-hover)",o.style.transform="scale(1.03)"}),o.addEventListener("mouseleave",()=>{o.style.borderColor="var(--hs-glass-border)",o.style.transform=""});break}return n&&o.addEventListener("click",c=>{c.stopPropagation(),n(c)}),o}function Rd(s,e){var t={};for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(s);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(s,i[r])&&(t[i[r]]=s[i[r]]);return t}var Md=function(){};const jo=(s,e,t)=>Math.min(Math.max(t,s),e),Xo=.001,O0=.01,B0=10,D0=.05,N0=1;function U0({duration:s=800,bounce:e=.25,velocity:t=0,mass:i=1}){let r,n,o=1-e;o=jo(D0,N0,o),s=jo(O0,B0,s/1e3),o<1?(r=c=>{const h=c*o,u=h*s,f=h-t,d=Yo(c,o),g=Math.exp(-u);return Xo-f/d*g},n=c=>{const u=c*o*s,f=u*t+t,d=Math.pow(o,2)*Math.pow(c,2)*s,g=Math.exp(-u),_=Yo(Math.pow(c,2),o);return(-r(c)+Xo>0?-1:1)*((f-d)*g)/_}):(r=c=>{const h=Math.exp(-c*s),u=(c-t)*s+1;return-Xo+h*u},n=c=>{const h=Math.exp(-c*s),u=(t-c)*(s*s);return h*u});const a=5/s,l=G0(r,n,a);if(s=s*1e3,isNaN(l))return{stiffness:100,damping:10,duration:s};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:o*2*Math.sqrt(i*c),duration:s}}}const F0=12;function G0(s,e,t){let i=t;for(let r=1;r<F0;r++)i=i-s(i)/e(i);return i}function Yo(s,e){return s*Math.sqrt(1-e*e)}const L0=["duration","bounce"],W0=["stiffness","damping","mass"];function Pd(s,e){return e.some(t=>s[t]!==void 0)}function H0(s){let e=Object.assign({velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1},s);if(!Pd(s,W0)&&Pd(s,L0)){const t=U0(s);e=Object.assign(Object.assign(Object.assign({},e),t),{velocity:0,mass:1}),e.isResolvedFromDuration=!0}return e}function qo(s){var{from:e=0,to:t=1,restSpeed:i=2,restDelta:r}=s,n=Rd(s,["from","to","restSpeed","restDelta"]);const o={done:!1,value:e};let{stiffness:a,damping:l,mass:c,velocity:h,duration:u,isResolvedFromDuration:f}=H0(n),d=kd,g=kd;function _(){const y=h?-(h/1e3):0,x=t-e,C=l/(2*Math.sqrt(a*c)),S=Math.sqrt(a/c)/1e3;if(r===void 0&&(r=Math.min(Math.abs(t-e)/100,.4)),C<1){const E=Yo(S,C);d=w=>{const R=Math.exp(-C*S*w);return t-R*((y+C*S*x)/E*Math.sin(E*w)+x*Math.cos(E*w))},g=w=>{const R=Math.exp(-C*S*w);return C*S*R*(Math.sin(E*w)*(y+C*S*x)/E+x*Math.cos(E*w))-R*(Math.cos(E*w)*(y+C*S*x)-E*x*Math.sin(E*w))}}else if(C===1)d=E=>t-Math.exp(-S*E)*(x+(y+S*x)*E);else{const E=S*Math.sqrt(C*C-1);d=w=>{const R=Math.exp(-C*S*w),M=Math.min(E*w,300);return t-R*((y+C*S*x)*Math.sinh(M)+E*x*Math.cosh(M))/E}}}return _(),{next:y=>{const x=d(y);if(f)o.done=y>=u;else{const C=g(y)*1e3,S=Math.abs(C)<=i,E=Math.abs(t-x)<=r;o.done=S&&E}return o.value=o.done?t:x,o},flipTarget:()=>{h=-h,[e,t]=[t,e],_()}}}qo.needsInterpolation=(s,e)=>typeof s=="string"||typeof e=="string";const kd=s=>0,Od=(s,e,t)=>{const i=e-s;return i===0?1:(t-s)/i},Ko=(s,e,t)=>-t*s+t*e+s,Bd=(s,e)=>t=>Math.max(Math.min(t,e),s),Rs=s=>s%1?Number(s.toFixed(5)):s,Ir=/(-)?([\d]*\.?[\d])+/g,Zo=/(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi,V0=/^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;function Ms(s){return typeof s=="string"}const Rr={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},Dd=Object.assign(Object.assign({},Rr),{transform:Bd(0,1)});Object.assign(Object.assign({},Rr),{default:1});const Ps=(s=>({test:e=>Ms(e)&&e.endsWith(s)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${s}`}))("%");Object.assign(Object.assign({},Ps),{parse:s=>Ps.parse(s)/100,transform:s=>Ps.transform(s*100)});const Jo=(s,e)=>t=>!!(Ms(t)&&V0.test(t)&&t.startsWith(s)||e&&Object.prototype.hasOwnProperty.call(t,e)),Nd=(s,e,t)=>i=>{if(!Ms(i))return i;const[r,n,o,a]=i.match(Ir);return{[s]:parseFloat(r),[e]:parseFloat(n),[t]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},hi={test:Jo("hsl","hue"),parse:Nd("hue","saturation","lightness"),transform:({hue:s,saturation:e,lightness:t,alpha:i=1})=>"hsla("+Math.round(s)+", "+Ps.transform(Rs(e))+", "+Ps.transform(Rs(t))+", "+Rs(Dd.transform(i))+")"},z0=Bd(0,255),Qo=Object.assign(Object.assign({},Rr),{transform:s=>Math.round(z0(s))}),Zt={test:Jo("rgb","red"),parse:Nd("red","green","blue"),transform:({red:s,green:e,blue:t,alpha:i=1})=>"rgba("+Qo.transform(s)+", "+Qo.transform(e)+", "+Qo.transform(t)+", "+Rs(Dd.transform(i))+")"};function $0(s){let e="",t="",i="",r="";return s.length>5?(e=s.substr(1,2),t=s.substr(3,2),i=s.substr(5,2),r=s.substr(7,2)):(e=s.substr(1,1),t=s.substr(2,1),i=s.substr(3,1),r=s.substr(4,1),e+=e,t+=t,i+=i,r+=r),{red:parseInt(e,16),green:parseInt(t,16),blue:parseInt(i,16),alpha:r?parseInt(r,16)/255:1}}const ea={test:Jo("#"),parse:$0,transform:Zt.transform},Mr={test:s=>Zt.test(s)||ea.test(s)||hi.test(s),parse:s=>Zt.test(s)?Zt.parse(s):hi.test(s)?hi.parse(s):ea.parse(s),transform:s=>Ms(s)?s:s.hasOwnProperty("red")?Zt.transform(s):hi.transform(s)},Ud="${c}",Fd="${n}";function j0(s){var e,t,i,r;return isNaN(s)&&Ms(s)&&((t=(e=s.match(Ir))===null||e===void 0?void 0:e.length)!==null&&t!==void 0?t:0)+((r=(i=s.match(Zo))===null||i===void 0?void 0:i.length)!==null&&r!==void 0?r:0)>0}function Gd(s){typeof s=="number"&&(s=`${s}`);const e=[];let t=0;const i=s.match(Zo);i&&(t=i.length,s=s.replace(Zo,Ud),e.push(...i.map(Mr.parse)));const r=s.match(Ir);return r&&(s=s.replace(Ir,Fd),e.push(...r.map(Rr.parse))),{values:e,numColors:t,tokenised:s}}function Ld(s){return Gd(s).values}function Wd(s){const{values:e,numColors:t,tokenised:i}=Gd(s),r=e.length;return n=>{let o=i;for(let a=0;a<r;a++)o=o.replace(a<t?Ud:Fd,a<t?Mr.transform(n[a]):Rs(n[a]));return o}}const X0=s=>typeof s=="number"?0:s;function Y0(s){const e=Ld(s);return Wd(s)(e.map(X0))}const Hd={test:j0,parse:Ld,createTransformer:Wd,getAnimatableNone:Y0};function ta(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?s+(e-s)*6*t:t<1/2?e:t<2/3?s+(e-s)*(2/3-t)*6:s}function Vd({hue:s,saturation:e,lightness:t,alpha:i}){s/=360,e/=100,t/=100;let r=0,n=0,o=0;if(!e)r=n=o=t;else{const a=t<.5?t*(1+e):t+e-t*e,l=2*t-a;r=ta(l,a,s+1/3),n=ta(l,a,s),o=ta(l,a,s-1/3)}return{red:Math.round(r*255),green:Math.round(n*255),blue:Math.round(o*255),alpha:i}}const q0=(s,e,t)=>{const i=s*s,r=e*e;return Math.sqrt(Math.max(0,t*(r-i)+i))},K0=[ea,Zt,hi],zd=s=>K0.find(e=>e.test(s)),$d=(s,e)=>{let t=zd(s),i=zd(e),r=t.parse(s),n=i.parse(e);t===hi&&(r=Vd(r),t=Zt),i===hi&&(n=Vd(n),i=Zt);const o=Object.assign({},r);return a=>{for(const l in o)l!=="alpha"&&(o[l]=q0(r[l],n[l],a));return o.alpha=Ko(r.alpha,n.alpha,a),t.transform(o)}},Z0=s=>typeof s=="number",J0=(s,e)=>t=>e(s(t)),jd=(...s)=>s.reduce(J0);function Xd(s,e){return Z0(s)?t=>Ko(s,e,t):Mr.test(s)?$d(s,e):Kd(s,e)}const Yd=(s,e)=>{const t=[...s],i=t.length,r=s.map((n,o)=>Xd(n,e[o]));return n=>{for(let o=0;o<i;o++)t[o]=r[o](n);return t}},Q0=(s,e)=>{const t=Object.assign(Object.assign({},s),e),i={};for(const r in t)s[r]!==void 0&&e[r]!==void 0&&(i[r]=Xd(s[r],e[r]));return r=>{for(const n in i)t[n]=i[n](r);return t}};function qd(s){const e=Hd.parse(s),t=e.length;let i=0,r=0,n=0;for(let o=0;o<t;o++)i||typeof e[o]=="number"?i++:e[o].hue!==void 0?n++:r++;return{parsed:e,numNumbers:i,numRGB:r,numHSL:n}}const Kd=(s,e)=>{const t=Hd.createTransformer(e),i=qd(s),r=qd(e);return i.numHSL===r.numHSL&&i.numRGB===r.numRGB&&i.numNumbers>=r.numNumbers?jd(Yd(i.parsed,r.parsed),t):o=>`${o>0?e:s}`},eC=(s,e)=>t=>Ko(s,e,t);function tC(s){if(typeof s=="number")return eC;if(typeof s=="string")return Mr.test(s)?$d:Kd;if(Array.isArray(s))return Yd;if(typeof s=="object")return Q0}function iC(s,e,t){const i=[],r=t||tC(s[0]),n=s.length-1;for(let o=0;o<n;o++){let a=r(s[o],s[o+1]);if(e){const l=Array.isArray(e)?e[o]:e;a=jd(l,a)}i.push(a)}return i}function sC([s,e],[t]){return i=>t(Od(s,e,i))}function rC(s,e){const t=s.length,i=t-1;return r=>{let n=0,o=!1;if(r<=s[0]?o=!0:r>=s[i]&&(n=i-1,o=!0),!o){let l=1;for(;l<t&&!(s[l]>r||l===i);l++);n=l-1}const a=Od(s[n],s[n+1],r);return e[n](a)}}function Zd(s,e,{clamp:t=!0,ease:i,mixer:r}={}){const n=s.length;Md(n===e.length),Md(!i||!Array.isArray(i)||i.length===n-1),s[0]>s[n-1]&&(s=[].concat(s),e=[].concat(e),s.reverse(),e.reverse());const o=iC(e,i,r),a=n===2?sC(s,o):rC(s,o);return t?l=>a(jo(s[0],s[n-1],l)):a}const nC=s=>e=>e<=.5?s(2*e)/2:(2-s(2*(1-e)))/2,oC=(s=>e=>Math.pow(e,s))(2),aC=nC(oC);function lC(s,e){return s.map(()=>e||aC).splice(0,s.length-1)}function cC(s){const e=s.length;return s.map((t,i)=>i!==0?i/(e-1):0)}function hC(s,e){return s.map(t=>t*e)}function Pr({from:s=0,to:e=1,ease:t,offset:i,duration:r=300}){const n={done:!1,value:s},o=Array.isArray(e)?e:[s,e],a=hC(i&&i.length===o.length?i:cC(o),r);function l(){return Zd(a,o,{ease:Array.isArray(t)?t:lC(o,t)})}let c=l();return{next:h=>(n.value=c(h),n.done=h>=r,n),flipTarget:()=>{o.reverse(),c=l()}}}function uC({velocity:s=0,from:e=0,power:t=.8,timeConstant:i=350,restDelta:r=.5,modifyTarget:n}){const o={done:!1,value:e};let a=t*s;const l=e+a,c=n===void 0?l:n(l);return c!==l&&(a=c-e),{next:h=>{const u=-a*Math.exp(-h/i);return o.done=!(u>r||u<-r),o.value=o.done?c:c+u,o},flipTarget:()=>{}}}const Jd={keyframes:Pr,spring:qo,decay:uC};function dC(s){if(Array.isArray(s.to))return Pr;if(Jd[s.type])return Jd[s.type];const e=new Set(Object.keys(s));return e.has("ease")||e.has("duration")&&!e.has("dampingRatio")?Pr:e.has("dampingRatio")||e.has("stiffness")||e.has("mass")||e.has("damping")||e.has("restSpeed")||e.has("restDelta")?qo:Pr}const Qd=1/60*1e3,fC=typeof performance<"u"?()=>performance.now():()=>Date.now(),ef=typeof window<"u"?s=>window.requestAnimationFrame(s):s=>setTimeout(()=>s(fC()),Qd);function pC(s){let e=[],t=[],i=0,r=!1,n=!1;const o=new WeakSet,a={schedule:(l,c=!1,h=!1)=>{const u=h&&r,f=u?e:t;return c&&o.add(l),f.indexOf(l)===-1&&(f.push(l),u&&r&&(i=e.length)),l},cancel:l=>{const c=t.indexOf(l);c!==-1&&t.splice(c,1),o.delete(l)},process:l=>{if(r){n=!0;return}if(r=!0,[e,t]=[t,e],t.length=0,i=e.length,i)for(let c=0;c<i;c++){const h=e[c];h(l),o.has(h)&&(a.schedule(h),s())}r=!1,n&&(n=!1,a.process(l))}};return a}const mC=40;let ia=!0,ks=!1,sa=!1;const Os={delta:0,timestamp:0},Bs=["read","update","preRender","render","postRender"],kr=Bs.reduce((s,e)=>(s[e]=pC(()=>ks=!0),s),{}),gC=Bs.reduce((s,e)=>{const t=kr[e];return s[e]=(i,r=!1,n=!1)=>(ks||bC(),t.schedule(i,r,n)),s},{}),_C=Bs.reduce((s,e)=>(s[e]=kr[e].cancel,s),{});Bs.reduce((s,e)=>(s[e]=()=>kr[e].process(Os),s),{});const yC=s=>kr[s].process(Os),tf=s=>{ks=!1,Os.delta=ia?Qd:Math.max(Math.min(s-Os.timestamp,mC),1),Os.timestamp=s,sa=!0,Bs.forEach(yC),sa=!1,ks&&(ia=!1,ef(tf))},bC=()=>{ks=!0,ia=!0,sa||ef(tf)};function sf(s,e,t=0){return s-e-t}function xC(s,e,t=0,i=!0){return i?sf(e+-s,e,t):e-(s-e)+t}function vC(s,e,t,i){return i?s>=e+t:s<=-t}const CC=s=>{const e=({delta:t})=>s(t);return{start:()=>gC.update(e,!0),stop:()=>_C.update(e)}};function SC(s){var e,t,{from:i,autoplay:r=!0,driver:n=CC,elapsed:o=0,repeat:a=0,repeatType:l="loop",repeatDelay:c=0,onPlay:h,onStop:u,onComplete:f,onRepeat:d,onUpdate:g}=s,_=Rd(s,["from","autoplay","driver","elapsed","repeat","repeatType","repeatDelay","onPlay","onStop","onComplete","onRepeat","onUpdate"]);let{to:y}=_,x,C=0,S=_.duration,E,w=!1,R=!0,M;const D=dC(_);!((t=(e=D).needsInterpolation)===null||t===void 0)&&t.call(e,i,y)&&(M=Zd([0,100],[i,y],{clamp:!1}),i=0,y=100);const F=D(Object.assign(Object.assign({},_),{from:i,to:y}));function k(){C++,l==="reverse"?(R=C%2===0,o=xC(o,S,c,R)):(o=sf(o,S,c),l==="mirror"&&F.flipTarget()),w=!1,d&&d()}function O(){x.stop(),f&&f()}function V(z){if(R||(z=-z),o+=z,!w){const de=F.next(Math.max(0,o));E=de.value,M&&(E=M(E)),w=R?de.done:o<=0}g==null||g(E),w&&(C===0&&(S??(S=o)),C<a?vC(o,S,c,R)&&k():O())}function X(){h==null||h(),x=n(V),x.start()}return r&&X(),{stop:()=>{u==null||u(),x.stop()}}}const EC={snappy:{stiffness:300,damping:28,mass:.8},gentle:{stiffness:170,damping:26,mass:1},bouncy:{stiffness:400,damping:20,mass:.6},smooth:{stiffness:200,damping:30,mass:1}};function Jt(s){const e=s.preset?EC[s.preset]:void 0,t=SC({from:s.from,to:s.to,type:"spring",stiffness:s.stiffness??(e==null?void 0:e.stiffness)??170,damping:s.damping??(e==null?void 0:e.damping)??26,mass:s.mass??(e==null?void 0:e.mass)??1,onUpdate:s.onUpdate,onComplete:s.onComplete});return{stop:()=>t.stop()}}function TC(s,e,t,i="smooth",r){return Jt({from:e,to:t,preset:i,onUpdate:n=>{s.style.opacity=String(n)},onComplete:r})}function rt(s,e={}){const{from:t={},preset:i="snappy",onComplete:r}=e,n=t.opacity??0,o=t.scale??.92,a=t.y??8;s.style.opacity=String(n),s.style.transform=`scale(${o}) translateY(${a}px)`;const l=[];let c=0;const h=3,u=()=>{++c>=h&&(r==null||r())};return l.push(Jt({from:n,to:1,preset:i,onUpdate:f=>{s.style.opacity=String(f)},onComplete:u})),l.push(Jt({from:o,to:1,preset:i,onUpdate:f=>{var g;const d=parseFloat(((g=s.style.transform.match(/translateY\(([^)]+)\)/))==null?void 0:g[1])??"0");s.style.transform=`scale(${f}) translateY(${d}px)`},onComplete:u})),l.push(Jt({from:a,to:0,preset:i,onUpdate:f=>{var g;const d=parseFloat(((g=s.style.transform.match(/scale\(([^)]+)\)/))==null?void 0:g[1])??"1");s.style.transform=`scale(${d}) translateY(${f}px)`},onComplete:u})),{stop:()=>l.forEach(f=>f.stop())}}function Nt(s,e={}){const{to:t={},preset:i="smooth",remove:r=!0,onComplete:n}=e,o=t.opacity??0,a=t.scale??.92,l=t.y??8,c=[];let h=0;const u=3,f=()=>{++h>=u&&(r&&s.remove(),n==null||n())};return c.push(Jt({from:parseFloat(s.style.opacity||"1"),to:o,preset:i,onUpdate:d=>{s.style.opacity=String(d)},onComplete:f})),c.push(Jt({from:1,to:a,preset:i,onUpdate:d=>{var _;const g=parseFloat(((_=s.style.transform.match(/translateY\(([^)]+)\)/))==null?void 0:_[1])??"0");s.style.transform=`scale(${d}) translateY(${g}px)`},onComplete:f})),c.push(Jt({from:0,to:l,preset:i,onUpdate:d=>{var _;const g=parseFloat(((_=s.style.transform.match(/scale\(([^)]+)\)/))==null?void 0:_[1])??"1");s.style.transform=`scale(${g}) translateY(${d}px)`},onComplete:f})),{stop:()=>c.forEach(d=>d.stop())}}const rf="holostaff-liquid-tokens",W={glassBlur:"20px",glassSaturate:"180%",dark:{glassBg:"rgba(255, 255, 255, 0.10)",glassBgElevated:"rgba(255, 255, 255, 0.16)",glassBgSolid:"rgba(30, 30, 40, 0.85)",glassBorder:"rgba(255, 255, 255, 0.14)",glassBorderHover:"rgba(255, 255, 255, 0.28)",glassShadow:"0 8px 32px rgba(0, 0, 0, 0.24)",glassShadowElevated:"0 12px 48px rgba(0, 0, 0, 0.32)",textPrimary:"rgba(255, 255, 255, 0.92)",textSecondary:"rgba(255, 255, 255, 0.56)",textTertiary:"rgba(255, 255, 255, 0.32)",divider:"rgba(255, 255, 255, 0.08)"},light:{glassBg:"rgba(255, 255, 255, 0.55)",glassBgElevated:"rgba(255, 255, 255, 0.72)",glassBgSolid:"rgba(255, 255, 255, 0.92)",glassBorder:"rgba(0, 0, 0, 0.06)",glassBorderHover:"rgba(0, 0, 0, 0.12)",glassShadow:"0 8px 32px rgba(0, 0, 0, 0.08)",glassShadowElevated:"0 12px 48px rgba(0, 0, 0, 0.12)",textPrimary:"rgba(0, 0, 0, 0.85)",textSecondary:"rgba(0, 0, 0, 0.50)",textTertiary:"rgba(0, 0, 0, 0.28)",divider:"rgba(0, 0, 0, 0.06)"},radiusSm:"10px",radiusMd:"16px",radiusLg:"24px",radiusPill:"9999px",font:"-apple-system, 'Inter', 'Segoe UI', system-ui, sans-serif",textXs:"11px",textSm:"12px",textBase:"14px",textLg:"16px",textXl:"20px",weightNormal:"400",weightMedium:"500",weightSemibold:"600",lineHeight:"1.45",springDuration:"500ms",springEasing:"cubic-bezier(0.34, 1.56, 0.64, 1)",easeFast:"cubic-bezier(0.25, 0.1, 0.25, 1)",fadeDuration:"200ms",accent:"#7C5CFF",accentGlow:"rgba(124, 92, 255, 0.35)",accentText:"#ffffff",space1:"4px",space2:"8px",space3:"12px",space4:"16px",space5:"20px",space6:"24px",space8:"32px",zOverlay:"2147483644",zControls:"2147483646",zTop:"2147483647"};function St(){if(document.getElementById(rf))return;const s=document.createElement("style");s.id=rf,s.textContent=`
975
975
  /* Holostaff Liquid Glass Design Tokens */
976
976
  :root {
977
977
  --hs-glass-blur: ${W.glassBlur};
@@ -1048,20 +1048,20 @@ or you can use record.mirror to access the mirror instance during recording.`;le
1048
1048
  --hs-fade-duration: 0ms;
1049
1049
  }
1050
1050
  }
1051
- `,document.head.appendChild(s)}const TC=15e3;class AC{constructor(e){this.currentIntervention=null,this.autoDismissTimer=null,this._active=!1,this.cardOverlay=null,this.cardOverlayAnim=null,this.onAccept=null,this.wsClient=e.wsClient,this.getWidgetState=e.getWidgetState,this.getHomeVisible=e.getHomeVisible,this.inlineTarget=e.inlineTarget??null,this.pill=e.pill??null,this.wsClient.onIntervention=t=>this.handleIntervention(t)}get isActive(){return this._active}destroy(){this.cleanup(),this.wsClient.onIntervention=null}handleIntervention(e){const t=this.getWidgetState();if(t==="active"||t==="connecting"){this.wsClient.sendActionComplete(e.actionId,"ignored");return}if(this._active)return;console.log(`[ActionExecutor] Showing suggestion: "${e.message}"`),this.currentIntervention=e,this._active=!0;const i=this.getHomeVisible();this.inlineTarget&&i?this.showCardOverlay(e.message):this.pill&&this.showInPill(e.message),this.autoDismissTimer=setTimeout(()=>this.handleIgnore(),TC)}showCardOverlay(e){var r;if(!this.inlineTarget)return;St(),(r=this.inlineTarget.querySelector(".hs-suggestion-overlay"))==null||r.remove(),this.cardOverlay=Kt({radius:"lg",elevation:"solid",className:"hs-suggestion-overlay"}),Object.assign(this.cardOverlay.style,{position:"absolute",inset:"0",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:W.space4,boxSizing:"border-box",zIndex:"10",textAlign:"center",opacity:"0"}),this.cardOverlay.setAttribute("data-hs-theme","dark");const t=document.createElement("p");vt(t,"primary","base","normal"),Object.assign(t.style,{margin:`0 0 ${W.space4} 0`,maxWidth:"260px"}),t.textContent=e,this.cardOverlay.appendChild(t);const i=document.createElement("div");Object.assign(i.style,{display:"flex",gap:W.space3}),i.appendChild(Ct({label:"Let's talk",variant:"accent",size:"md",onClick:()=>this.handleAccept()})),i.appendChild(Ct({label:"Not now",variant:"ghost",size:"sm",onClick:()=>this.handleDecline()})),this.cardOverlay.appendChild(i),this.inlineTarget.style.position="relative",this.inlineTarget.appendChild(this.cardOverlay),this.cardOverlayAnim=rt(this.cardOverlay,{preset:"snappy",from:{opacity:0,scale:.96,y:8}})}hideCardOverlay(){var e;if((e=this.cardOverlayAnim)==null||e.stop(),this.cardOverlay){const t=this.cardOverlay;this.cardOverlay=null,this.cardOverlayAnim=Nt(t,{remove:!0,preset:"smooth"})}}showInPill(e){this.pill&&(this.pill.showSuggestion(e),this.pill.onSuggestionAccept=()=>this.handleAccept(),this.pill.onSuggestionDismiss=()=>this.handleDecline())}clearPillSuggestion(){this.pill&&(this.pill.clearSuggestion(),this.pill.onSuggestionAccept=null,this.pill.onSuggestionDismiss=null)}handleAccept(){var r;if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] User accepted suggestion");const e=this.currentIntervention,t=`${e.context}
1051
+ `,document.head.appendChild(s)}const AC=15e3;class wC{constructor(e){this.currentIntervention=null,this.autoDismissTimer=null,this._active=!1,this.cardOverlay=null,this.cardOverlayAnim=null,this.onInterventionShown=null,this.onAccept=null,this.wsClient=e.wsClient,this.getWidgetState=e.getWidgetState,this.getHomeVisible=e.getHomeVisible,this.inlineTarget=e.inlineTarget??null,this.pill=e.pill??null,this.wsClient.onIntervention=t=>this.handleIntervention(t)}get isActive(){return this._active}destroy(){this.cleanup(),this.wsClient.onIntervention=null}handleIntervention(e){var r;const t=this.getWidgetState();if(t==="active"||t==="connecting"){this.wsClient.sendActionComplete(e.actionId,"ignored");return}if(this._active)return;console.log(`[ActionExecutor] Showing suggestion: "${e.message}"`),this.currentIntervention=e,this._active=!0,(r=this.onInterventionShown)==null||r.call(this,e.goalId,e.message);const i=this.getHomeVisible();this.inlineTarget&&i?this.showCardOverlay(e.message):this.pill&&this.showInPill(e.message),this.autoDismissTimer=setTimeout(()=>this.handleIgnore(),AC)}showCardOverlay(e){var r;if(!this.inlineTarget)return;St(),(r=this.inlineTarget.querySelector(".hs-suggestion-overlay"))==null||r.remove(),this.cardOverlay=Kt({radius:"lg",elevation:"solid",className:"hs-suggestion-overlay"}),Object.assign(this.cardOverlay.style,{position:"absolute",inset:"0",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:W.space4,boxSizing:"border-box",zIndex:"10",textAlign:"center",opacity:"0"}),this.cardOverlay.setAttribute("data-hs-theme","dark");const t=document.createElement("p");vt(t,"primary","base","normal"),Object.assign(t.style,{margin:`0 0 ${W.space4} 0`,maxWidth:"260px"}),t.textContent=e,this.cardOverlay.appendChild(t);const i=document.createElement("div");Object.assign(i.style,{display:"flex",gap:W.space3}),i.appendChild(Ct({label:"Let's talk",variant:"accent",size:"md",onClick:()=>this.handleAccept()})),i.appendChild(Ct({label:"Not now",variant:"ghost",size:"sm",onClick:()=>this.handleDecline()})),this.cardOverlay.appendChild(i),this.inlineTarget.style.position="relative",this.inlineTarget.appendChild(this.cardOverlay),this.cardOverlayAnim=rt(this.cardOverlay,{preset:"snappy",from:{opacity:0,scale:.96,y:8}})}hideCardOverlay(){var e;if((e=this.cardOverlayAnim)==null||e.stop(),this.cardOverlay){const t=this.cardOverlay;this.cardOverlay=null,this.cardOverlayAnim=Nt(t,{remove:!0,preset:"smooth"})}}showInPill(e){this.pill&&(this.pill.showSuggestion(e),this.pill.onSuggestionAccept=()=>this.handleAccept(),this.pill.onSuggestionDismiss=()=>this.handleDecline())}clearPillSuggestion(){this.pill&&(this.pill.clearSuggestion(),this.pill.onSuggestionAccept=null,this.pill.onSuggestionDismiss=null)}handleAccept(){var r;if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] User accepted suggestion");const e=this.currentIntervention,t=`${e.context}
1052
1052
 
1053
1053
  The user accepted your suggestion: "${e.message}"
1054
- Continue the conversation naturally from this context.`,i=e.actionId;this.cleanup(),this.wsClient.sendActionComplete(i,"accepted"),(r=this.onAccept)==null||r.call(this,t)}handleDecline(){if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] User declined suggestion");const e=this.currentIntervention.actionId;this.cleanup(),this.wsClient.sendActionComplete(e,"declined")}handleIgnore(){if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] Suggestion auto-dismissed (ignored)");const e=this.currentIntervention.actionId;this.cleanup(),this.wsClient.sendActionComplete(e,"ignored")}cleanup(){this._active=!1,this.autoDismissTimer&&(clearTimeout(this.autoDismissTimer),this.autoDismissTimer=null),this.hideCardOverlay(),this.clearPillSuggestion(),this.currentIntervention=null}}function wC(s){try{const e=s.left+s.width/2,t=s.top+s.height/2,i=document.elementFromPoint(e,t);if(!i)return"dark";const r=IC(i);return MC(r)>.5?"light":"dark"}catch{return"dark"}}function IC(s){let e=s;for(;e;){const i=getComputedStyle(e).backgroundColor;if(i&&i!=="transparent"&&i!=="rgba(0, 0, 0, 0)")return RC(i);e=e.parentElement}return[255,255,255]}function RC(s){const e=s.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return e?[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]:[255,255,255]}function MC([s,e,t]){const[i,r,n]=[s/255,e/255,t/255].map(o=>o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4));return .2126*i+.7152*r+.0722*n}function PC(s,e){s.setAttribute("data-hs-theme",e)}function $i(s,e){const t=s.getBoundingClientRect(),i=wC(t);return PC(s,i),i}const nf={idle:"var(--hs-text-tertiary)",listening:"#34C759",thinking:"#FF9F0A",speaking:"var(--hs-accent)",connecting:"var(--hs-text-tertiary)"},kC={idle:"",listening:"Listening",thinking:"Thinking",speaking:"Speaking",connecting:"Connecting"};class OC{constructor(){this.pulseAnim=null,this.currentStatus="idle",this.theme="dark",St(),this.el=Kt({radius:"lg",elevation:"base",className:"hs-avatar-frame"}),Object.assign(this.el.style,{position:"relative",overflow:"hidden",display:"flex",flexDirection:"column"}),this.glowRing=document.createElement("div"),Object.assign(this.glowRing.style,{position:"absolute",inset:"-1px",borderRadius:"inherit",border:"2px solid transparent",pointerEvents:"none",transition:"border-color 0.3s ease, box-shadow 0.3s ease",zIndex:"2"}),this.el.appendChild(this.glowRing),this.statusBar=document.createElement("div"),Object.assign(this.statusBar.style,{position:"absolute",bottom:"0",left:"0",right:"0",display:"flex",alignItems:"center",justifyContent:"center",gap:"var(--hs-space-2)",padding:"var(--hs-space-2) var(--hs-space-3)",background:"linear-gradient(transparent, rgba(0,0,0,0.3))",zIndex:"3",opacity:"0",transition:"opacity 0.2s ease",pointerEvents:"none"}),this.statusDot=document.createElement("div"),Object.assign(this.statusDot.style,{width:"6px",height:"6px",borderRadius:"50%",background:nf.idle,transition:"background 0.3s ease, box-shadow 0.3s ease",flexShrink:"0"}),this.statusLabel=document.createElement("span"),Object.assign(this.statusLabel.style,{fontSize:"var(--hs-text-xs)",fontFamily:"var(--hs-font)",fontWeight:"var(--hs-weight-medium)",color:"rgba(255,255,255,0.8)",letterSpacing:"0.02em"}),this.statusBar.appendChild(this.statusDot),this.statusBar.appendChild(this.statusLabel),this.el.appendChild(this.statusBar)}setSize(e,t){this.el.style.width=`${e}px`,this.el.style.height=`${t}px`}appendContent(e){this.el.insertBefore(e,this.glowRing)}setStatus(e){if(e===this.currentStatus)return;this.currentStatus=e;const t=nf[e],i=kC[e];this.statusDot.style.background=t,this.statusDot.style.boxShadow=e!=="idle"?`0 0 6px ${t}`:"none",this.statusLabel.textContent=i,this.statusBar.style.opacity=e==="idle"?"0":"1",e==="speaking"||e==="listening"?(this.glowRing.style.borderColor=t,this.glowRing.style.boxShadow=`0 0 16px ${t}40, inset 0 0 16px ${t}10`,this.startPulse(t)):(this.glowRing.style.borderColor="transparent",this.glowRing.style.boxShadow="none",this.stopPulse())}detectTheme(){return this.theme=$i(this.el),this.theme}setTheme(e){this.theme=e,this.el.setAttribute("data-hs-theme",e)}show(){return this.el.style.display="flex",rt(this.el,{preset:"gentle"})}hide(e=!1){return Nt(this.el,{remove:e,preset:"smooth"})}startPulse(e){this.stopPulse(),this.pulseAnim=Jt({from:0,to:1,preset:"gentle",onUpdate:t=>{const i=.15+t*.25;this.glowRing.style.boxShadow=`0 0 ${16+t*8}px ${e}${Math.round(i*255).toString(16).padStart(2,"0")}, inset 0 0 ${16+t*4}px ${e}10`},onComplete:()=>{(this.currentStatus==="speaking"||this.currentStatus==="listening")&&this.startPulse(e)}})}stopPulse(){var e;(e=this.pulseAnim)==null||e.stop(),this.pulseAnim=null}destroy(){this.stopPulse(),this.el.remove()}}const kr=30,BC=3e3,DC=500;class NC{constructor(e){this.prompts=[],this.promptIndex=0,this.typeTimer=null,this.holdTimer=null,this.cycling=!1,this.currentAnim=null,this.onClick=null,this.onAccept=null,this.onDismiss=null,St(),this.prompts=e??["Need help finding something?","I can walk you through this page.","Questions? I'm here to help."],this.el=Kt({radius:"md",elevation:"elevated",className:"hs-speech-bubble"}),Object.assign(this.el.style,{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"12px",padding:"var(--hs-space-3) var(--hs-space-4)",maxWidth:"280px",minWidth:"120px",pointerEvents:"auto",cursor:"pointer",opacity:"0",display:"none",zIndex:"4"}),this.textEl=document.createElement("span"),vt(this.textEl,"primary","base","normal"),this.textEl.style.display="block",this.el.appendChild(this.textEl),this.actionsEl=document.createElement("div"),Object.assign(this.actionsEl.style,{display:"none",gap:"var(--hs-space-2)",marginTop:"var(--hs-space-3)",justifyContent:"flex-end"}),this.el.appendChild(this.actionsEl),this.tailEl=document.createElement("div"),Object.assign(this.tailEl.style,{position:"absolute",bottom:"-6px",left:"50%",transform:"translateX(-50%) rotate(45deg)",width:"12px",height:"12px",background:"var(--hs-glass-bg-elevated)",backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",borderRight:"1px solid var(--hs-glass-border)",borderBottom:"1px solid var(--hs-glass-border)",zIndex:"-1"}),this.el.appendChild(this.tailEl),this.el.addEventListener("click",t=>{var i;t.stopPropagation(),(i=this.onClick)==null||i.call(this)})}start(){this.cycling||(this.cycling=!0,this.promptIndex=0,this.showNextPrompt())}stop(){this.cycling=!1,this.clearTimers(),this.hide()}showNextPrompt(){if(!this.cycling)return;const e=this.prompts[this.promptIndex%this.prompts.length];this.promptIndex++,this.actionsEl.style.display="none",this.typewrite(e,()=>{this.holdTimer=setTimeout(()=>{this.fadeOutAndNext()},BC)})}fadeOutAndNext(){this.currentAnim=Nt(this.el,{remove:!1,preset:"smooth",onComplete:()=>{this.el.style.display="none",setTimeout(()=>{this.cycling&&this.showNextPrompt()},DC)}})}typewrite(e,t){this.clearTimers(),this.textEl.textContent="",this.el.style.display="block",this.currentAnim=rt(this.el,{preset:"snappy"});let i=0;const r=()=>{i<e.length?(this.textEl.textContent=e.slice(0,++i),this.typeTimer=setTimeout(r,kr)):t==null||t()};this.typeTimer=setTimeout(r,kr)}showStatic(e){this.clearTimers(),this.cycling=!1,this.actionsEl.style.display="none",this.textEl.textContent=e,this.el.style.display="block",this.currentAnim=rt(this.el,{preset:"snappy"})}hideStatic(){this.hide()}showSuggestion(e){this.clearTimers(),this.cycling=!1,this.textEl.textContent="",this.actionsEl.innerHTML="";const t=Ct({label:"Sure",variant:"accent",size:"sm",icon:"✓",onClick:()=>{var o;(o=this.onAccept)==null||o.call(this),this.hide()}}),i=Ct({label:"Not now",variant:"ghost",size:"sm",icon:"✕",onClick:()=>{var o;(o=this.onDismiss)==null||o.call(this),this.hide()}});this.actionsEl.appendChild(t),this.actionsEl.appendChild(i),this.actionsEl.style.display="flex",this.el.style.display="block",this.currentAnim=rt(this.el,{preset:"snappy"});let r=0;const n=()=>{r<e.length&&(this.textEl.textContent=e.slice(0,++r),this.typeTimer=setTimeout(n,kr))};this.typeTimer=setTimeout(n,kr)}hide(){var e;(e=this.currentAnim)==null||e.stop(),this.el.style.display!=="none"&&(this.currentAnim=Nt(this.el,{remove:!1,preset:"smooth",onComplete:()=>{this.el.style.display="none"}}))}clearTimers(){this.typeTimer&&(clearTimeout(this.typeTimer),this.typeTimer=null),this.holdTimer&&(clearTimeout(this.holdTimer),this.holdTimer=null)}destroy(){var e;(e=this.currentAnim)==null||e.stop(),this.clearTimers(),this.el.remove()}}const UC=`
1054
+ Continue the conversation naturally from this context.`,i=e.actionId;this.cleanup(),this.wsClient.sendActionComplete(i,"accepted"),(r=this.onAccept)==null||r.call(this,t)}handleDecline(){if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] User declined suggestion");const e=this.currentIntervention.actionId;this.cleanup(),this.wsClient.sendActionComplete(e,"declined")}handleIgnore(){if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] Suggestion auto-dismissed (ignored)");const e=this.currentIntervention.actionId;this.cleanup(),this.wsClient.sendActionComplete(e,"ignored")}cleanup(){this._active=!1,this.autoDismissTimer&&(clearTimeout(this.autoDismissTimer),this.autoDismissTimer=null),this.hideCardOverlay(),this.clearPillSuggestion(),this.currentIntervention=null}}function IC(s){try{const e=s.left+s.width/2,t=s.top+s.height/2,i=document.elementFromPoint(e,t);if(!i)return"dark";const r=RC(i);return PC(r)>.5?"light":"dark"}catch{return"dark"}}function RC(s){let e=s;for(;e;){const i=getComputedStyle(e).backgroundColor;if(i&&i!=="transparent"&&i!=="rgba(0, 0, 0, 0)")return MC(i);e=e.parentElement}return[255,255,255]}function MC(s){const e=s.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return e?[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]:[255,255,255]}function PC([s,e,t]){const[i,r,n]=[s/255,e/255,t/255].map(o=>o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4));return .2126*i+.7152*r+.0722*n}function kC(s,e){s.setAttribute("data-hs-theme",e)}function $i(s,e){const t=s.getBoundingClientRect(),i=IC(t);return kC(s,i),i}const nf={idle:"var(--hs-text-tertiary)",listening:"#34C759",thinking:"#FF9F0A",speaking:"var(--hs-accent)",connecting:"var(--hs-text-tertiary)"},OC={idle:"",listening:"Listening",thinking:"Thinking",speaking:"Speaking",connecting:"Connecting"};class BC{constructor(){this.pulseAnim=null,this.currentStatus="idle",this.theme="dark",St(),this.el=Kt({radius:"lg",elevation:"base",className:"hs-avatar-frame"}),Object.assign(this.el.style,{position:"relative",overflow:"hidden",display:"flex",flexDirection:"column"}),this.glowRing=document.createElement("div"),Object.assign(this.glowRing.style,{position:"absolute",inset:"-1px",borderRadius:"inherit",border:"2px solid transparent",pointerEvents:"none",transition:"border-color 0.3s ease, box-shadow 0.3s ease",zIndex:"2"}),this.el.appendChild(this.glowRing),this.statusBar=document.createElement("div"),Object.assign(this.statusBar.style,{position:"absolute",bottom:"0",left:"0",right:"0",display:"flex",alignItems:"center",justifyContent:"center",gap:"var(--hs-space-2)",padding:"var(--hs-space-2) var(--hs-space-3)",background:"linear-gradient(transparent, rgba(0,0,0,0.3))",zIndex:"3",opacity:"0",transition:"opacity 0.2s ease",pointerEvents:"none"}),this.statusDot=document.createElement("div"),Object.assign(this.statusDot.style,{width:"6px",height:"6px",borderRadius:"50%",background:nf.idle,transition:"background 0.3s ease, box-shadow 0.3s ease",flexShrink:"0"}),this.statusLabel=document.createElement("span"),Object.assign(this.statusLabel.style,{fontSize:"var(--hs-text-xs)",fontFamily:"var(--hs-font)",fontWeight:"var(--hs-weight-medium)",color:"rgba(255,255,255,0.8)",letterSpacing:"0.02em"}),this.statusBar.appendChild(this.statusDot),this.statusBar.appendChild(this.statusLabel),this.el.appendChild(this.statusBar)}setSize(e,t){this.el.style.width=`${e}px`,this.el.style.height=`${t}px`}appendContent(e){this.el.insertBefore(e,this.glowRing)}setStatus(e){if(e===this.currentStatus)return;this.currentStatus=e;const t=nf[e],i=OC[e];this.statusDot.style.background=t,this.statusDot.style.boxShadow=e!=="idle"?`0 0 6px ${t}`:"none",this.statusLabel.textContent=i,this.statusBar.style.opacity=e==="idle"?"0":"1",e==="speaking"||e==="listening"?(this.glowRing.style.borderColor=t,this.glowRing.style.boxShadow=`0 0 16px ${t}40, inset 0 0 16px ${t}10`,this.startPulse(t)):(this.glowRing.style.borderColor="transparent",this.glowRing.style.boxShadow="none",this.stopPulse())}detectTheme(){return this.theme=$i(this.el),this.theme}setTheme(e){this.theme=e,this.el.setAttribute("data-hs-theme",e)}show(){return this.el.style.display="flex",rt(this.el,{preset:"gentle"})}hide(e=!1){return Nt(this.el,{remove:e,preset:"smooth"})}startPulse(e){this.stopPulse(),this.pulseAnim=Jt({from:0,to:1,preset:"gentle",onUpdate:t=>{const i=.15+t*.25;this.glowRing.style.boxShadow=`0 0 ${16+t*8}px ${e}${Math.round(i*255).toString(16).padStart(2,"0")}, inset 0 0 ${16+t*4}px ${e}10`},onComplete:()=>{(this.currentStatus==="speaking"||this.currentStatus==="listening")&&this.startPulse(e)}})}stopPulse(){var e;(e=this.pulseAnim)==null||e.stop(),this.pulseAnim=null}destroy(){this.stopPulse(),this.el.remove()}}const Or=30,DC=3e3,NC=500;class UC{constructor(e){this.prompts=[],this.promptIndex=0,this.typeTimer=null,this.holdTimer=null,this.cycling=!1,this.currentAnim=null,this.onClick=null,this.onAccept=null,this.onDismiss=null,St(),this.prompts=e??["Need help finding something?","I can walk you through this page.","Questions? I'm here to help."],this.el=Kt({radius:"md",elevation:"elevated",className:"hs-speech-bubble"}),Object.assign(this.el.style,{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"12px",padding:"var(--hs-space-3) var(--hs-space-4)",maxWidth:"280px",minWidth:"120px",pointerEvents:"auto",cursor:"pointer",opacity:"0",display:"none",zIndex:"4"}),this.textEl=document.createElement("span"),vt(this.textEl,"primary","base","normal"),this.textEl.style.display="block",this.el.appendChild(this.textEl),this.actionsEl=document.createElement("div"),Object.assign(this.actionsEl.style,{display:"none",gap:"var(--hs-space-2)",marginTop:"var(--hs-space-3)",justifyContent:"flex-end"}),this.el.appendChild(this.actionsEl),this.tailEl=document.createElement("div"),Object.assign(this.tailEl.style,{position:"absolute",bottom:"-6px",left:"50%",transform:"translateX(-50%) rotate(45deg)",width:"12px",height:"12px",background:"var(--hs-glass-bg-elevated)",backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",borderRight:"1px solid var(--hs-glass-border)",borderBottom:"1px solid var(--hs-glass-border)",zIndex:"-1"}),this.el.appendChild(this.tailEl),this.el.addEventListener("click",t=>{var i;t.stopPropagation(),(i=this.onClick)==null||i.call(this)})}start(){this.cycling||(this.cycling=!0,this.promptIndex=0,this.showNextPrompt())}stop(){this.cycling=!1,this.clearTimers(),this.hide()}showNextPrompt(){if(!this.cycling)return;const e=this.prompts[this.promptIndex%this.prompts.length];this.promptIndex++,this.actionsEl.style.display="none",this.typewrite(e,()=>{this.holdTimer=setTimeout(()=>{this.fadeOutAndNext()},DC)})}fadeOutAndNext(){this.currentAnim=Nt(this.el,{remove:!1,preset:"smooth",onComplete:()=>{this.el.style.display="none",setTimeout(()=>{this.cycling&&this.showNextPrompt()},NC)}})}typewrite(e,t){this.clearTimers(),this.textEl.textContent="",this.el.style.display="block",this.currentAnim=rt(this.el,{preset:"snappy"});let i=0;const r=()=>{i<e.length?(this.textEl.textContent=e.slice(0,++i),this.typeTimer=setTimeout(r,Or)):t==null||t()};this.typeTimer=setTimeout(r,Or)}showStatic(e){this.clearTimers(),this.cycling=!1,this.actionsEl.style.display="none",this.textEl.textContent=e,this.el.style.display="block",this.currentAnim=rt(this.el,{preset:"snappy"})}hideStatic(){this.hide()}showSuggestion(e){this.clearTimers(),this.cycling=!1,this.textEl.textContent="",this.actionsEl.innerHTML="";const t=Ct({label:"Sure",variant:"accent",size:"sm",icon:"✓",onClick:()=>{var o;(o=this.onAccept)==null||o.call(this),this.hide()}}),i=Ct({label:"Not now",variant:"ghost",size:"sm",icon:"✕",onClick:()=>{var o;(o=this.onDismiss)==null||o.call(this),this.hide()}});this.actionsEl.appendChild(t),this.actionsEl.appendChild(i),this.actionsEl.style.display="flex",this.el.style.display="block",this.currentAnim=rt(this.el,{preset:"snappy"});let r=0;const n=()=>{r<e.length&&(this.textEl.textContent=e.slice(0,++r),this.typeTimer=setTimeout(n,Or))};this.typeTimer=setTimeout(n,Or)}hide(){var e;(e=this.currentAnim)==null||e.stop(),this.el.style.display!=="none"&&(this.currentAnim=Nt(this.el,{remove:!1,preset:"smooth",onComplete:()=>{this.el.style.display="none"}}))}clearTimers(){this.typeTimer&&(clearTimeout(this.typeTimer),this.typeTimer=null),this.holdTimer&&(clearTimeout(this.holdTimer),this.holdTimer=null)}destroy(){var e;(e=this.currentAnim)==null||e.stop(),this.clearTimers(),this.el.remove()}}const FC=`
1055
1055
  @keyframes hs-pill-pulse {
1056
1056
  0%, 100% { box-shadow: 0 0 0 0 var(--hs-accent-glow); }
1057
1057
  50% { box-shadow: 0 0 14px 5px var(--hs-accent-glow); }
1058
1058
  }
1059
- `;class of{constructor(){this.el=null,this.avatarWrap=null,this.avatarImg=null,this.avatarVideo=null,this.nameEl=null,this.suggestionArea=null,this.suggestionText=null,this.currentAnim=null,this._state="hidden",this.pulseStyleInjected=!1,this.avatarUrl=null,this.videoUrl=null,this.staffName="",this.onClick=null,this.onSuggestionAccept=null,this.onSuggestionDismiss=null}init(e,t,i){if(this.el)return;if(St(),this.avatarUrl=e,this.videoUrl=t,this.staffName=i,this.el=Kt({radius:"pill",elevation:"elevated",interactive:!0,className:"hs-chat-pill"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-5)",left:"0",right:"0",margin:"0 auto",width:"fit-content",maxWidth:"min(90vw, 600px)",display:"none",alignItems:"center",gap:"0px",padding:"5px",zIndex:W.zControls,cursor:"pointer",userSelect:"none",opacity:"0",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.18)",transition:"gap 0.3s ease, padding 0.3s ease, box-shadow 0.2s ease",overflow:"hidden"}),$i(this.el),this.el.addEventListener("mouseenter",()=>{this.el&&(this.el.style.boxShadow="0 6px 32px rgba(0, 0, 0, 0.24)")}),this.el.addEventListener("mouseleave",()=>{this.el&&(this.el.style.boxShadow="0 4px 24px rgba(0, 0, 0, 0.18)")}),this.avatarWrap=document.createElement("div"),Object.assign(this.avatarWrap.style,{width:"36px",height:"36px",borderRadius:"50%",overflow:"hidden",flexShrink:"0",position:"relative",border:"1.5px solid var(--hs-glass-border)",transition:"box-shadow 0.3s ease, width 0.3s ease, height 0.3s ease"}),e)this.avatarImg=document.createElement("img"),this.avatarImg.src=e,this.avatarImg.alt=i,Object.assign(this.avatarImg.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),this.avatarWrap.appendChild(this.avatarImg);else{const a=document.createElement("div");Object.assign(a.style,{width:"100%",height:"100%",background:"var(--hs-accent)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"var(--hs-text-sm)",fontWeight:"var(--hs-weight-semibold)",color:"var(--hs-accent-text)"}),a.textContent=i.charAt(0).toUpperCase(),this.avatarWrap.appendChild(a)}t&&(this.avatarVideo=document.createElement("video"),this.avatarVideo.src=t,this.avatarVideo.muted=!0,this.avatarVideo.loop=!0,this.avatarVideo.playsInline=!0,this.avatarVideo.setAttribute("playsinline",""),Object.assign(this.avatarVideo.style,{position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"cover",display:"none"}),this.avatarWrap.appendChild(this.avatarVideo)),this.el.appendChild(this.avatarWrap),this.nameEl=document.createElement("span"),vt(this.nameEl,"primary","base","medium"),this.nameEl.textContent=i,Object.assign(this.nameEl.style,{whiteSpace:"nowrap",overflow:"hidden",maxWidth:"0",opacity:"0",transition:"max-width 0.3s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"}),this.el.appendChild(this.nameEl),this.suggestionArea=document.createElement("div"),Object.assign(this.suggestionArea.style,{display:"flex",alignItems:"center",gap:"var(--hs-space-2)",maxWidth:"0",opacity:"0",overflow:"hidden",transition:"max-width 0.35s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"});const r=document.createElement("span");Object.assign(r.style,{width:"1px",height:"20px",background:"var(--hs-divider)",flexShrink:"0"}),this.suggestionArea.appendChild(r),this.suggestionText=document.createElement("span"),vt(this.suggestionText,"secondary","sm","normal"),Object.assign(this.suggestionText.style,{whiteSpace:"normal",lineHeight:"1.4",display:"-webkit-box",WebkitLineClamp:"2",WebkitBoxOrient:"vertical",overflow:"hidden"}),this.suggestionArea.appendChild(this.suggestionText);const n=Ct({label:"Let's talk",variant:"accent",size:"sm",onClick:a=>{var l;a.stopPropagation(),(l=this.onSuggestionAccept)==null||l.call(this)}});n.style.flexShrink="0",this.suggestionArea.appendChild(n);const o=document.createElement("button");o.textContent="✕",Object.assign(o.style,{background:"none",border:"none",color:"var(--hs-text-tertiary)",fontSize:"12px",cursor:"pointer",padding:"4px",flexShrink:"0",lineHeight:"1",transition:"color 0.15s ease"}),o.addEventListener("mouseenter",()=>{o.style.color="var(--hs-text-primary)"}),o.addEventListener("mouseleave",()=>{o.style.color="var(--hs-text-tertiary)"}),o.addEventListener("click",a=>{var l;a.stopPropagation(),(l=this.onSuggestionDismiss)==null||l.call(this),this.clearSuggestion()}),this.suggestionArea.appendChild(o),this.el.appendChild(this.suggestionArea),this.el.addEventListener("click",a=>{var l;a.target.closest("button")||(l=this.onClick)==null||l.call(this)}),document.documentElement.appendChild(this.el)}showAmbient(){var e;!this.el||this._state==="ambient"||(this._state="ambient",this.collapseName(),this.collapseSuggestion(),this.stopAvatarVideo(),this.el.style.display="flex",this.el.style.gap="0px",this.el.style.padding="5px",(e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.8,y:12}}))}showNamed(){var t;if(!this.el||this._state==="named")return;const e=this._state==="hidden";this._state="named",this.collapseSuggestion(),this.stopAvatarVideo(),this.expandName(),this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",e&&((t=this.currentAnim)==null||t.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.85,y:16}}))}showSuggestion(e){var i;if(!this.el||!this.suggestionText)return;const t=this._state==="hidden";this._state="suggestion",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="10px 16px 10px 10px",this.el.style.borderRadius="var(--hs-radius-lg)",this.collapseName(),t&&((i=this.currentAnim)==null||i.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.9,y:12}})),this.startAvatarVideo(),this.startAvatarPulse(),this.suggestionText.textContent=e,this.suggestionText.title=e,requestAnimationFrame(()=>{this.suggestionArea&&(this.suggestionArea.style.maxWidth="500px",this.suggestionArea.style.opacity="1",this.suggestionArea.style.marginLeft="var(--hs-space-2)")})}clearSuggestion(){this.el&&(this._state="named",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.el.style.padding="8px 20px 8px 8px",this.el.style.borderRadius="var(--hs-radius-pill)")}showConnecting(){var e;!this.el||!this.nameEl||(this._state="connecting",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.nameEl.textContent="Connecting...",this.nameEl.style.opacity="0.6",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",this.el.style.opacity==="0"&&((e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})))}restoreName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1")}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;this._state="hidden",this.stopAvatarPulse(),this.stopAvatarVideo();const e=this.el;this.currentAnim=Nt(e,{remove:!1,preset:"smooth",to:{opacity:0,scale:.9,y:12},onComplete:()=>{e.style.display="none"}})}destroy(){var e,t;(e=this.currentAnim)==null||e.stop(),this.stopAvatarPulse(),this.stopAvatarVideo(),(t=this.el)==null||t.remove(),this.el=null,this._state="hidden"}get state(){return this._state}get isVisible(){return this._state!=="hidden"}expandName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1",this.nameEl.style.maxWidth="150px",this.nameEl.style.marginLeft="var(--hs-space-2)")}collapseName(){this.nameEl&&(this.nameEl.style.maxWidth="0",this.nameEl.style.opacity="0",this.nameEl.style.marginLeft="0")}collapseSuggestion(){this.suggestionArea&&(this.suggestionArea.style.maxWidth="0",this.suggestionArea.style.opacity="0",this.suggestionArea.style.marginLeft="0")}startAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.style.display="block",this.avatarVideo.currentTime=0,this.avatarVideo.play().catch(()=>{}),this.avatarImg.style.opacity="0")}stopAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.pause(),this.avatarVideo.style.display="none",this.avatarImg.style.opacity="1")}startAvatarPulse(){this.avatarWrap&&(this.injectPulseStyle(),this.avatarWrap.style.animation="hs-pill-pulse 1.5s ease-in-out infinite")}stopAvatarPulse(){this.avatarWrap&&(this.avatarWrap.style.animation="")}injectPulseStyle(){if(this.pulseStyleInjected)return;this.pulseStyleInjected=!0;const e=document.createElement("style");e.textContent=UC,document.head.appendChild(e)}}const FC=15e3,GC=320;class LC{constructor(){this.cards=[],this.anchor=null}setAnchor(e){this.anchor=e}showTextCard(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,n.style.whiteSpace="pre-wrap",i.el.appendChild(n),this.mountCard(i)}showImageCard(e,t){const i=this.createCard(),r=document.createElement("img");if(r.src=e,r.alt=t||"",Object.assign(r.style,{width:"100%",borderRadius:"var(--hs-radius-sm)",display:"block",marginBottom:t?"var(--hs-space-2)":"0"}),i.el.appendChild(r),t){const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,i.el.appendChild(n)}this.mountCard(i)}showBulletList(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("ul");Object.assign(n.style,{margin:"0",paddingLeft:"var(--hs-space-5)",listStyleType:"none"}),t.forEach(o=>{const a=document.createElement("li");Object.assign(a.style,{marginBottom:"var(--hs-space-1)",position:"relative",paddingLeft:"0"});const l=document.createElement("span");Object.assign(l.style,{position:"absolute",left:"-16px",top:"6px",width:"5px",height:"5px",borderRadius:"50%",background:"var(--hs-accent)"}),a.appendChild(l);const c=document.createElement("span");vt(c,"secondary","sm","normal"),c.textContent=o,a.appendChild(c),n.appendChild(a)}),i.el.appendChild(n),this.mountCard(i)}dismissAll(){this.cards.forEach(e=>this.removeCard(e)),this.cards=[]}createCard(){St();const e=Kt({radius:"md",elevation:"elevated",className:"hs-overlay-card"});Object.assign(e.style,{position:"fixed",maxWidth:`${Math.min(GC,window.innerWidth-32)}px`,padding:"var(--hs-space-4)",zIndex:W.zOverlay,opacity:"0",pointerEvents:"auto"});const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>this.dismiss(r)});Object.assign(t.style,{position:"absolute",top:"var(--hs-space-2)",right:"var(--hs-space-2)",minWidth:"0",padding:"2px 6px",fontSize:"var(--hs-text-xs)"}),e.appendChild(t);const i=setTimeout(()=>this.dismiss(r),FC),r={el:e,timer:i,anim:null};return r}mountCard(e){document.body.appendChild(e.el),this.positionCard(e.el,this.cards.length),this.cards.push(e),e.anim=rt(e.el,{preset:"snappy"})}positionCard(e,t){const i=500+t*10,r=e.offsetHeight||80;Object.assign(e.style,{bottom:`${i+t*(r+8)}px`,left:"50%",transform:"translateX(-50%)"})}dismiss(e){const t=this.cards.indexOf(e);t>=0&&this.cards.splice(t,1),this.removeCard(e)}removeCard(e){var t;clearTimeout(e.timer),(t=e.anim)==null||t.stop(),e.anim=Nt(e.el,{remove:!0,preset:"smooth"})}}class WC{constructor(){this.el=null,this.currentAnim=null,this.minimized=!1,this.onMinimize=null,this.onRestore=null,this.onClose=null}show(){St(),this.hide(),this.el=Kt({radius:"pill",elevation:"elevated",className:"hs-controls"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-3)",left:"0",right:"0",margin:"0 auto",width:"fit-content",display:"flex",alignItems:"center",gap:"var(--hs-space-1)",padding:"4px",zIndex:W.zControls,opacity:"0"}),$i(this.el);const e=Ct({label:this.minimized?"▲":"—",variant:"ghost",size:"sm",onClick:()=>{var i,r;this.minimized?(this.minimized=!1,e.textContent="—",(i=this.onRestore)==null||i.call(this)):(this.minimized=!0,e.textContent="▲",(r=this.onMinimize)==null||r.call(this))}});Object.assign(e.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(e);const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>{var i;return(i=this.onClose)==null?void 0:i.call(this)}});Object.assign(t.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(t),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;const e=this.el;this.el=null,this.minimized=!1,this.currentAnim=Nt(e,{remove:!0,preset:"smooth"})}}const HC=1e4;class VC{constructor(){this.el=null,this.currentAnim=null,this.autoTimer=null,this.resolver=null}ask(e){return St(),this.dismiss(),new Promise(t=>{this.resolver=t,this.el=Kt({radius:"lg",elevation:"elevated",role:"alertdialog",className:"hs-confirm-prompt"}),Object.assign(this.el.style,{position:"fixed",bottom:"320px",left:"50%",transform:"translateX(-50%)",padding:"var(--hs-space-5)",maxWidth:"340px",minWidth:"240px",zIndex:W.zTop,opacity:"0",textAlign:"center"}),this.el.setAttribute("aria-label","Action confirmation"),$i(this.el);const i=document.createElement("p");vt(i,"primary","base","normal"),i.textContent=e,i.style.marginBottom="var(--hs-space-4)",this.el.appendChild(i);const r=document.createElement("div");Object.assign(r.style,{display:"flex",gap:"var(--hs-space-3)",justifyContent:"center"}),r.appendChild(Ct({label:"Yes",variant:"accent",size:"md",onClick:()=>this.resolve(!0)})),r.appendChild(Ct({label:"No",variant:"default",size:"md",onClick:()=>this.resolve(!1)})),this.el.appendChild(r),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy"}),this.autoTimer=setTimeout(()=>this.resolve(!1),HC)})}dismiss(){this.resolver&&(this.resolver(!1),this.resolver=null),this.cleanup()}resolve(e){var t;(t=this.resolver)==null||t.call(this,e),this.resolver=null,this.cleanup()}cleanup(){var e;if(this.autoTimer&&(clearTimeout(this.autoTimer),this.autoTimer=null),(e=this.currentAnim)==null||e.stop(),this.el){const t=this.el;this.el=null,this.currentAnim=Nt(t,{remove:!0,preset:"smooth"})}}}const zC=520,$C=340,ra=12;class jC{constructor(){this.currentAnim=null,St(),this.el=Kt({radius:"lg",elevation:"elevated",className:"hs-stage-backdrop"}),Object.assign(this.el.style,{position:"fixed",bottom:"0",left:"0",right:"0",margin:"0 auto",width:`${zC}px`,height:`${$C}px`,zIndex:W.zOverlay,overflow:"hidden",display:"flex",flexDirection:"column",opacity:"0",padding:`${ra}px ${ra}px 0 ${ra}px`,borderRadius:"var(--hs-radius-lg) var(--hs-radius-lg) 0 0",borderBottom:"none"}),$i(this.el),this.contentArea=document.createElement("div"),Object.assign(this.contentArea.style,{flex:"1",position:"relative",overflow:"hidden",borderRadius:"var(--hs-radius-md) var(--hs-radius-md) 0 0"}),this.el.appendChild(this.contentArea)}appendContent(e){Object.assign(e.style,{width:"100%",height:"100%",objectFit:"cover",display:"block",borderRadius:"inherit"}),this.contentArea.appendChild(e)}show(){document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.95,y:24}})}hide(){var e;(e=this.currentAnim)==null||e.stop(),this.currentAnim=Nt(this.el,{remove:!0,preset:"smooth",to:{opacity:0,scale:.95,y:16}})}get contentElement(){return this.contentArea}destroy(){var e;(e=this.currentAnim)==null||e.stop(),this.el.remove()}}const XC=`
1059
+ `;class of{constructor(){this.el=null,this.avatarWrap=null,this.avatarImg=null,this.avatarVideo=null,this.nameEl=null,this.suggestionArea=null,this.suggestionText=null,this.currentAnim=null,this._state="hidden",this.pulseStyleInjected=!1,this.avatarUrl=null,this.videoUrl=null,this.staffName="",this.onClick=null,this.onSuggestionAccept=null,this.onSuggestionDismiss=null}init(e,t,i){if(this.el)return;if(St(),this.avatarUrl=e,this.videoUrl=t,this.staffName=i,this.el=Kt({radius:"pill",elevation:"elevated",interactive:!0,className:"hs-chat-pill"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-5)",left:"0",right:"0",margin:"0 auto",width:"fit-content",maxWidth:"min(90vw, 600px)",display:"none",alignItems:"center",gap:"0px",padding:"5px",zIndex:W.zControls,cursor:"pointer",userSelect:"none",opacity:"0",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.18)",transition:"gap 0.3s ease, padding 0.3s ease, box-shadow 0.2s ease",overflow:"hidden"}),$i(this.el),this.el.addEventListener("mouseenter",()=>{this.el&&(this.el.style.boxShadow="0 6px 32px rgba(0, 0, 0, 0.24)")}),this.el.addEventListener("mouseleave",()=>{this.el&&(this.el.style.boxShadow="0 4px 24px rgba(0, 0, 0, 0.18)")}),this.avatarWrap=document.createElement("div"),Object.assign(this.avatarWrap.style,{width:"36px",height:"36px",borderRadius:"50%",overflow:"hidden",flexShrink:"0",position:"relative",border:"1.5px solid var(--hs-glass-border)",transition:"box-shadow 0.3s ease, width 0.3s ease, height 0.3s ease"}),e)this.avatarImg=document.createElement("img"),this.avatarImg.src=e,this.avatarImg.alt=i,Object.assign(this.avatarImg.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),this.avatarWrap.appendChild(this.avatarImg);else{const a=document.createElement("div");Object.assign(a.style,{width:"100%",height:"100%",background:"var(--hs-accent)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"var(--hs-text-sm)",fontWeight:"var(--hs-weight-semibold)",color:"var(--hs-accent-text)"}),a.textContent=i.charAt(0).toUpperCase(),this.avatarWrap.appendChild(a)}t&&(this.avatarVideo=document.createElement("video"),this.avatarVideo.src=t,this.avatarVideo.muted=!0,this.avatarVideo.loop=!0,this.avatarVideo.playsInline=!0,this.avatarVideo.setAttribute("playsinline",""),Object.assign(this.avatarVideo.style,{position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"cover",display:"none"}),this.avatarWrap.appendChild(this.avatarVideo)),this.el.appendChild(this.avatarWrap),this.nameEl=document.createElement("span"),vt(this.nameEl,"primary","base","medium"),this.nameEl.textContent=i,Object.assign(this.nameEl.style,{whiteSpace:"nowrap",overflow:"hidden",maxWidth:"0",opacity:"0",transition:"max-width 0.3s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"}),this.el.appendChild(this.nameEl),this.suggestionArea=document.createElement("div"),Object.assign(this.suggestionArea.style,{display:"flex",alignItems:"center",gap:"var(--hs-space-2)",maxWidth:"0",opacity:"0",overflow:"hidden",transition:"max-width 0.35s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"});const r=document.createElement("span");Object.assign(r.style,{width:"1px",height:"20px",background:"var(--hs-divider)",flexShrink:"0"}),this.suggestionArea.appendChild(r),this.suggestionText=document.createElement("span"),vt(this.suggestionText,"secondary","sm","normal"),Object.assign(this.suggestionText.style,{whiteSpace:"normal",lineHeight:"1.4",display:"-webkit-box",WebkitLineClamp:"2",WebkitBoxOrient:"vertical",overflow:"hidden"}),this.suggestionArea.appendChild(this.suggestionText);const n=Ct({label:"Let's talk",variant:"accent",size:"sm",onClick:a=>{var l;a.stopPropagation(),(l=this.onSuggestionAccept)==null||l.call(this)}});n.style.flexShrink="0",this.suggestionArea.appendChild(n);const o=document.createElement("button");o.textContent="✕",Object.assign(o.style,{background:"none",border:"none",color:"var(--hs-text-tertiary)",fontSize:"12px",cursor:"pointer",padding:"4px",flexShrink:"0",lineHeight:"1",transition:"color 0.15s ease"}),o.addEventListener("mouseenter",()=>{o.style.color="var(--hs-text-primary)"}),o.addEventListener("mouseleave",()=>{o.style.color="var(--hs-text-tertiary)"}),o.addEventListener("click",a=>{var l;a.stopPropagation(),(l=this.onSuggestionDismiss)==null||l.call(this),this.clearSuggestion()}),this.suggestionArea.appendChild(o),this.el.appendChild(this.suggestionArea),this.el.addEventListener("click",a=>{var l;a.target.closest("button")||(l=this.onClick)==null||l.call(this)}),document.documentElement.appendChild(this.el)}showAmbient(){var e;!this.el||this._state==="ambient"||(this._state="ambient",this.collapseName(),this.collapseSuggestion(),this.stopAvatarVideo(),this.el.style.display="flex",this.el.style.gap="0px",this.el.style.padding="5px",(e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.8,y:12}}))}showNamed(){var t;if(!this.el||this._state==="named")return;const e=this._state==="hidden";this._state="named",this.collapseSuggestion(),this.stopAvatarVideo(),this.expandName(),this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",e&&((t=this.currentAnim)==null||t.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.85,y:16}}))}showSuggestion(e){var i;if(!this.el||!this.suggestionText)return;const t=this._state==="hidden";this._state="suggestion",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="10px 16px 10px 10px",this.el.style.borderRadius="var(--hs-radius-lg)",this.collapseName(),t&&((i=this.currentAnim)==null||i.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.9,y:12}})),this.startAvatarVideo(),this.startAvatarPulse(),this.suggestionText.textContent=e,this.suggestionText.title=e,requestAnimationFrame(()=>{this.suggestionArea&&(this.suggestionArea.style.maxWidth="500px",this.suggestionArea.style.opacity="1",this.suggestionArea.style.marginLeft="var(--hs-space-2)")})}clearSuggestion(){this.el&&(this._state="named",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.el.style.padding="8px 20px 8px 8px",this.el.style.borderRadius="var(--hs-radius-pill)")}showConnecting(){var e;!this.el||!this.nameEl||(this._state="connecting",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.nameEl.textContent="Connecting...",this.nameEl.style.opacity="0.6",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",this.el.style.opacity==="0"&&((e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})))}restoreName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1")}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;this._state="hidden",this.stopAvatarPulse(),this.stopAvatarVideo();const e=this.el;this.currentAnim=Nt(e,{remove:!1,preset:"smooth",to:{opacity:0,scale:.9,y:12},onComplete:()=>{e.style.display="none"}})}destroy(){var e,t;(e=this.currentAnim)==null||e.stop(),this.stopAvatarPulse(),this.stopAvatarVideo(),(t=this.el)==null||t.remove(),this.el=null,this._state="hidden"}get state(){return this._state}get isVisible(){return this._state!=="hidden"}expandName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1",this.nameEl.style.maxWidth="150px",this.nameEl.style.marginLeft="var(--hs-space-2)")}collapseName(){this.nameEl&&(this.nameEl.style.maxWidth="0",this.nameEl.style.opacity="0",this.nameEl.style.marginLeft="0")}collapseSuggestion(){this.suggestionArea&&(this.suggestionArea.style.maxWidth="0",this.suggestionArea.style.opacity="0",this.suggestionArea.style.marginLeft="0")}startAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.style.display="block",this.avatarVideo.currentTime=0,this.avatarVideo.play().catch(()=>{}),this.avatarImg.style.opacity="0")}stopAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.pause(),this.avatarVideo.style.display="none",this.avatarImg.style.opacity="1")}startAvatarPulse(){this.avatarWrap&&(this.injectPulseStyle(),this.avatarWrap.style.animation="hs-pill-pulse 1.5s ease-in-out infinite")}stopAvatarPulse(){this.avatarWrap&&(this.avatarWrap.style.animation="")}injectPulseStyle(){if(this.pulseStyleInjected)return;this.pulseStyleInjected=!0;const e=document.createElement("style");e.textContent=FC,document.head.appendChild(e)}}const GC=15e3,LC=320;class WC{constructor(){this.cards=[],this.anchor=null}setAnchor(e){this.anchor=e}showTextCard(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,n.style.whiteSpace="pre-wrap",i.el.appendChild(n),this.mountCard(i)}showImageCard(e,t){const i=this.createCard(),r=document.createElement("img");if(r.src=e,r.alt=t||"",Object.assign(r.style,{width:"100%",borderRadius:"var(--hs-radius-sm)",display:"block",marginBottom:t?"var(--hs-space-2)":"0"}),i.el.appendChild(r),t){const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,i.el.appendChild(n)}this.mountCard(i)}showBulletList(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("ul");Object.assign(n.style,{margin:"0",paddingLeft:"var(--hs-space-5)",listStyleType:"none"}),t.forEach(o=>{const a=document.createElement("li");Object.assign(a.style,{marginBottom:"var(--hs-space-1)",position:"relative",paddingLeft:"0"});const l=document.createElement("span");Object.assign(l.style,{position:"absolute",left:"-16px",top:"6px",width:"5px",height:"5px",borderRadius:"50%",background:"var(--hs-accent)"}),a.appendChild(l);const c=document.createElement("span");vt(c,"secondary","sm","normal"),c.textContent=o,a.appendChild(c),n.appendChild(a)}),i.el.appendChild(n),this.mountCard(i)}dismissAll(){this.cards.forEach(e=>this.removeCard(e)),this.cards=[]}createCard(){St();const e=Kt({radius:"md",elevation:"elevated",className:"hs-overlay-card"});Object.assign(e.style,{position:"fixed",maxWidth:`${Math.min(LC,window.innerWidth-32)}px`,padding:"var(--hs-space-4)",zIndex:W.zOverlay,opacity:"0",pointerEvents:"auto"});const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>this.dismiss(r)});Object.assign(t.style,{position:"absolute",top:"var(--hs-space-2)",right:"var(--hs-space-2)",minWidth:"0",padding:"2px 6px",fontSize:"var(--hs-text-xs)"}),e.appendChild(t);const i=setTimeout(()=>this.dismiss(r),GC),r={el:e,timer:i,anim:null};return r}mountCard(e){document.body.appendChild(e.el),this.positionCard(e.el,this.cards.length),this.cards.push(e),e.anim=rt(e.el,{preset:"snappy"})}positionCard(e,t){const i=500+t*10,r=e.offsetHeight||80;Object.assign(e.style,{bottom:`${i+t*(r+8)}px`,left:"50%",transform:"translateX(-50%)"})}dismiss(e){const t=this.cards.indexOf(e);t>=0&&this.cards.splice(t,1),this.removeCard(e)}removeCard(e){var t;clearTimeout(e.timer),(t=e.anim)==null||t.stop(),e.anim=Nt(e.el,{remove:!0,preset:"smooth"})}}class HC{constructor(){this.el=null,this.currentAnim=null,this.minimized=!1,this.onMinimize=null,this.onRestore=null,this.onClose=null}show(){St(),this.hide(),this.el=Kt({radius:"pill",elevation:"elevated",className:"hs-controls"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-3)",left:"0",right:"0",margin:"0 auto",width:"fit-content",display:"flex",alignItems:"center",gap:"var(--hs-space-1)",padding:"4px",zIndex:W.zControls,opacity:"0"}),$i(this.el);const e=Ct({label:this.minimized?"▲":"—",variant:"ghost",size:"sm",onClick:()=>{var i,r;this.minimized?(this.minimized=!1,e.textContent="—",(i=this.onRestore)==null||i.call(this)):(this.minimized=!0,e.textContent="▲",(r=this.onMinimize)==null||r.call(this))}});Object.assign(e.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(e);const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>{var i;return(i=this.onClose)==null?void 0:i.call(this)}});Object.assign(t.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(t),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;const e=this.el;this.el=null,this.minimized=!1,this.currentAnim=Nt(e,{remove:!0,preset:"smooth"})}}const VC=1e4;class zC{constructor(){this.el=null,this.currentAnim=null,this.autoTimer=null,this.resolver=null}ask(e){return St(),this.dismiss(),new Promise(t=>{this.resolver=t,this.el=Kt({radius:"lg",elevation:"elevated",role:"alertdialog",className:"hs-confirm-prompt"}),Object.assign(this.el.style,{position:"fixed",bottom:"320px",left:"50%",transform:"translateX(-50%)",padding:"var(--hs-space-5)",maxWidth:"340px",minWidth:"240px",zIndex:W.zTop,opacity:"0",textAlign:"center"}),this.el.setAttribute("aria-label","Action confirmation"),$i(this.el);const i=document.createElement("p");vt(i,"primary","base","normal"),i.textContent=e,i.style.marginBottom="var(--hs-space-4)",this.el.appendChild(i);const r=document.createElement("div");Object.assign(r.style,{display:"flex",gap:"var(--hs-space-3)",justifyContent:"center"}),r.appendChild(Ct({label:"Yes",variant:"accent",size:"md",onClick:()=>this.resolve(!0)})),r.appendChild(Ct({label:"No",variant:"default",size:"md",onClick:()=>this.resolve(!1)})),this.el.appendChild(r),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy"}),this.autoTimer=setTimeout(()=>this.resolve(!1),VC)})}dismiss(){this.resolver&&(this.resolver(!1),this.resolver=null),this.cleanup()}resolve(e){var t;(t=this.resolver)==null||t.call(this,e),this.resolver=null,this.cleanup()}cleanup(){var e;if(this.autoTimer&&(clearTimeout(this.autoTimer),this.autoTimer=null),(e=this.currentAnim)==null||e.stop(),this.el){const t=this.el;this.el=null,this.currentAnim=Nt(t,{remove:!0,preset:"smooth"})}}}const $C=520,jC=340,ra=12;class XC{constructor(){this.currentAnim=null,St(),this.el=Kt({radius:"lg",elevation:"elevated",className:"hs-stage-backdrop"}),Object.assign(this.el.style,{position:"fixed",bottom:"0",left:"0",right:"0",margin:"0 auto",width:`${$C}px`,height:`${jC}px`,zIndex:W.zOverlay,overflow:"hidden",display:"flex",flexDirection:"column",opacity:"0",padding:`${ra}px ${ra}px 0 ${ra}px`,borderRadius:"var(--hs-radius-lg) var(--hs-radius-lg) 0 0",borderBottom:"none"}),$i(this.el),this.contentArea=document.createElement("div"),Object.assign(this.contentArea.style,{flex:"1",position:"relative",overflow:"hidden",borderRadius:"var(--hs-radius-md) var(--hs-radius-md) 0 0"}),this.el.appendChild(this.contentArea)}appendContent(e){Object.assign(e.style,{width:"100%",height:"100%",objectFit:"cover",display:"block",borderRadius:"inherit"}),this.contentArea.appendChild(e)}show(){document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.95,y:24}})}hide(){var e;(e=this.currentAnim)==null||e.stop(),this.currentAnim=Nt(this.el,{remove:!0,preset:"smooth",to:{opacity:0,scale:.95,y:16}})}get contentElement(){return this.contentArea}destroy(){var e;(e=this.currentAnim)==null||e.stop(),this.el.remove()}}const YC=`
1060
1060
  @keyframes hs-highlight-glow {
1061
1061
  0%, 100% { box-shadow: 0 0 8px var(--hs-accent-glow), inset 0 0 4px var(--hs-accent-glow); }
1062
1062
  50% { box-shadow: 0 0 20px var(--hs-accent-glow), inset 0 0 8px var(--hs-accent-glow); }
1063
1063
  }
1064
- `;let af=!1;class YC{constructor(){this.highlights=[]}highlight(e,t=3e3){St(),this.injectPulseStyle();const i=document.createElement("div");i.className="hs-highlight-overlay",i.setAttribute("data-hs-theme","dark");const r=()=>{const l=e.getBoundingClientRect();Object.assign(i.style,{position:"fixed",top:`${l.top-3}px`,left:`${l.left-3}px`,width:`${l.width+6}px`,height:`${l.height+6}px`,border:"2px solid var(--hs-accent)",borderRadius:"var(--hs-radius-sm)",animation:"hs-highlight-glow 1.5s ease-in-out infinite",pointerEvents:"none",zIndex:W.zOverlay,boxSizing:"border-box"})};r(),document.body.appendChild(i);const n=()=>r();window.addEventListener("scroll",n,{passive:!0});const o=setTimeout(()=>this.removeHighlight(a),t),a={overlay:i,timer:o,scrollHandler:n,anim:null};this.highlights.push(a)}clearAll(){this.highlights.forEach(e=>this.removeHighlight(e)),this.highlights=[]}removeHighlight(e){clearTimeout(e.timer),window.removeEventListener("scroll",e.scrollHandler),e.anim=EC(e.overlay,1,0,"smooth",()=>{e.overlay.remove()});const t=this.highlights.indexOf(e);t>=0&&this.highlights.splice(t,1)}injectPulseStyle(){if(af)return;af=!0;const e=document.createElement("style");e.textContent=XC,document.head.appendChild(e)}}const qC=800,KC=600*1e3,ZC=540*1e3,lf=60*1e3,JC=90*1e3,QC=[{type:"function",name:"page_action",description:"Interact with the webpage the visitor is viewing. You can scroll to elements, highlight elements, click buttons/links, fill form fields, or read the page content. Describe what you want to do in natural language. Call this to understand the page, guide the visitor, or take actions on their behalf.",parameters:{type:"object",properties:{instruction:{type:"string",description:"What to do on the page, e.g. 'scroll to pricing section', 'highlight the sign-up button', 'fill the email field with test@example.com', 'read the page to understand what it contains'"}},required:["instruction"]}},{type:"function",name:"show_text_card",description:"Display a floating text card overlay near the avatar with additional information for the visitor. Use for key points, explanations, or summaries that benefit from visual display.",parameters:{type:"object",properties:{title:{type:"string",description:"Card title"},body:{type:"string",description:"Card body text"}},required:["title","body"]}},{type:"function",name:"show_image_card",description:"Display a floating image card overlay with an optional caption.",parameters:{type:"object",properties:{image_url:{type:"string",description:"URL of the image to display"},caption:{type:"string",description:"Optional caption below the image"}},required:["image_url"]}},{type:"function",name:"show_bullet_list",description:"Display a styled list of key points as a floating overlay card.",parameters:{type:"object",properties:{title:{type:"string",description:"List title"},items:{type:"array",items:{type:"string"},description:"List items"}},required:["title","items"]}},{type:"function",name:"dismiss_overlays",description:"Dismiss all currently visible overlay cards.",parameters:{type:"object",properties:{},required:[]}},{type:"function",name:"get_skill_instructions",description:'Retrieve the full playbook for one of your configured skills. Call this when you determine a skill is relevant to the current conversation — it returns detailed guidance on what to say, tone, and what to avoid. Use the skill name exactly as listed in the "Your Skills" section of your instructions.',parameters:{type:"object",properties:{skill_name:{type:"string",description:'The exact skill name as listed in Your Skills (e.g. "Convert Visitor", "Get Started").'}},required:["skill_name"]}}];class cf{constructor(e,t){this.stage=null,this.avatar=null,this.state="idle",this.avatarState="idle",this.scrollHandler=null,this.idleVideoUrl=null,this.idleImageUrl=null,this.bubbleTimer=null,this.realtimeSession=null,this.audioForwarder=null,this.anamSession=null,this.sessionResponse=null,this.domAnalyzer=null,this.toolHandler=null,this.maxDurationTimer=null,this.maxDurationWarnTimer=null,this.inactivityTimer=null,this.inactivityCloseTimer=null,this.sessionStartTime=0,this.logger=null,this.rrwebRecorder=null,this.visionWs=null,this.externalObserver=!1,this.actionExecutor=null,this.visionContext=null,this.staffDisplayName="Assistant",this.staffAvatarUrl=null,this.hasHadConversation=!1,this.avatarFrame=null,this.bubble=null,this.chatPill=null,this.overlayRenderer=null,this.controls=null,this.confirmationPrompt=null,this.highlightRenderer=null,this.stageBackdrop=null,this.stageEl=null,this.homePlaceholder=null,this.homeObserver=null,this.homeVisible=!0,this.homeEverSeen=!1,this.pillProtected=!1,this.paused=!1,this.config=e,this.widgetPrompts=t??null,this.visitorId=this.getOrCreateVisitorId()}get isInline(){return this.config.mode==="inline"&&!!this.config.container}get activeContainer(){return this.config.container}async init(){St(),this.stage=new ux,await this.stage.init(this.config.mode,this.config.container),this.avatar=new fx(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.avatarFrame=new OC,this.stage.rootElement&&$i(this.stage.rootElement),this.bubble=new NC(this.widgetPrompts??void 0),this.bubble.onClick=()=>this.onAvatarClick(),this.stage.rootElement&&(this.stage.rootElement.style.position="relative",this.stage.rootElement.appendChild(this.bubble.el)),this.avatar.setInteractive(()=>this.onAvatarClick()),this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick(),this.isInline?(setTimeout(()=>{var t;(this.state==="idle"||this.state==="teasing")&&!this.homeVisible&&((t=this.chatPill)==null?void 0:t.state)==="hidden"&&this.chatPill.showNamed()},5e3),this.startHomeObserver()):this.homeVisible=!1,this.setupTrigger(),this.startVisionLoop(),window.addEventListener("beforeunload",()=>{var e;(this.state==="active"||this.state==="connecting")&&((e=this.logger)==null||e.flush())}),console.log("[HolostaffWidget] Initialized",{staffId:this.config.staffId,trigger:this.config.trigger,visionEnabled:!!this.config.visionWsUrl})}async loadIdleAsset(){if(!(!this.avatar||!this.stage)){if(this.idleVideoUrl)try{if(this.isInline&&this.stage.inlineTarget){const e=this.stage.inlineTarget;e.style.position="relative";const t=document.createElement("div");t.className="hs-inline-card",t.setAttribute("data-hs-theme","dark"),Object.assign(t.style,{position:"absolute",inset:"0",display:"flex",flexDirection:"column",borderRadius:"var(--hs-radius-lg)",overflow:"hidden",background:"var(--hs-glass-bg)",backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",border:"1px solid var(--hs-glass-border)",boxShadow:"var(--hs-glass-shadow)",cursor:"pointer",padding:"var(--hs-space-3)",boxSizing:"border-box"});const i=document.createElement("div");Object.assign(i.style,{flex:"1",overflow:"hidden",position:"relative",borderRadius:"var(--hs-radius-md)",border:"1px solid var(--hs-glass-border)"});const r=document.createElement("video");r.src=this.idleVideoUrl,r.autoplay=!0,r.loop=!0,r.muted=!0,r.playsInline=!0,r.setAttribute("playsinline",""),Object.assign(r.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),i.appendChild(r),t.appendChild(i);const n=document.createElement("div");Object.assign(n.style,{padding:"var(--hs-space-3) var(--hs-space-4)",textAlign:"center"});const o=document.createElement("div");Object.assign(o.style,{color:"var(--hs-text-primary)",fontSize:"var(--hs-text-base)",fontWeight:"var(--hs-weight-semibold)",fontFamily:"var(--hs-font)",lineHeight:"var(--hs-line-height)"}),o.textContent=`${this.staffDisplayName}, your AI copilot`,n.appendChild(o);const a=document.createElement("div");Object.assign(a.style,{color:"var(--hs-text-tertiary)",fontSize:"var(--hs-text-xs)",fontFamily:"var(--hs-font)",marginTop:"2px"}),a.textContent="Powered by Holostaff",n.appendChild(a),t.appendChild(n),t.addEventListener("click",()=>this.onAvatarClick()),e.appendChild(t),this.stage.rootElement&&(this.stage.rootElement.style.display="none")}else{const e=this.stage.rootElement;if(!e)throw new Error("Widget root not available");await this.avatar.loadIdleVideo(this.idleVideoUrl,e)}return}catch{console.warn("[HolostaffWidget] Failed to load idle video, trying image fallback")}this.idleImageUrl?await this.avatar.loadIdleImage(this.idleImageUrl):console.warn("[HolostaffWidget] No idle video or image configured")}}setIdleVideo(e){this.idleVideoUrl=e}setIdleImage(e){this.idleImageUrl=e}setObserver(e,t){this.rrwebRecorder=e,this.visionWs=t,this.externalObserver=!0}setStaffInfo(e,t){this.staffDisplayName=e,this.staffAvatarUrl=t}setupTrigger(){if(this.isInline){this.showAvatarOnly();return}if(this.config.visionWsUrl){this.showAvatarOnly();return}switch(this.config.trigger){case"scroll":this.setupScrollTrigger();break;case"delay":setTimeout(()=>this.showTeaser(),this.config.delayMs);break;case"immediate":this.showTeaser();break}}setupScrollTrigger(){this.scrollHandler=()=>{const e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight,i=t>0?e/t:0;i>=this.config.scrollThreshold&&this.state==="idle"?this.showTeaser():i<this.config.scrollThreshold*.5&&this.state==="teasing"&&this.hideTeaser()},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}showAvatarOnly(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker))}showTeaser(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker),this.bubbleTimer=setTimeout(()=>{var e;return(e=this.bubble)==null?void 0:e.start()},qC))}hideTeaser(){var e;this.state!=="teasing"||!this.avatar||!this.stage||(this.state="idle",this.bubbleTimer&&(clearTimeout(this.bubbleTimer),this.bubbleTimer=null),(e=this.bubble)==null||e.stop(),this.avatar.slideOut(this.stage.app.ticker))}async onAvatarClick(){var e,t,i,r,n,o,a,l,c,h,u,f;if(!(this.state!=="teasing"&&this.state!=="idle")){if(this.state="connecting",(e=this.bubble)==null||e.stop(),(t=this.bubble)==null||t.hideStatic(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null,this.isInline){(r=this.chatPill)==null||r.showConnecting();const d=(o=(n=this.stage)==null?void 0:n.inlineTarget)==null?void 0:o.querySelector(".hs-inline-card video");d&&d.pause()}else{(a=this.stage)!=null&&a.rootElement&&(this.stage.rootElement.style.display="");const d=document.querySelector("#holostaff-widget-root video");d&&d.pause(),(l=this.bubble)==null||l.showStatic("Connecting...")}console.log("[HolostaffWidget] Starting conversation...");try{this.sessionResponse=await Bf(this.config.staffId,this.config.backendUrl),console.log("[HolostaffWidget] Session tokens received"),this.logger=new uv({staffId:this.config.staffId,staffName:this.sessionResponse.staff.name,backendUrl:this.config.backendUrl}),await this.connectAnam(),await this.connectRealtimeApi(),this.state="active",this.setAvatarState("listening"),this.sessionStartTime=Date.now(),(c=this.bubble)==null||c.hideStatic(),this.showControls(),this.startSessionTimers(),(h=this.visionWs)==null||h.sendConversationStarted(),(u=this.rrwebRecorder)==null||u.pause(),console.log("[HolostaffWidget] Conversation active")}catch(d){console.error("[HolostaffWidget] Failed to start conversation:",d),(f=this.bubble)==null||f.hideStatic(),this.endConversation()}}}moveToStage(){var t;if(!this.isInline||!((t=this.stage)!=null&&t.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display="none"),this.stage.inlineTarget.querySelectorAll("video").forEach(i=>{i instanceof HTMLVideoElement&&i.pause()}),this.homePlaceholder=document.createElement("div"),this.homePlaceholder.setAttribute("data-hs-theme","dark"),Object.assign(this.homePlaceholder.style,{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",color:"var(--hs-text-secondary)",fontSize:"var(--hs-text-sm)",fontFamily:"var(--hs-font)",textAlign:"center",padding:"var(--hs-space-4)",boxSizing:"border-box"}),this.homePlaceholder.innerHTML="Agent is active below&nbsp;&darr;",this.stage.inlineTarget.appendChild(this.homePlaceholder),this.stageBackdrop=new jC,this.stageEl=this.stageBackdrop.el,this.stageBackdrop.show(),console.log("[HolostaffWidget] Moved to glass stage (bottom-center)")}returnToHome(){var t,i,r;if((t=this.stageBackdrop)==null||t.destroy(),this.stageBackdrop=null,this.stageEl=null,(i=this.homePlaceholder)==null||i.remove(),this.homePlaceholder=null,!((r=this.stage)!=null&&r.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display=""),this.stage.inlineTarget.querySelectorAll(".hs-inline-card video").forEach(n=>{n.style.display="",n instanceof HTMLVideoElement&&n.play()}),console.log("[HolostaffWidget] Returned to home (inline container)")}startHomeObserver(){var i;this.stopHomeObserver();const e=(i=this.stage)==null?void 0:i.inlineTarget;if(!e)return;const t=e.getBoundingClientRect();this.homeVisible=t.top<window.innerHeight&&t.bottom>0,this.homeObserver=new IntersectionObserver(([r])=>{const n=this.homeVisible;if(this.homeVisible=r.isIntersecting,this.homeVisible&&!this.homeEverSeen&&(this.homeEverSeen=!0),(this.state==="idle"||this.state==="teasing")&&this.chatPill)if(this.homeVisible){if(this.pillProtected){this.pillProtected=!1;return}this.chatPill.hide()}else!this.homeVisible&&n&&this.homeEverSeen?this.chatPill.showNamed():!this.homeVisible&&!this.homeEverSeen&&this.chatPill.state==="hidden"&&this.chatPill.showNamed()},{threshold:.1}),this.homeObserver.observe(e)}stopHomeObserver(){var e;(e=this.homeObserver)==null||e.disconnect(),this.homeObserver=null}async connectAnam(){this.sessionResponse&&(this.anamSession=new ev({sessionToken:this.sessionResponse.anamSessionToken,inlineMode:this.isInline&&!!this.stageBackdrop}),this.anamSession.onConnected=()=>{console.log("[HolostaffWidget] Anam connected")},this.anamSession.onVideoReady=e=>{var t,i,r;console.log("[HolostaffWidget] Anam avatar video ready"),(t=this.bubble)==null||t.hideStatic(),(i=this.chatPill)==null||i.hide(),this.isInline?(this.moveToStage(),(r=this.stageBackdrop)==null||r.appendContent(e)):this.avatar&&this.stage&&this.avatar.setLiveVideo(e,this.stage.app.ticker)},this.anamSession.onTalkStreamInterrupted=()=>{console.log("[HolostaffWidget] Anam talk stream interrupted")},this.anamSession.onDisconnected=e=>{console.log("[HolostaffWidget] Anam disconnected:",e),this.endConversation()},this.anamSession.onError=e=>{console.error("[HolostaffWidget] Anam error:",e.message)},await this.anamSession.connect(),console.log("[HolostaffWidget] Anam session ready"))}async connectRealtimeApi(){var o;if(!this.sessionResponse)return;const e=document.title||"",t=location.href,i=((o=document.querySelector('meta[name="description"]'))==null?void 0:o.getAttribute("content"))||"",r=Array.from(document.querySelectorAll("h1, h2, h3")).slice(0,10).map(a=>{var l;return(l=a.textContent)==null?void 0:l.trim()}).filter(Boolean).join(" | ");let n=(this.sessionResponse.staff.instructions??"")+`
1064
+ `;let af=!1;class qC{constructor(){this.highlights=[]}highlight(e,t=3e3){St(),this.injectPulseStyle();const i=document.createElement("div");i.className="hs-highlight-overlay",i.setAttribute("data-hs-theme","dark");const r=()=>{const l=e.getBoundingClientRect();Object.assign(i.style,{position:"fixed",top:`${l.top-3}px`,left:`${l.left-3}px`,width:`${l.width+6}px`,height:`${l.height+6}px`,border:"2px solid var(--hs-accent)",borderRadius:"var(--hs-radius-sm)",animation:"hs-highlight-glow 1.5s ease-in-out infinite",pointerEvents:"none",zIndex:W.zOverlay,boxSizing:"border-box"})};r(),document.body.appendChild(i);const n=()=>r();window.addEventListener("scroll",n,{passive:!0});const o=setTimeout(()=>this.removeHighlight(a),t),a={overlay:i,timer:o,scrollHandler:n,anim:null};this.highlights.push(a)}clearAll(){this.highlights.forEach(e=>this.removeHighlight(e)),this.highlights=[]}removeHighlight(e){clearTimeout(e.timer),window.removeEventListener("scroll",e.scrollHandler),e.anim=TC(e.overlay,1,0,"smooth",()=>{e.overlay.remove()});const t=this.highlights.indexOf(e);t>=0&&this.highlights.splice(t,1)}injectPulseStyle(){if(af)return;af=!0;const e=document.createElement("style");e.textContent=YC,document.head.appendChild(e)}}const KC=800,ZC=600*1e3,JC=540*1e3,lf=60*1e3,QC=90*1e3,eS=[{type:"function",name:"page_action",description:"Interact with the webpage the visitor is viewing. You can scroll to elements, highlight elements, click buttons/links, fill form fields, or read the page content. Describe what you want to do in natural language. Call this to understand the page, guide the visitor, or take actions on their behalf.",parameters:{type:"object",properties:{instruction:{type:"string",description:"What to do on the page, e.g. 'scroll to pricing section', 'highlight the sign-up button', 'fill the email field with test@example.com', 'read the page to understand what it contains'"}},required:["instruction"]}},{type:"function",name:"show_text_card",description:"Display a floating text card overlay near the avatar with additional information for the visitor. Use for key points, explanations, or summaries that benefit from visual display.",parameters:{type:"object",properties:{title:{type:"string",description:"Card title"},body:{type:"string",description:"Card body text"}},required:["title","body"]}},{type:"function",name:"show_image_card",description:"Display a floating image card overlay with an optional caption.",parameters:{type:"object",properties:{image_url:{type:"string",description:"URL of the image to display"},caption:{type:"string",description:"Optional caption below the image"}},required:["image_url"]}},{type:"function",name:"show_bullet_list",description:"Display a styled list of key points as a floating overlay card.",parameters:{type:"object",properties:{title:{type:"string",description:"List title"},items:{type:"array",items:{type:"string"},description:"List items"}},required:["title","items"]}},{type:"function",name:"dismiss_overlays",description:"Dismiss all currently visible overlay cards.",parameters:{type:"object",properties:{},required:[]}},{type:"function",name:"get_skill_instructions",description:'Retrieve the full playbook for one of your configured skills. Call this when you determine a skill is relevant to the current conversation — it returns detailed guidance on what to say, tone, and what to avoid. Use the skill name exactly as listed in the "Your Skills" section of your instructions.',parameters:{type:"object",properties:{skill_name:{type:"string",description:'The exact skill name as listed in Your Skills (e.g. "Convert Visitor", "Get Started").'}},required:["skill_name"]}},{type:"function",name:"end_conversation",description:"Gracefully end the current conversation. Call this after two failed attempts to steer an off-topic visitor back to the platform's purpose. Before calling, deliver your exit message naturally in speech — do not include it as a parameter. Set flag=true to mark this visitor as non-serious so they are not interrupted by the agent on future visits.",parameters:{type:"object",properties:{flag:{type:"boolean",description:"If true, flag this visitor as non-serious. The widget will be fully suppressed on their future visits."},reason:{type:"string",description:'Short reason for logging. E.g. "visitor not interested in platform".'}},required:["flag"]}}];class cf{constructor(e,t,i){this.stage=null,this.avatar=null,this.state="idle",this.avatarState="idle",this.scrollHandler=null,this.idleVideoUrl=null,this.idleImageUrl=null,this.bubbleTimer=null,this.realtimeSession=null,this.audioForwarder=null,this.anamSession=null,this.sessionResponse=null,this.domAnalyzer=null,this.toolHandler=null,this.maxDurationTimer=null,this.maxDurationWarnTimer=null,this.inactivityTimer=null,this.inactivityCloseTimer=null,this.sessionStartTime=0,this.logger=null,this.rrwebRecorder=null,this.visionWs=null,this.externalObserver=!1,this.actionExecutor=null,this.visionContext=null,this.staffDisplayName="Assistant",this.staffAvatarUrl=null,this.hasHadConversation=!1,this.pendingEndAfterResponse=null,this.avatarFrame=null,this.bubble=null,this.chatPill=null,this.overlayRenderer=null,this.controls=null,this.confirmationPrompt=null,this.highlightRenderer=null,this.stageBackdrop=null,this.stageEl=null,this.homePlaceholder=null,this.homeObserver=null,this.homeVisible=!0,this.homeEverSeen=!1,this.pillProtected=!1,this.paused=!1,this.config=e,this.widgetPrompts=t??null,this.evalMode=i??!1,this.visitorId=this.getOrCreateVisitorId()}get isInline(){return this.config.mode==="inline"&&!!this.config.container}get activeContainer(){return this.config.container}async init(){St(),this.stage=new dx,await this.stage.init(this.config.mode,this.config.container),this.avatar=new px(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.avatarFrame=new BC,this.stage.rootElement&&$i(this.stage.rootElement),this.bubble=new UC(this.widgetPrompts??void 0),this.bubble.onClick=()=>this.onAvatarClick(),this.stage.rootElement&&(this.stage.rootElement.style.position="relative",this.stage.rootElement.appendChild(this.bubble.el)),this.avatar.setInteractive(()=>this.onAvatarClick()),this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick(),this.isInline?(setTimeout(()=>{var t;(this.state==="idle"||this.state==="teasing")&&!this.homeVisible&&((t=this.chatPill)==null?void 0:t.state)==="hidden"&&this.chatPill.showNamed()},5e3),this.startHomeObserver()):this.homeVisible=!1,this.setupTrigger(),this.startVisionLoop(),window.addEventListener("beforeunload",()=>{var e;(this.state==="active"||this.state==="connecting")&&((e=this.logger)==null||e.flush())}),console.log("[HolostaffWidget] Initialized",{staffId:this.config.staffId,trigger:this.config.trigger,visionEnabled:!!this.config.visionWsUrl})}async loadIdleAsset(){if(!(!this.avatar||!this.stage)){if(this.idleVideoUrl)try{if(this.isInline&&this.stage.inlineTarget){const e=this.stage.inlineTarget;e.style.position="relative";const t=document.createElement("div");t.className="hs-inline-card",t.setAttribute("data-hs-theme","dark"),Object.assign(t.style,{position:"absolute",inset:"0",display:"flex",flexDirection:"column",borderRadius:"var(--hs-radius-lg)",overflow:"hidden",background:"var(--hs-glass-bg)",backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",border:"1px solid var(--hs-glass-border)",boxShadow:"var(--hs-glass-shadow)",cursor:"pointer",padding:"var(--hs-space-3)",boxSizing:"border-box"});const i=document.createElement("div");Object.assign(i.style,{flex:"1",overflow:"hidden",position:"relative",borderRadius:"var(--hs-radius-md)",border:"1px solid var(--hs-glass-border)"});const r=document.createElement("video");r.src=this.idleVideoUrl,r.autoplay=!0,r.loop=!0,r.muted=!0,r.playsInline=!0,r.setAttribute("playsinline",""),Object.assign(r.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),i.appendChild(r),t.appendChild(i);const n=document.createElement("div");Object.assign(n.style,{padding:"var(--hs-space-3) var(--hs-space-4)",textAlign:"center"});const o=document.createElement("div");Object.assign(o.style,{color:"var(--hs-text-primary)",fontSize:"var(--hs-text-base)",fontWeight:"var(--hs-weight-semibold)",fontFamily:"var(--hs-font)",lineHeight:"var(--hs-line-height)"}),o.textContent=`${this.staffDisplayName}, your AI copilot`,n.appendChild(o);const a=document.createElement("div");Object.assign(a.style,{color:"var(--hs-text-tertiary)",fontSize:"var(--hs-text-xs)",fontFamily:"var(--hs-font)",marginTop:"2px"}),a.textContent="Powered by Holostaff",n.appendChild(a),t.appendChild(n),t.addEventListener("click",()=>this.onAvatarClick()),e.appendChild(t),this.stage.rootElement&&(this.stage.rootElement.style.display="none")}else{const e=this.stage.rootElement;if(!e)throw new Error("Widget root not available");await this.avatar.loadIdleVideo(this.idleVideoUrl,e)}return}catch{console.warn("[HolostaffWidget] Failed to load idle video, trying image fallback")}this.idleImageUrl?await this.avatar.loadIdleImage(this.idleImageUrl):console.warn("[HolostaffWidget] No idle video or image configured")}}setIdleVideo(e){this.idleVideoUrl=e}setIdleImage(e){this.idleImageUrl=e}setObserver(e,t){this.rrwebRecorder=e,this.visionWs=t,this.externalObserver=!0}setStaffInfo(e,t){this.staffDisplayName=e,this.staffAvatarUrl=t}updateEvalState(e){if(!this.evalMode)return;const t=window.__HS_EVAL_STATE__;t&&Object.assign(t,e)}setupTrigger(){if(this.isInline){this.showAvatarOnly();return}if(this.config.visionWsUrl){this.showAvatarOnly();return}switch(this.config.trigger){case"scroll":this.setupScrollTrigger();break;case"delay":setTimeout(()=>this.showTeaser(),this.config.delayMs);break;case"immediate":this.showTeaser();break}}setupScrollTrigger(){this.scrollHandler=()=>{const e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight,i=t>0?e/t:0;i>=this.config.scrollThreshold&&this.state==="idle"?this.showTeaser():i<this.config.scrollThreshold*.5&&this.state==="teasing"&&this.hideTeaser()},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}showAvatarOnly(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker))}showTeaser(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker),this.bubbleTimer=setTimeout(()=>{var e;return(e=this.bubble)==null?void 0:e.start()},KC))}hideTeaser(){var e;this.state!=="teasing"||!this.avatar||!this.stage||(this.state="idle",this.bubbleTimer&&(clearTimeout(this.bubbleTimer),this.bubbleTimer=null),(e=this.bubble)==null||e.stop(),this.avatar.slideOut(this.stage.app.ticker))}async onAvatarClick(){var e,t,i,r,n,o,a,l,c,h,u,f;if(!(this.state!=="teasing"&&this.state!=="idle")){if(this.state="connecting",(e=this.bubble)==null||e.stop(),(t=this.bubble)==null||t.hideStatic(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null,this.isInline){(r=this.chatPill)==null||r.showConnecting();const d=(o=(n=this.stage)==null?void 0:n.inlineTarget)==null?void 0:o.querySelector(".hs-inline-card video");d&&d.pause()}else{(a=this.stage)!=null&&a.rootElement&&(this.stage.rootElement.style.display="");const d=document.querySelector("#holostaff-widget-root video");d&&d.pause(),(l=this.bubble)==null||l.showStatic("Connecting...")}console.log("[HolostaffWidget] Starting conversation...");try{this.sessionResponse=await Bf(this.config.staffId,this.config.backendUrl),console.log("[HolostaffWidget] Session tokens received"),this.logger=new dv({staffId:this.config.staffId,staffName:this.sessionResponse.staff.name,backendUrl:this.config.backendUrl}),await this.connectAnam(),await this.connectRealtimeApi(),this.state="active",this.setAvatarState("listening"),this.sessionStartTime=Date.now(),(c=this.bubble)==null||c.hideStatic(),this.updateEvalState({conversationStarted:!0}),this.showControls(),this.startSessionTimers(),(h=this.visionWs)==null||h.sendConversationStarted(),(u=this.rrwebRecorder)==null||u.pause(),console.log("[HolostaffWidget] Conversation active")}catch(d){console.error("[HolostaffWidget] Failed to start conversation:",d),(f=this.bubble)==null||f.hideStatic(),this.endConversation()}}}moveToStage(){var t;if(!this.isInline||!((t=this.stage)!=null&&t.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display="none"),this.stage.inlineTarget.querySelectorAll("video").forEach(i=>{i instanceof HTMLVideoElement&&i.pause()}),this.homePlaceholder=document.createElement("div"),this.homePlaceholder.setAttribute("data-hs-theme","dark"),Object.assign(this.homePlaceholder.style,{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",color:"var(--hs-text-secondary)",fontSize:"var(--hs-text-sm)",fontFamily:"var(--hs-font)",textAlign:"center",padding:"var(--hs-space-4)",boxSizing:"border-box"}),this.homePlaceholder.innerHTML="Agent is active below&nbsp;&darr;",this.stage.inlineTarget.appendChild(this.homePlaceholder),this.stageBackdrop=new XC,this.stageEl=this.stageBackdrop.el,this.stageBackdrop.show(),console.log("[HolostaffWidget] Moved to glass stage (bottom-center)")}returnToHome(){var t,i,r;if((t=this.stageBackdrop)==null||t.destroy(),this.stageBackdrop=null,this.stageEl=null,(i=this.homePlaceholder)==null||i.remove(),this.homePlaceholder=null,!((r=this.stage)!=null&&r.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display=""),this.stage.inlineTarget.querySelectorAll(".hs-inline-card video").forEach(n=>{n.style.display="",n instanceof HTMLVideoElement&&n.play()}),console.log("[HolostaffWidget] Returned to home (inline container)")}startHomeObserver(){var i;this.stopHomeObserver();const e=(i=this.stage)==null?void 0:i.inlineTarget;if(!e)return;const t=e.getBoundingClientRect();this.homeVisible=t.top<window.innerHeight&&t.bottom>0,this.homeObserver=new IntersectionObserver(([r])=>{const n=this.homeVisible;if(this.homeVisible=r.isIntersecting,this.homeVisible&&!this.homeEverSeen&&(this.homeEverSeen=!0),(this.state==="idle"||this.state==="teasing")&&this.chatPill)if(this.homeVisible){if(this.pillProtected){this.pillProtected=!1;return}this.chatPill.hide()}else!this.homeVisible&&n&&this.homeEverSeen?this.chatPill.showNamed():!this.homeVisible&&!this.homeEverSeen&&this.chatPill.state==="hidden"&&this.chatPill.showNamed()},{threshold:.1}),this.homeObserver.observe(e)}stopHomeObserver(){var e;(e=this.homeObserver)==null||e.disconnect(),this.homeObserver=null}async connectAnam(){this.sessionResponse&&(this.anamSession=new tv({sessionToken:this.sessionResponse.anamSessionToken,inlineMode:this.isInline&&!!this.stageBackdrop}),this.anamSession.onConnected=()=>{console.log("[HolostaffWidget] Anam connected")},this.anamSession.onVideoReady=e=>{var t,i,r;console.log("[HolostaffWidget] Anam avatar video ready"),(t=this.bubble)==null||t.hideStatic(),(i=this.chatPill)==null||i.hide(),this.isInline?(this.moveToStage(),(r=this.stageBackdrop)==null||r.appendContent(e)):this.avatar&&this.stage&&this.avatar.setLiveVideo(e,this.stage.app.ticker)},this.anamSession.onTalkStreamInterrupted=()=>{console.log("[HolostaffWidget] Anam talk stream interrupted")},this.anamSession.onDisconnected=e=>{console.log("[HolostaffWidget] Anam disconnected:",e),this.endConversation()},this.anamSession.onError=e=>{console.error("[HolostaffWidget] Anam error:",e.message)},await this.anamSession.connect(),console.log("[HolostaffWidget] Anam session ready"))}async connectRealtimeApi(){var o;if(!this.sessionResponse)return;const e=document.title||"",t=location.href,i=((o=document.querySelector('meta[name="description"]'))==null?void 0:o.getAttribute("content"))||"",r=Array.from(document.querySelectorAll("h1, h2, h3")).slice(0,10).map(a=>{var l;return(l=a.textContent)==null?void 0:l.trim()}).filter(Boolean).join(" | ");let n=(this.sessionResponse.staff.instructions??"")+`
1065
1065
 
1066
1066
  ## Current Page
1067
1067
  Title: ${e}
@@ -1076,5 +1076,5 @@ Then you can scroll to elements, highlight them, click links/buttons, or fill fo
1076
1076
  All actions except form filling require the visitor to confirm before executing.`;this.visionContext&&(n+=`
1077
1077
 
1078
1078
  ## Context from observing the user's session
1079
- `+this.visionContext,this.visionContext=null),this.realtimeSession=new _x({ephemeralKey:this.sessionResponse.realtimeEphemeralKey,webrtcUrl:this.sessionResponse.realtimeWebrtcUrl,voice:this.sessionResponse.staff.voiceId,instructions:n,tools:QC}),this.domAnalyzer=new nv,this.highlightRenderer=new YC,this.confirmationPrompt=new VC,this.realtimeSession.onConnected=()=>{var l,c,h,u;console.log("[HolostaffWidget] Realtime API connected");const a=(l=this.sessionResponse)==null?void 0:l.staff.openingText;a!=null&&a.trim()&&((c=this.realtimeSession)==null||c.sendJSON({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:"(conversation started — greet the visitor now)"}]}}),(h=this.realtimeSession)==null||h.sendJSON({type:"conversation.item.create",item:{type:"message",role:"assistant",content:[{type:"text",text:a}]}}),(u=this.realtimeSession)==null||u.sendJSON({type:"response.create"}))},this.realtimeSession.onDisconnected=()=>{console.log("[HolostaffWidget] Realtime API disconnected"),(this.state==="active"||this.state==="connecting")&&this.endConversation()},this.realtimeSession.onRemoteTrack=async a=>{console.log("[HolostaffWidget] Remote audio track → starting audio forwarder"),this.audioForwarder=new vx,this.audioForwarder.onAudioChunk=l=>{var c;(c=this.anamSession)==null||c.sendAudioChunk(l)},await this.audioForwarder.start(a)},this.overlayRenderer=new LC,this.toolHandler=new av({realtimeSession:this.realtimeSession,domAnalyzer:this.domAnalyzer,pageActions:new lv(this.domAnalyzer,this.highlightRenderer),overlayActions:new cv(this.overlayRenderer),confirmationPrompt:this.confirmationPrompt,staffId:this.config.staffId,backendUrl:this.config.backendUrl,skills:this.sessionResponse.skills??{}}),this.toolHandler.onToolCall=(a,l)=>{var c;(c=this.logger)==null||c.addAction(a,l)},this.realtimeSession.onDataMessage=a=>{this.handleDataChannelMessage(a)},this.realtimeSession.onError=a=>{console.error("[HolostaffWidget] Realtime error:",a.message),this.endConversation()},await this.realtimeSession.connect()}handleDataChannelMessage(e){var i,r,n,o,a,l,c,h;if((i=this.toolHandler)!=null&&i.handleMessage(e))return;const t=e.type;switch(t){case"session.created":case"session.updated":console.log("[HolostaffWidget] Data:",t);break;case"input_audio_buffer.speech_started":console.log("[HolostaffWidget] User started speaking"),(r=this.anamSession)==null||r.interrupt(),(n=this.audioForwarder)==null||n.pause(),this.setAvatarState("listening"),this.resetInactivityTimer();break;case"input_audio_buffer.speech_stopped":console.log("[HolostaffWidget] User stopped speaking"),this.setAvatarState("thinking");break;case"response.created":console.log("[HolostaffWidget] AI response started"),(o=this.audioForwarder)==null||o.resume(),this.setAvatarState("speaking");break;case"response.done":console.log("[HolostaffWidget] AI response done"),(a=this.anamSession)==null||a.endSequence(),this.setAvatarState("listening"),this.resetInactivityTimer(),this.extractAiTranscript(e.response);break;case"conversation.item.input_audio_transcription.completed":console.log("[HolostaffWidget] User said:",e.transcript),(l=this.logger)==null||l.addUserMessage(e.transcript??"");break;case"error":console.error("[HolostaffWidget] Realtime error event:",e.error);break;case"response.cancelled":case"response.canceled":case"response.failed":console.warn("[HolostaffWidget] Response ended:",t),(c=this.anamSession)==null||c.endSequence(),(h=this.audioForwarder)==null||h.pause(),this.setAvatarState("listening");break}}extractAiTranscript(e){if(!(!(e!=null&&e.output)||!this.logger)){for(const t of e.output)if(t.type==="message"&&t.content)for(const i of t.content)i.transcript?this.logger.addStaffMessage(i.transcript):i.text&&this.logger.addStaffMessage(i.text)}}setAvatarState(e){if(this.avatarState===e)return;const t=this.avatarState;this.avatarState=e,console.log(`[HolostaffWidget] Avatar: ${t} → ${e}`)}showControls(){this.controls=new WC,this.controls.onMinimize=()=>{var e;this.state="minimized",this.avatar&&this.stage&&this.avatar.slideOut(this.stage.app.ticker),(e=this.overlayRenderer)==null||e.dismissAll(),console.log("[HolostaffWidget] Minimized")},this.controls.onRestore=()=>{this.state="active",this.avatar&&this.stage&&this.avatar.slideIn(this.stage.app.ticker),console.log("[HolostaffWidget] Restored")},this.controls.onClose=()=>{console.log("[HolostaffWidget] Close button clicked"),this.endConversation()},this.controls.show()}startSessionTimers(){this.maxDurationWarnTimer=setTimeout(()=>{var e,t;console.log("[HolostaffWidget] Session approaching max duration"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:"The session will end in about one minute. Please wrap up the conversation gracefully."}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"})},ZC),this.maxDurationTimer=setTimeout(()=>{console.log("[HolostaffWidget] Max session duration reached"),this.endConversation()},KC),this.resetInactivityTimer()}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityCloseTimer&&clearTimeout(this.inactivityCloseTimer),this.inactivityTimer=setTimeout(()=>{var e,t;this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — prompting user"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:'The visitor has been silent for a while. Ask them "Still there?" in a friendly way.'}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"}),this.inactivityCloseTimer=setTimeout(()=>{this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — auto-closing"),this.endConversation())},JC-lf))},lf)}clearSessionTimers(){this.maxDurationTimer&&(clearTimeout(this.maxDurationTimer),this.maxDurationTimer=null),this.maxDurationWarnTimer&&(clearTimeout(this.maxDurationWarnTimer),this.maxDurationWarnTimer=null),this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.inactivityCloseTimer&&(clearTimeout(this.inactivityCloseTimer),this.inactivityCloseTimer=null)}endConversation(){var t,i,r,n,o,a,l,c,h,u,f,d,g;(t=this.logger)==null||t.flush(),this.logger=null,this.clearSessionTimers(),(i=this.controls)==null||i.hide(),this.controls=null,(r=this.audioForwarder)==null||r.stop(),this.audioForwarder=null,(n=this.anamSession)==null||n.close(),this.anamSession=null,(o=this.realtimeSession)==null||o.close(),this.realtimeSession=null,this.sessionResponse=null,this.avatarState="idle",this.toolHandler=null,this.domAnalyzer=null,(a=this.highlightRenderer)==null||a.clearAll(),this.highlightRenderer=null,(l=this.confirmationPrompt)==null||l.dismiss(),this.confirmationPrompt=null,(c=this.overlayRenderer)==null||c.dismissAll(),this.overlayRenderer=null,this.avatar&&this.stage&&this.avatar.clearLiveVideo(this.stage.app.ticker);const e=this.buildConversationSummary();(h=this.visionWs)==null||h.sendConversationEnded(e),(u=this.rrwebRecorder)==null||u.resume(),this.hasHadConversation=!0,this.state="idle",document.querySelectorAll('[id^="anam-avatar-wrapper"]').forEach(_=>_.remove()),document.querySelectorAll('video[id^="anam-avatar-video"]').forEach(_=>_.remove()),this.isInline?(this.returnToHome(),this.pillProtected=!0,(f=this.chatPill)==null||f.restoreName(),(d=this.chatPill)==null||d.showNamed(),this.attachActionExecutor()):(this.avatar&&(this.avatar.container.visible=!1),(g=this.stage)!=null&&g.rootElement&&(this.stage.rootElement.style.display="none"),this.showChatPill()),console.log("[HolostaffWidget] Conversation ended")}showChatPill(){this.chatPill||(this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick()),this.chatPill.showNamed()}hideChatPill(){var e;(e=this.chatPill)==null||e.hide()}startVisionLoop(){if(this.externalObserver&&this.visionWs){this.attachActionExecutor(),console.log("[HolostaffWidget] Action executor attached to external observer");return}const e=this.config.visionWsUrl;e&&(this.rrwebRecorder=new Ad,this.visionWs=new Id(e,{staffId:this.config.staffId,visitorId:this.visitorId,pageUrl:location.href,pageTitle:document.title}),this.rrwebRecorder.onEvent=t=>{var i;(i=this.visionWs)==null||i.sendRRWebEvent(t)},this.attachActionExecutor(),this.visionWs.connect(),this.config.visionConsent==="required"?console.log("[HolostaffWidget] Vision loop started (recording deferred — consent required)"):(this.rrwebRecorder.start(),console.log("[HolostaffWidget] Vision loop started",{visitorId:this.visitorId})))}attachActionExecutor(){var e;this.visionWs&&(this.actionExecutor=new AC({wsClient:this.visionWs,getWidgetState:()=>this.state,getHomeVisible:()=>this.homeVisible,inlineTarget:((e=this.stage)==null?void 0:e.inlineTarget)??null,pill:this.chatPill}),this.actionExecutor.onAccept=t=>{console.log("[HolostaffWidget] Suggestion accepted — starting conversation with vision context"),this.visionContext=t,this.onAvatarClick()})}stopVisionLoop(){var e,t,i;(e=this.actionExecutor)==null||e.destroy(),this.actionExecutor=null,this.externalObserver||((t=this.rrwebRecorder)==null||t.stop(),this.rrwebRecorder=null,(i=this.visionWs)==null||i.close(),this.visionWs=null)}buildConversationSummary(){var e;return((e=this.logger)==null?void 0:e.getSummary())??"Conversation ended (no transcript available)."}getOrCreateVisitorId(){var r;const e="hs_visitor_id",t=(r=document.cookie.split("; ").find(n=>n.startsWith(`${e}=`)))==null?void 0:r.split("=")[1];if(t)return t;const i=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${e}=${i}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,i}pause(){var e,t,i;this.paused||(this.paused=!0,console.log("[HolostaffWidget] Presenter paused (page not targeted — observer continues)"),(this.state==="active"||this.state==="connecting")&&this.endConversation(),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display="none"),this.hideChatPill(),(t=this.bubble)==null||t.stop(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null)}resume(){var e;this.paused&&(this.paused=!1,console.log("[HolostaffWidget] Presenter resumed (page targeted)"),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display=""),this.attachActionExecutor(),(this.state==="idle"||this.state==="teasing")&&(this.state="idle",this.setupTrigger()))}updateContainer(e){var r,n;const t=e?"inline":"floating";(this.config.container!==e||this.config.mode!==t)&&(console.log("[HolostaffWidget] Updating container:",e??"(floating)"),this.config={...this.config,mode:t,container:e},this.stage&&((this.state==="active"||this.state==="connecting")&&this.endConversation(),(r=this.bubble)==null||r.destroy(),(n=this.avatar)==null||n.destroy(),this.stage.destroy(),this.stage=null,this.avatar=null,this.bubble=null,this.state="idle",this.init()))}destroy(){var e,t,i;this.state="destroyed",this.endConversation(),this.hideChatPill(),this.stopHomeObserver(),this.stopVisionLoop(),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.bubbleTimer&&clearTimeout(this.bubbleTimer),(e=this.bubble)==null||e.destroy(),(t=this.avatar)==null||t.destroy(),(i=this.stage)==null||i.destroy(),this.bubble=null,this.avatar=null,this.stage=null}}function eS(s){return!s||s.length===0?[{pattern:"*"}]:s.map(e=>typeof e=="string"?{pattern:e}:e)}function tS(s,e){if(e==="*")return!0;if(!e.endsWith("/*")){const n=s.replace(/\/+$/,"")||"/",o=e.replace(/\/+$/,"")||"/";return n===o}const t=e.slice(0,-2),i=s.replace(/\/+$/,"")||"/",r=t.replace(/\/+$/,"")||"/";return i===r||i.startsWith(r+"/")}function hf(s,e){for(const t of e)if(tS(s,t.pattern))return t;return null}class iS{constructor(e){this.currentPath=location.pathname,this.onChange=e,this.origPushState=history.pushState.bind(history),this.origReplaceState=history.replaceState.bind(history),history.pushState=(...t)=>{this.origPushState(...t),this.check()},history.replaceState=(...t)=>{this.origReplaceState(...t),this.check()},window.addEventListener("popstate",()=>this.check())}check(){const e=location.pathname;e!==this.currentPath&&(this.currentPath=e,this.onChange(e))}destroy(){history.pushState=this.origPushState,history.replaceState=this.origReplaceState}}function sS(){var i;const s="hs_visitor_id",e=(i=document.cookie.split("; ").find(r=>r.startsWith(`${s}=`)))==null?void 0:i.split("=")[1];if(e)return e;const t=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${s}=${t}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,t}function rS(){const s=document.currentScript??document.querySelector("script[data-staff-id]");if(!s){console.error("[HolostaffWidget] Could not find script tag with data-staff-id");return}try{let e=function(r,n,o,a,l){const c=new cf(r,o);return a&&l&&c.setObserver(a,l),n!=null&&n.idleVideoUrl?c.setIdleVideo(n.idleVideoUrl):n!=null&&n.avatarImageUrl&&c.setIdleImage(n.avatarImageUrl),n&&c.setStaffInfo(n.name,n.avatarImageUrl),c};const t=Rf(s);async function i(){let r=t,n=null,o=null;try{o=await Nf(t.staffId,t.backendUrl),r=Of(t,s,o),n=o.widgetPrompts}catch(g){if(g.name==="WidgetDisabledError"){console.log("[HolostaffWidget] Agent is not active — widget suppressed");return}console.warn("[HolostaffWidget] Failed to fetch server config, using embed defaults:",g)}const a=eS(o==null?void 0:o.pagePatterns),l=sS();let c=null,h=null;r.visionWsUrl&&(c=new Ad,h=new Id(r.visionWsUrl,{staffId:r.staffId,visitorId:l,pageUrl:location.href,pageTitle:document.title,pagePatterns:a.map(g=>{const _={pattern:g.pattern};return g.container&&(_.container=g.container),_})}),c.onEvent=g=>{h==null||h.sendRRWebEvent(g)},h.connect(),r.visionConsent==="required"?console.log("[HolostaffWidget] Observer started (recording deferred — consent required)"):(c.start(),console.log("[HolostaffWidget] Observer started on all pages",{visitorId:l})));let u=hf(location.pathname,a),f=null;if(u){let g=r;u.container&&(g={...r,mode:"inline",container:u.container}),f=e(g,o,n,c,h),window.holostaffWidget=f,f.init()}else console.log("[HolostaffWidget] No matching page pattern for",location.pathname,"— presenter not loaded (observer active)");const d=new iS(g=>{h==null||h.sendPageChanged(location.href,g,document.title);const _=hf(g,a);if(_&&!f){console.log("[HolostaffWidget] SPA navigated to matching page:",g);let b=r;_.container&&(b={...r,mode:"inline",container:_.container}),f=e(b,o,n,c,h),window.holostaffWidget=f,f.init()}else if(_&&f){const b=_.container??null;b!==f.activeContainer&&f.updateContainer(b),f.resume()}else!_&&f&&f.pause()});window.__holostaffSPARouter=d}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>i()):i()}catch(e){console.error("[HolostaffWidget]",e)}}rS(),Q.add(Qm),Q.mixin(Ve,eg),Q.add(sh),Q.add(rh),Q.mixin(Ve,sy),Q.add(lh),Q.add(oh);const nS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),oS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));fi.HolostaffWidget=cf,Object.defineProperty(fi,Symbol.toStringTag,{value:"Module"})}));
1079
+ `+this.visionContext,this.visionContext=null),this.realtimeSession=new yx({ephemeralKey:this.sessionResponse.realtimeEphemeralKey,webrtcUrl:this.sessionResponse.realtimeWebrtcUrl,voice:this.sessionResponse.staff.voiceId,instructions:n,tools:eS}),this.domAnalyzer=new ov,this.highlightRenderer=new qC,this.confirmationPrompt=new zC,this.realtimeSession.onConnected=()=>{var l,c,h,u;console.log("[HolostaffWidget] Realtime API connected");const a=(l=this.sessionResponse)==null?void 0:l.staff.openingText;a!=null&&a.trim()&&((c=this.realtimeSession)==null||c.sendJSON({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:"(conversation started — greet the visitor now)"}]}}),(h=this.realtimeSession)==null||h.sendJSON({type:"conversation.item.create",item:{type:"message",role:"assistant",content:[{type:"text",text:a}]}}),(u=this.realtimeSession)==null||u.sendJSON({type:"response.create"}))},this.realtimeSession.onDisconnected=()=>{console.log("[HolostaffWidget] Realtime API disconnected"),(this.state==="active"||this.state==="connecting")&&this.endConversation()},this.realtimeSession.onRemoteTrack=async a=>{console.log("[HolostaffWidget] Remote audio track → starting audio forwarder"),this.audioForwarder=new Cx,this.audioForwarder.onAudioChunk=l=>{var c;(c=this.anamSession)==null||c.sendAudioChunk(l)},await this.audioForwarder.start(a)},this.overlayRenderer=new WC,this.toolHandler=new lv({realtimeSession:this.realtimeSession,domAnalyzer:this.domAnalyzer,pageActions:new cv(this.domAnalyzer,this.highlightRenderer),overlayActions:new hv(this.overlayRenderer),confirmationPrompt:this.confirmationPrompt,staffId:this.config.staffId,backendUrl:this.config.backendUrl,skills:this.sessionResponse.skills??{}}),this.toolHandler.onToolCall=(a,l)=>{var c;(c=this.logger)==null||c.addAction(a,l)},this.toolHandler.onEndConversation=(a,l)=>{console.log(`[HolostaffWidget] end_conversation requested (flag=${a})`),this.pendingEndAfterResponse={flag:a,reason:l}},this.realtimeSession.onDataMessage=a=>{this.handleDataChannelMessage(a)},this.realtimeSession.onError=a=>{console.error("[HolostaffWidget] Realtime error:",a.message),this.endConversation()},await this.realtimeSession.connect()}handleDataChannelMessage(e){var i,r,n,o,a,l,c,h;if((i=this.toolHandler)!=null&&i.handleMessage(e))return;const t=e.type;switch(t){case"session.created":case"session.updated":console.log("[HolostaffWidget] Data:",t);break;case"input_audio_buffer.speech_started":console.log("[HolostaffWidget] User started speaking"),(r=this.anamSession)==null||r.interrupt(),(n=this.audioForwarder)==null||n.pause(),this.setAvatarState("listening"),this.resetInactivityTimer();break;case"input_audio_buffer.speech_stopped":console.log("[HolostaffWidget] User stopped speaking"),this.setAvatarState("thinking");break;case"response.created":console.log("[HolostaffWidget] AI response started"),(o=this.audioForwarder)==null||o.resume(),this.setAvatarState("speaking");break;case"response.done":if(console.log("[HolostaffWidget] AI response done"),(a=this.anamSession)==null||a.endSequence(),this.setAvatarState("listening"),this.extractAiTranscript(e.response),this.pendingEndAfterResponse){const{flag:u,reason:f}=this.pendingEndAfterResponse;this.pendingEndAfterResponse=null,u&&Uf(this.config.staffId,this.visitorId,f,this.config.backendUrl),this.endConversation()}else this.resetInactivityTimer();break;case"conversation.item.input_audio_transcription.completed":console.log("[HolostaffWidget] User said:",e.transcript),(l=this.logger)==null||l.addUserMessage(e.transcript??"");break;case"error":console.error("[HolostaffWidget] Realtime error event:",e.error);break;case"response.cancelled":case"response.canceled":case"response.failed":console.warn("[HolostaffWidget] Response ended:",t),(c=this.anamSession)==null||c.endSequence(),(h=this.audioForwarder)==null||h.pause(),this.setAvatarState("listening");break}}extractAiTranscript(e){if(!(!(e!=null&&e.output)||!this.logger)){for(const t of e.output)if(t.type==="message"&&t.content)for(const i of t.content)i.transcript?this.logger.addStaffMessage(i.transcript):i.text&&this.logger.addStaffMessage(i.text)}}setAvatarState(e){if(this.avatarState===e)return;const t=this.avatarState;this.avatarState=e,console.log(`[HolostaffWidget] Avatar: ${t} → ${e}`)}showControls(){this.controls=new HC,this.controls.onMinimize=()=>{var e;this.state="minimized",this.avatar&&this.stage&&this.avatar.slideOut(this.stage.app.ticker),(e=this.overlayRenderer)==null||e.dismissAll(),console.log("[HolostaffWidget] Minimized")},this.controls.onRestore=()=>{this.state="active",this.avatar&&this.stage&&this.avatar.slideIn(this.stage.app.ticker),console.log("[HolostaffWidget] Restored")},this.controls.onClose=()=>{console.log("[HolostaffWidget] Close button clicked"),this.endConversation()},this.controls.show()}startSessionTimers(){this.maxDurationWarnTimer=setTimeout(()=>{var e,t;console.log("[HolostaffWidget] Session approaching max duration"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:"The session will end in about one minute. Please wrap up the conversation gracefully."}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"})},JC),this.maxDurationTimer=setTimeout(()=>{console.log("[HolostaffWidget] Max session duration reached"),this.endConversation()},ZC),this.resetInactivityTimer()}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityCloseTimer&&clearTimeout(this.inactivityCloseTimer),this.inactivityTimer=setTimeout(()=>{var e,t;this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — prompting user"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:'The visitor has been silent for a while. Ask them "Still there?" in a friendly way.'}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"}),this.inactivityCloseTimer=setTimeout(()=>{this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — auto-closing"),this.endConversation())},QC-lf))},lf)}clearSessionTimers(){this.maxDurationTimer&&(clearTimeout(this.maxDurationTimer),this.maxDurationTimer=null),this.maxDurationWarnTimer&&(clearTimeout(this.maxDurationWarnTimer),this.maxDurationWarnTimer=null),this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.inactivityCloseTimer&&(clearTimeout(this.inactivityCloseTimer),this.inactivityCloseTimer=null)}endConversation(){var t,i,r,n,o,a,l,c,h,u,f,d,g;this.updateEvalState({conversationEnded:!0}),(t=this.logger)==null||t.flush(),this.logger=null,this.clearSessionTimers(),(i=this.controls)==null||i.hide(),this.controls=null,(r=this.audioForwarder)==null||r.stop(),this.audioForwarder=null,(n=this.anamSession)==null||n.close(),this.anamSession=null,(o=this.realtimeSession)==null||o.close(),this.realtimeSession=null,this.sessionResponse=null,this.avatarState="idle",this.pendingEndAfterResponse=null,this.toolHandler=null,this.domAnalyzer=null,(a=this.highlightRenderer)==null||a.clearAll(),this.highlightRenderer=null,(l=this.confirmationPrompt)==null||l.dismiss(),this.confirmationPrompt=null,(c=this.overlayRenderer)==null||c.dismissAll(),this.overlayRenderer=null,this.avatar&&this.stage&&this.avatar.clearLiveVideo(this.stage.app.ticker);const e=this.buildConversationSummary();(h=this.visionWs)==null||h.sendConversationEnded(e),(u=this.rrwebRecorder)==null||u.resume(),this.hasHadConversation=!0,this.state="idle",document.querySelectorAll('[id^="anam-avatar-wrapper"]').forEach(_=>_.remove()),document.querySelectorAll('video[id^="anam-avatar-video"]').forEach(_=>_.remove()),this.isInline?(this.returnToHome(),this.pillProtected=!0,(f=this.chatPill)==null||f.restoreName(),(d=this.chatPill)==null||d.showNamed(),this.attachActionExecutor()):(this.avatar&&(this.avatar.container.visible=!1),(g=this.stage)!=null&&g.rootElement&&(this.stage.rootElement.style.display="none"),this.showChatPill()),console.log("[HolostaffWidget] Conversation ended")}showChatPill(){this.chatPill||(this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick()),this.chatPill.showNamed()}hideChatPill(){var e;(e=this.chatPill)==null||e.hide()}startVisionLoop(){if(this.externalObserver&&this.visionWs){this.attachActionExecutor(),console.log("[HolostaffWidget] Action executor attached to external observer");return}const e=this.config.visionWsUrl;e&&(this.rrwebRecorder=new Ad,this.visionWs=new Id(e,{staffId:this.config.staffId,visitorId:this.visitorId,pageUrl:location.href,pageTitle:document.title}),this.rrwebRecorder.onEvent=t=>{var i;(i=this.visionWs)==null||i.sendRRWebEvent(t)},this.attachActionExecutor(),this.visionWs.connect(),this.config.visionConsent==="required"?console.log("[HolostaffWidget] Vision loop started (recording deferred — consent required)"):(this.rrwebRecorder.start(),console.log("[HolostaffWidget] Vision loop started",{visitorId:this.visitorId})))}attachActionExecutor(){var e;this.visionWs&&(this.actionExecutor=new wC({wsClient:this.visionWs,getWidgetState:()=>this.state,getHomeVisible:()=>this.homeVisible,inlineTarget:((e=this.stage)==null?void 0:e.inlineTarget)??null,pill:this.chatPill}),this.actionExecutor.onInterventionShown=(t,i)=>{this.updateEvalState({interventionFired:!0,skillId:t,openingMessage:i})},this.actionExecutor.onAccept=t=>{console.log("[HolostaffWidget] Suggestion accepted — starting conversation with vision context"),this.visionContext=t,this.onAvatarClick()})}stopVisionLoop(){var e,t,i;(e=this.actionExecutor)==null||e.destroy(),this.actionExecutor=null,this.externalObserver||((t=this.rrwebRecorder)==null||t.stop(),this.rrwebRecorder=null,(i=this.visionWs)==null||i.close(),this.visionWs=null)}buildConversationSummary(){var e;return((e=this.logger)==null?void 0:e.getSummary())??"Conversation ended (no transcript available)."}getOrCreateVisitorId(){var r;const e="hs_visitor_id",t=(r=document.cookie.split("; ").find(n=>n.startsWith(`${e}=`)))==null?void 0:r.split("=")[1];if(t)return t;const i=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${e}=${i}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,i}pause(){var e,t,i;this.paused||(this.paused=!0,console.log("[HolostaffWidget] Presenter paused (page not targeted — observer continues)"),(this.state==="active"||this.state==="connecting")&&this.endConversation(),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display="none"),this.hideChatPill(),(t=this.bubble)==null||t.stop(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null)}resume(){var e;this.paused&&(this.paused=!1,console.log("[HolostaffWidget] Presenter resumed (page targeted)"),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display=""),this.attachActionExecutor(),(this.state==="idle"||this.state==="teasing")&&(this.state="idle",this.setupTrigger()))}updateContainer(e){var r,n;const t=e?"inline":"floating";(this.config.container!==e||this.config.mode!==t)&&(console.log("[HolostaffWidget] Updating container:",e??"(floating)"),this.config={...this.config,mode:t,container:e},this.stage&&((this.state==="active"||this.state==="connecting")&&this.endConversation(),(r=this.bubble)==null||r.destroy(),(n=this.avatar)==null||n.destroy(),this.stage.destroy(),this.stage=null,this.avatar=null,this.bubble=null,this.state="idle",this.init()))}destroy(){var e,t,i;this.state="destroyed",this.endConversation(),this.hideChatPill(),this.stopHomeObserver(),this.stopVisionLoop(),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.bubbleTimer&&clearTimeout(this.bubbleTimer),(e=this.bubble)==null||e.destroy(),(t=this.avatar)==null||t.destroy(),(i=this.stage)==null||i.destroy(),this.bubble=null,this.avatar=null,this.stage=null}}function tS(s){return!s||s.length===0?[{pattern:"*"}]:s.map(e=>typeof e=="string"?{pattern:e}:e)}function iS(s,e){if(e==="*")return!0;if(!e.endsWith("/*")){const n=s.replace(/\/+$/,"")||"/",o=e.replace(/\/+$/,"")||"/";return n===o}const t=e.slice(0,-2),i=s.replace(/\/+$/,"")||"/",r=t.replace(/\/+$/,"")||"/";return i===r||i.startsWith(r+"/")}function hf(s,e){for(const t of e)if(iS(s,t.pattern))return t;return null}class sS{constructor(e){this.currentPath=location.pathname,this.onChange=e,this.origPushState=history.pushState.bind(history),this.origReplaceState=history.replaceState.bind(history),history.pushState=(...t)=>{this.origPushState(...t),this.check()},history.replaceState=(...t)=>{this.origReplaceState(...t),this.check()},window.addEventListener("popstate",()=>this.check())}check(){const e=location.pathname;e!==this.currentPath&&(this.currentPath=e,this.onChange(e))}destroy(){history.pushState=this.origPushState,history.replaceState=this.origReplaceState}}function rS(){var i;const s="hs_visitor_id",e=(i=document.cookie.split("; ").find(r=>r.startsWith(`${s}=`)))==null?void 0:i.split("=")[1];if(e)return e;const t=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${s}=${t}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,t}function nS(){const s=document.currentScript??document.querySelector("script[data-staff-id]");if(!s){console.error("[HolostaffWidget] Could not find script tag with data-staff-id");return}try{let e=function(r,n,o,a,l){const c=new cf(r,o,n==null?void 0:n.evalMode);return a&&l&&c.setObserver(a,l),n!=null&&n.idleVideoUrl?c.setIdleVideo(n.idleVideoUrl):n!=null&&n.avatarImageUrl&&c.setIdleImage(n.avatarImageUrl),n&&c.setStaffInfo(n.name,n.avatarImageUrl),c};const t=Rf(s);async function i(){let r=t,n=null,o=null;const a=window.__HS_EVAL__,l=(a==null?void 0:a.visitorId)??rS();try{if(o=await Nf(t.staffId,t.backendUrl,l),o.blocked){console.log("[HolostaffWidget] Visitor blocked — widget suppressed.");return}r=Of(t,s,o),n=o.widgetPrompts,o.evalMode&&(window.__HS_EVAL_STATE__={interventionFired:!1,skillId:null,openingMessage:null,conversationStarted:!1,conversationEnded:!1},console.log("[HolostaffWidget] Eval mode active — __HS_EVAL_STATE__ initialized"))}catch(_){if(_.name==="WidgetDisabledError"){console.log("[HolostaffWidget] Agent is not active — widget suppressed");return}console.warn("[HolostaffWidget] Failed to fetch server config, using embed defaults:",_)}const c=tS(o==null?void 0:o.pagePatterns);let h=null,u=null;r.visionWsUrl&&(h=new Ad,u=new Id(r.visionWsUrl,{staffId:r.staffId,visitorId:l,pageUrl:location.href,pageTitle:document.title,pagePatterns:c.map(_=>{const y={pattern:_.pattern};return _.container&&(y.container=_.container),y})}),h.onEvent=_=>{u==null||u.sendRRWebEvent(_)},u.connect(),r.visionConsent==="required"?console.log("[HolostaffWidget] Observer started (recording deferred — consent required)"):(h.start(),console.log("[HolostaffWidget] Observer started on all pages",{visitorId:l})));let f=hf(location.pathname,c),d=null;if(f){let _=r;f.container&&(_={...r,mode:"inline",container:f.container}),d=e(_,o,n,h,u),window.holostaffWidget=d,d.init()}else console.log("[HolostaffWidget] No matching page pattern for",location.pathname,"— presenter not loaded (observer active)");const g=new sS(_=>{u==null||u.sendPageChanged(location.href,_,document.title);const y=hf(_,c);if(y&&!d){console.log("[HolostaffWidget] SPA navigated to matching page:",_);let x=r;y.container&&(x={...r,mode:"inline",container:y.container}),d=e(x,o,n,h,u),window.holostaffWidget=d,d.init()}else if(y&&d){const x=y.container??null;x!==d.activeContainer&&d.updateContainer(x),d.resume()}else!y&&d&&d.pause()});window.__holostaffSPARouter=g}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>i()):i()}catch(e){console.error("[HolostaffWidget]",e)}}nS(),Q.add(eg),Q.mixin(Ve,tg),Q.add(sh),Q.add(rh),Q.mixin(Ve,ry),Q.add(lh),Q.add(oh);const oS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),aS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));fi.HolostaffWidget=cf,Object.defineProperty(fi,Symbol.toStringTag,{value:"Module"})}));
1080
1080
  //# sourceMappingURL=hs-widget.umd.js.map