bridgeapp-ai-chat-widget 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,19 +15,19 @@ import { ChatWidgetInstance } from "bridge-ai-chat-widget";
15
15
 
16
16
  const widget = new ChatWidgetInstance({
17
17
  mountElementId: "chat-widget-root",
18
- agentId: "AGENT_ID",
18
+ agentId: "222d810a-92dd-4bb4-9ce6-1fee92238e7f",
19
19
  customerInteractionSession: {
20
20
  accessToken: "ACCESS_TOKEN",
21
21
  chatId: "CHAT_ID",
22
22
  expiresAt: new Date(Date.now() + 86400000).toISOString(),
23
23
  },
24
24
  assetsUrl: "ASSETS_URL",
25
- wsUrl: "wss://ws.brid93.dev/ws",
26
- apiUrl: "https://api.brid93.dev",
25
+ wsUrl: "wss://ws.brid93.com/ws",
26
+ apiUrl: "https://api.brid93.com",
27
27
  AIAvatar: true,
28
28
  background: false,
29
29
  voiceEnabled: true,
30
- footer: falseб
30
+ footer: false,
31
31
  manualOpen: false
32
32
  });
33
33
 
@@ -39949,7 +39949,7 @@ const PU = (i) => {
39949
39949
  function vE(i, e) {
39950
39950
  i.message.includes("401") && e?.();
39951
39951
  }
39952
- const dee = "b48c3d08-0eb9-42a5-8076-51b6559f410a", hee = { voice: "ara" }, FU = async (i, e) => {
39952
+ const dee = "6bd37ad5-19e3-449a-9bbf-7ef51e4b4db8", hee = { voice: "ara" }, FU = async (i, e) => {
39953
39953
  try {
39954
39954
  const t = await fetch(
39955
39955
  `${i.apiUrl}/agents.Agents/StartVoiceSession`,
@@ -4550,7 +4550,7 @@ void main() {
4550
4550
  `).map(e=>{const t=e.split(" ");return{time:Number(t[0]),viseme:t[1]}}).filter(e=>e.viseme!=="X")}convertVisemeDataToAnimationScenario(){}update(e,t=0){this.mixer&&this.mixer.update(e),!(this.visemeDataIndex>=this.visemeData.length)&&t&&t>=this.visemeData[this.visemeDataIndex].time-this.blendShapeResetAnimationLength*.7&&(this.playVisemeAnimation(t,this.visemeData[this.visemeDataIndex],this.visemeData[this.visemeDataIndex+1]),this.visemeDataIndex++)}resetMorphing(){this.animations.forEach(e=>e.kill()),mu.to(this.head.morphTargetInfluences,this.blendShapeResetAnimationLength,this.zeroMorphingInfluences)}blendShapeAnimationLength=.2;blendShapeResetAnimationLength=.1;playVisemeAnimation(e,t,n){if(this.resetMorphing(),t.viseme==="X")return;let r=1,o=t.viseme;const c=_W[bW[o]],u=this.head?.morphTargetDictionary[c],h=n?.time-e,m=Math.min(this.blendShapeAnimationLength,h-.07),_={influence:0},p=mu.to(_,{influence:r,duration:m,delay:this.blendShapeResetAnimationLength*.7,onUpdate:()=>{this.head.morphTargetInfluences[u]=_.influence}}),y=mu.to(_,{influence:0,duration:this.blendShapeAnimationLength,delay:m+.07,onUpdate:()=>{this.head.morphTargetInfluences[u]=_.influence}});this.animations=[p,y]}shapeFadeInDuration=.6;shapeFadeOutDuration=.6;showcaseBlendShape(e){this.resetMorphing();const t=this.head?.morphTargetDictionary[e],n={influence:0};mu.to(n,{influence:1,duration:this.shapeFadeInDuration,delay:this.blendShapeResetAnimationLength,onUpdate:()=>{this.head.morphTargetInfluences[t]=n.influence}}),mu.to(n,{influence:0,duration:this.shapeFadeOutDuration,delay:this.blendShapeResetAnimationLength+3,onUpdate:()=>{this.head.morphTargetInfluences[t]=n.influence}})}}class SW extends EventTarget{constructor(e,t,n,r){super(),this.canvas=e,this.videoContainer=t,this.config=n,this.onAvatarReady=r,this.renderer=new a$({canvas:this.canvas,antialias:!0,powerPreference:"high-performance",logarithmicDepthBuffer:!0,alpha:!0}),this.renderer.outputColorSpace=on,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=iN,this.init()}renderer;sound;gui;cubeTexture;initialAssetsfbxLoader;textureLoader;clock=new DV;scene;camera;hair;head;body;animationManager;cameraParams={zoomIn:{position:new Se(0,140,200),lookAt:new Se(-7,115,0),fov:35},zoomOut:{position:new Se(0,125,200),lookAt:new Se(-7,90,0),fov:48}};controls;get baseUrl(){return this.config.assetsUrl.at(-1)==="/"?this.config.assetsUrl:this.config.assetsUrl+"/"}resolveAsset(e){return new URL(e,this.baseUrl).href}lightAmbient;lightDirectional;loadingManager;async init(){this.loadingManager=new U3;const e=23;this.loadingManager.onProgress=(ie,fe,me)=>{const q=fe/e,K=new CustomEvent("loading_progress",{detail:q});this.dispatchEvent(K)},this.initialAssetsfbxLoader=new dk(this.loadingManager),this.textureLoader=new T5(this.loadingManager),this.sound=new J$.Howl({src:[`${this.baseUrl}sounds/voice-test.wav`]}),this.sound.mute(!0);const t=new IH;this.scene=t,this.lightAmbient=new R5(4210752,50),t.add(this.lightAmbient);const n=2048,r=new C5(16777215,2);r.position.set(50,170,50),r.target.position.set(0,80,0),r.castShadow=!0,this.scene.add(r),this.lightDirectional=r,t.add(r.target),r.shadow.bias=-5e-4,r.shadow.normalBias=.1,r.shadow.mapSize.width=n,r.shadow.mapSize.height=n,r.shadow.camera.near=30,r.shadow.camera.far=230,r.shadow.camera.left=-50,r.shadow.camera.right=50,r.shadow.camera.top=75,r.shadow.camera.bottom=-70;const{width:o,height:c}=this.canvas.getBoundingClientRect(),u=new ms(65,o/c,.1,1e3);if(this.camera=u,this.setCamera(this.cameraParams.zoomIn),this.config.background){const ie=this.textureLoader.load(this.resolveAsset("textures/bg1.jpg"));ie.colorSpace=on,t.background=ie}const h=new EV(this.loadingManager).setPath(this.resolveAsset("textures/cube-map/"));this.cubeTexture=h.load(["px.png","nx.png","py.png","ny.png","pz.png","nz.png"]);const m=this.textureLoader.load(this.resolveAsset("textures/pbr/brows_base_color.png")),_=this.textureLoader.load(this.resolveAsset("textures/pbr/eyes_base_color.png"));_.wrapS=Yr,_.wrapT=Yr;const p=this.textureLoader.load(this.resolveAsset("textures/pbr/body_base_color.png"));p.wrapS=Yr,p.wrapT=Yr;const y=this.textureLoader.load(this.resolveAsset("textures/pbr/body_metallic.png"));y.wrapS=Yr,y.wrapT=Yr;const x=this.textureLoader.load(this.resolveAsset("textures/pbr/body_normal.png"));x.wrapS=Yr,x.wrapT=Yr;const T=this.textureLoader.load(this.resolveAsset("textures/pbr/body_roughness.png"));T.wrapS=Yr,T.wrapT=Yr;const M=new hm({map:p,normalMap:x}),w=new N3({map:p,normalMap:x,metalnessMap:y,metalness:.94,roughness:.738,roughnessMap:T,envMap:this.cubeTexture,envMapIntensity:.496}),A=this.textureLoader.load(this.resolveAsset("textures/pbr/hair_base_color.png")),L=this.textureLoader.load(this.resolveAsset("textures/pbr/hair_metallic.png")),N=this.textureLoader.load(this.resolveAsset("textures/pbr/hair_normal.png")),I=this.textureLoader.load(this.resolveAsset("textures/pbr/hair_roughness.png")),z=new N3({map:A,normalMap:N,metalnessMap:L,metalness:1,roughnessMap:I,envMap:this.cubeTexture}),P=this.textureLoader.load(this.resolveAsset("textures/pbr/head_base_color.png")),G=this.textureLoader.load(this.resolveAsset("textures/pbr/head_metallic.png")),$=this.textureLoader.load(this.resolveAsset("textures/pbr/head_roughness.png")),U=new hm({map:P}),H=new hm({map:m}),J=this.textureLoader.load(this.resolveAsset("textures/shared/shadow_base_color.png"));J.wrapS=Yr,J.wrapT=Yr;const ne=this.textureLoader.load(this.resolveAsset("textures/shared/shadow_opacity.png"));ne.wrapS=Yr,ne.wrapT=Yr,m.colorSpace=on,_.colorSpace=on,p.colorSpace=on,y.colorSpace=on,x.colorSpace=on,T.colorSpace=on,A.colorSpace=on,L.colorSpace=on,N.colorSpace=on,I.colorSpace=on,P.colorSpace=on,G.colorSpace=on,$.colorSpace=on,J.colorSpace=on,ne.colorSpace=on,this.initialAssetsfbxLoader.load(this.resolveAsset("models/female_rig.fbx"),async ie=>{t.add(ie),ie.traverse(fe=>{if(fe instanceof dl&&(fe.castShadow=!0,fe.receiveShadow=!0),fe.name=="eye_shadows"){const q=fe.material;q.map=J,q.alphaMap=ne,q.transparent=!0;return}if(fe.name=="Hair"){this.hair=fe;return}if(fe.name=="Eyes"){const me=fe,q=new N3({map:_});me.material=q;return}if(fe.name=="Head"){this.head=fe;return}if(fe.name=="Body"){this.body=fe;return}}),this.hair.material=z,this.head.material=[U,H],this.body.material=[w,M],this.animationManager=new xW(ie,this.head,this.initialAssetsfbxLoader,this.baseUrl,this),this.animationManager.init(),this.animationManager.setVisemeData(),this.animate(),this.onResize(),this.config.debug&&this.addGui()})}tempLookAt=new Se;setCamera(e,t){const{position:n,lookAt:r,fov:o}=e;mu.to(this.camera.position,{x:n.x,y:n.y,z:n.z,duration:.5}),mu.to(this.camera,{fov:o,duration:.5,onUpdate:()=>{this.camera.updateProjectionMatrix()}}),mu.to(this.tempLookAt,{x:r.x,y:r.y,z:r.z,duration:.5,onUpdate:()=>{this.camera.lookAt(this.tempLookAt)},onComplete:t})}width=0;height=0;onResize=(e,t)=>{if(!e||!t){const n=this.canvas.getBoundingClientRect();e=n.width,t=n.height}!e||!t||e==this.width&&t==this.height||(this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t,!1),this.render(),this.width=e,this.height=t)};animate=()=>{requestAnimationFrame(this.animate);const e=this.clock.getDelta(),t=this.sound.seek();this.animationManager.update(e,t),this.controls?.update(),this.render()};speakingAnimationName="generic_speaking_1";idleAnimationName="idle_1";setTalking(e){e?(this.sound.play(),this.animationManager.fadeToAction(this.speakingAnimationName)):(this.sound.stop(),this.sound.seek(0),this.animationManager.resetMorphing(),this.speakingAnimationName=this.speakingAnimationName==="generic_speaking_1"?"generic_speaking_2":"generic_speaking_1",this.idleAnimationName=this.idleAnimationName==="idle_1"?"waiting_idle":"idle_1",this.animationManager.fadeToAction(this.idleAnimationName))}externalLaunchAnimationAction=e=>{this.animationManager.fadeToAction(e)};playAction=(e,t)=>{this.shutDownVideo(),this.setCamera(this.cameraParams.zoomIn),this.animationManager.reset(),this.sound.stop(),t&&this.sound.play(),this.animationManager.fadeToAction(e)};playVideo=async(e,t)=>new Promise(r=>{this.setCamera(this.cameraParams.zoomOut,()=>{for(const c of this.videoContainer.children)c.style.visibility="hidden",c.onended=null;const o=this.videoContainer.querySelector(`#${e}`);o.style.visibility="visible",t&&this.sound.play(),o.play(),o.onended=()=>{this.sound.stop(),r(void 0)}})});shutDownVideo=()=>{for(const e of this.videoContainer.children)e.style.visibility="hidden"};showcaseBlendShape(e){this.sound.stop(),this.animationManager.showcaseBlendShape(e)}render(){this.renderer.render(this.scene,this.camera)}onAllAssetsLoaded=()=>{this.onAvatarReady(this.externalLaunchAnimationAction)};addGui(){this.gui=new nR,this.gui.domElement.style.position="absolute",this.gui.domElement.style.top="0",this.gui.domElement.style.left="0",this.gui.domElement.style.zIndex="50";const e=this.gui.addFolder("3D Animations").close(),t=this.gui.addFolder("Video + 3D Animations").close(),n=this.gui.addFolder("Scene parameters"),r={excited:()=>this.playAction("excited",!1),fixHair:()=>this.playAction("fix_hair",!1),genericSpeaking:()=>this.playAction("generic_speaking_1",!0),genericSpeaking2:()=>this.playAction("generic_speaking_2",!0),spin:()=>this.playAction("spin",!1),waitingIdle:()=>this.playAction("waiting_idle",!1),speak:()=>this.playAction("voice_1",!0),kiss:()=>this.playAction("kiss",!1),playVideoIdle:async()=>{await this.playVideo("idle"),this.playAction("waiting_idle",!1)},playVideoWave:async()=>{await this.playVideo("wave"),this.playAction("waiting_idle",!1)},playVideoSpeaking1:async()=>{await this.playVideo("speaking_1",!0),this.playVideo("idle")},playVideoSpeaking2:async()=>{await this.playVideo("speaking_2",!0),this.playVideo("idle")},playVideoSpeakingLong:async()=>{await this.playVideo("long_speaking",!0),this.playVideo("idle")},toggleShadow:()=>{this.renderer.shadowMap.enabled=!this.renderer.shadowMap.enabled},ambientColor:this.lightAmbient.color.getHex(),directionalColor:this.lightDirectional.color.getHex()};e.add(r,"excited").name("Excited"),e.add(r,"fixHair").name("Fix Hair"),e.add(r,"genericSpeaking").name("Generic Speaking"),e.add(r,"genericSpeaking2").name("Generic Speaking 2"),e.add(r,"spin").name("Spin"),e.add(r,"waitingIdle").name("Waiting Idle"),e.add(r,"speak").name("Speak"),e.add(r,"kiss").name("Kiss"),t.add(r,"playVideoIdle").name("Video Idle -> 3D Waiting Idle"),t.add(r,"playVideoWave").name("Video Wave -> 3D Waiting Idle"),t.add(r,"playVideoSpeakingLong").name("Video Long Speaking -> Video Idle"),t.add(r,"playVideoSpeaking1").name("Video Speaking 1 -> Video Idle"),t.add(r,"playVideoSpeaking2").name("Video Speaking 2 -> Video Idle"),n.add(this.body.material[0],"roughness",0,1).name("Shell material roughness"),n.add(this.body.material[0],"metalness",0,1).name("Shell material metalness"),n.add(this.body.material[0],"envMapIntensity",0,1).name("Shell material env map intensity"),n.add(this.hair.material,"roughness",0,1).name("Hair material roughness"),n.add(this.hair.material,"metalness",0,1).name("Hair material metalness"),n.add(this.hair.material,"envMapIntensity",0,1).name("Hair material env map intensity"),n.addColor(r,"ambientColor").name("Ambient light color").onChange(o=>{this.lightAmbient.color.setHex(o)}),n.add(this.lightAmbient,"intensity").name("Ambient light intensity"),n.addColor(r,"directionalColor").name("Directional light color").onChange(o=>{this.lightDirectional.color.setHex(o)}),n.add(this.lightDirectional,"intensity").name("Directional light intensity")}}const EW=i=>te.createElement("svg",{width:15,height:22,viewBox:"0 0 15 22",fill:"none",xmlns:"http://www.w3.org/2000/svg",...i},te.createElement("path",{d:"M3 10.5V4.5C3 3.30653 3.47411 2.16193 4.31802 1.31802C5.16193 0.474106 6.30653 0 7.5 0C8.69347 0 9.83807 0.474106 10.682 1.31802C11.5259 2.16193 12 3.30653 12 4.5V10.5C12 11.6935 11.5259 12.8381 10.682 13.682C9.83807 14.5259 8.69347 15 7.5 15C6.30653 15 5.16193 14.5259 4.31802 13.682C3.47411 12.8381 3 11.6935 3 10.5ZM15 10.5C15 10.3011 14.921 10.1103 14.7803 9.96967C14.6397 9.82902 14.4489 9.75 14.25 9.75C14.0511 9.75 13.8603 9.82902 13.7197 9.96967C13.579 10.1103 13.5 10.3011 13.5 10.5C13.5 12.0913 12.8679 13.6174 11.7426 14.7426C10.6174 15.8679 9.0913 16.5 7.5 16.5C5.9087 16.5 4.38258 15.8679 3.25736 14.7426C2.13214 13.6174 1.5 12.0913 1.5 10.5C1.5 10.3011 1.42098 10.1103 1.28033 9.96967C1.13968 9.82902 0.948912 9.75 0.75 9.75C0.551088 9.75 0.360322 9.82902 0.21967 9.96967C0.0790178 10.1103 0 10.3011 0 10.5C0.00228386 12.3586 0.693677 14.1504 1.94048 15.5288C3.18728 16.9072 4.90091 17.7743 6.75 17.9625V21C6.75 21.1989 6.82902 21.3897 6.96967 21.5303C7.11032 21.671 7.30109 21.75 7.5 21.75C7.69891 21.75 7.88968 21.671 8.03033 21.5303C8.17098 21.3897 8.25 21.1989 8.25 21V17.9625C10.0991 17.7743 11.8127 16.9072 13.0595 15.5288C14.3063 14.1504 14.9977 12.3586 15 10.5Z",fill:"white"})),TW=i=>te.createElement("svg",{width:17,height:22,viewBox:"0 0 17 22",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...i},te.createElement("path",{d:"M16.2483 20.05C16.1011 20.1838 15.9068 20.2536 15.7082 20.2441C15.5095 20.2346 15.3227 20.1466 15.189 19.9994L12.2902 16.8119C11.2986 17.4511 10.1683 17.8436 8.99395 17.9566V20.995C8.99395 21.1939 8.91494 21.3847 8.77428 21.5253C8.63363 21.666 8.44287 21.745 8.24395 21.745C8.04504 21.745 7.85428 21.666 7.71362 21.5253C7.57297 21.3847 7.49395 21.1939 7.49395 20.995V17.9575C5.64487 17.7694 3.93123 16.9022 2.68443 15.5238C1.43763 14.1454 0.746237 12.3536 0.743953 10.495C0.743953 10.2961 0.822971 10.1053 0.963623 9.96468C1.10428 9.82403 1.29504 9.74501 1.49395 9.74501C1.69287 9.74501 1.88363 9.82403 2.02428 9.96468C2.16494 10.1053 2.24395 10.2961 2.24395 10.495C2.24569 12.0858 2.87839 13.6109 4.00323 14.7357C5.12807 15.8606 6.65319 16.4933 8.24395 16.495C9.3051 16.4981 10.3477 16.2172 11.2636 15.6813L10.223 14.5375C9.53688 14.8735 8.77649 15.0293 8.01351 14.9902C7.25052 14.951 6.51006 14.7183 5.86189 14.3139C5.21372 13.9095 4.67918 13.3467 4.30864 12.6786C3.93811 12.0105 3.74377 11.259 3.74395 10.495V7.4097L0.188953 3.49939C0.0579834 3.35175 -0.00951799 3.15845 0.00108397 2.96138C0.0116859 2.76431 0.0995364 2.57936 0.245589 2.44663C0.391643 2.3139 0.584126 2.24408 0.781309 2.25232C0.978492 2.26056 1.16448 2.34619 1.29895 2.49064L16.299 18.9906C16.4327 19.1378 16.5025 19.3321 16.493 19.5308C16.4835 19.7295 16.3955 19.9162 16.2483 20.05ZM13.9805 14.1316C14.0828 14.1823 14.1954 14.2086 14.3096 14.2085C14.4501 14.2085 14.5878 14.169 14.7069 14.0946C14.8261 14.0202 14.922 13.9138 14.9836 13.7875C15.4869 12.7631 15.7471 11.6364 15.744 10.495C15.744 10.2961 15.6649 10.1053 15.5243 9.96468C15.3836 9.82403 15.1929 9.74501 14.994 9.74501C14.795 9.74501 14.6043 9.82403 14.4636 9.96468C14.323 10.1053 14.244 10.2961 14.244 10.495C14.2466 11.4079 14.0387 12.309 13.6365 13.1285C13.5491 13.3071 13.5363 13.5131 13.6008 13.7013C13.6653 13.8894 13.8019 14.0442 13.9805 14.1316ZM11.4183 11.3922C11.5158 11.4995 11.6422 11.5762 11.7824 11.6131C11.9225 11.65 12.0703 11.6456 12.208 11.6002C12.3456 11.5549 12.4672 11.4707 12.558 11.3577C12.6488 11.2448 12.7049 11.1079 12.7196 10.9638C12.7356 10.808 12.7437 10.6516 12.744 10.495V4.49501C12.7428 3.46146 12.3859 2.45981 11.7333 1.6584C11.0806 0.85698 10.172 0.304654 9.16007 0.0942441C8.14816 -0.116166 7.09467 0.0281652 6.17664 0.502981C5.25861 0.977798 4.53201 1.75415 4.11895 2.70158C4.06128 2.834 4.04308 2.98027 4.06652 3.1228C4.08997 3.26532 4.15408 3.39804 4.25114 3.50501L11.4183 11.3922Z"})),MW=i=>te.createElement("svg",{width:19,height:17,viewBox:"0 0 19 17",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...i},te.createElement("path",{d:"M12.5227 3.81607C11.8966 2.45748 10.8252 1.35355 9.48597 0.687157C8.14671 0.0207681 6.61998 -0.168078 5.15872 0.151907C3.69745 0.471891 2.38936 1.2815 1.45116 2.4466C0.512966 3.6117 0.000969112 5.06237 0 6.55826V11.5583C0 11.9727 0.16462 12.3701 0.457646 12.6631C0.750671 12.9561 1.1481 13.1208 1.5625 13.1208H5.63281C6.16643 14.2418 7.00649 15.1889 8.05583 15.8525C9.10517 16.5161 10.3209 16.8692 11.5625 16.8708H16.5625C16.9769 16.8708 17.3743 16.7061 17.6674 16.4131C17.9604 16.1201 18.125 15.7227 18.125 15.3083V10.3083C18.1251 8.73409 17.5593 7.21234 16.5309 6.02056C15.5024 4.82878 14.0799 4.04638 12.5227 3.81607ZM1.875 6.55826C1.875 5.63116 2.14992 4.72488 2.66499 3.95402C3.18006 3.18317 3.91214 2.58236 4.76867 2.22757C5.6252 1.87278 6.5677 1.77996 7.47699 1.96082C8.38627 2.14169 9.2215 2.58813 9.87706 3.24369C10.5326 3.89925 10.9791 4.73448 11.1599 5.64377C11.3408 6.55306 11.248 7.49556 10.8932 8.35209C10.5384 9.20861 9.93759 9.9407 9.16674 10.4558C8.39588 10.9708 7.4896 11.2458 6.5625 11.2458H1.875V6.55826ZM16.25 14.9958H11.5625C10.8125 14.9949 10.0737 14.8145 9.40771 14.4697C8.74173 14.1249 8.16796 13.6256 7.73438 13.0137C9.36318 12.7195 10.8205 11.8202 11.8138 10.4962C12.8071 9.17219 13.2629 7.52154 13.0898 5.87544C14.0125 6.19342 14.8129 6.79144 15.3794 7.58608C15.9459 8.38072 16.2502 9.33236 16.25 10.3083V14.9958Z"}));var wm=(i=>(i.Voice="voice",i.Text="text",i))(wm||{});const es={list:"/chats",voice:"/chat/voice",text:"/chat/text"};function wW(i){return i===es.text||i.endsWith(es.text)?"text":"voice"}function AW(i){return i===es.list||i.endsWith(es.list)}function IU(i){var e,t,n="";if(typeof i=="string"||typeof i=="number")n+=i;else if(typeof i=="object")if(Array.isArray(i)){var r=i.length;for(e=0;e<r;e++)i[e]&&(t=IU(i[e]))&&(n&&(n+=" "),n+=t)}else for(t in i)i[t]&&(n&&(n+=" "),n+=t);return n}function CW(){for(var i,e,t=0,n="",r=arguments.length;t<r;t++)(i=arguments[t])&&(e=IU(i))&&(n&&(n+=" "),n+=e);return n}const RW=(i,e)=>{const t=new Array(i.length+e.length);for(let n=0;n<i.length;n++)t[n]=i[n];for(let n=0;n<e.length;n++)t[i.length+n]=e[n];return t},DW=(i,e)=>({classGroupId:i,validator:e}),zU=(i=new Map,e=null,t)=>({nextPart:i,validators:e,classGroupId:t}),VT="-",BU=[],OW="arbitrary..",LW=i=>{const e=kW(i),{conflictingClassGroups:t,conflictingClassGroupModifiers:n}=i;return{getClassGroupId:c=>{if(c.startsWith("[")&&c.endsWith("]"))return NW(c);const u=c.split(VT),h=u[0]===""&&u.length>1?1:0;return PU(u,h,e)},getConflictingClassGroupIds:(c,u)=>{if(u){const h=n[c],m=t[c];return h?m?RW(m,h):h:m||BU}return t[c]||BU}}},PU=(i,e,t)=>{if(i.length-e===0)return t.classGroupId;const r=i[e],o=t.nextPart.get(r);if(o){const m=PU(i,e+1,o);if(m)return m}const c=t.validators;if(c===null)return;const u=e===0?i.join(VT):i.slice(e).join(VT),h=c.length;for(let m=0;m<h;m++){const _=c[m];if(_.validator(u))return _.classGroupId}},NW=i=>i.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=i.slice(1,-1),t=e.indexOf(":"),n=e.slice(0,t);return n?OW+n:void 0})(),kW=i=>{const{theme:e,classGroups:t}=i;return UW(t,e)},UW=(i,e)=>{const t=zU();for(const n in i){const r=i[n];jR(r,t,n,e)}return t},jR=(i,e,t,n)=>{const r=i.length;for(let o=0;o<r;o++){const c=i[o];IW(c,e,t,n)}},IW=(i,e,t,n)=>{if(typeof i=="string"){zW(i,e,t);return}if(typeof i=="function"){BW(i,e,t,n);return}PW(i,e,t,n)},zW=(i,e,t)=>{const n=i===""?e:FU(e,i);n.classGroupId=t},BW=(i,e,t,n)=>{if(FW(i)){jR(i(n),e,t,n);return}e.validators===null&&(e.validators=[]),e.validators.push(DW(t,i))},PW=(i,e,t,n)=>{const r=Object.entries(i),o=r.length;for(let c=0;c<o;c++){const[u,h]=r[c];jR(h,FU(e,u),t,n)}},FU=(i,e)=>{let t=i;const n=e.split(VT),r=n.length;for(let o=0;o<r;o++){const c=n[o];let u=t.nextPart.get(c);u||(u=zU(),t.nextPart.set(c,u)),t=u}return t},FW=i=>"isThemeGetter"in i&&i.isThemeGetter===!0,HW=i=>{if(i<1)return{get:()=>{},set:()=>{}};let e=0,t=Object.create(null),n=Object.create(null);const r=(o,c)=>{t[o]=c,e++,e>i&&(e=0,n=t,t=Object.create(null))};return{get(o){let c=t[o];if(c!==void 0)return c;if((c=n[o])!==void 0)return r(o,c),c},set(o,c){o in t?t[o]=c:r(o,c)}}},XR="!",HU=":",VW=[],VU=(i,e,t,n,r)=>({modifiers:i,hasImportantModifier:e,baseClassName:t,maybePostfixModifierPosition:n,isExternal:r}),GW=i=>{const{prefix:e,experimentalParseClassName:t}=i;let n=r=>{const o=[];let c=0,u=0,h=0,m;const _=r.length;for(let M=0;M<_;M++){const w=r[M];if(c===0&&u===0){if(w===HU){o.push(r.slice(h,M)),h=M+1;continue}if(w==="/"){m=M;continue}}w==="["?c++:w==="]"?c--:w==="("?u++:w===")"&&u--}const p=o.length===0?r:r.slice(h);let y=p,x=!1;p.endsWith(XR)?(y=p.slice(0,-1),x=!0):p.startsWith(XR)&&(y=p.slice(1),x=!0);const T=m&&m>h?m-h:void 0;return VU(o,x,y,T)};if(e){const r=e+HU,o=n;n=c=>c.startsWith(r)?o(c.slice(r.length)):VU(VW,!1,c,void 0,!0)}if(t){const r=n;n=o=>t({className:o,parseClassName:r})}return n},jW=i=>{const e=new Map;return i.orderSensitiveModifiers.forEach((t,n)=>{e.set(t,1e6+n)}),t=>{const n=[];let r=[];for(let o=0;o<t.length;o++){const c=t[o],u=c[0]==="[",h=e.has(c);u||h?(r.length>0&&(r.sort(),n.push(...r),r=[]),n.push(c)):r.push(c)}return r.length>0&&(r.sort(),n.push(...r)),n}},XW=i=>({cache:HW(i.cacheSize),parseClassName:GW(i),sortModifiers:jW(i),...LW(i)}),qW=/\s+/,$W=(i,e)=>{const{parseClassName:t,getClassGroupId:n,getConflictingClassGroupIds:r,sortModifiers:o}=e,c=[],u=i.trim().split(qW);let h="";for(let m=u.length-1;m>=0;m-=1){const _=u[m],{isExternal:p,modifiers:y,hasImportantModifier:x,baseClassName:T,maybePostfixModifierPosition:M}=t(_);if(p){h=_+(h.length>0?" "+h:h);continue}let w=!!M,A=n(w?T.substring(0,M):T);if(!A){if(!w){h=_+(h.length>0?" "+h:h);continue}if(A=n(T),!A){h=_+(h.length>0?" "+h:h);continue}w=!1}const L=y.length===0?"":y.length===1?y[0]:o(y).join(":"),N=x?L+XR:L,I=N+A;if(c.indexOf(I)>-1)continue;c.push(I);const z=r(A,w);for(let P=0;P<z.length;++P){const G=z[P];c.push(N+G)}h=_+(h.length>0?" "+h:h)}return h},YW=(...i)=>{let e=0,t,n,r="";for(;e<i.length;)(t=i[e++])&&(n=GU(t))&&(r&&(r+=" "),r+=n);return r},GU=i=>{if(typeof i=="string")return i;let e,t="";for(let n=0;n<i.length;n++)i[n]&&(e=GU(i[n]))&&(t&&(t+=" "),t+=e);return t},WW=(i,...e)=>{let t,n,r,o;const c=h=>{const m=e.reduce((_,p)=>p(_),i());return t=XW(m),n=t.cache.get,r=t.cache.set,o=u,u(h)},u=h=>{const m=n(h);if(m)return m;const _=$W(h,t);return r(h,_),_};return o=c,(...h)=>o(YW(...h))},ZW=[],Jr=i=>{const e=t=>t[i]||ZW;return e.isThemeGetter=!0,e},jU=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,XU=/^\((?:(\w[\w-]*):)?(.+)\)$/i,KW=/^\d+\/\d+$/,JW=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,QW=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,eZ=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,tZ=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,nZ=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Rv=i=>KW.test(i),Mn=i=>!!i&&!Number.isNaN(Number(i)),sh=i=>!!i&&Number.isInteger(Number(i)),qR=i=>i.endsWith("%")&&Mn(i.slice(0,-1)),Tf=i=>JW.test(i),iZ=()=>!0,rZ=i=>QW.test(i)&&!eZ.test(i),qU=()=>!1,aZ=i=>tZ.test(i),sZ=i=>nZ.test(i),oZ=i=>!At(i)&&!Ct(i),lZ=i=>Dv(i,KU,qU),At=i=>jU.test(i),Am=i=>Dv(i,JU,rZ),$R=i=>Dv(i,hZ,Mn),$U=i=>Dv(i,WU,qU),cZ=i=>Dv(i,ZU,sZ),GT=i=>Dv(i,QU,aZ),Ct=i=>XU.test(i),Qb=i=>Ov(i,JU),uZ=i=>Ov(i,pZ),YU=i=>Ov(i,WU),fZ=i=>Ov(i,KU),dZ=i=>Ov(i,ZU),jT=i=>Ov(i,QU,!0),Dv=(i,e,t)=>{const n=jU.exec(i);return n?n[1]?e(n[1]):t(n[2]):!1},Ov=(i,e,t=!1)=>{const n=XU.exec(i);return n?n[1]?e(n[1]):t:!1},WU=i=>i==="position"||i==="percentage",ZU=i=>i==="image"||i==="url",KU=i=>i==="length"||i==="size"||i==="bg-size",JU=i=>i==="length",hZ=i=>i==="number",pZ=i=>i==="family-name",QU=i=>i==="shadow",mZ=WW(()=>{const i=Jr("color"),e=Jr("font"),t=Jr("text"),n=Jr("font-weight"),r=Jr("tracking"),o=Jr("leading"),c=Jr("breakpoint"),u=Jr("container"),h=Jr("spacing"),m=Jr("radius"),_=Jr("shadow"),p=Jr("inset-shadow"),y=Jr("text-shadow"),x=Jr("drop-shadow"),T=Jr("blur"),M=Jr("perspective"),w=Jr("aspect"),A=Jr("ease"),L=Jr("animate"),N=()=>["auto","avoid","all","avoid-page","page","left","right","column"],I=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],z=()=>[...I(),Ct,At],P=()=>["auto","hidden","clip","visible","scroll"],G=()=>["auto","contain","none"],$=()=>[Ct,At,h],U=()=>[Rv,"full","auto",...$()],H=()=>[sh,"none","subgrid",Ct,At],J=()=>["auto",{span:["full",sh,Ct,At]},sh,Ct,At],ne=()=>[sh,"auto",Ct,At],ie=()=>["auto","min","max","fr",Ct,At],fe=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],me=()=>["start","end","center","stretch","center-safe","end-safe"],q=()=>["auto",...$()],K=()=>[Rv,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...$()],ee=()=>[i,Ct,At],ke=()=>[...I(),YU,$U,{position:[Ct,At]}],Pe=()=>["no-repeat",{repeat:["","x","y","space","round"]}],X=()=>["auto","cover","contain",fZ,lZ,{size:[Ct,At]}],le=()=>[qR,Qb,Am],Ee=()=>["","none","full",m,Ct,At],Re=()=>["",Mn,Qb,Am],Qe=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],_e=()=>[Mn,qR,YU,$U],nt=()=>["","none",T,Ct,At],lt=()=>["none",Mn,Ct,At],ut=()=>["none",Mn,Ct,At],Ze=()=>[Mn,Ct,At],Ln=()=>[Rv,"full",...$()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Tf],breakpoint:[Tf],color:[iZ],container:[Tf],"drop-shadow":[Tf],ease:["in","out","in-out"],font:[oZ],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Tf],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Tf],shadow:[Tf],spacing:["px",Mn],text:[Tf],"text-shadow":[Tf],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Rv,At,Ct,w]}],container:["container"],columns:[{columns:[Mn,At,Ct,u]}],"break-after":[{"break-after":N()}],"break-before":[{"break-before":N()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:z()}],overflow:[{overflow:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:G()}],"overscroll-x":[{"overscroll-x":G()}],"overscroll-y":[{"overscroll-y":G()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{start:U()}],end:[{end:U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[sh,"auto",Ct,At]}],basis:[{basis:[Rv,"full","auto",u,...$()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Mn,Rv,"auto","initial","none",At]}],grow:[{grow:["",Mn,Ct,At]}],shrink:[{shrink:["",Mn,Ct,At]}],order:[{order:[sh,"first","last","none",Ct,At]}],"grid-cols":[{"grid-cols":H()}],"col-start-end":[{col:J()}],"col-start":[{"col-start":ne()}],"col-end":[{"col-end":ne()}],"grid-rows":[{"grid-rows":H()}],"row-start-end":[{row:J()}],"row-start":[{"row-start":ne()}],"row-end":[{"row-end":ne()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ie()}],"auto-rows":[{"auto-rows":ie()}],gap:[{gap:$()}],"gap-x":[{"gap-x":$()}],"gap-y":[{"gap-y":$()}],"justify-content":[{justify:[...fe(),"normal"]}],"justify-items":[{"justify-items":[...me(),"normal"]}],"justify-self":[{"justify-self":["auto",...me()]}],"align-content":[{content:["normal",...fe()]}],"align-items":[{items:[...me(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...me(),{baseline:["","last"]}]}],"place-content":[{"place-content":fe()}],"place-items":[{"place-items":[...me(),"baseline"]}],"place-self":[{"place-self":["auto",...me()]}],p:[{p:$()}],px:[{px:$()}],py:[{py:$()}],ps:[{ps:$()}],pe:[{pe:$()}],pt:[{pt:$()}],pr:[{pr:$()}],pb:[{pb:$()}],pl:[{pl:$()}],m:[{m:q()}],mx:[{mx:q()}],my:[{my:q()}],ms:[{ms:q()}],me:[{me:q()}],mt:[{mt:q()}],mr:[{mr:q()}],mb:[{mb:q()}],ml:[{ml:q()}],"space-x":[{"space-x":$()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":$()}],"space-y-reverse":["space-y-reverse"],size:[{size:K()}],w:[{w:[u,"screen",...K()]}],"min-w":[{"min-w":[u,"screen","none",...K()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[c]},...K()]}],h:[{h:["screen","lh",...K()]}],"min-h":[{"min-h":["screen","lh","none",...K()]}],"max-h":[{"max-h":["screen","lh",...K()]}],"font-size":[{text:["base",t,Qb,Am]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[n,Ct,$R]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",qR,At]}],"font-family":[{font:[uZ,At,e]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,Ct,At]}],"line-clamp":[{"line-clamp":[Mn,"none",Ct,$R]}],leading:[{leading:[o,...$()]}],"list-image":[{"list-image":["none",Ct,At]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Ct,At]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:ee()}],"text-color":[{text:ee()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Qe(),"wavy"]}],"text-decoration-thickness":[{decoration:[Mn,"from-font","auto",Ct,Am]}],"text-decoration-color":[{decoration:ee()}],"underline-offset":[{"underline-offset":[Mn,"auto",Ct,At]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:$()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ct,At]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Ct,At]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:ke()}],"bg-repeat":[{bg:Pe()}],"bg-size":[{bg:X()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},sh,Ct,At],radial:["",Ct,At],conic:[sh,Ct,At]},dZ,cZ]}],"bg-color":[{bg:ee()}],"gradient-from-pos":[{from:le()}],"gradient-via-pos":[{via:le()}],"gradient-to-pos":[{to:le()}],"gradient-from":[{from:ee()}],"gradient-via":[{via:ee()}],"gradient-to":[{to:ee()}],rounded:[{rounded:Ee()}],"rounded-s":[{"rounded-s":Ee()}],"rounded-e":[{"rounded-e":Ee()}],"rounded-t":[{"rounded-t":Ee()}],"rounded-r":[{"rounded-r":Ee()}],"rounded-b":[{"rounded-b":Ee()}],"rounded-l":[{"rounded-l":Ee()}],"rounded-ss":[{"rounded-ss":Ee()}],"rounded-se":[{"rounded-se":Ee()}],"rounded-ee":[{"rounded-ee":Ee()}],"rounded-es":[{"rounded-es":Ee()}],"rounded-tl":[{"rounded-tl":Ee()}],"rounded-tr":[{"rounded-tr":Ee()}],"rounded-br":[{"rounded-br":Ee()}],"rounded-bl":[{"rounded-bl":Ee()}],"border-w":[{border:Re()}],"border-w-x":[{"border-x":Re()}],"border-w-y":[{"border-y":Re()}],"border-w-s":[{"border-s":Re()}],"border-w-e":[{"border-e":Re()}],"border-w-t":[{"border-t":Re()}],"border-w-r":[{"border-r":Re()}],"border-w-b":[{"border-b":Re()}],"border-w-l":[{"border-l":Re()}],"divide-x":[{"divide-x":Re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Qe(),"hidden","none"]}],"divide-style":[{divide:[...Qe(),"hidden","none"]}],"border-color":[{border:ee()}],"border-color-x":[{"border-x":ee()}],"border-color-y":[{"border-y":ee()}],"border-color-s":[{"border-s":ee()}],"border-color-e":[{"border-e":ee()}],"border-color-t":[{"border-t":ee()}],"border-color-r":[{"border-r":ee()}],"border-color-b":[{"border-b":ee()}],"border-color-l":[{"border-l":ee()}],"divide-color":[{divide:ee()}],"outline-style":[{outline:[...Qe(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Mn,Ct,At]}],"outline-w":[{outline:["",Mn,Qb,Am]}],"outline-color":[{outline:ee()}],shadow:[{shadow:["","none",_,jT,GT]}],"shadow-color":[{shadow:ee()}],"inset-shadow":[{"inset-shadow":["none",p,jT,GT]}],"inset-shadow-color":[{"inset-shadow":ee()}],"ring-w":[{ring:Re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:ee()}],"ring-offset-w":[{"ring-offset":[Mn,Am]}],"ring-offset-color":[{"ring-offset":ee()}],"inset-ring-w":[{"inset-ring":Re()}],"inset-ring-color":[{"inset-ring":ee()}],"text-shadow":[{"text-shadow":["none",y,jT,GT]}],"text-shadow-color":[{"text-shadow":ee()}],opacity:[{opacity:[Mn,Ct,At]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Mn]}],"mask-image-linear-from-pos":[{"mask-linear-from":_e()}],"mask-image-linear-to-pos":[{"mask-linear-to":_e()}],"mask-image-linear-from-color":[{"mask-linear-from":ee()}],"mask-image-linear-to-color":[{"mask-linear-to":ee()}],"mask-image-t-from-pos":[{"mask-t-from":_e()}],"mask-image-t-to-pos":[{"mask-t-to":_e()}],"mask-image-t-from-color":[{"mask-t-from":ee()}],"mask-image-t-to-color":[{"mask-t-to":ee()}],"mask-image-r-from-pos":[{"mask-r-from":_e()}],"mask-image-r-to-pos":[{"mask-r-to":_e()}],"mask-image-r-from-color":[{"mask-r-from":ee()}],"mask-image-r-to-color":[{"mask-r-to":ee()}],"mask-image-b-from-pos":[{"mask-b-from":_e()}],"mask-image-b-to-pos":[{"mask-b-to":_e()}],"mask-image-b-from-color":[{"mask-b-from":ee()}],"mask-image-b-to-color":[{"mask-b-to":ee()}],"mask-image-l-from-pos":[{"mask-l-from":_e()}],"mask-image-l-to-pos":[{"mask-l-to":_e()}],"mask-image-l-from-color":[{"mask-l-from":ee()}],"mask-image-l-to-color":[{"mask-l-to":ee()}],"mask-image-x-from-pos":[{"mask-x-from":_e()}],"mask-image-x-to-pos":[{"mask-x-to":_e()}],"mask-image-x-from-color":[{"mask-x-from":ee()}],"mask-image-x-to-color":[{"mask-x-to":ee()}],"mask-image-y-from-pos":[{"mask-y-from":_e()}],"mask-image-y-to-pos":[{"mask-y-to":_e()}],"mask-image-y-from-color":[{"mask-y-from":ee()}],"mask-image-y-to-color":[{"mask-y-to":ee()}],"mask-image-radial":[{"mask-radial":[Ct,At]}],"mask-image-radial-from-pos":[{"mask-radial-from":_e()}],"mask-image-radial-to-pos":[{"mask-radial-to":_e()}],"mask-image-radial-from-color":[{"mask-radial-from":ee()}],"mask-image-radial-to-color":[{"mask-radial-to":ee()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":I()}],"mask-image-conic-pos":[{"mask-conic":[Mn]}],"mask-image-conic-from-pos":[{"mask-conic-from":_e()}],"mask-image-conic-to-pos":[{"mask-conic-to":_e()}],"mask-image-conic-from-color":[{"mask-conic-from":ee()}],"mask-image-conic-to-color":[{"mask-conic-to":ee()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:ke()}],"mask-repeat":[{mask:Pe()}],"mask-size":[{mask:X()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Ct,At]}],filter:[{filter:["","none",Ct,At]}],blur:[{blur:nt()}],brightness:[{brightness:[Mn,Ct,At]}],contrast:[{contrast:[Mn,Ct,At]}],"drop-shadow":[{"drop-shadow":["","none",x,jT,GT]}],"drop-shadow-color":[{"drop-shadow":ee()}],grayscale:[{grayscale:["",Mn,Ct,At]}],"hue-rotate":[{"hue-rotate":[Mn,Ct,At]}],invert:[{invert:["",Mn,Ct,At]}],saturate:[{saturate:[Mn,Ct,At]}],sepia:[{sepia:["",Mn,Ct,At]}],"backdrop-filter":[{"backdrop-filter":["","none",Ct,At]}],"backdrop-blur":[{"backdrop-blur":nt()}],"backdrop-brightness":[{"backdrop-brightness":[Mn,Ct,At]}],"backdrop-contrast":[{"backdrop-contrast":[Mn,Ct,At]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Mn,Ct,At]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Mn,Ct,At]}],"backdrop-invert":[{"backdrop-invert":["",Mn,Ct,At]}],"backdrop-opacity":[{"backdrop-opacity":[Mn,Ct,At]}],"backdrop-saturate":[{"backdrop-saturate":[Mn,Ct,At]}],"backdrop-sepia":[{"backdrop-sepia":["",Mn,Ct,At]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":$()}],"border-spacing-x":[{"border-spacing-x":$()}],"border-spacing-y":[{"border-spacing-y":$()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Ct,At]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Mn,"initial",Ct,At]}],ease:[{ease:["linear","initial",A,Ct,At]}],delay:[{delay:[Mn,Ct,At]}],animate:[{animate:["none",L,Ct,At]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[M,Ct,At]}],"perspective-origin":[{"perspective-origin":z()}],rotate:[{rotate:lt()}],"rotate-x":[{"rotate-x":lt()}],"rotate-y":[{"rotate-y":lt()}],"rotate-z":[{"rotate-z":lt()}],scale:[{scale:ut()}],"scale-x":[{"scale-x":ut()}],"scale-y":[{"scale-y":ut()}],"scale-z":[{"scale-z":ut()}],"scale-3d":["scale-3d"],skew:[{skew:Ze()}],"skew-x":[{"skew-x":Ze()}],"skew-y":[{"skew-y":Ze()}],transform:[{transform:[Ct,At,"","none","gpu","cpu"]}],"transform-origin":[{origin:z()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Ln()}],"translate-x":[{"translate-x":Ln()}],"translate-y":[{"translate-y":Ln()}],"translate-z":[{"translate-z":Ln()}],"translate-none":["translate-none"],accent:[{accent:ee()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:ee()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Ct,At]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":$()}],"scroll-mx":[{"scroll-mx":$()}],"scroll-my":[{"scroll-my":$()}],"scroll-ms":[{"scroll-ms":$()}],"scroll-me":[{"scroll-me":$()}],"scroll-mt":[{"scroll-mt":$()}],"scroll-mr":[{"scroll-mr":$()}],"scroll-mb":[{"scroll-mb":$()}],"scroll-ml":[{"scroll-ml":$()}],"scroll-p":[{"scroll-p":$()}],"scroll-px":[{"scroll-px":$()}],"scroll-py":[{"scroll-py":$()}],"scroll-ps":[{"scroll-ps":$()}],"scroll-pe":[{"scroll-pe":$()}],"scroll-pt":[{"scroll-pt":$()}],"scroll-pr":[{"scroll-pr":$()}],"scroll-pb":[{"scroll-pb":$()}],"scroll-pl":[{"scroll-pl":$()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Ct,At]}],fill:[{fill:["none",...ee()]}],"stroke-w":[{stroke:[Mn,Qb,Am,$R]}],stroke:[{stroke:["none",...ee()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function Ao(...i){return mZ(CW(i))}const gZ=typeof document<"u"?em.useLayoutEffect:()=>{},oh=i=>{var e;return(e=i?.ownerDocument)!==null&&e!==void 0?e:document},Cm=i=>i&&"window"in i&&i.window===i?i:oh(i).defaultView||window;function vZ(i){return i!==null&&typeof i=="object"&&"nodeType"in i&&typeof i.nodeType=="number"}function yZ(i){return vZ(i)&&i.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in i}let _Z=!1;function YR(){return _Z}function eI(i,e){if(!YR())return e&&i?i.contains(e):!1;if(!i||!e)return!1;let t=e;for(;t!==null;){if(t===i)return!0;t.tagName==="SLOT"&&t.assignedSlot?t=t.assignedSlot.parentNode:yZ(t)?t=t.host:t=t.parentNode}return!1}const WR=(i=document)=>{var e;if(!YR())return i.activeElement;let t=i.activeElement;for(;t&&"shadowRoot"in t&&(!((e=t.shadowRoot)===null||e===void 0)&&e.activeElement);)t=t.shadowRoot.activeElement;return t};function tI(i){return YR()&&i.target.shadowRoot&&i.composedPath?i.composedPath()[0]:i.target}function bZ(i){if(xZ())i.focus({preventScroll:!0});else{let e=SZ(i);i.focus(),EZ(e)}}let XT=null;function xZ(){if(XT==null){XT=!1;try{document.createElement("div").focus({get preventScroll(){return XT=!0,!0}})}catch{}}return XT}function SZ(i){let e=i.parentNode,t=[],n=document.scrollingElement||document.documentElement;for(;e instanceof HTMLElement&&e!==n;)(e.offsetHeight<e.scrollHeight||e.offsetWidth<e.scrollWidth)&&t.push({element:e,scrollTop:e.scrollTop,scrollLeft:e.scrollLeft}),e=e.parentNode;return n instanceof HTMLElement&&t.push({element:n,scrollTop:n.scrollTop,scrollLeft:n.scrollLeft}),t}function EZ(i){for(let{element:e,scrollTop:t,scrollLeft:n}of i)e.scrollTop=t,e.scrollLeft=n}function qT(i){var e;if(typeof window>"u"||window.navigator==null)return!1;let t=(e=window.navigator.userAgentData)===null||e===void 0?void 0:e.brands;return Array.isArray(t)&&t.some(n=>i.test(n.brand))||i.test(window.navigator.userAgent)}function ZR(i){var e;return typeof window<"u"&&window.navigator!=null?i.test(((e=window.navigator.userAgentData)===null||e===void 0?void 0:e.platform)||window.navigator.platform):!1}function Mf(i){if(process.env.NODE_ENV==="test")return i;let e=null;return()=>(e==null&&(e=i()),e)}const e1=Mf(function(){return ZR(/^Mac/i)}),TZ=Mf(function(){return ZR(/^iPhone/i)}),nI=Mf(function(){return ZR(/^iPad/i)||e1()&&navigator.maxTouchPoints>1}),MZ=Mf(function(){return TZ()||nI()});Mf(function(){return e1()||MZ()});const wZ=Mf(function(){return qT(/AppleWebKit/i)&&!AZ()}),AZ=Mf(function(){return qT(/Chrome/i)}),CZ=Mf(function(){return qT(/Android/i)}),RZ=Mf(function(){return qT(/Firefox/i)});function t1(i,e,t=!0){var n,r;let{metaKey:o,ctrlKey:c,altKey:u,shiftKey:h}=e;RZ()&&(!((r=window.event)===null||r===void 0||(n=r.type)===null||n===void 0)&&n.startsWith("key"))&&i.target==="_blank"&&(e1()?o=!0:c=!0);let m=wZ()&&e1()&&!nI()&&process.env.NODE_ENV!=="test"?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:o,ctrlKey:c,altKey:u,shiftKey:h}):new MouseEvent("click",{metaKey:o,ctrlKey:c,altKey:u,shiftKey:h,detail:1,bubbles:!0,cancelable:!0});t1.isOpening=t,bZ(i),i.dispatchEvent(m),t1.isOpening=!1}t1.isOpening=!1;function iI(){let i=te.useRef(new Map),e=te.useCallback((r,o,c,u)=>{let h=u?.once?(...m)=>{i.current.delete(c),c(...m)}:c;i.current.set(c,{type:o,eventTarget:r,fn:h,options:u}),r.addEventListener(o,h,u)},[]),t=te.useCallback((r,o,c,u)=>{var h;let m=((h=i.current.get(c))===null||h===void 0?void 0:h.fn)||c;r.removeEventListener(o,m,u),i.current.delete(c)},[]),n=te.useCallback(()=>{i.current.forEach((r,o)=>{t(r.eventTarget,r.type,o,r.options)})},[t]);return te.useEffect(()=>n,[n]),{addGlobalListener:e,removeGlobalListener:t,removeAllGlobalListeners:n}}function DZ(i){return i.pointerType===""&&i.isTrusted?!0:CZ()&&i.pointerType?i.type==="click"&&i.buttons===1:i.detail===0&&!i.pointerType}function rI(i){let e=i;return e.nativeEvent=i,e.isDefaultPrevented=()=>e.defaultPrevented,e.isPropagationStopped=()=>e.cancelBubble,e.persist=()=>{},e}function OZ(i,e){Object.defineProperty(i,"target",{value:e}),Object.defineProperty(i,"currentTarget",{value:e})}function aI(i){let e=te.useRef({isFocused:!1,observer:null});return gZ(()=>{const t=e.current;return()=>{t.observer&&(t.observer.disconnect(),t.observer=null)}},[]),te.useCallback(t=>{if(t.target instanceof HTMLButtonElement||t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement||t.target instanceof HTMLSelectElement){e.current.isFocused=!0;let n=t.target,r=o=>{if(e.current.isFocused=!1,n.disabled){let c=rI(o);i?.(c)}e.current.observer&&(e.current.observer.disconnect(),e.current.observer=null)};n.addEventListener("focusout",r,{once:!0}),e.current.observer=new MutationObserver(()=>{if(e.current.isFocused&&n.disabled){var o;(o=e.current.observer)===null||o===void 0||o.disconnect();let c=n===document.activeElement?null:document.activeElement;n.dispatchEvent(new FocusEvent("blur",{relatedTarget:c})),n.dispatchEvent(new FocusEvent("focusout",{bubbles:!0,relatedTarget:c}))}}),e.current.observer.observe(n,{attributes:!0,attributeFilter:["disabled"]})}},[i])}let LZ=!1,n1=null,KR=new Set,i1=new Map,Rm=!1,JR=!1;const NZ={Tab:!0,Escape:!0};function QR(i,e){for(let t of KR)t(i,e)}function kZ(i){return!(i.metaKey||!e1()&&i.altKey||i.ctrlKey||i.key==="Control"||i.key==="Shift"||i.key==="Meta")}function $T(i){Rm=!0,!t1.isOpening&&kZ(i)&&(n1="keyboard",QR("keyboard",i))}function vl(i){n1="pointer","pointerType"in i&&i.pointerType,(i.type==="mousedown"||i.type==="pointerdown")&&(Rm=!0,QR("pointer",i))}function sI(i){!t1.isOpening&&DZ(i)&&(Rm=!0,n1="virtual")}function oI(i){i.target===window||i.target===document||LZ||!i.isTrusted||(!Rm&&!JR&&(n1="virtual",QR("virtual",i)),Rm=!1,JR=!1)}function lI(){Rm=!1,JR=!0}function eD(i){if(typeof window>"u"||typeof document>"u"||i1.get(Cm(i)))return;const e=Cm(i),t=oh(i);let n=e.HTMLElement.prototype.focus;e.HTMLElement.prototype.focus=function(){Rm=!0,n.apply(this,arguments)},t.addEventListener("keydown",$T,!0),t.addEventListener("keyup",$T,!0),t.addEventListener("click",sI,!0),e.addEventListener("focus",oI,!0),e.addEventListener("blur",lI,!1),typeof PointerEvent<"u"?(t.addEventListener("pointerdown",vl,!0),t.addEventListener("pointermove",vl,!0),t.addEventListener("pointerup",vl,!0)):process.env.NODE_ENV==="test"&&(t.addEventListener("mousedown",vl,!0),t.addEventListener("mousemove",vl,!0),t.addEventListener("mouseup",vl,!0)),e.addEventListener("beforeunload",()=>{cI(i)},{once:!0}),i1.set(e,{focus:n})}const cI=(i,e)=>{const t=Cm(i),n=oh(i);e&&n.removeEventListener("DOMContentLoaded",e),i1.has(t)&&(t.HTMLElement.prototype.focus=i1.get(t).focus,n.removeEventListener("keydown",$T,!0),n.removeEventListener("keyup",$T,!0),n.removeEventListener("click",sI,!0),t.removeEventListener("focus",oI,!0),t.removeEventListener("blur",lI,!1),typeof PointerEvent<"u"?(n.removeEventListener("pointerdown",vl,!0),n.removeEventListener("pointermove",vl,!0),n.removeEventListener("pointerup",vl,!0)):process.env.NODE_ENV==="test"&&(n.removeEventListener("mousedown",vl,!0),n.removeEventListener("mousemove",vl,!0),n.removeEventListener("mouseup",vl,!0)),i1.delete(t))};function UZ(i){const e=oh(i);let t;return e.readyState!=="loading"?eD(i):(t=()=>{eD(i)},e.addEventListener("DOMContentLoaded",t)),()=>cI(i,t)}typeof document<"u"&&UZ();function uI(){return n1!=="pointer"}const IZ=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function zZ(i,e,t){let n=oh(t?.target);const r=typeof window<"u"?Cm(t?.target).HTMLInputElement:HTMLInputElement,o=typeof window<"u"?Cm(t?.target).HTMLTextAreaElement:HTMLTextAreaElement,c=typeof window<"u"?Cm(t?.target).HTMLElement:HTMLElement,u=typeof window<"u"?Cm(t?.target).KeyboardEvent:KeyboardEvent;return i=i||n.activeElement instanceof r&&!IZ.has(n.activeElement.type)||n.activeElement instanceof o||n.activeElement instanceof c&&n.activeElement.isContentEditable,!(i&&e==="keyboard"&&t instanceof u&&!NZ[t.key])}function BZ(i,e,t){eD(),te.useEffect(()=>{let n=(r,o)=>{zZ(!!t?.isTextInput,r,o)&&i(uI())};return KR.add(n),()=>{KR.delete(n)}},e)}function PZ(i){let{isDisabled:e,onFocus:t,onBlur:n,onFocusChange:r}=i;const o=te.useCallback(h=>{if(h.target===h.currentTarget)return n&&n(h),r&&r(!1),!0},[n,r]),c=aI(o),u=te.useCallback(h=>{const m=oh(h.target),_=m?WR(m):WR();h.target===h.currentTarget&&_===tI(h.nativeEvent)&&(t&&t(h),r&&r(!0),c(h))},[r,t,c]);return{focusProps:{onFocus:!e&&(t||r||n)?u:void 0,onBlur:!e&&(n||r)?o:void 0}}}function FZ(i){let{isDisabled:e,onBlurWithin:t,onFocusWithin:n,onFocusWithinChange:r}=i,o=te.useRef({isFocusWithin:!1}),{addGlobalListener:c,removeAllGlobalListeners:u}=iI(),h=te.useCallback(p=>{p.currentTarget.contains(p.target)&&o.current.isFocusWithin&&!p.currentTarget.contains(p.relatedTarget)&&(o.current.isFocusWithin=!1,u(),t&&t(p),r&&r(!1))},[t,r,o,u]),m=aI(h),_=te.useCallback(p=>{if(!p.currentTarget.contains(p.target))return;const y=oh(p.target),x=WR(y);if(!o.current.isFocusWithin&&x===tI(p.nativeEvent)){n&&n(p),r&&r(!0),o.current.isFocusWithin=!0,m(p);let T=p.currentTarget;c(y,"focus",M=>{if(o.current.isFocusWithin&&!eI(T,M.target)){let w=new y.defaultView.FocusEvent("blur",{relatedTarget:M.target});OZ(w,T);let A=rI(w);h(A)}},{capture:!0})}},[n,r,m,c,h]);return e?{focusWithinProps:{onFocus:void 0,onBlur:void 0}}:{focusWithinProps:{onFocus:_,onBlur:h}}}let YT=!1,WT=0;function tD(){YT=!0,setTimeout(()=>{YT=!1},50)}function fI(i){i.pointerType==="touch"&&tD()}function HZ(){if(!(typeof document>"u"))return WT===0&&(typeof PointerEvent<"u"?document.addEventListener("pointerup",fI):process.env.NODE_ENV==="test"&&document.addEventListener("touchend",tD)),WT++,()=>{WT--,!(WT>0)&&(typeof PointerEvent<"u"?document.removeEventListener("pointerup",fI):process.env.NODE_ENV==="test"&&document.removeEventListener("touchend",tD))}}function dI(i){let{onHoverStart:e,onHoverChange:t,onHoverEnd:n,isDisabled:r}=i,[o,c]=te.useState(!1),u=te.useRef({isHovered:!1,ignoreEmulatedMouseEvents:!1,pointerType:"",target:null}).current;te.useEffect(HZ,[]);let{addGlobalListener:h,removeAllGlobalListeners:m}=iI(),{hoverProps:_,triggerHoverEnd:p}=te.useMemo(()=>{let y=(M,w)=>{if(u.pointerType=w,r||w==="touch"||u.isHovered||!M.currentTarget.contains(M.target))return;u.isHovered=!0;let A=M.currentTarget;u.target=A,h(oh(M.target),"pointerover",L=>{u.isHovered&&u.target&&!eI(u.target,L.target)&&x(L,L.pointerType)},{capture:!0}),e&&e({type:"hoverstart",target:A,pointerType:w}),t&&t(!0),c(!0)},x=(M,w)=>{let A=u.target;u.pointerType="",u.target=null,!(w==="touch"||!u.isHovered||!A)&&(u.isHovered=!1,m(),n&&n({type:"hoverend",target:A,pointerType:w}),t&&t(!1),c(!1))},T={};return typeof PointerEvent<"u"?(T.onPointerEnter=M=>{YT&&M.pointerType==="mouse"||y(M,M.pointerType)},T.onPointerLeave=M=>{!r&&M.currentTarget.contains(M.target)&&x(M,M.pointerType)}):process.env.NODE_ENV==="test"&&(T.onTouchStart=()=>{u.ignoreEmulatedMouseEvents=!0},T.onMouseEnter=M=>{!u.ignoreEmulatedMouseEvents&&!YT&&y(M,"mouse"),u.ignoreEmulatedMouseEvents=!1},T.onMouseLeave=M=>{!r&&M.currentTarget.contains(M.target)&&x(M,"mouse")}),{hoverProps:T,triggerHoverEnd:x}},[e,t,n,r,u,h,m]);return te.useEffect(()=>{r&&p({currentTarget:u.target},u.pointerType)},[r]),{hoverProps:_,isHovered:o}}function hI(i={}){let{autoFocus:e=!1,isTextInput:t,within:n}=i,r=te.useRef({isFocused:!1,isFocusVisible:e||uI()}),[o,c]=te.useState(!1),[u,h]=te.useState(()=>r.current.isFocused&&r.current.isFocusVisible),m=te.useCallback(()=>h(r.current.isFocused&&r.current.isFocusVisible),[]),_=te.useCallback(x=>{r.current.isFocused=x,c(x),m()},[m]);BZ(x=>{r.current.isFocusVisible=x,m()},[],{isTextInput:t});let{focusProps:p}=PZ({isDisabled:n,onFocusChange:_}),{focusWithinProps:y}=FZ({isDisabled:!n,onFocusWithinChange:_});return{isFocused:o,isFocusVisible:u,focusProps:n?y:p}}var VZ=Object.defineProperty,GZ=(i,e,t)=>e in i?VZ(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,nD=(i,e,t)=>(GZ(i,typeof e!="symbol"?e+"":e,t),t);let jZ=class{constructor(){nD(this,"current",this.detect()),nD(this,"handoffState","pending"),nD(this,"currentId",0)}set(e){this.current!==e&&(this.handoffState="pending",this.currentId=0,this.current=e)}reset(){this.set(this.detect())}nextId(){return++this.currentId}get isServer(){return this.current==="server"}get isClient(){return this.current==="client"}detect(){return typeof window>"u"||typeof document>"u"?"server":"client"}handoff(){this.handoffState==="pending"&&(this.handoffState="complete")}get isHandoffComplete(){return this.handoffState==="complete"}},pI=new jZ;function XZ(i){var e;return pI.isServer?null:i==null?document:(e=i?.ownerDocument)!=null?e:document}function qZ(i){typeof queueMicrotask=="function"?queueMicrotask(i):Promise.resolve().then(i).catch(e=>setTimeout(()=>{throw e}))}function mI(){let i=[],e={addEventListener(t,n,r,o){return t.addEventListener(n,r,o),e.add(()=>t.removeEventListener(n,r,o))},requestAnimationFrame(...t){let n=requestAnimationFrame(...t);return e.add(()=>cancelAnimationFrame(n))},nextFrame(...t){return e.requestAnimationFrame(()=>e.requestAnimationFrame(...t))},setTimeout(...t){let n=setTimeout(...t);return e.add(()=>clearTimeout(n))},microTask(...t){let n={current:!0};return qZ(()=>{n.current&&t[0]()}),e.add(()=>{n.current=!1})},style(t,n,r){let o=t.style.getPropertyValue(n);return Object.assign(t.style,{[n]:r}),this.add(()=>{Object.assign(t.style,{[n]:o})})},group(t){let n=mI();return t(n),this.add(()=>n.dispose())},add(t){return i.includes(t)||i.push(t),()=>{let n=i.indexOf(t);if(n>=0)for(let r of i.splice(n,1))r()}},dispose(){for(let t of i.splice(0))t()}};return e}function $Z(){let[i]=te.useState(mI);return te.useEffect(()=>()=>i.dispose(),[i]),i}let iD=(i,e)=>{pI.isServer?te.useEffect(i,e):te.useLayoutEffect(i,e)};function YZ(i){let e=te.useRef(i);return iD(()=>{e.current=i},[i]),e}let ZT=function(i){let e=YZ(i);return em.useCallback((...t)=>e.current(...t),[e])};function WZ(i){let e=i.width/2,t=i.height/2;return{top:i.clientY-t,right:i.clientX+e,bottom:i.clientY+t,left:i.clientX-e}}function ZZ(i,e){return!(!i||!e||i.right<e.left||i.left>e.right||i.bottom<e.top||i.top>e.bottom)}function KZ({disabled:i=!1}={}){let e=te.useRef(null),[t,n]=te.useState(!1),r=$Z(),o=ZT(()=>{e.current=null,n(!1),r.dispose()}),c=ZT(u=>{if(r.dispose(),e.current===null){e.current=u.currentTarget,n(!0);{let h=XZ(u.currentTarget);r.addEventListener(h,"pointerup",o,!1),r.addEventListener(h,"pointermove",m=>{if(e.current){let _=WZ(m);n(ZZ(_,e.current.getBoundingClientRect()))}},!1),r.addEventListener(h,"pointercancel",o,!1)}}});return{pressed:t,pressProps:i?{}:{onPointerDown:c,onPointerUp:o,onClick:o}}}function KT(i){return te.useMemo(()=>i,Object.values(i))}let JZ=te.createContext(void 0);function JT(){return te.useContext(JZ)}function gI(...i){return Array.from(new Set(i.flatMap(e=>typeof e=="string"?e.split(" "):[]))).filter(Boolean).join(" ")}function vI(i,e,...t){if(i in e){let r=e[i];return typeof r=="function"?r(...t):r}let n=new Error(`Tried to handle "${i}" but there is no handler defined. Only defined handlers are: ${Object.keys(e).map(r=>`"${r}"`).join(", ")}.`);throw Error.captureStackTrace&&Error.captureStackTrace(n,vI),n}var QZ=(i=>(i[i.None=0]="None",i[i.RenderStrategy=1]="RenderStrategy",i[i.Static=2]="Static",i))(QZ||{}),eK=(i=>(i[i.Unmount=0]="Unmount",i[i.Hidden=1]="Hidden",i))(eK||{});function QT(){let i=nK();return te.useCallback(e=>tK({mergeRefs:i,...e}),[i])}function tK({ourProps:i,theirProps:e,slot:t,defaultTag:n,features:r,visible:o=!0,name:c,mergeRefs:u}){u=u??iK;let h=yI(e,i);if(o)return eM(h,t,n,c,u);let m=r??0;if(m&2){let{static:_=!1,...p}=h;if(_)return eM(p,t,n,c,u)}if(m&1){let{unmount:_=!0,...p}=h;return vI(_?0:1,{0(){return null},1(){return eM({...p,hidden:!0,style:{display:"none"}},t,n,c,u)}})}return eM(h,t,n,c,u)}function eM(i,e={},t,n,r){let{as:o=t,children:c,refName:u="ref",...h}=rD(i,["unmount","static"]),m=i.ref!==void 0?{[u]:i.ref}:{},_=typeof c=="function"?c(e):c;"className"in h&&h.className&&typeof h.className=="function"&&(h.className=h.className(e)),h["aria-labelledby"]&&h["aria-labelledby"]===h.id&&(h["aria-labelledby"]=void 0);let p={};if(e){let y=!1,x=[];for(let[T,M]of Object.entries(e))typeof M=="boolean"&&(y=!0),M===!0&&x.push(T.replace(/([A-Z])/g,w=>`-${w.toLowerCase()}`));if(y){p["data-headlessui-state"]=x.join(" ");for(let T of x)p[`data-${T}`]=""}}if(nM(o)&&(Object.keys(Lv(h)).length>0||Object.keys(Lv(p)).length>0))if(!te.isValidElement(_)||Array.isArray(_)&&_.length>1||aK(_)){if(Object.keys(Lv(h)).length>0)throw new Error(['Passing props on "Fragment"!',"",`The current component <${n} /> is rendering a "Fragment".`,"However we need to passthrough the following props:",Object.keys(Lv(h)).concat(Object.keys(Lv(p))).map(y=>` - ${y}`).join(`
4551
4551
  `),"","You can apply a few solutions:",['Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".',"Render a single element as the child so that we can forward the props onto that element."].map(y=>` - ${y}`).join(`
4552
4552
  `)].join(`
4553
- `))}else{let y=_.props,x=y?.className,T=typeof x=="function"?(...A)=>gI(x(...A),h.className):gI(x,h.className),M=T?{className:T}:{},w=yI(_.props,Lv(rD(h,["ref"])));for(let A in p)A in w&&delete p[A];return te.cloneElement(_,Object.assign({},w,p,m,{ref:r(rK(_),m.ref)},M))}return te.createElement(o,Object.assign({},rD(h,["ref"]),!nM(o)&&m,!nM(o)&&p),_)}function nK(){let i=te.useRef([]),e=te.useCallback(t=>{for(let n of i.current)n!=null&&(typeof n=="function"?n(t):n.current=t)},[]);return(...t)=>{if(!t.every(n=>n==null))return i.current=t,e}}function iK(...i){return i.every(e=>e==null)?void 0:e=>{for(let t of i)t!=null&&(typeof t=="function"?t(e):t.current=e)}}function yI(...i){if(i.length===0)return{};if(i.length===1)return i[0];let e={},t={};for(let n of i)for(let r in n)r.startsWith("on")&&typeof n[r]=="function"?(t[r]!=null||(t[r]=[]),t[r].push(n[r])):e[r]=n[r];if(e.disabled||e["aria-disabled"])for(let n in t)/^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(n)&&(t[n]=[r=>{var o;return(o=r?.preventDefault)==null?void 0:o.call(r)}]);for(let n in t)Object.assign(e,{[n](r,...o){let c=t[n];for(let u of c){if((r instanceof Event||r?.nativeEvent instanceof Event)&&r.defaultPrevented)return;u(r,...o)}}});return e}function _I(...i){if(i.length===0)return{};if(i.length===1)return i[0];let e={},t={};for(let n of i)for(let r in n)r.startsWith("on")&&typeof n[r]=="function"?(t[r]!=null||(t[r]=[]),t[r].push(n[r])):e[r]=n[r];for(let n in t)Object.assign(e,{[n](...r){let o=t[n];for(let c of o)c?.(...r)}});return e}function tM(i){var e;return Object.assign(te.forwardRef(i),{displayName:(e=i.displayName)!=null?e:i.name})}function Lv(i){let e=Object.assign({},i);for(let t in e)e[t]===void 0&&delete e[t];return e}function rD(i,e=[]){let t=Object.assign({},i);for(let n of e)n in t&&delete t[n];return t}function rK(i){return em.version.split(".")[0]>="19"?i.props.ref:i.ref}function nM(i){return i===te.Fragment||i===Symbol.for("react.fragment")}function aK(i){return nM(i.type)}let sK="button";function oK(i,e){var t;let n=JT(),{disabled:r=n||!1,autoFocus:o=!1,...c}=i,{isFocusVisible:u,focusProps:h}=hI({autoFocus:o}),{isHovered:m,hoverProps:_}=dI({isDisabled:r}),{pressed:p,pressProps:y}=KZ({disabled:r}),x=_I({ref:e,type:(t=c.type)!=null?t:"button",disabled:r||void 0,autoFocus:o},h,_,y),T=KT({disabled:r,hover:m,focus:u,active:p,autofocus:o});return QT()({ourProps:x,theirProps:c,slot:T,defaultTag:sK,name:"Button"})}let wf=tM(oK),lK=te.createContext(void 0);function bI(){return te.useContext(lK)}function cK(i){return typeof i!="object"||i===null?!1:"nodeType"in i}function xI(i){return cK(i)&&"tagName"in i}function SI(i){return xI(i)&&"accessKey"in i}function uK(i){return SI(i)&&i.nodeName==="INPUT"}function EI(i){return SI(i)&&i.nodeName==="LABEL"}function fK(i){return xI(i)?i.matches('a[href],audio[controls],button,details,embed,iframe,img[usemap],input:not([type="hidden"]),label,select,textarea,video[controls]'):!1}let dK=Symbol();function TI(...i){let e=te.useRef(i);te.useEffect(()=>{e.current=i},[i]);let t=ZT(n=>{for(let r of e.current)r!=null&&(typeof r=="function"?r(n):r.current=n)});return i.every(n=>n==null||n?.[dK])?void 0:t}let aD=te.createContext(null);aD.displayName="DescriptionContext";function MI(){let i=te.useContext(aD);if(i===null){let e=new Error("You used a <Description /> component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(e,MI),e}return i}function hK(){var i,e;return(e=(i=te.useContext(aD))==null?void 0:i.value)!=null?e:void 0}let pK="p";function mK(i,e){let t=te.useId(),n=JT(),{id:r=`headlessui-description-${t}`,...o}=i,c=MI(),u=TI(e);iD(()=>c.register(r),[r,c.register]);let h=KT({...c.slot,disabled:n||!1}),m={ref:u,...c.props,id:r};return QT()({ourProps:m,theirProps:o,slot:h,defaultTag:pK,name:c.name||"Description"})}let gK=tM(mK);Object.assign(gK,{});let sD=te.createContext(null);sD.displayName="LabelContext";function wI(){let i=te.useContext(sD);if(i===null){let e=new Error("You used a <Label /> component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(e,wI),e}return i}function vK(i){var e,t,n;let r=(t=(e=te.useContext(sD))==null?void 0:e.value)!=null?t:void 0;return((n=void 0)!=null?n:0)>0?[r,...i].filter(Boolean).join(" "):r}let yK="label";function _K(i,e){var t;let n=te.useId(),r=wI(),o=bI(),c=JT(),{id:u=`headlessui-label-${n}`,htmlFor:h=o??((t=r.props)==null?void 0:t.htmlFor),passive:m=!1,..._}=i,p=TI(e);iD(()=>r.register(u),[u,r.register]);let y=ZT(M=>{let w=M.currentTarget;if(!(M.target!==M.currentTarget&&fK(M.target))&&(EI(w)&&M.preventDefault(),r.props&&"onClick"in r.props&&typeof r.props.onClick=="function"&&r.props.onClick(M),EI(w))){let A=document.getElementById(w.htmlFor);if(A){let L=A.getAttribute("disabled");if(L==="true"||L==="")return;let N=A.getAttribute("aria-disabled");if(N==="true"||N==="")return;(uK(A)&&(A.type==="file"||A.type==="radio"||A.type==="checkbox")||A.role==="radio"||A.role==="checkbox"||A.role==="switch")&&A.click(),A.focus({preventScroll:!0})}}}),x=KT({...r.slot,disabled:c||!1}),T={ref:p,...r.props,id:u,htmlFor:h,onClick:y};return m&&("onClick"in T&&(delete T.htmlFor,delete T.onClick),"onClick"in _&&delete _.onClick),QT()({ourProps:T,theirProps:_,slot:x,defaultTag:h?yK:"div",name:r.name||"Label"})}let bK=tM(_K);Object.assign(bK,{});let xK="textarea";function SK(i,e){let t=te.useId(),n=bI(),r=JT(),{id:o=n||`headlessui-textarea-${t}`,disabled:c=r||!1,autoFocus:u=!1,invalid:h=!1,...m}=i,_=vK(),p=hK(),{isFocused:y,focusProps:x}=hI({autoFocus:u}),{isHovered:T,hoverProps:M}=dI({isDisabled:c}),w=_I({ref:e,id:o,"aria-labelledby":_,"aria-describedby":p,"aria-invalid":h?"true":void 0,disabled:c||void 0,autoFocus:u},x,M),A=KT({disabled:c,invalid:h,hover:T,focus:y,autofocus:u});return QT()({ourProps:w,theirProps:m,slot:A,defaultTag:xK,name:"Textarea"})}let EK=tM(SK);const TK=i=>te.createElement("svg",{width:16,height:16,viewBox:"0 0 16 16",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...i},te.createElement("path",{d:"M8 1.25C6.66498 1.25 5.35994 1.64588 4.2499 2.38758C3.13987 3.12928 2.27471 4.18349 1.76382 5.41689C1.25292 6.65029 1.11925 8.00749 1.3797 9.31686C1.64015 10.6262 2.28303 11.829 3.22703 12.773C4.17104 13.717 5.37377 14.3598 6.68314 14.6203C7.99252 14.8808 9.34971 14.7471 10.5831 14.2362C11.8165 13.7253 12.8707 12.8601 13.6124 11.7501C14.3541 10.6401 14.75 9.33502 14.75 8C14.748 6.2104 14.0362 4.49466 12.7708 3.22922C11.5053 1.96378 9.78961 1.25199 8 1.25ZM8 13.25C6.96165 13.25 5.94662 12.9421 5.08326 12.3652C4.2199 11.7883 3.547 10.9684 3.14964 10.0091C2.75228 9.04978 2.64831 7.99418 2.85088 6.97578C3.05345 5.95738 3.55347 5.02191 4.28769 4.28769C5.02192 3.55346 5.95738 3.05345 6.97578 2.85088C7.99418 2.6483 9.04978 2.75227 10.0091 3.14963C10.9684 3.54699 11.7883 4.2199 12.3652 5.08326C12.9421 5.94661 13.25 6.96165 13.25 8C13.2485 9.39193 12.6949 10.7264 11.7107 11.7107C10.7264 12.6949 9.39193 13.2485 8 13.25ZM7.25 8.25V5C7.25 4.80109 7.32902 4.61032 7.46967 4.46967C7.61032 4.32902 7.80109 4.25 8 4.25C8.19892 4.25 8.38968 4.32902 8.53033 4.46967C8.67098 4.61032 8.75 4.80109 8.75 5V8.25C8.75 8.44891 8.67098 8.63968 8.53033 8.78033C8.38968 8.92098 8.19892 9 8 9C7.80109 9 7.61032 8.92098 7.46967 8.78033C7.32902 8.63968 7.25 8.44891 7.25 8.25ZM9 10.75C9 10.9478 8.94135 11.1411 8.83147 11.3056C8.72159 11.47 8.56541 11.5982 8.38269 11.6739C8.19996 11.7496 7.99889 11.7694 7.80491 11.7308C7.61093 11.6922 7.43275 11.597 7.2929 11.4571C7.15304 11.3173 7.0578 11.1391 7.01922 10.9451C6.98063 10.7511 7.00044 10.55 7.07612 10.3673C7.15181 10.1846 7.27998 10.0284 7.44443 9.91853C7.60888 9.80865 7.80222 9.75 8 9.75C8.26522 9.75 8.51957 9.85536 8.70711 10.0429C8.89465 10.2304 9 10.4848 9 10.75Z",fill:"currentColor"}));function AI({message:i,className:e,...t}){return qe.jsxs("div",{...t,className:Ao("message flex h-fit min-h-9 w-fit max-w-70 flex-row items-center justify-center gap-1 bg-black",e),children:[qe.jsx(TK,{}),qe.jsx("span",{children:i})]})}let iM=()=>({emit(i,...e){for(let t=this.events[i]||[],n=0,r=t.length;n<r;n++)t[n](...e)},events:{},on(i,e){return(this.events[i]||=[]).push(e),()=>{this.events[i]=this.events[i]?.filter(t=>e!==t)}}});class r1 extends Error{constructor(e,t){e instanceof Error?(super(e.message),this.cause=e):super(e),this.reason=t,this.name="ReasonError"}}class CI extends r1{constructor(e){super("Rejected",e),this.name="SubscriptionRejectedError"}}class MK extends r1{constructor(e){super(e||"Timed out to receive subscription ack"),this.name="SubscriptionTimeoutError"}}class yc extends r1{constructor(e,t){t?super(e,t):super("Disconnected",e),this.name="DisconnectedError"}}class wK extends yc{constructor(e){super(e,"stale_connection"),this.name="StaleConnectionError"}}function RI(i){return i?`{${Object.keys(i).sort().filter(t=>i[t]!==void 0).map(t=>{let n=JSON.stringify(i[t]);return`${JSON.stringify(t)}:${n}`}).join(",")}}`:""}class AK{constructor(e){this.channel=e,this.listeners=[]}watch(){this.listeners.push(this.channel.on("presence",e=>{if(e.type==="info"){this._state||(this._state=this.stateFromInfo(e));return}this._state&&(e.type==="join"?this._state[e.id]=e.info:e.type==="leave"&&delete this._state[e.id])}))}reset(){delete this._state}dispose(){delete this._info,delete this._state,this.listeners.forEach(e=>e()),this.listeners.length=0}async join(e,t){if(!this._info)return this._info={id:e,info:t},this.channel.perform("$presence:join",this._info)}async leave(){if(!this._info)return;let e=await this.channel.perform("$presence:leave");return delete this._info,e}async info(){return this._state?this._state:(this._promise||(this._promise=this._sync()),await this._promise,this._state)}async _sync(){this.watch();try{let e=await this.channel.perform("$presence:info",{});return this._state=this.stateFromInfo(e),this._state}finally{delete this._promise}}stateFromInfo(e){return e.records.reduce((t,{id:n,info:r})=>(t[n]=r,t),{})}}const Dm=Symbol("state");class oD{constructor(e={}){this.emitter=iM(),this.params=Object.freeze(e),this.presence=new AK(this),this.initialConnect=!0,this[Dm]="idle"}get identifier(){return this._identifier?this._identifier:(this._identifier=RI({channel:this.channelId,...this.params}),this._identifier)}get channelId(){return this.constructor.identifier}get state(){return this[Dm]}attached(e){if(this.receiver){if(this.receiver!==e)throw Error("Already connected to a different receiver");return!1}return this.receiver=e,!0}connecting(){this[Dm]="connecting"}connected(){if(this.state==="connected"||this.state==="closed")return;this[Dm]="connected";let e=!1;this.initialConnect?(this.initialConnect=!1,this.emit("connect",{reconnect:!1,restored:e})):this.emit("connect",{reconnect:!0,restored:e})}restored(){if(this.state==="connected")throw Error("Already connected");this[Dm]="connected";let e=!0,t=!0;this.initialConnect=!1,this.emit("connect",{reconnect:t,restored:e})}disconnected(e){this.state==="disconnected"||this.state==="closed"||(this[Dm]="disconnected",this.presence.reset(),this.emit("disconnect",e))}closed(e){this.state!=="closed"&&(this[Dm]="closed",delete this.receiver,this.initialConnect=!0,this.presence.dispose(),this.emit("close",e))}disconnect(){this.state==="idle"||this.state==="closed"||this.receiver.unsubscribe(this)}async perform(e,t){if(this.state==="idle"||this.state==="closed")throw Error("Channel is not subscribed");return this.receiver.perform(this.identifier,e,t)}async send(e){return this.perform(void 0,e)}async whisper(e){try{await this.perform("$whisper",e)}catch(t){let n=this.receiver?this.receiver.logger:null;n&&n.warn("whisper failed: ",t)}}receive(e,t){this.emit("message",e,t)}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...r)=>{n(),t(...r)});return n}emit(e,...t){return this.emitter.emit(e,...t)}ensureSubscribed(){return this.state==="connected"?Promise.resolve():this.state==="closed"?Promise.reject(Error("Channel is unsubscribed")):this.pendingSubscribe()}pendingSubscribe(){return this._pendingSubscribe?this._pendingSubscribe:(this._pendingSubscribe=new Promise((e,t)=>{let n=[()=>delete this._pendingSubscribe];n.push(this.on("connect",()=>{n.forEach(r=>r()),e()})),n.push(this.on("close",r=>{n.forEach(o=>o()),t(r||new r1("Channel was disconnected before subscribing","canceled"))}))}),this._pendingSubscribe)}}class CK{constructor(e){this.id=e,this.intent="unsubscribed",this.state="idle",this.channels=[],this.disposed=!1,this._pendings=[]}add(e){this.channels.includes(e)||this.channels.push(e)}remove(e){let t=this.channels.indexOf(e);t>-1&&this.channels.splice(t,1)}notify(e,...t){this.state=e==="restored"?"connected":e,t.length===1?this.channels.forEach(n=>n[e](t[0])):this.channels.forEach(n=>n[e]())}pending(e){this._checkIntent(e);let t=this._pendings[0];return!t||t.intent!==e?Promise.resolve():t.promise}ensureResubscribed(){this.disposed||(this.intent=void 0,this.ensureSubscribed())}ensureSubscribed(){if(this.intent==="subscribed")return;if(this.disposed)throw Error("Subscription is disposed");this.intent="subscribed",!this._mergeWithPending("unsubscribed")&&this.subscriber(this)}maybeUnsubscribe(){this.disposed||this.intent==="unsubscribed"||this.channels.length>0||(this.intent="unsubscribed",this._mergeWithPending("subscribed"))||this.unsubscriber(this)}async acquire(e){this._checkIntent(e);let t,r={promise:new Promise(c=>{t=c}),intent:e,release:()=>{this._pendings.splice(this._pendings.indexOf(r),1),t(r)},canceled:!1,acquired:!1},o=this._pendingTop;return this._pendings.push(r),o&&await o.promise,this.gvl&&await this.gvl.acquire(r,e),r.acquired=!0,r}close(e){this.disposed=!0,this.intent=void 0,this.notify("closed",e)}_checkIntent(e){if(!(e==="unsubscribed"||e==="subscribed"))throw Error(`Unknown subscription intent: ${e}`)}get _pendingTop(){return this._pendings.length?this._pendings[this._pendings.length-1]:void 0}_mergeWithPending(e){let t=this._pendingTop;return!t||t.acquired||t.intent!==e?!1:(this._pendings.pop(),t.canceled=!0,!0)}}class RK{constructor(){this.queue=[]}async acquire(e,t){t==="subscribed"&&(this.queue.push(e.promise.then(()=>{this.queue.splice(this.queue.indexOf(e),1)})),this.queue.length>1&&await this.queue[this.queue.length-2])}}class DK{constructor(e){e.concurrentSubscribes===!1&&(this.glv=new RK),this._subscriptions={},this._localToRemote={}}all(){return Object.values(this._subscriptions)}get(e){return this._subscriptions[e]}create(e,{subscribe:t,unsubscribe:n}){let r=this._subscriptions[e]=new CK(e);return r.remoteId=this._localToRemote[e],r.subscriber=t,r.unsubscriber=n,r.gvl=this.glv,r}remove(e){delete this._subscriptions[e],delete this._localToRemote[e]}storeRemoteId(e,t){this._localToRemote[e]=t;let n=this.get(e);n&&(n.remoteId=t)}}class OK{constructor(e={}){this.subscriptions=new DK(e),this._pendingMessages=[],this._remoteToLocal={}}subscribe(e,t){this._remoteToLocal[t]=e,this.subscriptions.storeRemoteId(e,t),this.flush(t)}unsubscribe(e){let t=this.subscriptions.get(e);if(!t)return;let n=t.remoteId;n&&delete this._remoteToLocal[n],this.subscriptions.remove(e)}transmit(e,t,n){let r=this._remoteToLocal[e];if(!r){this._pendingMessages.push([e,t,n]);return}let o=this.subscriptions.get(r);o&&o.channels.forEach(c=>{c.receive(t,n)})}notify(e,t,n){let r=this._remoteToLocal[e];if(!r)return;let o=this.subscriptions.get(r);o&&o.channels.forEach(c=>c.emit(t,n))}close(){this._pendingMessages.length=0}get size(){return this.channels.length}get channels(){return this.subscriptions.all().flatMap(e=>e.channels)}flush(e){let t=[];for(let n of this._pendingMessages)n[0]===e?this.transmit(n[0],n[1],n[2]):t.push(n);this._pendingMessages=t}}const DI={debug:0,info:1,warn:2,error:3};class OI{constructor(e){this.level=e||"warn"}log(e,t,n){DI[e]<DI[this.level]||this.writeLogEntry(e,t,n)}writeLogEntry(){throw Error("Not implemented")}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}}class a1 extends OI{writeLogEntry(){}}class LK{encode(e){return JSON.stringify(e)}decode(e){try{return JSON.parse(e)}catch{}}}let NK=0;class LI{constructor(e={}){let{logger:t}=e;this.logger=t||new a1,this.pendingSubscriptions={},this.pendingUnsubscriptions={},this.subscribeCooldownInterval=e.subscribeCooldownInterval||250,this.subscribeRetryInterval=e.subscribeRetryInterval||5e3}attached(e){this.cable=e}subscribe(e,t){let n={channel:e};t&&Object.assign(n,t);let r=RI(n);if(this.pendingUnsubscriptions[r]){let c=this.subscribeCooldownInterval*1.5;return this.logger.debug(`unsubscribed recently, cooldown for ${c}`,r),new Promise(u=>{setTimeout(()=>{u(this.subscribe(e,t))},c)})}if(this.pendingSubscriptions[r])return this.logger.warn("subscription is already pending, skipping",r),Promise.reject(Error("Already subscribing"));let o=this.subscribeRetryInterval;return new Promise((c,u)=>{let h=++NK;this.pendingSubscriptions[r]={resolve:c,reject:u,id:h},this.cable.send(this.buildSubscribeRequest(r)),this.maybeRetrySubscribe(h,r,o)})}buildSubscribeRequest(e){return{command:"subscribe",identifier:e}}maybeRetrySubscribe(e,t,n){setTimeout(()=>{let r=this.pendingSubscriptions[t];r&&r.id===e&&(this.logger.warn(`no subscription ack received in ${n}ms, retrying subscribe`,t),this.cable.send(this.buildSubscribeRequest(t)),this.maybeExpireSubscribe(e,t,n))},n)}maybeExpireSubscribe(e,t,n){setTimeout(()=>{let r=this.pendingSubscriptions[t];r&&r.id===e&&(delete this.pendingSubscriptions[t],r.reject(new MK(`Haven't received subscription ack in ${n*2}ms for ${t}`)))},n)}unsubscribe(e){return this.cable.send({command:"unsubscribe",identifier:e}),this.pendingUnsubscriptions[e]=!0,setTimeout(()=>{delete this.pendingUnsubscriptions[e]},this.subscribeCooldownInterval),Promise.resolve()}perform(e,t,n){return t==="$whisper"?this.whisper(e,n):(n||(n={}),n.action||=t,this.cable.send({command:"message",identifier:e,data:JSON.stringify(n)}),Promise.resolve())}whisper(e,t){return this.cable.send({command:"whisper",identifier:e,data:t}),Promise.resolve()}receive(e){if(typeof e!="object"){this.logger.error("unsupported message format",{message:e});return}let{type:t,identifier:n,message:r,reason:o,reconnect:c}=e;if(t==="ping")return this.cable.keepalive(e.message);if(this.cable.keepalive(),t==="welcome"){let u=e.sid;return u&&this.cable.setSessionId(u),this.cable.connected()}if(t==="disconnect"){let u=new yc(o);this.reset(u),c===!1?this.cable.closed(u):this.cable.disconnected(u);return}if(t==="confirm_subscription"){let u=this.pendingSubscriptions[n];if(!u){this.logger.error("subscription not found, unsubscribing",{type:t,identifier:n}),this.unsubscribe(n);return}return delete this.pendingSubscriptions[n],u.resolve(n)}if(t==="reject_subscription"){let u=this.pendingSubscriptions[n];return u?(delete this.pendingSubscriptions[n],u.reject(new CI)):this.logger.error("subscription not found",{type:t,identifier:n})}if(r)return{identifier:n,message:r};this.logger.warn(`unknown message type: ${t}`,{message:e})}reset(e){for(let t in this.pendingSubscriptions)this.pendingSubscriptions[t].reject(e);this.pendingSubscriptions={}}recoverableClosure(){return!1}}const NI=()=>Date.now()/1e3|0;class kK extends LI{constructor(e={}){super(e),this.streamsPositions={},this.subscriptionStreams={},this.pendingHistory={},this.pendingPresence={},this.presenceInfo={},this.restoreSince=e.historyTimestamp,this.disableSessionRecovery=e.disableSessionRecovery,this.restoreSince===void 0&&(this.restoreSince=NI()),this.sessionId=void 0,this.sendPongs=e.pongs}reset(e){for(let t in this.pendingPresence)this.pendingPresence[t].reject(e);return this.pendingPresence={},super.reset()}receive(e){if(typeof e!="object"){this.logger.error("unsupported message format",{message:e});return}let{type:t,identifier:n,message:r}=e;if(t==="disconnect")return delete this.sessionId,this.cable.setSessionId(""),super.receive(e);if(t==="reject_subscription")return super.receive(e);if(t==="confirm_subscription")return this.subscriptionStreams[n]||(this.subscriptionStreams[n]=new Set),super.receive(e);if(t==="ping")return this.restoreSince&&(this.restoreSince=NI()),this.sendPongs&&this.sendPong(),this.cable.keepalive(e.message);if(this.cable.keepalive(),t==="confirm_history"){this.logger.debug("history result received",e),this.cable.notify("history_received",n);return}if(t==="reject_history"){this.logger.warn("failed to retrieve history",e),this.cable.notify("history_not_found",n);return}if(t==="welcome"){if(this.disableSessionRecovery||(this.sessionId=e.sid,this.sessionId&&this.cable.setSessionId(this.sessionId)),e.restored){let o=e.restored_ids||Object.keys(this.subscriptionStreams);for(let c of o)this.cable.send({identifier:c,command:"history",history:this.historyRequestFor(c)}),this.presenceInfo[c]&&this.cable.send({identifier:c,command:"join",presence:this.presenceInfo[c]});return this.cable.restored(o)}return this.cable.connected(this.sessionId)}if(t==="presence"){let o=r.type;if(o==="info"){let c=this.pendingPresence[n];c&&(delete this.pendingPresence[n],c.resolve(r))}else if(o==="error"){let c=this.pendingPresence[n];c&&(delete this.pendingPresence[n],c.reject(new Error("failed to retrieve presence")))}return{type:t,identifier:n,message:r}}if(r){let o=this.trackStreamPosition(n,e.stream_id,e.epoch,e.offset);return{identifier:n,message:r,meta:o}}this.logger.warn(`unknown message type: ${t}`,{message:e})}perform(e,t,n){switch(t){case"$presence:join":return this.join(e,n);case"$presence:leave":return this.leave(e,n);case"$presence:info":return this.presence(e,n)}return super.perform(e,t,n)}unsubscribe(e){return delete this.presenceInfo[e],super.unsubscribe(e)}buildSubscribeRequest(e){let t=super.buildSubscribeRequest(e),n=this.historyRequestFor(e);n&&(t.history=n,this.pendingHistory[e]=!0);let r=this.presenceInfo[e];return r&&(t.presence=r),t}recoverableClosure(){return!!this.sessionId}historyRequestFor(e){let t={},n=!1;if(this.subscriptionStreams[e])for(let r of this.subscriptionStreams[e]){let o=this.streamsPositions[r];o&&(n=!0,t[r]=o)}if(!(!n&&!this.restoreSince))return{since:this.restoreSince,streams:t}}trackStreamPosition(e,t,n,r){if(!(!t||!n))return this.subscriptionStreams[e]||(this.subscriptionStreams[e]=new Set),this.subscriptionStreams[e].add(t),this.streamsPositions[t]={epoch:n,offset:r},{stream:t,epoch:n,offset:r}}async sendPong(){await new Promise(e=>setTimeout(e,0)),this.cable.state==="connected"&&this.cable.send({command:"pong"})}async join(e,t){return this.presenceInfo[e]=t,this.cable.send({command:"join",identifier:e,presence:t}),Promise.resolve()}async leave(e,t){return delete this.presenceInfo[e],this.cable.send({command:"leave",identifier:e,presence:t}),Promise.resolve()}presence(e,t){return this.pendingPresence[e]?(this.logger.warn("presence is already pending, skipping",e),Promise.reject(Error("presence request is already pending"))):new Promise((n,r)=>{this.pendingPresence[e]={resolve:n,reject:r},this.cable.send({command:"presence",identifier:e,data:t})})}}class UK extends r1{constructor(){super("No connection","closed"),this.name="NoConnectionError"}}class IK extends oD{static identifier="__ghost__";constructor(e,t){super(t),this.channelId=e}set channelId(e){this._channelId=e}get channelId(){return this._channelId}}const zK="$pubsub";class kI extends oD{static identifier=zK;async perform(e,t){if(e.startsWith("$"))return super.perform(e,t);throw Error("not implemented")}}const Om=Symbol("state");class BK{constructor({transport:e,protocol:t,encoder:n,logger:r,lazy:o,hubOptions:c,performFailures:u,transportConfigurator:h}){this.emitter=iM(),this.transport=e,this.encoder=n,this.logger=r||new a1,this.protocol=t,this.performFailures=u||"throw",this.protocol.attached(this),this.hub=new OK(c||{}),this[Om]="idle",this.handleClose=this.handleClose.bind(this),this.handleIncoming=this.handleIncoming.bind(this),this.transportConfigurator=h,this.transport.on("close",this.handleClose),this.transport.on("data",this.handleIncoming),this.initialConnect=!0,this.recovering=!1,o===!1&&this.connect().catch(()=>{})}get state(){return this[Om]}async connect(){if(this.state==="connected")return Promise.resolve();if(this.state==="connecting")return this.pendingConnect();let e=this.state==="idle";this[Om]="connecting";let t=this.pendingConnect();this.logger.debug("connecting");try{this.transportConfigurator&&await this.transportConfigurator(this.transport,{initial:e}),await this.transport.open()}catch(n){this.handleClose(n)}return t}setSessionId(e){this.sessionId=e,this.transport.setParam("sid",e)}connected(){if(this.state==="connected")return;this.logger.info("connected"),this[Om]="connected",this.recovering&&this.hub.subscriptions.all().forEach(t=>t.notify("disconnected",new yc("recovery_failed"))),this.hub.subscriptions.all().forEach(t=>this._resubscribe(t));let e=!1;this.recovering=!1,this.initialConnect?(this.initialConnect=!1,this.emit("connect",{reconnect:!1,restored:e})):this.emit("connect",{reconnect:!0,restored:e})}restored(e){this.logger.info("connection recovered",{remoteIds:e}),this[Om]="connected",this.hub.subscriptions.all().forEach(r=>{e&&r.remoteId&&e.includes(r.remoteId)?r.notify("restored"):(r.notify("disconnected",new yc("recovery_failed")),this._resubscribe(r))});let t=!this.initialConnect,n=!0;this.recovering=!1,this.initialConnect=!1,this.emit("connect",{reconnect:t,restored:n})}notify(e,t,n){t&&typeof t!="string"&&(n=t,t=void 0),t?this.hub.notify(t,"info",{type:e,data:n}):this.emit("info",{type:e,data:n})}handleClose(e){this.logger.debug("transport closed",{error:e}),this.disconnected(new yc(e,"transport_closed"))}disconnected(e){(this.state==="connected"||this.state==="connecting")&&(this.logger.info("disconnected",{reason:e}),this[Om]="disconnected",this.recovering=this.protocol.recoverableClosure(e),this.recovering?this.hub.subscriptions.all().forEach(t=>t.notify("connecting")):this.hub.subscriptions.all().forEach(t=>{t.notify("disconnected",e)}),this.protocol.reset(e),this.hub.close(),this.transport.close(),this.emit("disconnect",e))}closed(e){if(this.state==="closed"||this.state==="idle")return;let t;e&&(t=e instanceof yc?e:new yc(e,void 0)),this.logger.info("closed",{reason:e||"user"}),this[Om]="closed";let n=t||new yc("cable_closed");this.hub.subscriptions.all().forEach(r=>r.notify("disconnected",n)),this.hub.close(),this.protocol.reset(),this.transport.close(),this.initialConnect=!0,this.emit("close",t)}disconnect(){this.closed()}handleIncoming(e){if(this.state==="closed"||this.state==="idle")return;let t=this.encoder.decode(e);if(t===void 0){this.logger.error("failed to decode message",{message:e});return}this.logger.debug("incoming data",t);let n=this.protocol.receive(t);if(n){this.logger.debug("processed incoming message",n);let{type:r,identifier:o,message:c,meta:u}=n;r?this.hub.notify(o,r,c):this.hub.transmit(o,c,u)}}send(e){if(this.state==="closed")throw Error("Cable is closed");let t=this.encoder.encode(e);if(t===void 0){this.logger.error("failed to encode message",{message:e});return}this.logger.debug("outgoing message",e),this.transport.send(t)}keepalive(e){this.emit("keepalive",e)}streamFrom(e){let t=new kI({stream_name:e});return this.subscribe(t)}streamFromSigned(e){let t=new kI({signed_stream_name:e});return this.subscribe(t)}subscribeTo(e,t){let n,r;return typeof e=="string"&&(r=e,e=IK),n=r?new e(r,t):new e(t),this.subscribe(n)}subscribe(e){if(!e.attached(this))return e;let t=e.identifier;e.connecting();let n=this.hub.subscriptions.get(t)||this.hub.subscriptions.create(t,{subscribe:r=>this._subscribe(r,e.channelId,e.params),unsubscribe:r=>this._unsubscribe(r)});return n.add(e),n.intent==="subscribed"&&n.state==="connected"&&e.connected(),n.ensureSubscribed(),e}async _resubscribe(e){e.intent!=="subscribed"||!e.channels[0]||(e.notify("connecting"),e.ensureResubscribed())}async _subscribe(e,t,n){let r=e.id;if(this.state==="idle"&&this.connect().catch(()=>{}),this.state!=="connected"){this.logger.debug("cancel subscribe, no connection",{identifier:r});return}this.logger.debug("acquiring subscribe lock",{identifier:r});let o=await e.acquire("subscribed");if(o.canceled){this.logger.debug("subscribe lock has been canceled",{identifier:r}),o.release();return}if(this.logger.debug("subscribe lock has been acquired",{identifier:r}),e.intent!=="subscribed"){this.logger.debug("cancel subscribe request, already unsubscribed"),o.release();return}if(this.state!=="connected"){this.logger.debug("cancel subscribe, no connection",{identifier:r}),o.release();return}if(e.state==="connected"){this.logger.debug("already connected, skip subscribe command",{identifier:r}),e.notify("connected"),o.release();return}let c={identifier:t,params:n};this.logger.debug("subscribing",c);try{let u=await this.protocol.subscribe(t,n);this.hub.subscribe(r,u),this.logger.debug("subscribed",{...c,remoteId:u}),e.notify("connected")}catch(u){if(u){if(u instanceof CI&&this.logger.warn("rejected",c),u instanceof yc){this.logger.debug("disconnected during subscription; will retry on connect",c),o.release();return}this.logger.error("failed to subscribe",{error:u,...c})}e.close(u),this.hub.unsubscribe(r)}o.release()}unsubscribe(e){let t=e.identifier,n=this.hub.subscriptions.get(t);if(!n)throw Error(`Subscription not found: ${t}`);n.remove(e),e.closed(),n.maybeUnsubscribe()}async _unsubscribe(e){let t=e.id;this.logger.debug("acquiring unsubscribe lock",{identifier:t});let n=await e.acquire("unsubscribed");if(n.canceled){this.logger.debug("unsubscribe lock has been canceled",{identifier:t}),n.release();return}if(this.logger.debug("unsubscribe lock has been acquired",{identifier:t}),e.intent!=="unsubscribed"){this.logger.debug("cancel unsubscribe, no longer needed",{identifier:t,intent:e.intent}),n.release();return}if(e.state==="disconnected"||e.state==="closed"){this.logger.debug(`already ${e.state} connected, skip unsubscribe command`,{identifier:t}),n.release();return}let r=e.remoteId;if(this.logger.debug("unsubscribing...",{remoteId:r}),this.state!=="connected"){this.logger.debug("unsubscribe skipped (cable is not connected)",{id:t}),e.close(),this.hub.unsubscribe(t),n.release();return}try{await this.protocol.unsubscribe(r),this.logger.debug("unsubscribed remotely",{id:t})}catch(o){o&&(o instanceof yc?this.logger.debug("cable disconnected during the unsubscribe command execution",{id:t,error:o}):this.logger.error("unsubscribe failed",{id:t,error:o}))}e.intent==="unsubscribed"?(e.close(),this.hub.unsubscribe(t)):e.state="closed",n.release()}async perform(e,t,n){if(this.performFailures==="throw")return this._perform(e,t,n);try{return await this._perform(e,t,n)}catch(r){this.performFailures==="warn"&&this.logger.warn("perform failed",{error:r});return}}async _perform(e,t,n){if(this.state==="connecting"&&await this.pendingConnect(),this.state==="closed"||this.state==="disconnected")throw new UK;let r=this.hub.subscriptions.get(e);if(!r)throw Error(`Subscription not found: ${e}`);if(await r.pending("subscribed"),r.intent!=="subscribed")throw Error(`Subscription is closed: ${e}`);let o=r.remoteId,c={id:o,action:t,payload:n};this.logger.debug("perform",c);try{let u=await this.protocol.perform(o,t,n);return u&&this.logger.debug("perform result",{message:u,request:c}),u}catch(u){throw this.logger.error("perform failed",{error:u,request:c}),u}}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...r)=>{n(),t(...r)});return n}emit(e,...t){return this.emitter.emit(e,...t)}pendingConnect(){return this._pendingConnect?this._pendingConnect:(this._pendingConnect=new Promise((e,t)=>{let n=[()=>delete this._pendingConnect];n.push(this.on("connect",()=>{n.forEach(r=>r()),e()})),n.push(this.on("close",r=>{n.forEach(o=>o()),t(r)})),n.push(this.on("disconnect",r=>{n.forEach(o=>o()),t(r)}))}),this._pendingConnect)}}const PK={maxMissingPings:2,maxReconnectAttempts:1/0},Nv=()=>Date.now(),UI=(i,e)=>{e=e||{};let{backoffRate:t,jitterRatio:n,maxInterval:r}=e;return t=t||2,n===void 0&&(n=.5),o=>{let c=i*t**o,u=c*t,h=c+(u-c)*Math.random(),m=2*(Math.random()-.5)*n;return h=h*(1+m),r&&r<h&&(h=r),h}};let II=class{constructor({pingInterval:e,...t}){if(this.pingInterval=e,!this.pingInterval)throw Error(`Incorrect pingInterval is provided: ${e}`);if(t=Object.assign({},PK,t),this.strategy=t.reconnectStrategy,!this.strategy)throw Error("Reconnect strategy must be provided");this.maxMissingPings=t.maxMissingPings,this.maxReconnectAttempts=t.maxReconnectAttempts,this.logger=t.logger||new a1,this.state="pending_connect",this.attempts=0,this.disconnectedAt=Nv()}watch(e){this.target=e,this.initListeners()}reconnectNow(){return this.state==="connected"||this.state==="pending_connect"||this.state==="closed"?!1:(this.cancelReconnect(),this.state="pending_connect",this.target.connect().catch(e=>{this.logger.info("Failed at reconnecting: "+e)}),!0)}initListeners(){this.unbind=[],this.unbind.push(this.target.on("connect",()=>{this.attempts=0,this.pingedAt=Nv(),this.state="connected",this.cancelReconnect(),this.startPolling()})),this.unbind.push(this.target.on("disconnect",()=>{this.disconnectedAt=Nv(),this.state="disconnected",this.stopPolling(),this.scheduleReconnect()})),this.unbind.push(this.target.on("close",()=>{this.disconnectedAt=Nv(),this.state="closed",this.cancelReconnect(),this.stopPolling()})),this.unbind.push(this.target.on("keepalive",()=>{this.pingedAt=Nv()})),this.unbind.push(()=>{this.cancelReconnect(),this.stopPolling()})}dispose(){delete this.target,this.unbind&&this.unbind.forEach(e=>e()),delete this.unbind}startPolling(){this.pollId&&clearTimeout(this.pollId);let e=this.pingInterval+(Math.random()-.5)*this.pingInterval*.5;this.pollId=setTimeout(()=>{this.checkStale(),this.state==="connected"&&this.startPolling()},e)}stopPolling(){this.pollId&&clearTimeout(this.pollId)}checkStale(){let e=Nv()-this.pingedAt;e>this.maxMissingPings*this.pingInterval&&(this.logger.warn(`Stale connection: ${e}ms without pings`),this.state="pending_disconnect",this.target.disconnected(new wK))}scheduleReconnect(){if(this.attempts>=this.maxReconnectAttempts){this.target.close();return}let e=this.strategy(this.attempts);this.attempts++,this.logger.info(`Reconnecting in ${e}ms (${this.attempts} attempt)`),this.state="pending_reconnect",this.reconnnectId=setTimeout(()=>this.reconnectNow(),e)}cancelReconnect(){this.reconnnectId&&(clearTimeout(this.reconnnectId),delete this.reconnnectId)}};class FK{constructor(e,t={}){this.transports=e,this.transport=null,this.emitter=iM(),this.unbind=[],this.logger=t.logger||new a1}displayName(){return"fallbacked transport"}async open(){for(let e=0;e<this.transports.length;e++){let t=this.transports[e];try{this.transport=t,this.resetListeners(),this.logger.debug(`Trying to connect via ${t.displayName()}`),await t.open(),this.logger.debug(`Connected via ${t.displayName()}`);return}catch(n){this.logger.debug(`Failed to connect via ${t.displayName()}: ${n.message}`)}}throw this.transport=null,this.resetListeners(),new Error("Couldn't connect via any available transport")}send(e){if(!this.transport)throw new Error("No transport is open");this.transport.send(e)}async close(){if(!this.transport)throw new Error("No transport is open");await this.transport.close(),this.transport=null}setURL(){throw new Error("Not implemented. Set URL for each transport separately")}setParam(e,t){this.transports.forEach(n=>{n.setParam(e,t)})}setToken(e,t){this.transports.forEach(n=>{n.setToken(e,t)})}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...r)=>{n(),t(...r)});return n}get url(){return this.transport?this.transport.url:""}resetListeners(){this.unbind.forEach(e=>e()),this.unbind.length=0,this.transport&&this.unbind.push(this.transport.on("open",()=>{this.emitter.emit("open")}),this.transport.on("data",e=>{this.emitter.emit("data",e)}),this.transport.on("close",e=>{this.emitter.emit("close",e)}),this.transport.on("error",e=>{this.emitter.emit("error",e)}))}}class HK{constructor(e,t={}){this.url=e;let n=t.websocketImplementation;if(n)this.Impl=n;else if(typeof WebSocket<"u")this.Impl=WebSocket;else throw new Error("No WebSocket support");this.connected=!1,this.emitter=iM();let{format:r,subprotocol:o,authStrategy:c}=t;this.format=r||"text",this.connectionOptions=t.websocketOptions,this.authStrategy=c||"param",this.authProtocol="",this.subprotocol=o}displayName(){return"WebSocket("+this.url+")"}open(){let e=this.subprotocol;return this.authStrategy==="sub-protocol"&&(e=[this.subprotocol,this.authProtocol]),this.connectionOptions?this.ws=new this.Impl(this.url,e,this.connectionOptions):this.ws=new this.Impl(this.url,e),this.ws.binaryType="arraybuffer",this.initListeners(),new Promise((t,n)=>{let r=[];r.push(this.once("open",()=>{r.forEach(o=>o()),t()})),r.push(this.once("close",()=>{r.forEach(o=>o()),n(Error("WS connection closed"))}))})}setURL(e){this.url=e}setParam(e,t){let n=new URL(this.url);n.searchParams.set(e,t);let r=`${n.protocol}//${n.host}${n.pathname}?${n.searchParams}`;this.setURL(r)}setToken(e,t="jid"){if(this.authStrategy==="param")this.setParam(t,e);else if(this.authStrategy==="header"){this.connectionOptions=this.connectionOptions||{},this.connectionOptions.headers=this.connectionOptions.headers||{};let n=`x-${t}`.toLowerCase();n=Object.keys(this.connectionOptions.headers).find(o=>o.toLowerCase()===n)||n,this.connectionOptions.headers[n]=e}else if(this.authStrategy==="sub-protocol")this.authProtocol=`anycable-token.${e}`;else throw new Error("Unknown auth strategy: "+this.authStrategy)}send(e){if(!this.ws||!this.connected)throw Error("WebSocket is not connected");this.ws.send(e)}close(){this.ws?this.onclose():this.connected=!1}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...r)=>{n(),t(...r)});return n}initListeners(){this.ws.onerror=e=>{this.connected&&this.emitter.emit("error",e.error||new Error("WS Error"))},this.ws.onclose=()=>{this.onclose()},this.ws.onmessage=e=>{let t=e.data;this.format==="binary"&&(t=new Uint8Array(t)),this.emitter.emit("data",t)},this.ws.onopen=()=>{this.connected=!0,this.emitter.emit("open")}}onclose(){this.ws.onclose=void 0,this.ws.onmessage=void 0,this.ws.onopen=void 0,this.ws.close(),delete this.ws,this.connected=!1,this.emitter.emit("close")}}const zI={protocol:"actioncable-v1-json",pingInterval:3e3,maxReconnectAttempts:1/0,maxMissingPings:2,logLevel:"warn",lazy:!0};function VK(i,e){if(typeof i=="object"&&typeof e>"u"&&(e=i,i=void 0),e=e||{},!i&&!e.transport)throw Error("URL or transport must be specified");e=Object.assign({},zI,e);let{protocol:t,websocketImplementation:n,websocketFormat:r,websocketOptions:o,websocketAuthStrategy:c,fallbacks:u,logLevel:h,logger:m,transport:_,encoder:p,lazy:y,monitor:x,pingInterval:T,reconnectStrategy:M,maxMissingPings:w,maxReconnectAttempts:A,subprotocol:L,tokenRefresher:N,historyTimestamp:I,protocolOptions:z,concurrentSubscribes:P,performFailures:G,transportConfigurator:$,auth:U}=e;if(m=m||new a1(h),typeof t=="string"){L=L||t;let ne=t.substring(0,t.lastIndexOf("-")),ie=t.substring(t.lastIndexOf("-")+1);if(z=z||{},ne==="actioncable-v1")t=new LI({logger:m,...z});else if(ne==="actioncable-v1-ext")t=new kK({logger:m,historyTimestamp:I,...z});else throw Error(`Protocol is not supported yet: ${t}`);if(ie==="json")p=p||new LK,r=r||"text";else if(ie==="msgpack"){if(r="binary",!p)throw Error("Msgpack encoder must be specified explicitly. Use `@anycable/msgpack-encoder` package or build your own")}else if(ie==="protobuf"){if(r=r||"binary",!p)throw Error("Protobuf encoder must be specified explicitly. Use `@anycable/protobuf-encoder` package or build your own")}else throw Error(`Protocol is not supported yet: ${t}`)}if(!t)throw Error("Protocol must be specified");_=_||new HK(i,{websocketImplementation:n,websocketOptions:o,subprotocol:L,authStrategy:c,format:r}),u&&(_=new FK([_,...u],{logger:m})),U&&U.token&&_.setToken(U.token,U.param||"jid"),M=M||UI(T),x!==!1&&(x=x||new II({pingInterval:T,reconnectStrategy:M,maxMissingPings:w,maxReconnectAttempts:A,logger:m}));let H={concurrentSubscribes:P},J=new BK({protocol:t,transport:_,encoder:p,logger:m,lazy:y,hubOptions:H,performFailures:G,transportConfigurator:$});return x&&(x.watch(J),J.monitor=x),N&&GK(J,async()=>{try{await N(_)}catch(ne){return m.error("Failed to refresh authentication token: "+ne),!1}return J.connect().catch(()=>{}),!0}),J}function GK(i,e){let t=!1;i.on("connect",()=>t=!1),i.on("close",async n=>{if(n){if(t){i.logger.warn("Token auto-refresh is disabled",n);return}n.reason==="token_expired"&&(t=!0,await e())}})}let jK=class extends OI{writeLogEntry(e,t,n){n?console[e](t,n):console[e](t)}};class XK extends II{watch(e){super.watch(e),this.initActivityListeners()}initActivityListeners(){if(typeof document<"u"&&typeof window<"u"&&document.addEventListener&&window.addEventListener){let e=()=>{document.hidden||this.reconnectNow()&&this.logger.debug("Trigger reconnect due to visibility change")},t=r=>{this.reconnectNow()&&this.logger.debug("Trigger reconnect",{event:r})},n=()=>this.disconnect(new yc("page_frozen"));document.addEventListener("visibilitychange",e,!1),window.addEventListener("focus",t,!1),window.addEventListener("online",t,!1),window.addEventListener("resume",t,!1),window.addEventListener("freeze",n,!1),this.unbind.push(()=>{document.removeEventListener("visibilitychange",e,!1),window.removeEventListener("focus",t,!1),window.removeEventListener("online",t,!1),window.removeEventListener("resume",t,!1),window.removeEventListener("freeze",n,!1)})}}disconnect(e){this.state==="disconnected"||this.state==="closed"||(this.logger.info("Disconnecting",{reason:e.message}),this.cancelReconnect(),this.stopPolling(),this.state="pending_disconnect",this.target.disconnected(e))}}const qK=["cable","action-cable"],$K="/cable",rM=(i,e)=>{for(let t of qK){let n=i.head.querySelector(`meta[name='${t}-${e}']`);if(n)return n.getAttribute("content")}},BI=i=>i.match(/wss?:\/\//)?i:typeof window<"u"?`${window.location.protocol.replace("http","ws")}//${window.location.host}${i}`:i,YK=()=>{if(typeof document<"u"&&document.head){let i=rM(document,"url");if(i)return BI(i)}return BI($K)},WK=()=>{if(typeof document<"u"&&document.head){let i=rM(document,"history-timestamp");if(i)return i|0}},ZK=()=>{if(typeof document<"u"&&document.head)return rM(document,"token")},KK=()=>{if(typeof document<"u"&&document.head)return rM(document,"token-param")};function JK(i,e){typeof i=="object"&&typeof e>"u"&&(e=i,i=void 0),i=i||YK(),e=e||{},e.historyTimestamp||=WK();let t=ZK();if(t){let m=KK();e.auth=Object.assign({token:t,param:m},e.auth||{})}e=Object.assign({},zI,e);let{logLevel:n,logger:r,pingInterval:o,reconnectStrategy:c,maxMissingPings:u,maxReconnectAttempts:h}=e;return r=e.logger=e.logger||new jK(n),c=e.reconnectStrategy=e.reconnectStrategy||UI(o),e.monitor!==!1&&(e.monitor=e.monitor||new XK({pingInterval:o,reconnectStrategy:c,maxMissingPings:u,maxReconnectAttempts:h,logger:r})),VK(i,e)}class QK extends oD{static identifier="WidgetChatChannel"}const s1={debug:0,info:1,warn:2,error:3};class eJ{level;prefix;constructor(e="Widget",t="info"){this.prefix=`[${e}]`,this.level=s1[t]}debug(...e){this.level<=s1.debug&&console.debug(this.prefix,...e)}info(...e){this.level<=s1.info&&console.info(this.prefix,...e)}warn(...e){this.level<=s1.warn&&console.warn(this.prefix,...e)}error(...e){this.level<=s1.error&&console.error(this.prefix,...e)}}let tJ="warn";const Ei=new eJ("BridgeApp-Widget",tJ);window.addEventListener("error",i=>{console.error("Unhandled error",i.error)});class nJ{url;cable;channels={chat:new QK};constructor(e){this.url=e,this.register()}subscribe(e){return Ei.info("SUBSCRIBE","[AnyCableService] Subscribing to channel",e.identifier),this.cable?.subscribe(e),this}unsubscribe(e){return this.cable?.unsubscribe(e),this}register(){return Ei.info("[AnyCableService] Registering cable with status: ",this.cable?.state),this.cable||(Ei.info("[AnyCableService] Creating cable"),this.cable=JK(this.url,{pingInterval:3e3,protocol:"actioncable-v1-ext-json",protocolOptions:{pongs:!0,subscribeRetryInterval:3e4}})),this.cable.state!=="connecting"&&this.cable.state!=="connected"&&(Ei.info("[AnyCableService] Connecting cable, state: ",this.cable.state),this.cable.connect().then(()=>{Ei.info("[AnyCableService] Cable connected, subscribing to channel: ",this.channels.chat.identifier),this.cable.subscribe(this.channels.chat)})),this}unregister(){this.cable&&(Ei.info("[AnyCableService] Disconnecting cable"),this.cable.disconnect())}}var _c=(i=>(i.Pending="pending",i.Available="available",i.Offline="offline",i.Unavailable="unavailable",i))(_c||{});const PI=te.createContext(void 0),iJ=i=>{const[e,t]=te.useState(!1),[n,r]=te.useState(_c.Pending),o=te.useRef(n);te.useEffect(()=>{o.current=n},[n]);const c=te.useRef(null);return te.useEffect(()=>{const u=new nJ(`${i.wsUrl}?access_token=${i.customerInteractionSession.accessToken}`);return c.current=u,u.channels.chat.on("info",h=>{h.type==="reject_history"&&document.location.reload()}),u.channels.chat.on("connect",()=>{console.info("[CableContext] Connected to the chat channel"),r(_c.Available)}),u.channels.chat.on("disconnect",h=>{r(_c.Unavailable),console.warn("[CableContext] Disconnected from the chat channel",h)}),window.addEventListener("online",()=>{o.current===_c.Offline&&r(_c.Available)}),window.addEventListener("offline",()=>{r(_c.Offline)}),u.channels.chat.on("close",h=>{console.warn("[CableContext] Closed the chat channel",h)}),t(!0),()=>{c.current&&(c.current.unregister(),c.current=null),t(!1)}},[i.wsUrl,i.customerInteractionSession.accessToken]),e?{anycableService:c.current,networkStatus:n}:null},rJ=({children:i,config:e})=>{const t=iJ(e);return t?qe.jsx(PI.Provider,{value:t,children:i}):null},lD=()=>{const i=te.useContext(PI);if(i===void 0)throw new Error("useCable must be used within an CableProvider");return i},kv={connectionFailed:"Connection failed",offline:"You're offline",agentResponseFailed:"Agent response failed",sendMessageFallback:"Failed to send message"},FI=i=>{let e;const t=new Set,n=(m,_)=>{const p=typeof m=="function"?m(e):m;if(!Object.is(p,e)){const y=e;e=_??(typeof p!="object"||p===null)?p:Object.assign({},e,p),t.forEach(x=>x(e,y))}},r=()=>e,u={setState:n,getState:r,getInitialState:()=>h,subscribe:m=>(t.add(m),()=>t.delete(m))},h=e=i(n,r,u);return u},aJ=(i=>i?FI(i):FI),sJ=i=>i;function oJ(i,e=sJ){const t=em.useSyncExternalStore(i.subscribe,em.useCallback(()=>e(i.getState()),[i,e]),em.useCallback(()=>e(i.getInitialState()),[i,e]));return em.useDebugValue(t),t}const HI=i=>{const e=aJ(i),t=n=>oJ(e,n);return Object.assign(t,e),t},VI=(i=>i?HI(i):HI);function o1(i,e){i.message.includes("401")&&e?.()}const lJ="b48c3d08-0eb9-42a5-8076-51b6559f410a",cJ={voice:"ara"},GI=async(i,e)=>{try{const t=await fetch(`${i.apiUrl}/agents.Agents/StartVoiceSession`,{method:"POST",headers:{Authorization:`Bearer ${i.customerInteractionSession.accessToken}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({agentId:i.agentId,voiceModelId:lJ,voiceConfig:cJ})});return{status:t.status,json:await t.json()}}catch(t){throw o1(t,e.onSessionExpired),t}};async function cD(i,e,t,n){try{const r=await fetch(`${i.apiUrl}/agents.Agents/EndVoiceSession`,{method:"POST",headers:{Authorization:`Bearer ${i.customerInteractionSession.accessToken}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({voiceSessionId:t,reason:n})});if(!r.ok)throw new Error(`Request failed: ${r.status} ${r.statusText}`);return await r.json()}catch(r){throw o1(r,e.onSessionExpired),r}}async function uJ({voiceBaseUrl:i,voiceSessionId:e,sessionToken:t,clientInstanceId:n,protocolVersion:r,expectedConnectionGeneration:o,offerSdp:c}){try{Ei.debug("sendOffer",{voiceSessionId:e,clientInstanceId:n,protocolVersion:r,expectedConnectionGeneration:o,offerSdpLength:c.length});const u=await fetch(`${i}/SendOffer`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({voiceSessionId:e,sessionToken:t,clientInstanceId:n,protocolVersion:r,expectedConnectionGeneration:o,offerSdp:c})});if(!u.ok)throw new Error(`Request failed: ${u.status} ${u.statusText}`);return await u.json()}catch(u){throw console.error("Request failed:",u),u}}async function fJ({voiceBaseUrl:i,voiceSessionId:e,sessionToken:t,clientInstanceId:n,connectionId:r,connectionGeneration:o,candidates:c}){try{const u=await fetch(`${i}/SendCandidates`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({voiceSessionId:e,sessionToken:t,clientInstanceId:n,connectionId:r,connectionGeneration:o,candidates:c})});if(!u.ok)throw new Error(`Request failed: ${u.status} ${u.statusText}`)}catch(u){throw console.error("Request failed:",u),u}}async function dJ({voiceBaseUrl:i,voiceSessionId:e,sessionToken:t,clientInstanceId:n,connectionId:r,connectionGeneration:o,reason:c}){const u=await fetch(`${i}/EndSession`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({voiceSessionId:e,sessionToken:t,clientInstanceId:n,connectionId:r,connectionGeneration:o,reason:c})});if(!u.ok)throw new Error(`Request failed: ${u.status} ${u.statusText}`)}const uD=globalThis.crypto?.randomUUID?.()??`widget-${Date.now()}-${Math.random().toString(16).slice(2)}`;function l1(){return{activeVoiceSessionData:null,config:null,api:null,status:"idle",errorMessage:null,isVoiceBootstrapped:!1,connection:null,connectionId:null,connectionGeneration:null,iceCandidates:[],voiceEventsChannel:null,voiceInputChannel:null,downstream:null,localStream:null,remoteAudioElement:null,customerMessageTranscript:"",customerMessageTranscriptVisible:!1,assistantMessageTranscript:"",assistantMessageTranscriptVisible:!1,assistantResponseInProgress:!1}}function fD(i){i?.getTracks().forEach(e=>e.stop())}function jI(i){if(!(!i||i.readyState==="closed"))try{i.close()}catch(e){Ei.debug("Failed to close data channel",e)}}function hJ(i){if(!(!i||i.connectionState==="closed"))try{i.close()}catch(e){Ei.debug("Failed to close peer connection",e)}}function XI(i){jI(i.voiceEventsChannel),jI(i.voiceInputChannel),hJ(i.connection),fD(i.localStream),fD(i.downstream),i.remoteAudioElement&&(i.remoteAudioElement.pause(),i.remoteAudioElement.srcObject=null)}function pJ(i){return i instanceof Error?i.message:"Voice session failed"}const yl=VI((i,e)=>({...l1(),async init(t,n,r){const o=r.getAudioTracks()[0];if(!o)throw fD(r),new Error("No audio input track available");i({...l1(),config:t,localStream:r,status:"connecting"});try{let c=await GI(t,n);if(c.status===409){const y=c.json.message.split(" ").pop();y&&(await cD(t,n,y,"replace_stale_session"),c=await GI(t,n))}if(c.status>=400)throw new Error(c.json.message||"Unable to start voice session");const u=c.json;Ei.debug("StartVoiceSession response",{sessionId:u.session.id,voiceBaseUrl:u.voiceBaseUrl,voiceProtocolVersion:u.voiceProtocolVersion}),i({config:t,localStream:r,activeVoiceSessionData:u});const h=e().createConnection();h.ondatachannel=p=>{Ei.debug("ondatachannel",p.channel.label),p.channel.label==="voice-events"&&(i({voiceEventsChannel:p.channel}),p.channel.onmessage=y=>{e().onVoiceEventsEvent(y)}),p.channel.label==="voice-input"&&(i({voiceInputChannel:p.channel}),p.channel.onmessage=y=>{e().onVoiceInputEvent(y)})},h.addEventListener("track",p=>{const y=p.streams[0];y&&(Ei.debug("Received remote audio track"),i({downstream:y}),e().playRemoteAudio(y))}),h.onicecandidate=p=>{if(p.candidate){i(y=>({iceCandidates:[...y.iceCandidates,p.candidate?.toJSON()??{}]}));return}e().sendCandidates()},h.addEventListener("connectionstatechange",()=>{if(Ei.debug("Peer connection state",h.connectionState),h.connectionState==="connected"){i({status:"live",errorMessage:null});return}(h.connectionState==="failed"||h.connectionState==="disconnected")&&i({status:"error",errorMessage:"Voice connection was interrupted"})}),h.addTrack(o,r),h.createDataChannel("voice-bootstrap");const m=await h.createOffer();await h.setLocalDescription(m);const _=await uJ({voiceBaseUrl:u.voiceBaseUrl,voiceSessionId:u.session.id,sessionToken:u.sessionToken,clientInstanceId:uD,protocolVersion:u.voiceProtocolVersion,expectedConnectionGeneration:0,offerSdp:h.localDescription?.sdp??m.sdp??""});Ei.debug("SendOffer response",{connectionId:_.connectionId,connectionGeneration:_.connectionGeneration}),i({connection:h,connectionId:_.connectionId,connectionGeneration:_.connectionGeneration,isVoiceBootstrapped:!0}),await h.setRemoteDescription({type:"answer",sdp:_.answerSdp}),await e().sendCandidates()}catch(c){Ei.error("Voice bootstrap failed",c);const u=e().activeVoiceSessionData;if(u)try{await cD(t,n,u.session.id,"bootstrap_failed")}catch(h){Ei.warn("Failed to close voice session after bootstrap error",h)}throw XI(e()),i({...l1(),status:"error",errorMessage:pJ(c)}),c}},sendCandidates:async()=>{const t=e().activeVoiceSessionData,n=e().connectionId,r=e().connectionGeneration,o=e().iceCandidates;if(!(!t||!n||r==null||o.length===0)){i({iceCandidates:[]});try{await fJ({voiceBaseUrl:t.voiceBaseUrl,voiceSessionId:t.session.id,sessionToken:t.sessionToken,clientInstanceId:uD,connectionId:n,connectionGeneration:r,candidates:o}),Ei.debug("Sent ICE candidates",{count:o.length})}catch(c){throw Ei.error("Failed to send ICE candidates",c),i(u=>({iceCandidates:[...o,...u.iceCandidates]})),c}}},createConnection:()=>{const t=e().activeVoiceSessionData;if(!t)throw new Error("Voice session data not found");const n={urls:t.voiceTurn.urls,username:t.voiceTurn.username};return t.voiceTurn.useSessionTokenCredential&&(n.credential=t.sessionToken),new RTCPeerConnection({iceServers:[n]})},playRemoteAudio(t){let n=e().remoteAudioElement;n||(n=new Audio,n.autoplay=!0,i({remoteAudioElement:n})),n.srcObject=t,n.muted=!1,n.play().catch(r=>{Ei.debug("audioElement play error",r)})},endSession:async(t="user_hangup")=>{const{activeVoiceSessionData:n,config:r,api:o,connectionGeneration:c,connectionId:u,voiceInputChannel:h}=e();if(!n&&!e().connection&&!e().localStream&&!e().downstream){i(l1());return}i({status:"ending"});try{h?.readyState==="open"&&h.send(JSON.stringify({type:"end_session",reason:t}))}catch(m){Ei.warn("Failed to notify runtime about session end",m)}try{n&&u&&c!=null&&await dJ({voiceBaseUrl:n.voiceBaseUrl,voiceSessionId:n.session.id,sessionToken:n.sessionToken,clientInstanceId:uD,connectionId:u,connectionGeneration:c,reason:t})}catch(m){Ei.warn("Failed to end WebRTC session",m)}try{n&&await cD(r,o,n.session.id,t)}catch(m){Ei.warn("Failed to end voice session",m)}finally{XI(e()),i(l1())}},setMicrophoneEnabled:t=>{e().localStream?.getAudioTracks().forEach(n=>n.enabled=t)},onVoiceEventsEvent:t=>{try{const n=JSON.parse(t.data);switch(Ei.debug("voice-events message",n),n.type){case"input_audio_speech_started":i({customerMessageTranscript:"",assistantMessageTranscriptVisible:!1});break;case"response_started":i({assistantResponseInProgress:!0,assistantMessageTranscript:""});break;case"assistant_transcript_delta":i({assistantMessageTranscript:e().assistantMessageTranscript+(n.text??""),assistantMessageTranscriptVisible:!0});break;case"assistant_transcript_final":i({assistantMessageTranscript:n.text??"",assistantMessageTranscriptVisible:!0});break;case"response_cancelled":case"assistant_turn_done":case"assistant_turn_failed":i({assistantResponseInProgress:!1});break;case"user_transcript_delta":i({customerMessageTranscriptVisible:!0,customerMessageTranscript:e().customerMessageTranscript+(n.text??"")});break;case"user_transcript_final":i({customerMessageTranscriptVisible:!0,customerMessageTranscript:n.text??""});break;case"realtime_error":i({status:"error",errorMessage:n.message??"Voice session failed"});break}}catch(n){Ei.warn("Failed to parse voice-events payload",n)}},onVoiceInputEvent:t=>{try{const n=JSON.parse(t.data);Ei.debug("voice-input message",n)}catch(n){Ei.warn("Failed to parse voice-input payload",n)}}})),qI="audioinput",mJ="audiooutput";function gJ(i){return{deviceId:i.deviceId,kind:i.kind,label:i.label||(i.kind===qI?"Default microphone":"Default speaker"),groupId:i.groupId}}function vJ(){return typeof navigator>"u"||!navigator.mediaDevices?null:navigator.mediaDevices}function $I(i,e){return i.filter(t=>t.kind===e).map(gJ)}function yJ(){const[i,e]=te.useState([]),[t,n]=te.useState([]),[r,o]=te.useState(""),[c,u]=te.useState(""),[h,m]=te.useState("prompt"),[_,p]=te.useState(!1),[y,x]=te.useState(null),T=vJ(),M=T!==null,w=te.useCallback(async()=>{if(T){x(null);try{const L=await T.enumerateDevices();e($I(L,qI)),n($I(L,mJ))}catch(L){const N=L instanceof Error?L.message:"Failed to list devices";x(N)}}},[T]),A=te.useCallback(async()=>{if(!T)return{ok:!1,error:new Error("MediaDevices not supported"),message:"Audio devices are not supported in this browser or context."};x(null),p(!0);try{return(await T.getUserMedia({audio:!0})).getTracks().forEach(N=>N.stop()),m("granted"),await w(),{ok:!0}}catch(L){const N=L instanceof Error?L:new Error(String(L)),I=N.name==="NotAllowedError"||N.name==="PermissionDeniedError";I&&m("denied");const z=I?"Microphone access was denied.":N.message||"Could not access microphone.";return x(z),{ok:!1,error:N,message:z}}finally{p(!1)}},[T,w]);return te.useEffect(()=>{T&&w()},[T,w]),te.useEffect(()=>{if(!T)return;const L=()=>{w()};return T.addEventListener("devicechange",L),()=>T.removeEventListener("devicechange",L)},[T,w]),{inputDevices:i,outputDevices:t,selectedInputId:r,selectedOutputId:c,permissionState:h,isLoading:_,error:y,requestPermission:A,refreshDevices:w,setInputDevice:o,setOutputDevice:u,isSupported:M}}function _J(i){return{audio:{advanced:[{deviceId:i?{exact:i}:void 0,noiseSuppression:!0,echoCancellation:!0,autoGainControl:!1}]}}}function Aa(i){this.content=i}Aa.prototype={constructor:Aa,find:function(i){for(var e=0;e<this.content.length;e+=2)if(this.content[e]===i)return e;return-1},get:function(i){var e=this.find(i);return e==-1?void 0:this.content[e+1]},update:function(i,e,t){var n=t&&t!=i?this.remove(t):this,r=n.find(i),o=n.content.slice();return r==-1?o.push(t||i,e):(o[r+1]=e,t&&(o[r]=t)),new Aa(o)},remove:function(i){var e=this.find(i);if(e==-1)return this;var t=this.content.slice();return t.splice(e,2),new Aa(t)},addToStart:function(i,e){return new Aa([i,e].concat(this.remove(i).content))},addToEnd:function(i,e){var t=this.remove(i).content.slice();return t.push(i,e),new Aa(t)},addBefore:function(i,e,t){var n=this.remove(e),r=n.content.slice(),o=n.find(i);return r.splice(o==-1?r.length:o,0,e,t),new Aa(r)},forEach:function(i){for(var e=0;e<this.content.length;e+=2)i(this.content[e],this.content[e+1])},prepend:function(i){return i=Aa.from(i),i.size?new Aa(i.content.concat(this.subtract(i).content)):this},append:function(i){return i=Aa.from(i),i.size?new Aa(this.subtract(i).content.concat(i.content)):this},subtract:function(i){var e=this;i=Aa.from(i);for(var t=0;t<i.content.length;t+=2)e=e.remove(i.content[t]);return e},toObject:function(){var i={};return this.forEach(function(e,t){i[e]=t}),i},get size(){return this.content.length>>1}},Aa.from=function(i){if(i instanceof Aa)return i;var e=[];if(i)for(var t in i)e.push(t,i[t]);return new Aa(e)};function YI(i,e,t){for(let n=0;;n++){if(n==i.childCount||n==e.childCount)return i.childCount==e.childCount?null:t;let r=i.child(n),o=e.child(n);if(r==o){t+=r.nodeSize;continue}if(!r.sameMarkup(o))return t;if(r.isText&&r.text!=o.text){for(let c=0;r.text[c]==o.text[c];c++)t++;return t}if(r.content.size||o.content.size){let c=YI(r.content,o.content,t+1);if(c!=null)return c}t+=r.nodeSize}}function WI(i,e,t,n){for(let r=i.childCount,o=e.childCount;;){if(r==0||o==0)return r==o?null:{a:t,b:n};let c=i.child(--r),u=e.child(--o),h=c.nodeSize;if(c==u){t-=h,n-=h;continue}if(!c.sameMarkup(u))return{a:t,b:n};if(c.isText&&c.text!=u.text){let m=0,_=Math.min(c.text.length,u.text.length);for(;m<_&&c.text[c.text.length-m-1]==u.text[u.text.length-m-1];)m++,t--,n--;return{a:t,b:n}}if(c.content.size||u.content.size){let m=WI(c.content,u.content,t-1,n-1);if(m)return m}t-=h,n-=h}}class it{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let n=0;n<e.length;n++)this.size+=e[n].nodeSize}nodesBetween(e,t,n,r=0,o){for(let c=0,u=0;u<t;c++){let h=this.content[c],m=u+h.nodeSize;if(m>e&&n(h,r+u,o||null,c)!==!1&&h.content.size){let _=u+1;h.nodesBetween(Math.max(0,e-_),Math.min(h.content.size,t-_),n,r+_)}u=m}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,r){let o="",c=!0;return this.nodesBetween(e,t,(u,h)=>{let m=u.isText?u.text.slice(Math.max(e,h)-h,t-h):u.isLeaf?r?typeof r=="function"?r(u):r:u.type.spec.leafText?u.type.spec.leafText(u):"":"";u.isBlock&&(u.isLeaf&&m||u.isTextblock)&&n&&(c?c=!1:o+=n),o+=m},0),o}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,n=e.firstChild,r=this.content.slice(),o=0;for(t.isText&&t.sameMarkup(n)&&(r[r.length-1]=t.withText(t.text+n.text),o=1);o<e.content.length;o++)r.push(e.content[o]);return new it(r,this.size+e.size)}cut(e,t=this.size){if(e==0&&t==this.size)return this;let n=[],r=0;if(t>e)for(let o=0,c=0;c<t;o++){let u=this.content[o],h=c+u.nodeSize;h>e&&((c<e||h>t)&&(u.isText?u=u.cut(Math.max(0,e-c),Math.min(u.text.length,t-c)):u=u.cut(Math.max(0,e-c-1),Math.min(u.content.size,t-c-1))),n.push(u),r+=u.nodeSize),c=h}return new it(n,r)}cutByIndex(e,t){return e==t?it.empty:e==0&&t==this.content.length?this:new it(this.content.slice(e,t))}replaceChild(e,t){let n=this.content[e];if(n==t)return this;let r=this.content.slice(),o=this.size+t.nodeSize-n.nodeSize;return r[e]=t,new it(r,o)}addToStart(e){return new it([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new it(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;t<this.content.length;t++)if(!this.content[t].eq(e.content[t]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(e){let t=this.content[e];if(!t)throw new RangeError("Index "+e+" out of range for "+this);return t}maybeChild(e){return this.content[e]||null}forEach(e){for(let t=0,n=0;t<this.content.length;t++){let r=this.content[t];e(r,n,t),n+=r.nodeSize}}findDiffStart(e,t=0){return YI(this,e,t)}findDiffEnd(e,t=this.size,n=e.size){return WI(this,e,t,n)}findIndex(e){if(e==0)return aM(0,e);if(e==this.size)return aM(this.content.length,e);if(e>this.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,n=0;;t++){let r=this.child(t),o=n+r.nodeSize;if(o>=e)return o==e?aM(t+1,o):aM(t,n);n=o}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return it.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return new it(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return it.empty;let t,n=0;for(let r=0;r<e.length;r++){let o=e[r];n+=o.nodeSize,r&&o.isText&&e[r-1].sameMarkup(o)?(t||(t=e.slice(0,r)),t[t.length-1]=o.withText(t[t.length-1].text+o.text)):t&&t.push(o)}return new it(t||e,n)}static from(e){if(!e)return it.empty;if(e instanceof it)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new it([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}it.empty=new it([],0);const dD={index:0,offset:0};function aM(i,e){return dD.index=i,dD.offset=e,dD}function sM(i,e){if(i===e)return!0;if(!(i&&typeof i=="object")||!(e&&typeof e=="object"))return!1;let t=Array.isArray(i);if(Array.isArray(e)!=t)return!1;if(t){if(i.length!=e.length)return!1;for(let n=0;n<i.length;n++)if(!sM(i[n],e[n]))return!1}else{for(let n in i)if(!(n in e)||!sM(i[n],e[n]))return!1;for(let n in e)if(!(n in i))return!1}return!0}let Hi=class v4{constructor(e,t){this.type=e,this.attrs=t}addToSet(e){let t,n=!1;for(let r=0;r<e.length;r++){let o=e[r];if(this.eq(o))return e;if(this.type.excludes(o.type))t||(t=e.slice(0,r));else{if(o.type.excludes(this.type))return e;!n&&o.type.rank>this.type.rank&&(t||(t=e.slice(0,r)),t.push(this),n=!0),t&&t.push(o)}}return t||(t=e.slice()),n||t.push(this),t}removeFromSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return e.slice(0,t).concat(e.slice(t+1));return e}isInSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return!0;return!1}eq(e){return this==e||this.type==e.type&&sM(this.attrs,e.attrs)}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Mark.fromJSON");let n=e.marks[t.type];if(!n)throw new RangeError(`There is no mark type ${t.type} in this schema`);let r=n.create(t.attrs);return n.checkAttrs(r.attrs),r}static sameSet(e,t){if(e==t)return!0;if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++)if(!e[n].eq(t[n]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&e.length==0)return v4.none;if(e instanceof v4)return[e];let t=e.slice();return t.sort((n,r)=>n.type.rank-r.type.rank),t}};Hi.none=[];class oM extends Error{}class St{constructor(e,t,n){this.content=e,this.openStart=t,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let n=KI(this.content,e+this.openStart,t);return n&&new St(n,this.openStart,this.openEnd)}removeBetween(e,t){return new St(ZI(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return St.empty;let n=t.openStart||0,r=t.openEnd||0;if(typeof n!="number"||typeof r!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new St(it.fromJSON(e,t.content),n,r)}static maxOpen(e,t=!0){let n=0,r=0;for(let o=e.firstChild;o&&!o.isLeaf&&(t||!o.type.spec.isolating);o=o.firstChild)n++;for(let o=e.lastChild;o&&!o.isLeaf&&(t||!o.type.spec.isolating);o=o.lastChild)r++;return new St(e,n,r)}}St.empty=new St(it.empty,0,0);function ZI(i,e,t){let{index:n,offset:r}=i.findIndex(e),o=i.maybeChild(n),{index:c,offset:u}=i.findIndex(t);if(r==e||o.isText){if(u!=t&&!i.child(c).isText)throw new RangeError("Removing non-flat range");return i.cut(0,e).append(i.cut(t))}if(n!=c)throw new RangeError("Removing non-flat range");return i.replaceChild(n,o.copy(ZI(o.content,e-r-1,t-r-1)))}function KI(i,e,t,n){let{index:r,offset:o}=i.findIndex(e),c=i.maybeChild(r);if(o==e||c.isText)return n&&!n.canReplace(r,r,t)?null:i.cut(0,e).append(t).append(i.cut(e));let u=KI(c.content,e-o-1,t,c);return u&&i.replaceChild(r,c.copy(u))}function bJ(i,e,t){if(t.openStart>i.depth)throw new oM("Inserted content deeper than insertion position");if(i.depth-t.openStart!=e.depth-t.openEnd)throw new oM("Inconsistent open depths");return JI(i,e,t,0)}function JI(i,e,t,n){let r=i.index(n),o=i.node(n);if(r==e.index(n)&&n<i.depth-t.openStart){let c=JI(i,e,t,n+1);return o.copy(o.content.replaceChild(r,c))}else if(t.content.size)if(!t.openStart&&!t.openEnd&&i.depth==n&&e.depth==n){let c=i.parent,u=c.content;return Nm(c,u.cut(0,i.parentOffset).append(t.content).append(u.cut(e.parentOffset)))}else{let{start:c,end:u}=xJ(t,i);return Nm(o,e6(i,c,u,e,n))}else return Nm(o,lM(i,e,n))}function QI(i,e){if(!e.type.compatibleContent(i.type))throw new oM("Cannot join "+e.type.name+" onto "+i.type.name)}function hD(i,e,t){let n=i.node(t);return QI(n,e.node(t)),n}function Lm(i,e){let t=e.length-1;t>=0&&i.isText&&i.sameMarkup(e[t])?e[t]=i.withText(e[t].text+i.text):e.push(i)}function c1(i,e,t,n){let r=(e||i).node(t),o=0,c=e?e.index(t):r.childCount;i&&(o=i.index(t),i.depth>t?o++:i.textOffset&&(Lm(i.nodeAfter,n),o++));for(let u=o;u<c;u++)Lm(r.child(u),n);e&&e.depth==t&&e.textOffset&&Lm(e.nodeBefore,n)}function Nm(i,e){return i.type.checkContent(e),i.copy(e)}function e6(i,e,t,n,r){let o=i.depth>r&&hD(i,e,r+1),c=n.depth>r&&hD(t,n,r+1),u=[];return c1(null,i,r,u),o&&c&&e.index(r)==t.index(r)?(QI(o,c),Lm(Nm(o,e6(i,e,t,n,r+1)),u)):(o&&Lm(Nm(o,lM(i,e,r+1)),u),c1(e,t,r,u),c&&Lm(Nm(c,lM(t,n,r+1)),u)),c1(n,null,r,u),new it(u)}function lM(i,e,t){let n=[];if(c1(null,i,t,n),i.depth>t){let r=hD(i,e,t+1);Lm(Nm(r,lM(i,e,t+1)),n)}return c1(e,null,t,n),new it(n)}function xJ(i,e){let t=e.depth-i.openStart,r=e.node(t).copy(i.content);for(let o=t-1;o>=0;o--)r=e.node(o).copy(it.from(r));return{start:r.resolveNoCache(i.openStart+t),end:r.resolveNoCache(r.content.size-i.openEnd-t)}}class u1{constructor(e,t,n){this.pos=e,this.path=t,this.parentOffset=n,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let n=this.pos-this.path[this.path.length-1],r=e.child(t);return n?e.child(t).cut(n):r}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let n=this.path[t*3],r=t==0?0:this.path[t*3-1]+1;for(let o=0;o<e;o++)r+=n.child(o).nodeSize;return r}marks(){let e=this.parent,t=this.index();if(e.content.size==0)return Hi.none;if(this.textOffset)return e.child(t).marks;let n=e.maybeChild(t-1),r=e.maybeChild(t);if(!n){let u=n;n=r,r=u}let o=n.marks;for(var c=0;c<o.length;c++)o[c].type.spec.inclusive===!1&&(!r||!o[c].isInSet(r.marks))&&(o=o[c--].removeFromSet(o));return o}marksAcross(e){let t=this.parent.maybeChild(this.index());if(!t||!t.isInline)return null;let n=t.marks,r=e.parent.maybeChild(e.index());for(var o=0;o<n.length;o++)n[o].type.spec.inclusive===!1&&(!r||!n[o].isInSet(r.marks))&&(n=n[o--].removeFromSet(n));return n}sharedDepth(e){for(let t=this.depth;t>0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos<this.pos)return e.blockRange(this);for(let n=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);n>=0;n--)if(e.pos<=this.end(n)&&(!t||t(this.node(n))))return new cM(this,e,n);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos<this.pos?e:this}toString(){let e="";for(let t=1;t<=this.depth;t++)e+=(e?"/":"")+this.node(t).type.name+"_"+this.index(t-1);return e+":"+this.parentOffset}static resolve(e,t){if(!(t>=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let n=[],r=0,o=t;for(let c=e;;){let{index:u,offset:h}=c.content.findIndex(o),m=o-h;if(n.push(c,u,r+h),!m||(c=c.child(u),c.isText))break;o=m-1,r+=h+1}return new u1(t,n,o)}static resolveCached(e,t){let n=t6.get(e);if(n)for(let o=0;o<n.elts.length;o++){let c=n.elts[o];if(c.pos==t)return c}else t6.set(e,n=new SJ);let r=n.elts[n.i]=u1.resolve(e,t);return n.i=(n.i+1)%EJ,r}}class SJ{constructor(){this.elts=[],this.i=0}}const EJ=12,t6=new WeakMap;class cM{constructor(e,t,n){this.$from=e,this.$to=t,this.depth=n}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}}const TJ=Object.create(null);let lh=class y4{constructor(e,t,n,r=Hi.none){this.type=e,this.attrs=t,this.marks=r,this.content=n||it.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(e){return this.content.child(e)}maybeChild(e){return this.content.maybeChild(e)}forEach(e){this.content.forEach(e)}nodesBetween(e,t,n,r=0){this.content.nodesBetween(e,t,n,r,this)}descendants(e){this.nodesBetween(0,this.content.size,e)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(e,t,n,r){return this.content.textBetween(e,t,n,r)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(e){return this==e||this.sameMarkup(e)&&this.content.eq(e.content)}sameMarkup(e){return this.hasMarkup(e.type,e.attrs,e.marks)}hasMarkup(e,t,n){return this.type==e&&sM(this.attrs,t||e.defaultAttrs||TJ)&&Hi.sameSet(this.marks,n||Hi.none)}copy(e=null){return e==this.content?this:new y4(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new y4(this.type,this.attrs,this.content,e)}cut(e,t=this.content.size){return e==0&&t==this.content.size?this:this.copy(this.content.cut(e,t))}slice(e,t=this.content.size,n=!1){if(e==t)return St.empty;let r=this.resolve(e),o=this.resolve(t),c=n?0:r.sharedDepth(t),u=r.start(c),m=r.node(c).content.cut(r.pos-u,o.pos-u);return new St(m,r.depth-c,o.depth-c)}replace(e,t,n){return bJ(this.resolve(e),this.resolve(t),n)}nodeAt(e){for(let t=this;;){let{index:n,offset:r}=t.content.findIndex(e);if(t=t.maybeChild(n),!t)return null;if(r==e||t.isText)return t;e-=r+1}}childAfter(e){let{index:t,offset:n}=this.content.findIndex(e);return{node:this.content.maybeChild(t),index:t,offset:n}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:t,offset:n}=this.content.findIndex(e);if(n<e)return{node:this.content.child(t),index:t,offset:n};let r=this.content.child(t-1);return{node:r,index:t-1,offset:n-r.nodeSize}}resolve(e){return u1.resolveCached(this,e)}resolveNoCache(e){return u1.resolve(this,e)}rangeHasMark(e,t,n){let r=!1;return t>e&&this.nodesBetween(e,t,o=>(n.isInSet(o.marks)&&(r=!0),!r)),r}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),n6(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,n=it.empty,r=0,o=n.childCount){let c=this.contentMatchAt(e).matchFragment(n,r,o),u=c&&c.matchFragment(this.content,t);if(!u||!u.validEnd)return!1;for(let h=r;h<o;h++)if(!this.type.allowsMarks(n.child(h).marks))return!1;return!0}canReplaceWith(e,t,n,r){if(r&&!this.type.allowsMarks(r))return!1;let o=this.contentMatchAt(e).matchType(n),c=o&&o.matchFragment(this.content,t);return c?c.validEnd:!1}canAppend(e){return e.content.size?this.canReplace(this.childCount,this.childCount,e.content):this.type.compatibleContent(e.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let e=Hi.none;for(let t=0;t<this.marks.length;t++){let n=this.marks[t];n.type.checkAttrs(n.attrs),e=n.addToSet(e)}if(!Hi.sameSet(e,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(t=>t.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let n;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");n=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,n)}let r=it.fromJSON(e,t.content),o=e.nodeType(t.type).create(t.attrs,r,n);return o.type.checkAttrs(o.attrs),o}};lh.prototype.text=void 0;class uM extends lh{constructor(e,t,n,r){if(super(e,t,null,r),!n)throw new RangeError("Empty text nodes are not allowed");this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):n6(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new uM(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new uM(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function n6(i,e){for(let t=i.length-1;t>=0;t--)e=i[t].type.name+"("+e+")";return e}class km{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let n=new MJ(e,t);if(n.next==null)return km.empty;let r=i6(n);n.next&&n.err("Unexpected trailing text");let o=LJ(OJ(r));return NJ(o,n),o}matchType(e){for(let t=0;t<this.next.length;t++)if(this.next[t].type==e)return this.next[t].next;return null}matchFragment(e,t=0,n=e.childCount){let r=this;for(let o=t;r&&o<n;o++)r=r.matchType(e.child(o).type);return r}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let e=0;e<this.next.length;e++){let{type:t}=this.next[e];if(!(t.isText||t.hasRequiredAttrs()))return t}return null}compatible(e){for(let t=0;t<this.next.length;t++)for(let n=0;n<e.next.length;n++)if(this.next[t].type==e.next[n].type)return!0;return!1}fillBefore(e,t=!1,n=0){let r=[this];function o(c,u){let h=c.matchFragment(e,n);if(h&&(!t||h.validEnd))return it.from(u.map(m=>m.createAndFill()));for(let m=0;m<c.next.length;m++){let{type:_,next:p}=c.next[m];if(!(_.isText||_.hasRequiredAttrs())&&r.indexOf(p)==-1){r.push(p);let y=o(p,u.concat(_));if(y)return y}}return null}return o(this,[])}findWrapping(e){for(let n=0;n<this.wrapCache.length;n+=2)if(this.wrapCache[n]==e)return this.wrapCache[n+1];let t=this.computeWrapping(e);return this.wrapCache.push(e,t),t}computeWrapping(e){let t=Object.create(null),n=[{match:this,type:null,via:null}];for(;n.length;){let r=n.shift(),o=r.match;if(o.matchType(e)){let c=[];for(let u=r;u.type;u=u.via)c.push(u.type);return c.reverse()}for(let c=0;c<o.next.length;c++){let{type:u,next:h}=o.next[c];!u.isLeaf&&!u.hasRequiredAttrs()&&!(u.name in t)&&(!r.type||h.validEnd)&&(n.push({match:u.contentMatch,type:u,via:r}),t[u.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(e){if(e>=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(n){e.push(n);for(let r=0;r<n.next.length;r++)e.indexOf(n.next[r].next)==-1&&t(n.next[r].next)}return t(this),e.map((n,r)=>{let o=r+(n.validEnd?"*":" ")+" ";for(let c=0;c<n.next.length;c++)o+=(c?", ":"")+n.next[c].type.name+"->"+e.indexOf(n.next[c].next);return o}).join(`
4553
+ `))}else{let y=_.props,x=y?.className,T=typeof x=="function"?(...A)=>gI(x(...A),h.className):gI(x,h.className),M=T?{className:T}:{},w=yI(_.props,Lv(rD(h,["ref"])));for(let A in p)A in w&&delete p[A];return te.cloneElement(_,Object.assign({},w,p,m,{ref:r(rK(_),m.ref)},M))}return te.createElement(o,Object.assign({},rD(h,["ref"]),!nM(o)&&m,!nM(o)&&p),_)}function nK(){let i=te.useRef([]),e=te.useCallback(t=>{for(let n of i.current)n!=null&&(typeof n=="function"?n(t):n.current=t)},[]);return(...t)=>{if(!t.every(n=>n==null))return i.current=t,e}}function iK(...i){return i.every(e=>e==null)?void 0:e=>{for(let t of i)t!=null&&(typeof t=="function"?t(e):t.current=e)}}function yI(...i){if(i.length===0)return{};if(i.length===1)return i[0];let e={},t={};for(let n of i)for(let r in n)r.startsWith("on")&&typeof n[r]=="function"?(t[r]!=null||(t[r]=[]),t[r].push(n[r])):e[r]=n[r];if(e.disabled||e["aria-disabled"])for(let n in t)/^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(n)&&(t[n]=[r=>{var o;return(o=r?.preventDefault)==null?void 0:o.call(r)}]);for(let n in t)Object.assign(e,{[n](r,...o){let c=t[n];for(let u of c){if((r instanceof Event||r?.nativeEvent instanceof Event)&&r.defaultPrevented)return;u(r,...o)}}});return e}function _I(...i){if(i.length===0)return{};if(i.length===1)return i[0];let e={},t={};for(let n of i)for(let r in n)r.startsWith("on")&&typeof n[r]=="function"?(t[r]!=null||(t[r]=[]),t[r].push(n[r])):e[r]=n[r];for(let n in t)Object.assign(e,{[n](...r){let o=t[n];for(let c of o)c?.(...r)}});return e}function tM(i){var e;return Object.assign(te.forwardRef(i),{displayName:(e=i.displayName)!=null?e:i.name})}function Lv(i){let e=Object.assign({},i);for(let t in e)e[t]===void 0&&delete e[t];return e}function rD(i,e=[]){let t=Object.assign({},i);for(let n of e)n in t&&delete t[n];return t}function rK(i){return em.version.split(".")[0]>="19"?i.props.ref:i.ref}function nM(i){return i===te.Fragment||i===Symbol.for("react.fragment")}function aK(i){return nM(i.type)}let sK="button";function oK(i,e){var t;let n=JT(),{disabled:r=n||!1,autoFocus:o=!1,...c}=i,{isFocusVisible:u,focusProps:h}=hI({autoFocus:o}),{isHovered:m,hoverProps:_}=dI({isDisabled:r}),{pressed:p,pressProps:y}=KZ({disabled:r}),x=_I({ref:e,type:(t=c.type)!=null?t:"button",disabled:r||void 0,autoFocus:o},h,_,y),T=KT({disabled:r,hover:m,focus:u,active:p,autofocus:o});return QT()({ourProps:x,theirProps:c,slot:T,defaultTag:sK,name:"Button"})}let wf=tM(oK),lK=te.createContext(void 0);function bI(){return te.useContext(lK)}function cK(i){return typeof i!="object"||i===null?!1:"nodeType"in i}function xI(i){return cK(i)&&"tagName"in i}function SI(i){return xI(i)&&"accessKey"in i}function uK(i){return SI(i)&&i.nodeName==="INPUT"}function EI(i){return SI(i)&&i.nodeName==="LABEL"}function fK(i){return xI(i)?i.matches('a[href],audio[controls],button,details,embed,iframe,img[usemap],input:not([type="hidden"]),label,select,textarea,video[controls]'):!1}let dK=Symbol();function TI(...i){let e=te.useRef(i);te.useEffect(()=>{e.current=i},[i]);let t=ZT(n=>{for(let r of e.current)r!=null&&(typeof r=="function"?r(n):r.current=n)});return i.every(n=>n==null||n?.[dK])?void 0:t}let aD=te.createContext(null);aD.displayName="DescriptionContext";function MI(){let i=te.useContext(aD);if(i===null){let e=new Error("You used a <Description /> component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(e,MI),e}return i}function hK(){var i,e;return(e=(i=te.useContext(aD))==null?void 0:i.value)!=null?e:void 0}let pK="p";function mK(i,e){let t=te.useId(),n=JT(),{id:r=`headlessui-description-${t}`,...o}=i,c=MI(),u=TI(e);iD(()=>c.register(r),[r,c.register]);let h=KT({...c.slot,disabled:n||!1}),m={ref:u,...c.props,id:r};return QT()({ourProps:m,theirProps:o,slot:h,defaultTag:pK,name:c.name||"Description"})}let gK=tM(mK);Object.assign(gK,{});let sD=te.createContext(null);sD.displayName="LabelContext";function wI(){let i=te.useContext(sD);if(i===null){let e=new Error("You used a <Label /> component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(e,wI),e}return i}function vK(i){var e,t,n;let r=(t=(e=te.useContext(sD))==null?void 0:e.value)!=null?t:void 0;return((n=void 0)!=null?n:0)>0?[r,...i].filter(Boolean).join(" "):r}let yK="label";function _K(i,e){var t;let n=te.useId(),r=wI(),o=bI(),c=JT(),{id:u=`headlessui-label-${n}`,htmlFor:h=o??((t=r.props)==null?void 0:t.htmlFor),passive:m=!1,..._}=i,p=TI(e);iD(()=>r.register(u),[u,r.register]);let y=ZT(M=>{let w=M.currentTarget;if(!(M.target!==M.currentTarget&&fK(M.target))&&(EI(w)&&M.preventDefault(),r.props&&"onClick"in r.props&&typeof r.props.onClick=="function"&&r.props.onClick(M),EI(w))){let A=document.getElementById(w.htmlFor);if(A){let L=A.getAttribute("disabled");if(L==="true"||L==="")return;let N=A.getAttribute("aria-disabled");if(N==="true"||N==="")return;(uK(A)&&(A.type==="file"||A.type==="radio"||A.type==="checkbox")||A.role==="radio"||A.role==="checkbox"||A.role==="switch")&&A.click(),A.focus({preventScroll:!0})}}}),x=KT({...r.slot,disabled:c||!1}),T={ref:p,...r.props,id:u,htmlFor:h,onClick:y};return m&&("onClick"in T&&(delete T.htmlFor,delete T.onClick),"onClick"in _&&delete _.onClick),QT()({ourProps:T,theirProps:_,slot:x,defaultTag:h?yK:"div",name:r.name||"Label"})}let bK=tM(_K);Object.assign(bK,{});let xK="textarea";function SK(i,e){let t=te.useId(),n=bI(),r=JT(),{id:o=n||`headlessui-textarea-${t}`,disabled:c=r||!1,autoFocus:u=!1,invalid:h=!1,...m}=i,_=vK(),p=hK(),{isFocused:y,focusProps:x}=hI({autoFocus:u}),{isHovered:T,hoverProps:M}=dI({isDisabled:c}),w=_I({ref:e,id:o,"aria-labelledby":_,"aria-describedby":p,"aria-invalid":h?"true":void 0,disabled:c||void 0,autoFocus:u},x,M),A=KT({disabled:c,invalid:h,hover:T,focus:y,autofocus:u});return QT()({ourProps:w,theirProps:m,slot:A,defaultTag:xK,name:"Textarea"})}let EK=tM(SK);const TK=i=>te.createElement("svg",{width:16,height:16,viewBox:"0 0 16 16",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...i},te.createElement("path",{d:"M8 1.25C6.66498 1.25 5.35994 1.64588 4.2499 2.38758C3.13987 3.12928 2.27471 4.18349 1.76382 5.41689C1.25292 6.65029 1.11925 8.00749 1.3797 9.31686C1.64015 10.6262 2.28303 11.829 3.22703 12.773C4.17104 13.717 5.37377 14.3598 6.68314 14.6203C7.99252 14.8808 9.34971 14.7471 10.5831 14.2362C11.8165 13.7253 12.8707 12.8601 13.6124 11.7501C14.3541 10.6401 14.75 9.33502 14.75 8C14.748 6.2104 14.0362 4.49466 12.7708 3.22922C11.5053 1.96378 9.78961 1.25199 8 1.25ZM8 13.25C6.96165 13.25 5.94662 12.9421 5.08326 12.3652C4.2199 11.7883 3.547 10.9684 3.14964 10.0091C2.75228 9.04978 2.64831 7.99418 2.85088 6.97578C3.05345 5.95738 3.55347 5.02191 4.28769 4.28769C5.02192 3.55346 5.95738 3.05345 6.97578 2.85088C7.99418 2.6483 9.04978 2.75227 10.0091 3.14963C10.9684 3.54699 11.7883 4.2199 12.3652 5.08326C12.9421 5.94661 13.25 6.96165 13.25 8C13.2485 9.39193 12.6949 10.7264 11.7107 11.7107C10.7264 12.6949 9.39193 13.2485 8 13.25ZM7.25 8.25V5C7.25 4.80109 7.32902 4.61032 7.46967 4.46967C7.61032 4.32902 7.80109 4.25 8 4.25C8.19892 4.25 8.38968 4.32902 8.53033 4.46967C8.67098 4.61032 8.75 4.80109 8.75 5V8.25C8.75 8.44891 8.67098 8.63968 8.53033 8.78033C8.38968 8.92098 8.19892 9 8 9C7.80109 9 7.61032 8.92098 7.46967 8.78033C7.32902 8.63968 7.25 8.44891 7.25 8.25ZM9 10.75C9 10.9478 8.94135 11.1411 8.83147 11.3056C8.72159 11.47 8.56541 11.5982 8.38269 11.6739C8.19996 11.7496 7.99889 11.7694 7.80491 11.7308C7.61093 11.6922 7.43275 11.597 7.2929 11.4571C7.15304 11.3173 7.0578 11.1391 7.01922 10.9451C6.98063 10.7511 7.00044 10.55 7.07612 10.3673C7.15181 10.1846 7.27998 10.0284 7.44443 9.91853C7.60888 9.80865 7.80222 9.75 8 9.75C8.26522 9.75 8.51957 9.85536 8.70711 10.0429C8.89465 10.2304 9 10.4848 9 10.75Z",fill:"currentColor"}));function AI({message:i,className:e,...t}){return qe.jsxs("div",{...t,className:Ao("message flex h-fit min-h-9 w-fit max-w-70 flex-row items-center justify-center gap-1 bg-black",e),children:[qe.jsx(TK,{}),qe.jsx("span",{children:i})]})}let iM=()=>({emit(i,...e){for(let t=this.events[i]||[],n=0,r=t.length;n<r;n++)t[n](...e)},events:{},on(i,e){return(this.events[i]||=[]).push(e),()=>{this.events[i]=this.events[i]?.filter(t=>e!==t)}}});class r1 extends Error{constructor(e,t){e instanceof Error?(super(e.message),this.cause=e):super(e),this.reason=t,this.name="ReasonError"}}class CI extends r1{constructor(e){super("Rejected",e),this.name="SubscriptionRejectedError"}}class MK extends r1{constructor(e){super(e||"Timed out to receive subscription ack"),this.name="SubscriptionTimeoutError"}}class yc extends r1{constructor(e,t){t?super(e,t):super("Disconnected",e),this.name="DisconnectedError"}}class wK extends yc{constructor(e){super(e,"stale_connection"),this.name="StaleConnectionError"}}function RI(i){return i?`{${Object.keys(i).sort().filter(t=>i[t]!==void 0).map(t=>{let n=JSON.stringify(i[t]);return`${JSON.stringify(t)}:${n}`}).join(",")}}`:""}class AK{constructor(e){this.channel=e,this.listeners=[]}watch(){this.listeners.push(this.channel.on("presence",e=>{if(e.type==="info"){this._state||(this._state=this.stateFromInfo(e));return}this._state&&(e.type==="join"?this._state[e.id]=e.info:e.type==="leave"&&delete this._state[e.id])}))}reset(){delete this._state}dispose(){delete this._info,delete this._state,this.listeners.forEach(e=>e()),this.listeners.length=0}async join(e,t){if(!this._info)return this._info={id:e,info:t},this.channel.perform("$presence:join",this._info)}async leave(){if(!this._info)return;let e=await this.channel.perform("$presence:leave");return delete this._info,e}async info(){return this._state?this._state:(this._promise||(this._promise=this._sync()),await this._promise,this._state)}async _sync(){this.watch();try{let e=await this.channel.perform("$presence:info",{});return this._state=this.stateFromInfo(e),this._state}finally{delete this._promise}}stateFromInfo(e){return e.records.reduce((t,{id:n,info:r})=>(t[n]=r,t),{})}}const Dm=Symbol("state");class oD{constructor(e={}){this.emitter=iM(),this.params=Object.freeze(e),this.presence=new AK(this),this.initialConnect=!0,this[Dm]="idle"}get identifier(){return this._identifier?this._identifier:(this._identifier=RI({channel:this.channelId,...this.params}),this._identifier)}get channelId(){return this.constructor.identifier}get state(){return this[Dm]}attached(e){if(this.receiver){if(this.receiver!==e)throw Error("Already connected to a different receiver");return!1}return this.receiver=e,!0}connecting(){this[Dm]="connecting"}connected(){if(this.state==="connected"||this.state==="closed")return;this[Dm]="connected";let e=!1;this.initialConnect?(this.initialConnect=!1,this.emit("connect",{reconnect:!1,restored:e})):this.emit("connect",{reconnect:!0,restored:e})}restored(){if(this.state==="connected")throw Error("Already connected");this[Dm]="connected";let e=!0,t=!0;this.initialConnect=!1,this.emit("connect",{reconnect:t,restored:e})}disconnected(e){this.state==="disconnected"||this.state==="closed"||(this[Dm]="disconnected",this.presence.reset(),this.emit("disconnect",e))}closed(e){this.state!=="closed"&&(this[Dm]="closed",delete this.receiver,this.initialConnect=!0,this.presence.dispose(),this.emit("close",e))}disconnect(){this.state==="idle"||this.state==="closed"||this.receiver.unsubscribe(this)}async perform(e,t){if(this.state==="idle"||this.state==="closed")throw Error("Channel is not subscribed");return this.receiver.perform(this.identifier,e,t)}async send(e){return this.perform(void 0,e)}async whisper(e){try{await this.perform("$whisper",e)}catch(t){let n=this.receiver?this.receiver.logger:null;n&&n.warn("whisper failed: ",t)}}receive(e,t){this.emit("message",e,t)}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...r)=>{n(),t(...r)});return n}emit(e,...t){return this.emitter.emit(e,...t)}ensureSubscribed(){return this.state==="connected"?Promise.resolve():this.state==="closed"?Promise.reject(Error("Channel is unsubscribed")):this.pendingSubscribe()}pendingSubscribe(){return this._pendingSubscribe?this._pendingSubscribe:(this._pendingSubscribe=new Promise((e,t)=>{let n=[()=>delete this._pendingSubscribe];n.push(this.on("connect",()=>{n.forEach(r=>r()),e()})),n.push(this.on("close",r=>{n.forEach(o=>o()),t(r||new r1("Channel was disconnected before subscribing","canceled"))}))}),this._pendingSubscribe)}}class CK{constructor(e){this.id=e,this.intent="unsubscribed",this.state="idle",this.channels=[],this.disposed=!1,this._pendings=[]}add(e){this.channels.includes(e)||this.channels.push(e)}remove(e){let t=this.channels.indexOf(e);t>-1&&this.channels.splice(t,1)}notify(e,...t){this.state=e==="restored"?"connected":e,t.length===1?this.channels.forEach(n=>n[e](t[0])):this.channels.forEach(n=>n[e]())}pending(e){this._checkIntent(e);let t=this._pendings[0];return!t||t.intent!==e?Promise.resolve():t.promise}ensureResubscribed(){this.disposed||(this.intent=void 0,this.ensureSubscribed())}ensureSubscribed(){if(this.intent==="subscribed")return;if(this.disposed)throw Error("Subscription is disposed");this.intent="subscribed",!this._mergeWithPending("unsubscribed")&&this.subscriber(this)}maybeUnsubscribe(){this.disposed||this.intent==="unsubscribed"||this.channels.length>0||(this.intent="unsubscribed",this._mergeWithPending("subscribed"))||this.unsubscriber(this)}async acquire(e){this._checkIntent(e);let t,r={promise:new Promise(c=>{t=c}),intent:e,release:()=>{this._pendings.splice(this._pendings.indexOf(r),1),t(r)},canceled:!1,acquired:!1},o=this._pendingTop;return this._pendings.push(r),o&&await o.promise,this.gvl&&await this.gvl.acquire(r,e),r.acquired=!0,r}close(e){this.disposed=!0,this.intent=void 0,this.notify("closed",e)}_checkIntent(e){if(!(e==="unsubscribed"||e==="subscribed"))throw Error(`Unknown subscription intent: ${e}`)}get _pendingTop(){return this._pendings.length?this._pendings[this._pendings.length-1]:void 0}_mergeWithPending(e){let t=this._pendingTop;return!t||t.acquired||t.intent!==e?!1:(this._pendings.pop(),t.canceled=!0,!0)}}class RK{constructor(){this.queue=[]}async acquire(e,t){t==="subscribed"&&(this.queue.push(e.promise.then(()=>{this.queue.splice(this.queue.indexOf(e),1)})),this.queue.length>1&&await this.queue[this.queue.length-2])}}class DK{constructor(e){e.concurrentSubscribes===!1&&(this.glv=new RK),this._subscriptions={},this._localToRemote={}}all(){return Object.values(this._subscriptions)}get(e){return this._subscriptions[e]}create(e,{subscribe:t,unsubscribe:n}){let r=this._subscriptions[e]=new CK(e);return r.remoteId=this._localToRemote[e],r.subscriber=t,r.unsubscriber=n,r.gvl=this.glv,r}remove(e){delete this._subscriptions[e],delete this._localToRemote[e]}storeRemoteId(e,t){this._localToRemote[e]=t;let n=this.get(e);n&&(n.remoteId=t)}}class OK{constructor(e={}){this.subscriptions=new DK(e),this._pendingMessages=[],this._remoteToLocal={}}subscribe(e,t){this._remoteToLocal[t]=e,this.subscriptions.storeRemoteId(e,t),this.flush(t)}unsubscribe(e){let t=this.subscriptions.get(e);if(!t)return;let n=t.remoteId;n&&delete this._remoteToLocal[n],this.subscriptions.remove(e)}transmit(e,t,n){let r=this._remoteToLocal[e];if(!r){this._pendingMessages.push([e,t,n]);return}let o=this.subscriptions.get(r);o&&o.channels.forEach(c=>{c.receive(t,n)})}notify(e,t,n){let r=this._remoteToLocal[e];if(!r)return;let o=this.subscriptions.get(r);o&&o.channels.forEach(c=>c.emit(t,n))}close(){this._pendingMessages.length=0}get size(){return this.channels.length}get channels(){return this.subscriptions.all().flatMap(e=>e.channels)}flush(e){let t=[];for(let n of this._pendingMessages)n[0]===e?this.transmit(n[0],n[1],n[2]):t.push(n);this._pendingMessages=t}}const DI={debug:0,info:1,warn:2,error:3};class OI{constructor(e){this.level=e||"warn"}log(e,t,n){DI[e]<DI[this.level]||this.writeLogEntry(e,t,n)}writeLogEntry(){throw Error("Not implemented")}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}}class a1 extends OI{writeLogEntry(){}}class LK{encode(e){return JSON.stringify(e)}decode(e){try{return JSON.parse(e)}catch{}}}let NK=0;class LI{constructor(e={}){let{logger:t}=e;this.logger=t||new a1,this.pendingSubscriptions={},this.pendingUnsubscriptions={},this.subscribeCooldownInterval=e.subscribeCooldownInterval||250,this.subscribeRetryInterval=e.subscribeRetryInterval||5e3}attached(e){this.cable=e}subscribe(e,t){let n={channel:e};t&&Object.assign(n,t);let r=RI(n);if(this.pendingUnsubscriptions[r]){let c=this.subscribeCooldownInterval*1.5;return this.logger.debug(`unsubscribed recently, cooldown for ${c}`,r),new Promise(u=>{setTimeout(()=>{u(this.subscribe(e,t))},c)})}if(this.pendingSubscriptions[r])return this.logger.warn("subscription is already pending, skipping",r),Promise.reject(Error("Already subscribing"));let o=this.subscribeRetryInterval;return new Promise((c,u)=>{let h=++NK;this.pendingSubscriptions[r]={resolve:c,reject:u,id:h},this.cable.send(this.buildSubscribeRequest(r)),this.maybeRetrySubscribe(h,r,o)})}buildSubscribeRequest(e){return{command:"subscribe",identifier:e}}maybeRetrySubscribe(e,t,n){setTimeout(()=>{let r=this.pendingSubscriptions[t];r&&r.id===e&&(this.logger.warn(`no subscription ack received in ${n}ms, retrying subscribe`,t),this.cable.send(this.buildSubscribeRequest(t)),this.maybeExpireSubscribe(e,t,n))},n)}maybeExpireSubscribe(e,t,n){setTimeout(()=>{let r=this.pendingSubscriptions[t];r&&r.id===e&&(delete this.pendingSubscriptions[t],r.reject(new MK(`Haven't received subscription ack in ${n*2}ms for ${t}`)))},n)}unsubscribe(e){return this.cable.send({command:"unsubscribe",identifier:e}),this.pendingUnsubscriptions[e]=!0,setTimeout(()=>{delete this.pendingUnsubscriptions[e]},this.subscribeCooldownInterval),Promise.resolve()}perform(e,t,n){return t==="$whisper"?this.whisper(e,n):(n||(n={}),n.action||=t,this.cable.send({command:"message",identifier:e,data:JSON.stringify(n)}),Promise.resolve())}whisper(e,t){return this.cable.send({command:"whisper",identifier:e,data:t}),Promise.resolve()}receive(e){if(typeof e!="object"){this.logger.error("unsupported message format",{message:e});return}let{type:t,identifier:n,message:r,reason:o,reconnect:c}=e;if(t==="ping")return this.cable.keepalive(e.message);if(this.cable.keepalive(),t==="welcome"){let u=e.sid;return u&&this.cable.setSessionId(u),this.cable.connected()}if(t==="disconnect"){let u=new yc(o);this.reset(u),c===!1?this.cable.closed(u):this.cable.disconnected(u);return}if(t==="confirm_subscription"){let u=this.pendingSubscriptions[n];if(!u){this.logger.error("subscription not found, unsubscribing",{type:t,identifier:n}),this.unsubscribe(n);return}return delete this.pendingSubscriptions[n],u.resolve(n)}if(t==="reject_subscription"){let u=this.pendingSubscriptions[n];return u?(delete this.pendingSubscriptions[n],u.reject(new CI)):this.logger.error("subscription not found",{type:t,identifier:n})}if(r)return{identifier:n,message:r};this.logger.warn(`unknown message type: ${t}`,{message:e})}reset(e){for(let t in this.pendingSubscriptions)this.pendingSubscriptions[t].reject(e);this.pendingSubscriptions={}}recoverableClosure(){return!1}}const NI=()=>Date.now()/1e3|0;class kK extends LI{constructor(e={}){super(e),this.streamsPositions={},this.subscriptionStreams={},this.pendingHistory={},this.pendingPresence={},this.presenceInfo={},this.restoreSince=e.historyTimestamp,this.disableSessionRecovery=e.disableSessionRecovery,this.restoreSince===void 0&&(this.restoreSince=NI()),this.sessionId=void 0,this.sendPongs=e.pongs}reset(e){for(let t in this.pendingPresence)this.pendingPresence[t].reject(e);return this.pendingPresence={},super.reset()}receive(e){if(typeof e!="object"){this.logger.error("unsupported message format",{message:e});return}let{type:t,identifier:n,message:r}=e;if(t==="disconnect")return delete this.sessionId,this.cable.setSessionId(""),super.receive(e);if(t==="reject_subscription")return super.receive(e);if(t==="confirm_subscription")return this.subscriptionStreams[n]||(this.subscriptionStreams[n]=new Set),super.receive(e);if(t==="ping")return this.restoreSince&&(this.restoreSince=NI()),this.sendPongs&&this.sendPong(),this.cable.keepalive(e.message);if(this.cable.keepalive(),t==="confirm_history"){this.logger.debug("history result received",e),this.cable.notify("history_received",n);return}if(t==="reject_history"){this.logger.warn("failed to retrieve history",e),this.cable.notify("history_not_found",n);return}if(t==="welcome"){if(this.disableSessionRecovery||(this.sessionId=e.sid,this.sessionId&&this.cable.setSessionId(this.sessionId)),e.restored){let o=e.restored_ids||Object.keys(this.subscriptionStreams);for(let c of o)this.cable.send({identifier:c,command:"history",history:this.historyRequestFor(c)}),this.presenceInfo[c]&&this.cable.send({identifier:c,command:"join",presence:this.presenceInfo[c]});return this.cable.restored(o)}return this.cable.connected(this.sessionId)}if(t==="presence"){let o=r.type;if(o==="info"){let c=this.pendingPresence[n];c&&(delete this.pendingPresence[n],c.resolve(r))}else if(o==="error"){let c=this.pendingPresence[n];c&&(delete this.pendingPresence[n],c.reject(new Error("failed to retrieve presence")))}return{type:t,identifier:n,message:r}}if(r){let o=this.trackStreamPosition(n,e.stream_id,e.epoch,e.offset);return{identifier:n,message:r,meta:o}}this.logger.warn(`unknown message type: ${t}`,{message:e})}perform(e,t,n){switch(t){case"$presence:join":return this.join(e,n);case"$presence:leave":return this.leave(e,n);case"$presence:info":return this.presence(e,n)}return super.perform(e,t,n)}unsubscribe(e){return delete this.presenceInfo[e],super.unsubscribe(e)}buildSubscribeRequest(e){let t=super.buildSubscribeRequest(e),n=this.historyRequestFor(e);n&&(t.history=n,this.pendingHistory[e]=!0);let r=this.presenceInfo[e];return r&&(t.presence=r),t}recoverableClosure(){return!!this.sessionId}historyRequestFor(e){let t={},n=!1;if(this.subscriptionStreams[e])for(let r of this.subscriptionStreams[e]){let o=this.streamsPositions[r];o&&(n=!0,t[r]=o)}if(!(!n&&!this.restoreSince))return{since:this.restoreSince,streams:t}}trackStreamPosition(e,t,n,r){if(!(!t||!n))return this.subscriptionStreams[e]||(this.subscriptionStreams[e]=new Set),this.subscriptionStreams[e].add(t),this.streamsPositions[t]={epoch:n,offset:r},{stream:t,epoch:n,offset:r}}async sendPong(){await new Promise(e=>setTimeout(e,0)),this.cable.state==="connected"&&this.cable.send({command:"pong"})}async join(e,t){return this.presenceInfo[e]=t,this.cable.send({command:"join",identifier:e,presence:t}),Promise.resolve()}async leave(e,t){return delete this.presenceInfo[e],this.cable.send({command:"leave",identifier:e,presence:t}),Promise.resolve()}presence(e,t){return this.pendingPresence[e]?(this.logger.warn("presence is already pending, skipping",e),Promise.reject(Error("presence request is already pending"))):new Promise((n,r)=>{this.pendingPresence[e]={resolve:n,reject:r},this.cable.send({command:"presence",identifier:e,data:t})})}}class UK extends r1{constructor(){super("No connection","closed"),this.name="NoConnectionError"}}class IK extends oD{static identifier="__ghost__";constructor(e,t){super(t),this.channelId=e}set channelId(e){this._channelId=e}get channelId(){return this._channelId}}const zK="$pubsub";class kI extends oD{static identifier=zK;async perform(e,t){if(e.startsWith("$"))return super.perform(e,t);throw Error("not implemented")}}const Om=Symbol("state");class BK{constructor({transport:e,protocol:t,encoder:n,logger:r,lazy:o,hubOptions:c,performFailures:u,transportConfigurator:h}){this.emitter=iM(),this.transport=e,this.encoder=n,this.logger=r||new a1,this.protocol=t,this.performFailures=u||"throw",this.protocol.attached(this),this.hub=new OK(c||{}),this[Om]="idle",this.handleClose=this.handleClose.bind(this),this.handleIncoming=this.handleIncoming.bind(this),this.transportConfigurator=h,this.transport.on("close",this.handleClose),this.transport.on("data",this.handleIncoming),this.initialConnect=!0,this.recovering=!1,o===!1&&this.connect().catch(()=>{})}get state(){return this[Om]}async connect(){if(this.state==="connected")return Promise.resolve();if(this.state==="connecting")return this.pendingConnect();let e=this.state==="idle";this[Om]="connecting";let t=this.pendingConnect();this.logger.debug("connecting");try{this.transportConfigurator&&await this.transportConfigurator(this.transport,{initial:e}),await this.transport.open()}catch(n){this.handleClose(n)}return t}setSessionId(e){this.sessionId=e,this.transport.setParam("sid",e)}connected(){if(this.state==="connected")return;this.logger.info("connected"),this[Om]="connected",this.recovering&&this.hub.subscriptions.all().forEach(t=>t.notify("disconnected",new yc("recovery_failed"))),this.hub.subscriptions.all().forEach(t=>this._resubscribe(t));let e=!1;this.recovering=!1,this.initialConnect?(this.initialConnect=!1,this.emit("connect",{reconnect:!1,restored:e})):this.emit("connect",{reconnect:!0,restored:e})}restored(e){this.logger.info("connection recovered",{remoteIds:e}),this[Om]="connected",this.hub.subscriptions.all().forEach(r=>{e&&r.remoteId&&e.includes(r.remoteId)?r.notify("restored"):(r.notify("disconnected",new yc("recovery_failed")),this._resubscribe(r))});let t=!this.initialConnect,n=!0;this.recovering=!1,this.initialConnect=!1,this.emit("connect",{reconnect:t,restored:n})}notify(e,t,n){t&&typeof t!="string"&&(n=t,t=void 0),t?this.hub.notify(t,"info",{type:e,data:n}):this.emit("info",{type:e,data:n})}handleClose(e){this.logger.debug("transport closed",{error:e}),this.disconnected(new yc(e,"transport_closed"))}disconnected(e){(this.state==="connected"||this.state==="connecting")&&(this.logger.info("disconnected",{reason:e}),this[Om]="disconnected",this.recovering=this.protocol.recoverableClosure(e),this.recovering?this.hub.subscriptions.all().forEach(t=>t.notify("connecting")):this.hub.subscriptions.all().forEach(t=>{t.notify("disconnected",e)}),this.protocol.reset(e),this.hub.close(),this.transport.close(),this.emit("disconnect",e))}closed(e){if(this.state==="closed"||this.state==="idle")return;let t;e&&(t=e instanceof yc?e:new yc(e,void 0)),this.logger.info("closed",{reason:e||"user"}),this[Om]="closed";let n=t||new yc("cable_closed");this.hub.subscriptions.all().forEach(r=>r.notify("disconnected",n)),this.hub.close(),this.protocol.reset(),this.transport.close(),this.initialConnect=!0,this.emit("close",t)}disconnect(){this.closed()}handleIncoming(e){if(this.state==="closed"||this.state==="idle")return;let t=this.encoder.decode(e);if(t===void 0){this.logger.error("failed to decode message",{message:e});return}this.logger.debug("incoming data",t);let n=this.protocol.receive(t);if(n){this.logger.debug("processed incoming message",n);let{type:r,identifier:o,message:c,meta:u}=n;r?this.hub.notify(o,r,c):this.hub.transmit(o,c,u)}}send(e){if(this.state==="closed")throw Error("Cable is closed");let t=this.encoder.encode(e);if(t===void 0){this.logger.error("failed to encode message",{message:e});return}this.logger.debug("outgoing message",e),this.transport.send(t)}keepalive(e){this.emit("keepalive",e)}streamFrom(e){let t=new kI({stream_name:e});return this.subscribe(t)}streamFromSigned(e){let t=new kI({signed_stream_name:e});return this.subscribe(t)}subscribeTo(e,t){let n,r;return typeof e=="string"&&(r=e,e=IK),n=r?new e(r,t):new e(t),this.subscribe(n)}subscribe(e){if(!e.attached(this))return e;let t=e.identifier;e.connecting();let n=this.hub.subscriptions.get(t)||this.hub.subscriptions.create(t,{subscribe:r=>this._subscribe(r,e.channelId,e.params),unsubscribe:r=>this._unsubscribe(r)});return n.add(e),n.intent==="subscribed"&&n.state==="connected"&&e.connected(),n.ensureSubscribed(),e}async _resubscribe(e){e.intent!=="subscribed"||!e.channels[0]||(e.notify("connecting"),e.ensureResubscribed())}async _subscribe(e,t,n){let r=e.id;if(this.state==="idle"&&this.connect().catch(()=>{}),this.state!=="connected"){this.logger.debug("cancel subscribe, no connection",{identifier:r});return}this.logger.debug("acquiring subscribe lock",{identifier:r});let o=await e.acquire("subscribed");if(o.canceled){this.logger.debug("subscribe lock has been canceled",{identifier:r}),o.release();return}if(this.logger.debug("subscribe lock has been acquired",{identifier:r}),e.intent!=="subscribed"){this.logger.debug("cancel subscribe request, already unsubscribed"),o.release();return}if(this.state!=="connected"){this.logger.debug("cancel subscribe, no connection",{identifier:r}),o.release();return}if(e.state==="connected"){this.logger.debug("already connected, skip subscribe command",{identifier:r}),e.notify("connected"),o.release();return}let c={identifier:t,params:n};this.logger.debug("subscribing",c);try{let u=await this.protocol.subscribe(t,n);this.hub.subscribe(r,u),this.logger.debug("subscribed",{...c,remoteId:u}),e.notify("connected")}catch(u){if(u){if(u instanceof CI&&this.logger.warn("rejected",c),u instanceof yc){this.logger.debug("disconnected during subscription; will retry on connect",c),o.release();return}this.logger.error("failed to subscribe",{error:u,...c})}e.close(u),this.hub.unsubscribe(r)}o.release()}unsubscribe(e){let t=e.identifier,n=this.hub.subscriptions.get(t);if(!n)throw Error(`Subscription not found: ${t}`);n.remove(e),e.closed(),n.maybeUnsubscribe()}async _unsubscribe(e){let t=e.id;this.logger.debug("acquiring unsubscribe lock",{identifier:t});let n=await e.acquire("unsubscribed");if(n.canceled){this.logger.debug("unsubscribe lock has been canceled",{identifier:t}),n.release();return}if(this.logger.debug("unsubscribe lock has been acquired",{identifier:t}),e.intent!=="unsubscribed"){this.logger.debug("cancel unsubscribe, no longer needed",{identifier:t,intent:e.intent}),n.release();return}if(e.state==="disconnected"||e.state==="closed"){this.logger.debug(`already ${e.state} connected, skip unsubscribe command`,{identifier:t}),n.release();return}let r=e.remoteId;if(this.logger.debug("unsubscribing...",{remoteId:r}),this.state!=="connected"){this.logger.debug("unsubscribe skipped (cable is not connected)",{id:t}),e.close(),this.hub.unsubscribe(t),n.release();return}try{await this.protocol.unsubscribe(r),this.logger.debug("unsubscribed remotely",{id:t})}catch(o){o&&(o instanceof yc?this.logger.debug("cable disconnected during the unsubscribe command execution",{id:t,error:o}):this.logger.error("unsubscribe failed",{id:t,error:o}))}e.intent==="unsubscribed"?(e.close(),this.hub.unsubscribe(t)):e.state="closed",n.release()}async perform(e,t,n){if(this.performFailures==="throw")return this._perform(e,t,n);try{return await this._perform(e,t,n)}catch(r){this.performFailures==="warn"&&this.logger.warn("perform failed",{error:r});return}}async _perform(e,t,n){if(this.state==="connecting"&&await this.pendingConnect(),this.state==="closed"||this.state==="disconnected")throw new UK;let r=this.hub.subscriptions.get(e);if(!r)throw Error(`Subscription not found: ${e}`);if(await r.pending("subscribed"),r.intent!=="subscribed")throw Error(`Subscription is closed: ${e}`);let o=r.remoteId,c={id:o,action:t,payload:n};this.logger.debug("perform",c);try{let u=await this.protocol.perform(o,t,n);return u&&this.logger.debug("perform result",{message:u,request:c}),u}catch(u){throw this.logger.error("perform failed",{error:u,request:c}),u}}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...r)=>{n(),t(...r)});return n}emit(e,...t){return this.emitter.emit(e,...t)}pendingConnect(){return this._pendingConnect?this._pendingConnect:(this._pendingConnect=new Promise((e,t)=>{let n=[()=>delete this._pendingConnect];n.push(this.on("connect",()=>{n.forEach(r=>r()),e()})),n.push(this.on("close",r=>{n.forEach(o=>o()),t(r)})),n.push(this.on("disconnect",r=>{n.forEach(o=>o()),t(r)}))}),this._pendingConnect)}}const PK={maxMissingPings:2,maxReconnectAttempts:1/0},Nv=()=>Date.now(),UI=(i,e)=>{e=e||{};let{backoffRate:t,jitterRatio:n,maxInterval:r}=e;return t=t||2,n===void 0&&(n=.5),o=>{let c=i*t**o,u=c*t,h=c+(u-c)*Math.random(),m=2*(Math.random()-.5)*n;return h=h*(1+m),r&&r<h&&(h=r),h}};let II=class{constructor({pingInterval:e,...t}){if(this.pingInterval=e,!this.pingInterval)throw Error(`Incorrect pingInterval is provided: ${e}`);if(t=Object.assign({},PK,t),this.strategy=t.reconnectStrategy,!this.strategy)throw Error("Reconnect strategy must be provided");this.maxMissingPings=t.maxMissingPings,this.maxReconnectAttempts=t.maxReconnectAttempts,this.logger=t.logger||new a1,this.state="pending_connect",this.attempts=0,this.disconnectedAt=Nv()}watch(e){this.target=e,this.initListeners()}reconnectNow(){return this.state==="connected"||this.state==="pending_connect"||this.state==="closed"?!1:(this.cancelReconnect(),this.state="pending_connect",this.target.connect().catch(e=>{this.logger.info("Failed at reconnecting: "+e)}),!0)}initListeners(){this.unbind=[],this.unbind.push(this.target.on("connect",()=>{this.attempts=0,this.pingedAt=Nv(),this.state="connected",this.cancelReconnect(),this.startPolling()})),this.unbind.push(this.target.on("disconnect",()=>{this.disconnectedAt=Nv(),this.state="disconnected",this.stopPolling(),this.scheduleReconnect()})),this.unbind.push(this.target.on("close",()=>{this.disconnectedAt=Nv(),this.state="closed",this.cancelReconnect(),this.stopPolling()})),this.unbind.push(this.target.on("keepalive",()=>{this.pingedAt=Nv()})),this.unbind.push(()=>{this.cancelReconnect(),this.stopPolling()})}dispose(){delete this.target,this.unbind&&this.unbind.forEach(e=>e()),delete this.unbind}startPolling(){this.pollId&&clearTimeout(this.pollId);let e=this.pingInterval+(Math.random()-.5)*this.pingInterval*.5;this.pollId=setTimeout(()=>{this.checkStale(),this.state==="connected"&&this.startPolling()},e)}stopPolling(){this.pollId&&clearTimeout(this.pollId)}checkStale(){let e=Nv()-this.pingedAt;e>this.maxMissingPings*this.pingInterval&&(this.logger.warn(`Stale connection: ${e}ms without pings`),this.state="pending_disconnect",this.target.disconnected(new wK))}scheduleReconnect(){if(this.attempts>=this.maxReconnectAttempts){this.target.close();return}let e=this.strategy(this.attempts);this.attempts++,this.logger.info(`Reconnecting in ${e}ms (${this.attempts} attempt)`),this.state="pending_reconnect",this.reconnnectId=setTimeout(()=>this.reconnectNow(),e)}cancelReconnect(){this.reconnnectId&&(clearTimeout(this.reconnnectId),delete this.reconnnectId)}};class FK{constructor(e,t={}){this.transports=e,this.transport=null,this.emitter=iM(),this.unbind=[],this.logger=t.logger||new a1}displayName(){return"fallbacked transport"}async open(){for(let e=0;e<this.transports.length;e++){let t=this.transports[e];try{this.transport=t,this.resetListeners(),this.logger.debug(`Trying to connect via ${t.displayName()}`),await t.open(),this.logger.debug(`Connected via ${t.displayName()}`);return}catch(n){this.logger.debug(`Failed to connect via ${t.displayName()}: ${n.message}`)}}throw this.transport=null,this.resetListeners(),new Error("Couldn't connect via any available transport")}send(e){if(!this.transport)throw new Error("No transport is open");this.transport.send(e)}async close(){if(!this.transport)throw new Error("No transport is open");await this.transport.close(),this.transport=null}setURL(){throw new Error("Not implemented. Set URL for each transport separately")}setParam(e,t){this.transports.forEach(n=>{n.setParam(e,t)})}setToken(e,t){this.transports.forEach(n=>{n.setToken(e,t)})}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...r)=>{n(),t(...r)});return n}get url(){return this.transport?this.transport.url:""}resetListeners(){this.unbind.forEach(e=>e()),this.unbind.length=0,this.transport&&this.unbind.push(this.transport.on("open",()=>{this.emitter.emit("open")}),this.transport.on("data",e=>{this.emitter.emit("data",e)}),this.transport.on("close",e=>{this.emitter.emit("close",e)}),this.transport.on("error",e=>{this.emitter.emit("error",e)}))}}class HK{constructor(e,t={}){this.url=e;let n=t.websocketImplementation;if(n)this.Impl=n;else if(typeof WebSocket<"u")this.Impl=WebSocket;else throw new Error("No WebSocket support");this.connected=!1,this.emitter=iM();let{format:r,subprotocol:o,authStrategy:c}=t;this.format=r||"text",this.connectionOptions=t.websocketOptions,this.authStrategy=c||"param",this.authProtocol="",this.subprotocol=o}displayName(){return"WebSocket("+this.url+")"}open(){let e=this.subprotocol;return this.authStrategy==="sub-protocol"&&(e=[this.subprotocol,this.authProtocol]),this.connectionOptions?this.ws=new this.Impl(this.url,e,this.connectionOptions):this.ws=new this.Impl(this.url,e),this.ws.binaryType="arraybuffer",this.initListeners(),new Promise((t,n)=>{let r=[];r.push(this.once("open",()=>{r.forEach(o=>o()),t()})),r.push(this.once("close",()=>{r.forEach(o=>o()),n(Error("WS connection closed"))}))})}setURL(e){this.url=e}setParam(e,t){let n=new URL(this.url);n.searchParams.set(e,t);let r=`${n.protocol}//${n.host}${n.pathname}?${n.searchParams}`;this.setURL(r)}setToken(e,t="jid"){if(this.authStrategy==="param")this.setParam(t,e);else if(this.authStrategy==="header"){this.connectionOptions=this.connectionOptions||{},this.connectionOptions.headers=this.connectionOptions.headers||{};let n=`x-${t}`.toLowerCase();n=Object.keys(this.connectionOptions.headers).find(o=>o.toLowerCase()===n)||n,this.connectionOptions.headers[n]=e}else if(this.authStrategy==="sub-protocol")this.authProtocol=`anycable-token.${e}`;else throw new Error("Unknown auth strategy: "+this.authStrategy)}send(e){if(!this.ws||!this.connected)throw Error("WebSocket is not connected");this.ws.send(e)}close(){this.ws?this.onclose():this.connected=!1}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...r)=>{n(),t(...r)});return n}initListeners(){this.ws.onerror=e=>{this.connected&&this.emitter.emit("error",e.error||new Error("WS Error"))},this.ws.onclose=()=>{this.onclose()},this.ws.onmessage=e=>{let t=e.data;this.format==="binary"&&(t=new Uint8Array(t)),this.emitter.emit("data",t)},this.ws.onopen=()=>{this.connected=!0,this.emitter.emit("open")}}onclose(){this.ws.onclose=void 0,this.ws.onmessage=void 0,this.ws.onopen=void 0,this.ws.close(),delete this.ws,this.connected=!1,this.emitter.emit("close")}}const zI={protocol:"actioncable-v1-json",pingInterval:3e3,maxReconnectAttempts:1/0,maxMissingPings:2,logLevel:"warn",lazy:!0};function VK(i,e){if(typeof i=="object"&&typeof e>"u"&&(e=i,i=void 0),e=e||{},!i&&!e.transport)throw Error("URL or transport must be specified");e=Object.assign({},zI,e);let{protocol:t,websocketImplementation:n,websocketFormat:r,websocketOptions:o,websocketAuthStrategy:c,fallbacks:u,logLevel:h,logger:m,transport:_,encoder:p,lazy:y,monitor:x,pingInterval:T,reconnectStrategy:M,maxMissingPings:w,maxReconnectAttempts:A,subprotocol:L,tokenRefresher:N,historyTimestamp:I,protocolOptions:z,concurrentSubscribes:P,performFailures:G,transportConfigurator:$,auth:U}=e;if(m=m||new a1(h),typeof t=="string"){L=L||t;let ne=t.substring(0,t.lastIndexOf("-")),ie=t.substring(t.lastIndexOf("-")+1);if(z=z||{},ne==="actioncable-v1")t=new LI({logger:m,...z});else if(ne==="actioncable-v1-ext")t=new kK({logger:m,historyTimestamp:I,...z});else throw Error(`Protocol is not supported yet: ${t}`);if(ie==="json")p=p||new LK,r=r||"text";else if(ie==="msgpack"){if(r="binary",!p)throw Error("Msgpack encoder must be specified explicitly. Use `@anycable/msgpack-encoder` package or build your own")}else if(ie==="protobuf"){if(r=r||"binary",!p)throw Error("Protobuf encoder must be specified explicitly. Use `@anycable/protobuf-encoder` package or build your own")}else throw Error(`Protocol is not supported yet: ${t}`)}if(!t)throw Error("Protocol must be specified");_=_||new HK(i,{websocketImplementation:n,websocketOptions:o,subprotocol:L,authStrategy:c,format:r}),u&&(_=new FK([_,...u],{logger:m})),U&&U.token&&_.setToken(U.token,U.param||"jid"),M=M||UI(T),x!==!1&&(x=x||new II({pingInterval:T,reconnectStrategy:M,maxMissingPings:w,maxReconnectAttempts:A,logger:m}));let H={concurrentSubscribes:P},J=new BK({protocol:t,transport:_,encoder:p,logger:m,lazy:y,hubOptions:H,performFailures:G,transportConfigurator:$});return x&&(x.watch(J),J.monitor=x),N&&GK(J,async()=>{try{await N(_)}catch(ne){return m.error("Failed to refresh authentication token: "+ne),!1}return J.connect().catch(()=>{}),!0}),J}function GK(i,e){let t=!1;i.on("connect",()=>t=!1),i.on("close",async n=>{if(n){if(t){i.logger.warn("Token auto-refresh is disabled",n);return}n.reason==="token_expired"&&(t=!0,await e())}})}let jK=class extends OI{writeLogEntry(e,t,n){n?console[e](t,n):console[e](t)}};class XK extends II{watch(e){super.watch(e),this.initActivityListeners()}initActivityListeners(){if(typeof document<"u"&&typeof window<"u"&&document.addEventListener&&window.addEventListener){let e=()=>{document.hidden||this.reconnectNow()&&this.logger.debug("Trigger reconnect due to visibility change")},t=r=>{this.reconnectNow()&&this.logger.debug("Trigger reconnect",{event:r})},n=()=>this.disconnect(new yc("page_frozen"));document.addEventListener("visibilitychange",e,!1),window.addEventListener("focus",t,!1),window.addEventListener("online",t,!1),window.addEventListener("resume",t,!1),window.addEventListener("freeze",n,!1),this.unbind.push(()=>{document.removeEventListener("visibilitychange",e,!1),window.removeEventListener("focus",t,!1),window.removeEventListener("online",t,!1),window.removeEventListener("resume",t,!1),window.removeEventListener("freeze",n,!1)})}}disconnect(e){this.state==="disconnected"||this.state==="closed"||(this.logger.info("Disconnecting",{reason:e.message}),this.cancelReconnect(),this.stopPolling(),this.state="pending_disconnect",this.target.disconnected(e))}}const qK=["cable","action-cable"],$K="/cable",rM=(i,e)=>{for(let t of qK){let n=i.head.querySelector(`meta[name='${t}-${e}']`);if(n)return n.getAttribute("content")}},BI=i=>i.match(/wss?:\/\//)?i:typeof window<"u"?`${window.location.protocol.replace("http","ws")}//${window.location.host}${i}`:i,YK=()=>{if(typeof document<"u"&&document.head){let i=rM(document,"url");if(i)return BI(i)}return BI($K)},WK=()=>{if(typeof document<"u"&&document.head){let i=rM(document,"history-timestamp");if(i)return i|0}},ZK=()=>{if(typeof document<"u"&&document.head)return rM(document,"token")},KK=()=>{if(typeof document<"u"&&document.head)return rM(document,"token-param")};function JK(i,e){typeof i=="object"&&typeof e>"u"&&(e=i,i=void 0),i=i||YK(),e=e||{},e.historyTimestamp||=WK();let t=ZK();if(t){let m=KK();e.auth=Object.assign({token:t,param:m},e.auth||{})}e=Object.assign({},zI,e);let{logLevel:n,logger:r,pingInterval:o,reconnectStrategy:c,maxMissingPings:u,maxReconnectAttempts:h}=e;return r=e.logger=e.logger||new jK(n),c=e.reconnectStrategy=e.reconnectStrategy||UI(o),e.monitor!==!1&&(e.monitor=e.monitor||new XK({pingInterval:o,reconnectStrategy:c,maxMissingPings:u,maxReconnectAttempts:h,logger:r})),VK(i,e)}class QK extends oD{static identifier="WidgetChatChannel"}const s1={debug:0,info:1,warn:2,error:3};class eJ{level;prefix;constructor(e="Widget",t="info"){this.prefix=`[${e}]`,this.level=s1[t]}debug(...e){this.level<=s1.debug&&console.debug(this.prefix,...e)}info(...e){this.level<=s1.info&&console.info(this.prefix,...e)}warn(...e){this.level<=s1.warn&&console.warn(this.prefix,...e)}error(...e){this.level<=s1.error&&console.error(this.prefix,...e)}}let tJ="warn";const Ei=new eJ("BridgeApp-Widget",tJ);window.addEventListener("error",i=>{console.error("Unhandled error",i.error)});class nJ{url;cable;channels={chat:new QK};constructor(e){this.url=e,this.register()}subscribe(e){return Ei.info("SUBSCRIBE","[AnyCableService] Subscribing to channel",e.identifier),this.cable?.subscribe(e),this}unsubscribe(e){return this.cable?.unsubscribe(e),this}register(){return Ei.info("[AnyCableService] Registering cable with status: ",this.cable?.state),this.cable||(Ei.info("[AnyCableService] Creating cable"),this.cable=JK(this.url,{pingInterval:3e3,protocol:"actioncable-v1-ext-json",protocolOptions:{pongs:!0,subscribeRetryInterval:3e4}})),this.cable.state!=="connecting"&&this.cable.state!=="connected"&&(Ei.info("[AnyCableService] Connecting cable, state: ",this.cable.state),this.cable.connect().then(()=>{Ei.info("[AnyCableService] Cable connected, subscribing to channel: ",this.channels.chat.identifier),this.cable.subscribe(this.channels.chat)})),this}unregister(){this.cable&&(Ei.info("[AnyCableService] Disconnecting cable"),this.cable.disconnect())}}var _c=(i=>(i.Pending="pending",i.Available="available",i.Offline="offline",i.Unavailable="unavailable",i))(_c||{});const PI=te.createContext(void 0),iJ=i=>{const[e,t]=te.useState(!1),[n,r]=te.useState(_c.Pending),o=te.useRef(n);te.useEffect(()=>{o.current=n},[n]);const c=te.useRef(null);return te.useEffect(()=>{const u=new nJ(`${i.wsUrl}?access_token=${i.customerInteractionSession.accessToken}`);return c.current=u,u.channels.chat.on("info",h=>{h.type==="reject_history"&&document.location.reload()}),u.channels.chat.on("connect",()=>{console.info("[CableContext] Connected to the chat channel"),r(_c.Available)}),u.channels.chat.on("disconnect",h=>{r(_c.Unavailable),console.warn("[CableContext] Disconnected from the chat channel",h)}),window.addEventListener("online",()=>{o.current===_c.Offline&&r(_c.Available)}),window.addEventListener("offline",()=>{r(_c.Offline)}),u.channels.chat.on("close",h=>{console.warn("[CableContext] Closed the chat channel",h)}),t(!0),()=>{c.current&&(c.current.unregister(),c.current=null),t(!1)}},[i.wsUrl,i.customerInteractionSession.accessToken]),e?{anycableService:c.current,networkStatus:n}:null},rJ=({children:i,config:e})=>{const t=iJ(e);return t?qe.jsx(PI.Provider,{value:t,children:i}):null},lD=()=>{const i=te.useContext(PI);if(i===void 0)throw new Error("useCable must be used within an CableProvider");return i},kv={connectionFailed:"Connection failed",offline:"You're offline",agentResponseFailed:"Agent response failed",sendMessageFallback:"Failed to send message"},FI=i=>{let e;const t=new Set,n=(m,_)=>{const p=typeof m=="function"?m(e):m;if(!Object.is(p,e)){const y=e;e=_??(typeof p!="object"||p===null)?p:Object.assign({},e,p),t.forEach(x=>x(e,y))}},r=()=>e,u={setState:n,getState:r,getInitialState:()=>h,subscribe:m=>(t.add(m),()=>t.delete(m))},h=e=i(n,r,u);return u},aJ=(i=>i?FI(i):FI),sJ=i=>i;function oJ(i,e=sJ){const t=em.useSyncExternalStore(i.subscribe,em.useCallback(()=>e(i.getState()),[i,e]),em.useCallback(()=>e(i.getInitialState()),[i,e]));return em.useDebugValue(t),t}const HI=i=>{const e=aJ(i),t=n=>oJ(e,n);return Object.assign(t,e),t},VI=(i=>i?HI(i):HI);function o1(i,e){i.message.includes("401")&&e?.()}const lJ="6bd37ad5-19e3-449a-9bbf-7ef51e4b4db8",cJ={voice:"ara"},GI=async(i,e)=>{try{const t=await fetch(`${i.apiUrl}/agents.Agents/StartVoiceSession`,{method:"POST",headers:{Authorization:`Bearer ${i.customerInteractionSession.accessToken}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({agentId:i.agentId,voiceModelId:lJ,voiceConfig:cJ})});return{status:t.status,json:await t.json()}}catch(t){throw o1(t,e.onSessionExpired),t}};async function cD(i,e,t,n){try{const r=await fetch(`${i.apiUrl}/agents.Agents/EndVoiceSession`,{method:"POST",headers:{Authorization:`Bearer ${i.customerInteractionSession.accessToken}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({voiceSessionId:t,reason:n})});if(!r.ok)throw new Error(`Request failed: ${r.status} ${r.statusText}`);return await r.json()}catch(r){throw o1(r,e.onSessionExpired),r}}async function uJ({voiceBaseUrl:i,voiceSessionId:e,sessionToken:t,clientInstanceId:n,protocolVersion:r,expectedConnectionGeneration:o,offerSdp:c}){try{Ei.debug("sendOffer",{voiceSessionId:e,clientInstanceId:n,protocolVersion:r,expectedConnectionGeneration:o,offerSdpLength:c.length});const u=await fetch(`${i}/SendOffer`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({voiceSessionId:e,sessionToken:t,clientInstanceId:n,protocolVersion:r,expectedConnectionGeneration:o,offerSdp:c})});if(!u.ok)throw new Error(`Request failed: ${u.status} ${u.statusText}`);return await u.json()}catch(u){throw console.error("Request failed:",u),u}}async function fJ({voiceBaseUrl:i,voiceSessionId:e,sessionToken:t,clientInstanceId:n,connectionId:r,connectionGeneration:o,candidates:c}){try{const u=await fetch(`${i}/SendCandidates`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({voiceSessionId:e,sessionToken:t,clientInstanceId:n,connectionId:r,connectionGeneration:o,candidates:c})});if(!u.ok)throw new Error(`Request failed: ${u.status} ${u.statusText}`)}catch(u){throw console.error("Request failed:",u),u}}async function dJ({voiceBaseUrl:i,voiceSessionId:e,sessionToken:t,clientInstanceId:n,connectionId:r,connectionGeneration:o,reason:c}){const u=await fetch(`${i}/EndSession`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({voiceSessionId:e,sessionToken:t,clientInstanceId:n,connectionId:r,connectionGeneration:o,reason:c})});if(!u.ok)throw new Error(`Request failed: ${u.status} ${u.statusText}`)}const uD=globalThis.crypto?.randomUUID?.()??`widget-${Date.now()}-${Math.random().toString(16).slice(2)}`;function l1(){return{activeVoiceSessionData:null,config:null,api:null,status:"idle",errorMessage:null,isVoiceBootstrapped:!1,connection:null,connectionId:null,connectionGeneration:null,iceCandidates:[],voiceEventsChannel:null,voiceInputChannel:null,downstream:null,localStream:null,remoteAudioElement:null,customerMessageTranscript:"",customerMessageTranscriptVisible:!1,assistantMessageTranscript:"",assistantMessageTranscriptVisible:!1,assistantResponseInProgress:!1}}function fD(i){i?.getTracks().forEach(e=>e.stop())}function jI(i){if(!(!i||i.readyState==="closed"))try{i.close()}catch(e){Ei.debug("Failed to close data channel",e)}}function hJ(i){if(!(!i||i.connectionState==="closed"))try{i.close()}catch(e){Ei.debug("Failed to close peer connection",e)}}function XI(i){jI(i.voiceEventsChannel),jI(i.voiceInputChannel),hJ(i.connection),fD(i.localStream),fD(i.downstream),i.remoteAudioElement&&(i.remoteAudioElement.pause(),i.remoteAudioElement.srcObject=null)}function pJ(i){return i instanceof Error?i.message:"Voice session failed"}const yl=VI((i,e)=>({...l1(),async init(t,n,r){const o=r.getAudioTracks()[0];if(!o)throw fD(r),new Error("No audio input track available");i({...l1(),config:t,localStream:r,status:"connecting"});try{let c=await GI(t,n);if(c.status===409){const y=c.json.message.split(" ").pop();y&&(await cD(t,n,y,"replace_stale_session"),c=await GI(t,n))}if(c.status>=400)throw new Error(c.json.message||"Unable to start voice session");const u=c.json;Ei.debug("StartVoiceSession response",{sessionId:u.session.id,voiceBaseUrl:u.voiceBaseUrl,voiceProtocolVersion:u.voiceProtocolVersion}),i({config:t,localStream:r,activeVoiceSessionData:u});const h=e().createConnection();h.ondatachannel=p=>{Ei.debug("ondatachannel",p.channel.label),p.channel.label==="voice-events"&&(i({voiceEventsChannel:p.channel}),p.channel.onmessage=y=>{e().onVoiceEventsEvent(y)}),p.channel.label==="voice-input"&&(i({voiceInputChannel:p.channel}),p.channel.onmessage=y=>{e().onVoiceInputEvent(y)})},h.addEventListener("track",p=>{const y=p.streams[0];y&&(Ei.debug("Received remote audio track"),i({downstream:y}),e().playRemoteAudio(y))}),h.onicecandidate=p=>{if(p.candidate){i(y=>({iceCandidates:[...y.iceCandidates,p.candidate?.toJSON()??{}]}));return}e().sendCandidates()},h.addEventListener("connectionstatechange",()=>{if(Ei.debug("Peer connection state",h.connectionState),h.connectionState==="connected"){i({status:"live",errorMessage:null});return}(h.connectionState==="failed"||h.connectionState==="disconnected")&&i({status:"error",errorMessage:"Voice connection was interrupted"})}),h.addTrack(o,r),h.createDataChannel("voice-bootstrap");const m=await h.createOffer();await h.setLocalDescription(m);const _=await uJ({voiceBaseUrl:u.voiceBaseUrl,voiceSessionId:u.session.id,sessionToken:u.sessionToken,clientInstanceId:uD,protocolVersion:u.voiceProtocolVersion,expectedConnectionGeneration:0,offerSdp:h.localDescription?.sdp??m.sdp??""});Ei.debug("SendOffer response",{connectionId:_.connectionId,connectionGeneration:_.connectionGeneration}),i({connection:h,connectionId:_.connectionId,connectionGeneration:_.connectionGeneration,isVoiceBootstrapped:!0}),await h.setRemoteDescription({type:"answer",sdp:_.answerSdp}),await e().sendCandidates()}catch(c){Ei.error("Voice bootstrap failed",c);const u=e().activeVoiceSessionData;if(u)try{await cD(t,n,u.session.id,"bootstrap_failed")}catch(h){Ei.warn("Failed to close voice session after bootstrap error",h)}throw XI(e()),i({...l1(),status:"error",errorMessage:pJ(c)}),c}},sendCandidates:async()=>{const t=e().activeVoiceSessionData,n=e().connectionId,r=e().connectionGeneration,o=e().iceCandidates;if(!(!t||!n||r==null||o.length===0)){i({iceCandidates:[]});try{await fJ({voiceBaseUrl:t.voiceBaseUrl,voiceSessionId:t.session.id,sessionToken:t.sessionToken,clientInstanceId:uD,connectionId:n,connectionGeneration:r,candidates:o}),Ei.debug("Sent ICE candidates",{count:o.length})}catch(c){throw Ei.error("Failed to send ICE candidates",c),i(u=>({iceCandidates:[...o,...u.iceCandidates]})),c}}},createConnection:()=>{const t=e().activeVoiceSessionData;if(!t)throw new Error("Voice session data not found");const n={urls:t.voiceTurn.urls,username:t.voiceTurn.username};return t.voiceTurn.useSessionTokenCredential&&(n.credential=t.sessionToken),new RTCPeerConnection({iceServers:[n]})},playRemoteAudio(t){let n=e().remoteAudioElement;n||(n=new Audio,n.autoplay=!0,i({remoteAudioElement:n})),n.srcObject=t,n.muted=!1,n.play().catch(r=>{Ei.debug("audioElement play error",r)})},endSession:async(t="user_hangup")=>{const{activeVoiceSessionData:n,config:r,api:o,connectionGeneration:c,connectionId:u,voiceInputChannel:h}=e();if(!n&&!e().connection&&!e().localStream&&!e().downstream){i(l1());return}i({status:"ending"});try{h?.readyState==="open"&&h.send(JSON.stringify({type:"end_session",reason:t}))}catch(m){Ei.warn("Failed to notify runtime about session end",m)}try{n&&u&&c!=null&&await dJ({voiceBaseUrl:n.voiceBaseUrl,voiceSessionId:n.session.id,sessionToken:n.sessionToken,clientInstanceId:uD,connectionId:u,connectionGeneration:c,reason:t})}catch(m){Ei.warn("Failed to end WebRTC session",m)}try{n&&await cD(r,o,n.session.id,t)}catch(m){Ei.warn("Failed to end voice session",m)}finally{XI(e()),i(l1())}},setMicrophoneEnabled:t=>{e().localStream?.getAudioTracks().forEach(n=>n.enabled=t)},onVoiceEventsEvent:t=>{try{const n=JSON.parse(t.data);switch(Ei.debug("voice-events message",n),n.type){case"input_audio_speech_started":i({customerMessageTranscript:"",assistantMessageTranscriptVisible:!1});break;case"response_started":i({assistantResponseInProgress:!0,assistantMessageTranscript:""});break;case"assistant_transcript_delta":i({assistantMessageTranscript:e().assistantMessageTranscript+(n.text??""),assistantMessageTranscriptVisible:!0});break;case"assistant_transcript_final":i({assistantMessageTranscript:n.text??"",assistantMessageTranscriptVisible:!0});break;case"response_cancelled":case"assistant_turn_done":case"assistant_turn_failed":i({assistantResponseInProgress:!1});break;case"user_transcript_delta":i({customerMessageTranscriptVisible:!0,customerMessageTranscript:e().customerMessageTranscript+(n.text??"")});break;case"user_transcript_final":i({customerMessageTranscriptVisible:!0,customerMessageTranscript:n.text??""});break;case"realtime_error":i({status:"error",errorMessage:n.message??"Voice session failed"});break}}catch(n){Ei.warn("Failed to parse voice-events payload",n)}},onVoiceInputEvent:t=>{try{const n=JSON.parse(t.data);Ei.debug("voice-input message",n)}catch(n){Ei.warn("Failed to parse voice-input payload",n)}}})),qI="audioinput",mJ="audiooutput";function gJ(i){return{deviceId:i.deviceId,kind:i.kind,label:i.label||(i.kind===qI?"Default microphone":"Default speaker"),groupId:i.groupId}}function vJ(){return typeof navigator>"u"||!navigator.mediaDevices?null:navigator.mediaDevices}function $I(i,e){return i.filter(t=>t.kind===e).map(gJ)}function yJ(){const[i,e]=te.useState([]),[t,n]=te.useState([]),[r,o]=te.useState(""),[c,u]=te.useState(""),[h,m]=te.useState("prompt"),[_,p]=te.useState(!1),[y,x]=te.useState(null),T=vJ(),M=T!==null,w=te.useCallback(async()=>{if(T){x(null);try{const L=await T.enumerateDevices();e($I(L,qI)),n($I(L,mJ))}catch(L){const N=L instanceof Error?L.message:"Failed to list devices";x(N)}}},[T]),A=te.useCallback(async()=>{if(!T)return{ok:!1,error:new Error("MediaDevices not supported"),message:"Audio devices are not supported in this browser or context."};x(null),p(!0);try{return(await T.getUserMedia({audio:!0})).getTracks().forEach(N=>N.stop()),m("granted"),await w(),{ok:!0}}catch(L){const N=L instanceof Error?L:new Error(String(L)),I=N.name==="NotAllowedError"||N.name==="PermissionDeniedError";I&&m("denied");const z=I?"Microphone access was denied.":N.message||"Could not access microphone.";return x(z),{ok:!1,error:N,message:z}}finally{p(!1)}},[T,w]);return te.useEffect(()=>{T&&w()},[T,w]),te.useEffect(()=>{if(!T)return;const L=()=>{w()};return T.addEventListener("devicechange",L),()=>T.removeEventListener("devicechange",L)},[T,w]),{inputDevices:i,outputDevices:t,selectedInputId:r,selectedOutputId:c,permissionState:h,isLoading:_,error:y,requestPermission:A,refreshDevices:w,setInputDevice:o,setOutputDevice:u,isSupported:M}}function _J(i){return{audio:{advanced:[{deviceId:i?{exact:i}:void 0,noiseSuppression:!0,echoCancellation:!0,autoGainControl:!1}]}}}function Aa(i){this.content=i}Aa.prototype={constructor:Aa,find:function(i){for(var e=0;e<this.content.length;e+=2)if(this.content[e]===i)return e;return-1},get:function(i){var e=this.find(i);return e==-1?void 0:this.content[e+1]},update:function(i,e,t){var n=t&&t!=i?this.remove(t):this,r=n.find(i),o=n.content.slice();return r==-1?o.push(t||i,e):(o[r+1]=e,t&&(o[r]=t)),new Aa(o)},remove:function(i){var e=this.find(i);if(e==-1)return this;var t=this.content.slice();return t.splice(e,2),new Aa(t)},addToStart:function(i,e){return new Aa([i,e].concat(this.remove(i).content))},addToEnd:function(i,e){var t=this.remove(i).content.slice();return t.push(i,e),new Aa(t)},addBefore:function(i,e,t){var n=this.remove(e),r=n.content.slice(),o=n.find(i);return r.splice(o==-1?r.length:o,0,e,t),new Aa(r)},forEach:function(i){for(var e=0;e<this.content.length;e+=2)i(this.content[e],this.content[e+1])},prepend:function(i){return i=Aa.from(i),i.size?new Aa(i.content.concat(this.subtract(i).content)):this},append:function(i){return i=Aa.from(i),i.size?new Aa(this.subtract(i).content.concat(i.content)):this},subtract:function(i){var e=this;i=Aa.from(i);for(var t=0;t<i.content.length;t+=2)e=e.remove(i.content[t]);return e},toObject:function(){var i={};return this.forEach(function(e,t){i[e]=t}),i},get size(){return this.content.length>>1}},Aa.from=function(i){if(i instanceof Aa)return i;var e=[];if(i)for(var t in i)e.push(t,i[t]);return new Aa(e)};function YI(i,e,t){for(let n=0;;n++){if(n==i.childCount||n==e.childCount)return i.childCount==e.childCount?null:t;let r=i.child(n),o=e.child(n);if(r==o){t+=r.nodeSize;continue}if(!r.sameMarkup(o))return t;if(r.isText&&r.text!=o.text){for(let c=0;r.text[c]==o.text[c];c++)t++;return t}if(r.content.size||o.content.size){let c=YI(r.content,o.content,t+1);if(c!=null)return c}t+=r.nodeSize}}function WI(i,e,t,n){for(let r=i.childCount,o=e.childCount;;){if(r==0||o==0)return r==o?null:{a:t,b:n};let c=i.child(--r),u=e.child(--o),h=c.nodeSize;if(c==u){t-=h,n-=h;continue}if(!c.sameMarkup(u))return{a:t,b:n};if(c.isText&&c.text!=u.text){let m=0,_=Math.min(c.text.length,u.text.length);for(;m<_&&c.text[c.text.length-m-1]==u.text[u.text.length-m-1];)m++,t--,n--;return{a:t,b:n}}if(c.content.size||u.content.size){let m=WI(c.content,u.content,t-1,n-1);if(m)return m}t-=h,n-=h}}class it{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let n=0;n<e.length;n++)this.size+=e[n].nodeSize}nodesBetween(e,t,n,r=0,o){for(let c=0,u=0;u<t;c++){let h=this.content[c],m=u+h.nodeSize;if(m>e&&n(h,r+u,o||null,c)!==!1&&h.content.size){let _=u+1;h.nodesBetween(Math.max(0,e-_),Math.min(h.content.size,t-_),n,r+_)}u=m}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,r){let o="",c=!0;return this.nodesBetween(e,t,(u,h)=>{let m=u.isText?u.text.slice(Math.max(e,h)-h,t-h):u.isLeaf?r?typeof r=="function"?r(u):r:u.type.spec.leafText?u.type.spec.leafText(u):"":"";u.isBlock&&(u.isLeaf&&m||u.isTextblock)&&n&&(c?c=!1:o+=n),o+=m},0),o}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,n=e.firstChild,r=this.content.slice(),o=0;for(t.isText&&t.sameMarkup(n)&&(r[r.length-1]=t.withText(t.text+n.text),o=1);o<e.content.length;o++)r.push(e.content[o]);return new it(r,this.size+e.size)}cut(e,t=this.size){if(e==0&&t==this.size)return this;let n=[],r=0;if(t>e)for(let o=0,c=0;c<t;o++){let u=this.content[o],h=c+u.nodeSize;h>e&&((c<e||h>t)&&(u.isText?u=u.cut(Math.max(0,e-c),Math.min(u.text.length,t-c)):u=u.cut(Math.max(0,e-c-1),Math.min(u.content.size,t-c-1))),n.push(u),r+=u.nodeSize),c=h}return new it(n,r)}cutByIndex(e,t){return e==t?it.empty:e==0&&t==this.content.length?this:new it(this.content.slice(e,t))}replaceChild(e,t){let n=this.content[e];if(n==t)return this;let r=this.content.slice(),o=this.size+t.nodeSize-n.nodeSize;return r[e]=t,new it(r,o)}addToStart(e){return new it([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new it(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;t<this.content.length;t++)if(!this.content[t].eq(e.content[t]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(e){let t=this.content[e];if(!t)throw new RangeError("Index "+e+" out of range for "+this);return t}maybeChild(e){return this.content[e]||null}forEach(e){for(let t=0,n=0;t<this.content.length;t++){let r=this.content[t];e(r,n,t),n+=r.nodeSize}}findDiffStart(e,t=0){return YI(this,e,t)}findDiffEnd(e,t=this.size,n=e.size){return WI(this,e,t,n)}findIndex(e){if(e==0)return aM(0,e);if(e==this.size)return aM(this.content.length,e);if(e>this.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,n=0;;t++){let r=this.child(t),o=n+r.nodeSize;if(o>=e)return o==e?aM(t+1,o):aM(t,n);n=o}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return it.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return new it(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return it.empty;let t,n=0;for(let r=0;r<e.length;r++){let o=e[r];n+=o.nodeSize,r&&o.isText&&e[r-1].sameMarkup(o)?(t||(t=e.slice(0,r)),t[t.length-1]=o.withText(t[t.length-1].text+o.text)):t&&t.push(o)}return new it(t||e,n)}static from(e){if(!e)return it.empty;if(e instanceof it)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new it([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}it.empty=new it([],0);const dD={index:0,offset:0};function aM(i,e){return dD.index=i,dD.offset=e,dD}function sM(i,e){if(i===e)return!0;if(!(i&&typeof i=="object")||!(e&&typeof e=="object"))return!1;let t=Array.isArray(i);if(Array.isArray(e)!=t)return!1;if(t){if(i.length!=e.length)return!1;for(let n=0;n<i.length;n++)if(!sM(i[n],e[n]))return!1}else{for(let n in i)if(!(n in e)||!sM(i[n],e[n]))return!1;for(let n in e)if(!(n in i))return!1}return!0}let Hi=class v4{constructor(e,t){this.type=e,this.attrs=t}addToSet(e){let t,n=!1;for(let r=0;r<e.length;r++){let o=e[r];if(this.eq(o))return e;if(this.type.excludes(o.type))t||(t=e.slice(0,r));else{if(o.type.excludes(this.type))return e;!n&&o.type.rank>this.type.rank&&(t||(t=e.slice(0,r)),t.push(this),n=!0),t&&t.push(o)}}return t||(t=e.slice()),n||t.push(this),t}removeFromSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return e.slice(0,t).concat(e.slice(t+1));return e}isInSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return!0;return!1}eq(e){return this==e||this.type==e.type&&sM(this.attrs,e.attrs)}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Mark.fromJSON");let n=e.marks[t.type];if(!n)throw new RangeError(`There is no mark type ${t.type} in this schema`);let r=n.create(t.attrs);return n.checkAttrs(r.attrs),r}static sameSet(e,t){if(e==t)return!0;if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++)if(!e[n].eq(t[n]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&e.length==0)return v4.none;if(e instanceof v4)return[e];let t=e.slice();return t.sort((n,r)=>n.type.rank-r.type.rank),t}};Hi.none=[];class oM extends Error{}class St{constructor(e,t,n){this.content=e,this.openStart=t,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let n=KI(this.content,e+this.openStart,t);return n&&new St(n,this.openStart,this.openEnd)}removeBetween(e,t){return new St(ZI(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return St.empty;let n=t.openStart||0,r=t.openEnd||0;if(typeof n!="number"||typeof r!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new St(it.fromJSON(e,t.content),n,r)}static maxOpen(e,t=!0){let n=0,r=0;for(let o=e.firstChild;o&&!o.isLeaf&&(t||!o.type.spec.isolating);o=o.firstChild)n++;for(let o=e.lastChild;o&&!o.isLeaf&&(t||!o.type.spec.isolating);o=o.lastChild)r++;return new St(e,n,r)}}St.empty=new St(it.empty,0,0);function ZI(i,e,t){let{index:n,offset:r}=i.findIndex(e),o=i.maybeChild(n),{index:c,offset:u}=i.findIndex(t);if(r==e||o.isText){if(u!=t&&!i.child(c).isText)throw new RangeError("Removing non-flat range");return i.cut(0,e).append(i.cut(t))}if(n!=c)throw new RangeError("Removing non-flat range");return i.replaceChild(n,o.copy(ZI(o.content,e-r-1,t-r-1)))}function KI(i,e,t,n){let{index:r,offset:o}=i.findIndex(e),c=i.maybeChild(r);if(o==e||c.isText)return n&&!n.canReplace(r,r,t)?null:i.cut(0,e).append(t).append(i.cut(e));let u=KI(c.content,e-o-1,t,c);return u&&i.replaceChild(r,c.copy(u))}function bJ(i,e,t){if(t.openStart>i.depth)throw new oM("Inserted content deeper than insertion position");if(i.depth-t.openStart!=e.depth-t.openEnd)throw new oM("Inconsistent open depths");return JI(i,e,t,0)}function JI(i,e,t,n){let r=i.index(n),o=i.node(n);if(r==e.index(n)&&n<i.depth-t.openStart){let c=JI(i,e,t,n+1);return o.copy(o.content.replaceChild(r,c))}else if(t.content.size)if(!t.openStart&&!t.openEnd&&i.depth==n&&e.depth==n){let c=i.parent,u=c.content;return Nm(c,u.cut(0,i.parentOffset).append(t.content).append(u.cut(e.parentOffset)))}else{let{start:c,end:u}=xJ(t,i);return Nm(o,e6(i,c,u,e,n))}else return Nm(o,lM(i,e,n))}function QI(i,e){if(!e.type.compatibleContent(i.type))throw new oM("Cannot join "+e.type.name+" onto "+i.type.name)}function hD(i,e,t){let n=i.node(t);return QI(n,e.node(t)),n}function Lm(i,e){let t=e.length-1;t>=0&&i.isText&&i.sameMarkup(e[t])?e[t]=i.withText(e[t].text+i.text):e.push(i)}function c1(i,e,t,n){let r=(e||i).node(t),o=0,c=e?e.index(t):r.childCount;i&&(o=i.index(t),i.depth>t?o++:i.textOffset&&(Lm(i.nodeAfter,n),o++));for(let u=o;u<c;u++)Lm(r.child(u),n);e&&e.depth==t&&e.textOffset&&Lm(e.nodeBefore,n)}function Nm(i,e){return i.type.checkContent(e),i.copy(e)}function e6(i,e,t,n,r){let o=i.depth>r&&hD(i,e,r+1),c=n.depth>r&&hD(t,n,r+1),u=[];return c1(null,i,r,u),o&&c&&e.index(r)==t.index(r)?(QI(o,c),Lm(Nm(o,e6(i,e,t,n,r+1)),u)):(o&&Lm(Nm(o,lM(i,e,r+1)),u),c1(e,t,r,u),c&&Lm(Nm(c,lM(t,n,r+1)),u)),c1(n,null,r,u),new it(u)}function lM(i,e,t){let n=[];if(c1(null,i,t,n),i.depth>t){let r=hD(i,e,t+1);Lm(Nm(r,lM(i,e,t+1)),n)}return c1(e,null,t,n),new it(n)}function xJ(i,e){let t=e.depth-i.openStart,r=e.node(t).copy(i.content);for(let o=t-1;o>=0;o--)r=e.node(o).copy(it.from(r));return{start:r.resolveNoCache(i.openStart+t),end:r.resolveNoCache(r.content.size-i.openEnd-t)}}class u1{constructor(e,t,n){this.pos=e,this.path=t,this.parentOffset=n,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let n=this.pos-this.path[this.path.length-1],r=e.child(t);return n?e.child(t).cut(n):r}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let n=this.path[t*3],r=t==0?0:this.path[t*3-1]+1;for(let o=0;o<e;o++)r+=n.child(o).nodeSize;return r}marks(){let e=this.parent,t=this.index();if(e.content.size==0)return Hi.none;if(this.textOffset)return e.child(t).marks;let n=e.maybeChild(t-1),r=e.maybeChild(t);if(!n){let u=n;n=r,r=u}let o=n.marks;for(var c=0;c<o.length;c++)o[c].type.spec.inclusive===!1&&(!r||!o[c].isInSet(r.marks))&&(o=o[c--].removeFromSet(o));return o}marksAcross(e){let t=this.parent.maybeChild(this.index());if(!t||!t.isInline)return null;let n=t.marks,r=e.parent.maybeChild(e.index());for(var o=0;o<n.length;o++)n[o].type.spec.inclusive===!1&&(!r||!n[o].isInSet(r.marks))&&(n=n[o--].removeFromSet(n));return n}sharedDepth(e){for(let t=this.depth;t>0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos<this.pos)return e.blockRange(this);for(let n=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);n>=0;n--)if(e.pos<=this.end(n)&&(!t||t(this.node(n))))return new cM(this,e,n);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos<this.pos?e:this}toString(){let e="";for(let t=1;t<=this.depth;t++)e+=(e?"/":"")+this.node(t).type.name+"_"+this.index(t-1);return e+":"+this.parentOffset}static resolve(e,t){if(!(t>=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let n=[],r=0,o=t;for(let c=e;;){let{index:u,offset:h}=c.content.findIndex(o),m=o-h;if(n.push(c,u,r+h),!m||(c=c.child(u),c.isText))break;o=m-1,r+=h+1}return new u1(t,n,o)}static resolveCached(e,t){let n=t6.get(e);if(n)for(let o=0;o<n.elts.length;o++){let c=n.elts[o];if(c.pos==t)return c}else t6.set(e,n=new SJ);let r=n.elts[n.i]=u1.resolve(e,t);return n.i=(n.i+1)%EJ,r}}class SJ{constructor(){this.elts=[],this.i=0}}const EJ=12,t6=new WeakMap;class cM{constructor(e,t,n){this.$from=e,this.$to=t,this.depth=n}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}}const TJ=Object.create(null);let lh=class y4{constructor(e,t,n,r=Hi.none){this.type=e,this.attrs=t,this.marks=r,this.content=n||it.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(e){return this.content.child(e)}maybeChild(e){return this.content.maybeChild(e)}forEach(e){this.content.forEach(e)}nodesBetween(e,t,n,r=0){this.content.nodesBetween(e,t,n,r,this)}descendants(e){this.nodesBetween(0,this.content.size,e)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(e,t,n,r){return this.content.textBetween(e,t,n,r)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(e){return this==e||this.sameMarkup(e)&&this.content.eq(e.content)}sameMarkup(e){return this.hasMarkup(e.type,e.attrs,e.marks)}hasMarkup(e,t,n){return this.type==e&&sM(this.attrs,t||e.defaultAttrs||TJ)&&Hi.sameSet(this.marks,n||Hi.none)}copy(e=null){return e==this.content?this:new y4(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new y4(this.type,this.attrs,this.content,e)}cut(e,t=this.content.size){return e==0&&t==this.content.size?this:this.copy(this.content.cut(e,t))}slice(e,t=this.content.size,n=!1){if(e==t)return St.empty;let r=this.resolve(e),o=this.resolve(t),c=n?0:r.sharedDepth(t),u=r.start(c),m=r.node(c).content.cut(r.pos-u,o.pos-u);return new St(m,r.depth-c,o.depth-c)}replace(e,t,n){return bJ(this.resolve(e),this.resolve(t),n)}nodeAt(e){for(let t=this;;){let{index:n,offset:r}=t.content.findIndex(e);if(t=t.maybeChild(n),!t)return null;if(r==e||t.isText)return t;e-=r+1}}childAfter(e){let{index:t,offset:n}=this.content.findIndex(e);return{node:this.content.maybeChild(t),index:t,offset:n}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:t,offset:n}=this.content.findIndex(e);if(n<e)return{node:this.content.child(t),index:t,offset:n};let r=this.content.child(t-1);return{node:r,index:t-1,offset:n-r.nodeSize}}resolve(e){return u1.resolveCached(this,e)}resolveNoCache(e){return u1.resolve(this,e)}rangeHasMark(e,t,n){let r=!1;return t>e&&this.nodesBetween(e,t,o=>(n.isInSet(o.marks)&&(r=!0),!r)),r}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),n6(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,n=it.empty,r=0,o=n.childCount){let c=this.contentMatchAt(e).matchFragment(n,r,o),u=c&&c.matchFragment(this.content,t);if(!u||!u.validEnd)return!1;for(let h=r;h<o;h++)if(!this.type.allowsMarks(n.child(h).marks))return!1;return!0}canReplaceWith(e,t,n,r){if(r&&!this.type.allowsMarks(r))return!1;let o=this.contentMatchAt(e).matchType(n),c=o&&o.matchFragment(this.content,t);return c?c.validEnd:!1}canAppend(e){return e.content.size?this.canReplace(this.childCount,this.childCount,e.content):this.type.compatibleContent(e.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let e=Hi.none;for(let t=0;t<this.marks.length;t++){let n=this.marks[t];n.type.checkAttrs(n.attrs),e=n.addToSet(e)}if(!Hi.sameSet(e,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(t=>t.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let n;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");n=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,n)}let r=it.fromJSON(e,t.content),o=e.nodeType(t.type).create(t.attrs,r,n);return o.type.checkAttrs(o.attrs),o}};lh.prototype.text=void 0;class uM extends lh{constructor(e,t,n,r){if(super(e,t,null,r),!n)throw new RangeError("Empty text nodes are not allowed");this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):n6(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new uM(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new uM(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function n6(i,e){for(let t=i.length-1;t>=0;t--)e=i[t].type.name+"("+e+")";return e}class km{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let n=new MJ(e,t);if(n.next==null)return km.empty;let r=i6(n);n.next&&n.err("Unexpected trailing text");let o=LJ(OJ(r));return NJ(o,n),o}matchType(e){for(let t=0;t<this.next.length;t++)if(this.next[t].type==e)return this.next[t].next;return null}matchFragment(e,t=0,n=e.childCount){let r=this;for(let o=t;r&&o<n;o++)r=r.matchType(e.child(o).type);return r}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let e=0;e<this.next.length;e++){let{type:t}=this.next[e];if(!(t.isText||t.hasRequiredAttrs()))return t}return null}compatible(e){for(let t=0;t<this.next.length;t++)for(let n=0;n<e.next.length;n++)if(this.next[t].type==e.next[n].type)return!0;return!1}fillBefore(e,t=!1,n=0){let r=[this];function o(c,u){let h=c.matchFragment(e,n);if(h&&(!t||h.validEnd))return it.from(u.map(m=>m.createAndFill()));for(let m=0;m<c.next.length;m++){let{type:_,next:p}=c.next[m];if(!(_.isText||_.hasRequiredAttrs())&&r.indexOf(p)==-1){r.push(p);let y=o(p,u.concat(_));if(y)return y}}return null}return o(this,[])}findWrapping(e){for(let n=0;n<this.wrapCache.length;n+=2)if(this.wrapCache[n]==e)return this.wrapCache[n+1];let t=this.computeWrapping(e);return this.wrapCache.push(e,t),t}computeWrapping(e){let t=Object.create(null),n=[{match:this,type:null,via:null}];for(;n.length;){let r=n.shift(),o=r.match;if(o.matchType(e)){let c=[];for(let u=r;u.type;u=u.via)c.push(u.type);return c.reverse()}for(let c=0;c<o.next.length;c++){let{type:u,next:h}=o.next[c];!u.isLeaf&&!u.hasRequiredAttrs()&&!(u.name in t)&&(!r.type||h.validEnd)&&(n.push({match:u.contentMatch,type:u,via:r}),t[u.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(e){if(e>=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(n){e.push(n);for(let r=0;r<n.next.length;r++)e.indexOf(n.next[r].next)==-1&&t(n.next[r].next)}return t(this),e.map((n,r)=>{let o=r+(n.validEnd?"*":" ")+" ";for(let c=0;c<n.next.length;c++)o+=(c?", ":"")+n.next[c].type.name+"->"+e.indexOf(n.next[c].next);return o}).join(`
4554
4554
  `)}}km.empty=new km(!0);class MJ{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function i6(i){let e=[];do e.push(wJ(i));while(i.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function wJ(i){let e=[];do e.push(AJ(i));while(i.next&&i.next!=")"&&i.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function AJ(i){let e=DJ(i);for(;;)if(i.eat("+"))e={type:"plus",expr:e};else if(i.eat("*"))e={type:"star",expr:e};else if(i.eat("?"))e={type:"opt",expr:e};else if(i.eat("{"))e=CJ(i,e);else break;return e}function r6(i){/\D/.test(i.next)&&i.err("Expected number, got '"+i.next+"'");let e=Number(i.next);return i.pos++,e}function CJ(i,e){let t=r6(i),n=t;return i.eat(",")&&(i.next!="}"?n=r6(i):n=-1),i.eat("}")||i.err("Unclosed braced range"),{type:"range",min:t,max:n,expr:e}}function RJ(i,e){let t=i.nodeTypes,n=t[e];if(n)return[n];let r=[];for(let o in t){let c=t[o];c.isInGroup(e)&&r.push(c)}return r.length==0&&i.err("No node type or group '"+e+"' found"),r}function DJ(i){if(i.eat("(")){let e=i6(i);return i.eat(")")||i.err("Missing closing paren"),e}else if(/\W/.test(i.next))i.err("Unexpected token '"+i.next+"'");else{let e=RJ(i,i.next).map(t=>(i.inline==null?i.inline=t.isInline:i.inline!=t.isInline&&i.err("Mixing inline and block content"),{type:"name",value:t}));return i.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function OJ(i){let e=[[]];return r(o(i,0),t()),e;function t(){return e.push([])-1}function n(c,u,h){let m={term:h,to:u};return e[c].push(m),m}function r(c,u){c.forEach(h=>h.to=u)}function o(c,u){if(c.type=="choice")return c.exprs.reduce((h,m)=>h.concat(o(m,u)),[]);if(c.type=="seq")for(let h=0;;h++){let m=o(c.exprs[h],u);if(h==c.exprs.length-1)return m;r(m,u=t())}else if(c.type=="star"){let h=t();return n(u,h),r(o(c.expr,h),h),[n(h)]}else if(c.type=="plus"){let h=t();return r(o(c.expr,u),h),r(o(c.expr,h),h),[n(h)]}else{if(c.type=="opt")return[n(u)].concat(o(c.expr,u));if(c.type=="range"){let h=u;for(let m=0;m<c.min;m++){let _=t();r(o(c.expr,h),_),h=_}if(c.max==-1)r(o(c.expr,h),h);else for(let m=c.min;m<c.max;m++){let _=t();n(h,_),r(o(c.expr,h),_),h=_}return[n(h)]}else{if(c.type=="name")return[n(u,void 0,c.value)];throw new Error("Unknown expr type")}}}}function a6(i,e){return e-i}function s6(i,e){let t=[];return n(e),t.sort(a6);function n(r){let o=i[r];if(o.length==1&&!o[0].term)return n(o[0].to);t.push(r);for(let c=0;c<o.length;c++){let{term:u,to:h}=o[c];!u&&t.indexOf(h)==-1&&n(h)}}}function LJ(i){let e=Object.create(null);return t(s6(i,0));function t(n){let r=[];n.forEach(c=>{i[c].forEach(({term:u,to:h})=>{if(!u)return;let m;for(let _=0;_<r.length;_++)r[_][0]==u&&(m=r[_][1]);s6(i,h).forEach(_=>{m||r.push([u,m=[]]),m.indexOf(_)==-1&&m.push(_)})})});let o=e[n.join(",")]=new km(n.indexOf(i.length-1)>-1);for(let c=0;c<r.length;c++){let u=r[c][1].sort(a6);o.next.push({type:r[c][0],next:e[u.join(",")]||t(u)})}return o}}function NJ(i,e){for(let t=0,n=[i];t<n.length;t++){let r=n[t],o=!r.validEnd,c=[];for(let u=0;u<r.next.length;u++){let{type:h,next:m}=r.next[u];c.push(h.name),o&&!(h.isText||h.hasRequiredAttrs())&&(o=!1),n.indexOf(m)==-1&&n.push(m)}o&&e.err("Only non-generatable nodes ("+c.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function o6(i){let e=Object.create(null);for(let t in i){let n=i[t];if(!n.hasDefault)return null;e[t]=n.default}return e}function l6(i,e){let t=Object.create(null);for(let n in i){let r=e&&e[n];if(r===void 0){let o=i[n];if(o.hasDefault)r=o.default;else throw new RangeError("No value supplied for attribute "+n)}t[n]=r}return t}function c6(i,e,t,n){for(let r in e)if(!(r in i))throw new RangeError(`Unsupported attribute ${r} for ${t} of type ${r}`);for(let r in i){let o=i[r];o.validate&&o.validate(e[r])}}function u6(i,e){let t=Object.create(null);if(e)for(let n in e)t[n]=new UJ(i,n,e[n]);return t}let f6=class M7{constructor(e,t,n){this.name=e,this.schema=t,this.spec=n,this.markSet=null,this.groups=n.group?n.group.split(" "):[],this.attrs=u6(e,n.attrs),this.defaultAttrs=o6(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(n.inline||e=="text"),this.isText=e=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==km.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:l6(this.attrs,e)}create(e=null,t,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new lh(this,this.computeAttrs(e),it.from(t),Hi.setFrom(n))}createChecked(e=null,t,n){return t=it.from(t),this.checkContent(t),new lh(this,this.computeAttrs(e),t,Hi.setFrom(n))}createAndFill(e=null,t,n){if(e=this.computeAttrs(e),t=it.from(t),t.size){let c=this.contentMatch.fillBefore(t);if(!c)return null;t=c.append(t)}let r=this.contentMatch.matchFragment(t),o=r&&r.fillBefore(it.empty,!0);return o?new lh(this,e,t.append(o),Hi.setFrom(n)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let n=0;n<e.childCount;n++)if(!this.allowsMarks(e.child(n).marks))return!1;return!0}checkContent(e){if(!this.validContent(e))throw new RangeError(`Invalid content for node ${this.name}: ${e.toString().slice(0,50)}`)}checkAttrs(e){c6(this.attrs,e,"node",this.name)}allowsMarkType(e){return this.markSet==null||this.markSet.indexOf(e)>-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;t<e.length;t++)if(!this.allowsMarkType(e[t].type))return!1;return!0}allowedMarks(e){if(this.markSet==null)return e;let t;for(let n=0;n<e.length;n++)this.allowsMarkType(e[n].type)?t&&t.push(e[n]):t||(t=e.slice(0,n));return t?t.length?t:Hi.none:e}static compile(e,t){let n=Object.create(null);e.forEach((o,c)=>n[o]=new M7(o,t,c));let r=t.spec.topNode||"doc";if(!n[r])throw new RangeError("Schema is missing its top node type ('"+r+"')");if(!n.text)throw new RangeError("Every schema needs a 'text' type");for(let o in n.text.attrs)throw new RangeError("The text node type should not have attributes");return n}};function kJ(i,e,t){let n=t.split("|");return r=>{let o=r===null?"null":typeof r;if(n.indexOf(o)<0)throw new RangeError(`Expected value of type ${n} for attribute ${e} on type ${i}, got ${o}`)}}class UJ{constructor(e,t,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?kJ(e,t,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class fM{constructor(e,t,n,r){this.name=e,this.rank=t,this.schema=n,this.spec=r,this.attrs=u6(e,r.attrs),this.excluded=null;let o=o6(this.attrs);this.instance=o?new Hi(this,o):null}create(e=null){return!e&&this.instance?this.instance:new Hi(this,l6(this.attrs,e))}static compile(e,t){let n=Object.create(null),r=0;return e.forEach((o,c)=>n[o]=new fM(o,r++,t,c)),n}removeFromSet(e){for(var t=0;t<e.length;t++)e[t].type==this&&(e=e.slice(0,t).concat(e.slice(t+1)),t--);return e}isInSet(e){for(let t=0;t<e.length;t++)if(e[t].type==this)return e[t]}checkAttrs(e){c6(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class d6{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let r in e)t[r]=e[r];t.nodes=Aa.from(e.nodes),t.marks=Aa.from(e.marks||{}),this.nodes=f6.compile(this.spec.nodes,this),this.marks=fM.compile(this.spec.marks,this);let n=Object.create(null);for(let r in this.nodes){if(r in this.marks)throw new RangeError(r+" can not be both a node and a mark");let o=this.nodes[r],c=o.spec.content||"",u=o.spec.marks;if(o.contentMatch=n[c]||(n[c]=km.parse(c,this.nodes)),o.inlineContent=o.contentMatch.inlineContent,o.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!o.isInline||!o.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=o}o.markSet=u=="_"?null:u?h6(this,u.split(" ")):u==""||!o.inlineContent?[]:null}for(let r in this.marks){let o=this.marks[r],c=o.spec.excludes;o.excluded=c==null?[o]:c==""?[]:h6(this,c.split(" "))}this.nodeFromJSON=r=>lh.fromJSON(this,r),this.markFromJSON=r=>Hi.fromJSON(this,r),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,n,r){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof f6){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,n,r)}text(e,t){let n=this.nodes.text;return new uM(n,n.defaultAttrs,e,Hi.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function h6(i,e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=i.marks[r],c=o;if(o)t.push(o);else for(let u in i.marks){let h=i.marks[u];(r=="_"||h.spec.group&&h.spec.group.split(" ").indexOf(r)>-1)&&t.push(c=h)}if(!c)throw new SyntaxError("Unknown mark type: '"+e[n]+"'")}return t}function IJ(i){return i.tag!=null}function zJ(i){return i.style!=null}let dM=class _4{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let n=this.matchedStyles=[];t.forEach(r=>{if(IJ(r))this.tags.push(r);else if(zJ(r)){let o=/[^=]*/.exec(r.style)[0];n.indexOf(o)<0&&n.push(o),this.styles.push(r)}}),this.normalizeLists=!this.tags.some(r=>{if(!/^(ul|ol)\b/.test(r.tag)||!r.node)return!1;let o=e.nodes[r.node];return o.contentMatch.matchType(o)})}parse(e,t={}){let n=new v6(this,t,!1);return n.addAll(e,Hi.none,t.from,t.to),n.finish()}parseSlice(e,t={}){let n=new v6(this,t,!0);return n.addAll(e,Hi.none,t.from,t.to),St.maxOpen(n.finish())}matchTag(e,t,n){for(let r=n?this.tags.indexOf(n)+1:0;r<this.tags.length;r++){let o=this.tags[r];if(FJ(e,o.tag)&&(o.namespace===void 0||e.namespaceURI==o.namespace)&&(!o.context||t.matchesContext(o.context))){if(o.getAttrs){let c=o.getAttrs(e);if(c===!1)continue;o.attrs=c||void 0}return o}}}matchStyle(e,t,n,r){for(let o=r?this.styles.indexOf(r)+1:0;o<this.styles.length;o++){let c=this.styles[o],u=c.style;if(!(u.indexOf(e)!=0||c.context&&!n.matchesContext(c.context)||u.length>e.length&&(u.charCodeAt(e.length)!=61||u.slice(e.length+1)!=t))){if(c.getAttrs){let h=c.getAttrs(t);if(h===!1)continue;c.attrs=h||void 0}return c}}}static schemaRules(e){let t=[];function n(r){let o=r.priority==null?50:r.priority,c=0;for(;c<t.length;c++){let u=t[c];if((u.priority==null?50:u.priority)<o)break}t.splice(c,0,r)}for(let r in e.marks){let o=e.marks[r].spec.parseDOM;o&&o.forEach(c=>{n(c=y6(c)),c.mark||c.ignore||c.clearMark||(c.mark=r)})}for(let r in e.nodes){let o=e.nodes[r].spec.parseDOM;o&&o.forEach(c=>{n(c=y6(c)),c.node||c.ignore||c.mark||(c.node=r)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new _4(e,_4.schemaRules(e)))}};const p6={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},BJ={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},m6={ol:!0,ul:!0},f1=1,pD=2,d1=4;function g6(i,e,t){return e!=null?(e?f1:0)|(e==="full"?pD:0):i&&i.whitespace=="pre"?f1|pD:t&~d1}class hM{constructor(e,t,n,r,o,c){this.type=e,this.attrs=t,this.marks=n,this.solid=r,this.options=c,this.content=[],this.activeMarks=Hi.none,this.match=o||(c&d1?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(it.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let n=this.type.contentMatch,r;return(r=n.findWrapping(e.type))?(this.match=n,r):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&f1)){let n=this.content[this.content.length-1],r;if(n&&n.isText&&(r=/[ \t\r\n\u000c]+$/.exec(n.text))){let o=n;n.text.length==r[0].length?this.content.pop():this.content[this.content.length-1]=o.withText(o.text.slice(0,o.text.length-r[0].length))}}let t=it.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(it.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!p6.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class v6{constructor(e,t,n){this.parser=e,this.options=t,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let r=t.topNode,o,c=g6(null,t.preserveWhitespace,0)|(n?d1:0);r?o=new hM(r.type,r.attrs,Hi.none,!0,t.topMatch||r.type.contentMatch,c):n?o=new hM(null,null,Hi.none,!0,null,c):o=new hM(e.schema.topNodeType,null,Hi.none,!0,null,c),this.nodes=[o],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let n=e.nodeValue,r=this.top,o=r.options&pD?"full":this.localPreserveWS||(r.options&f1)>0,{schema:c}=this.parser;if(o==="full"||r.inlineContext(e)||/[^ \t\r\n\u000c]/.test(n)){if(o)if(o==="full")n=n.replace(/\r\n?/g,`
4555
4555
  `);else if(c.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(c.linebreakReplacement.create())){let u=n.split(/\r?\n|\r/);for(let h=0;h<u.length;h++)h&&this.insertNode(c.linebreakReplacement.create(),t,!0),u[h]&&this.insertNode(c.text(u[h]),t,!/\S/.test(u[h]));n=""}else n=n.replace(/\r?\n|\r/g," ");else if(n=n.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(n)&&this.open==this.nodes.length-1){let u=r.content[r.content.length-1],h=e.previousSibling;(!u||h&&h.nodeName=="BR"||u.isText&&/[ \t\r\n\u000c]$/.test(u.text))&&(n=n.slice(1))}n&&this.insertNode(c.text(n),t,!/\S/.test(n)),this.findInText(e)}else this.findInside(e)}addElement(e,t,n){let r=this.localPreserveWS,o=this.top;(e.tagName=="PRE"||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let c=e.nodeName.toLowerCase(),u;m6.hasOwnProperty(c)&&this.parser.normalizeLists&&PJ(e);let h=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(u=this.parser.matchTag(e,this,n));e:if(h?h.ignore:BJ.hasOwnProperty(c))this.findInside(e),this.ignoreFallback(e,t);else if(!h||h.skip||h.closeParent){h&&h.closeParent?this.open=Math.max(0,this.open-1):h&&h.skip.nodeType&&(e=h.skip);let m,_=this.needsBlock;if(p6.hasOwnProperty(c))o.content.length&&o.content[0].isInline&&this.open&&(this.open--,o=this.top),m=!0,o.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,t);break e}let p=h&&h.skip?t:this.readStyles(e,t);p&&this.addAll(e,p),m&&this.sync(o),this.needsBlock=_}else{let m=this.readStyles(e,t);m&&this.addElementByRule(e,h,m,h.consuming===!1?u:void 0)}this.localPreserveWS=r}leafFallback(e,t){e.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
4556
4556
  `),t)}ignoreFallback(e,t){e.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),t,!0)}readStyles(e,t){let n=e.style;if(n&&n.length)for(let r=0;r<this.parser.matchedStyles.length;r++){let o=this.parser.matchedStyles[r],c=n.getPropertyValue(o);if(c)for(let u=void 0;;){let h=this.parser.matchStyle(o,c,this,u);if(!h)break;if(h.ignore)return null;if(h.clearMark?t=t.filter(m=>!h.clearMark(m)):t=t.concat(this.parser.schema.marks[h.mark].create(h.attrs)),h.consuming===!1)u=h;else break}}return t}addElementByRule(e,t,n,r){let o,c;if(t.node)if(c=this.parser.schema.nodes[t.node],c.isLeaf)this.insertNode(c.create(t.attrs),n,e.nodeName=="BR")||this.leafFallback(e,n);else{let h=this.enter(c,t.attrs||null,n,t.preserveWhitespace);h&&(o=!0,n=h)}else{let h=this.parser.schema.marks[t.mark];n=n.concat(h.create(t.attrs))}let u=this.top;if(c&&c.isLeaf)this.findInside(e);else if(r)this.addElement(e,n,r);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(h=>this.insertNode(h,n,!1));else{let h=e;typeof t.contentElement=="string"?h=e.querySelector(t.contentElement):typeof t.contentElement=="function"?h=t.contentElement(e):t.contentElement&&(h=t.contentElement),this.findAround(e,h,!0),this.addAll(h,n),this.findAround(e,h,!1)}o&&this.sync(u)&&this.open--}addAll(e,t,n,r){let o=n||0;for(let c=n?e.childNodes[n]:e.firstChild,u=r==null?null:e.childNodes[r];c!=u;c=c.nextSibling,++o)this.findAtPoint(e,o),this.addDOM(c,t);this.findAtPoint(e,o)}findPlace(e,t,n){let r,o;for(let c=this.open,u=0;c>=0;c--){let h=this.nodes[c],m=h.findWrapping(e);if(m&&(!r||r.length>m.length+u)&&(r=m,o=h,!m.length))break;if(h.solid){if(n)break;u+=2}}if(!r)return null;this.sync(o);for(let c=0;c<r.length;c++)t=this.enterInner(r[c],null,t,!1);return t}insertNode(e,t,n){if(e.isInline&&this.needsBlock&&!this.top.type){let o=this.textblockFromContext();o&&(t=this.enterInner(o,null,t))}let r=this.findPlace(e,t,n);if(r){this.closeExtra();let o=this.top;o.match&&(o.match=o.match.matchType(e.type));let c=Hi.none;for(let u of r.concat(e.marks))(o.type?o.type.allowsMarkType(u.type):_6(u.type,e.type))&&(c=u.addToSet(c));return o.content.push(e.mark(c)),!0}return!1}enter(e,t,n,r){let o=this.findPlace(e.create(t),n,!1);return o&&(o=this.enterInner(e,t,n,!0,r)),o}enterInner(e,t,n,r=!1,o){this.closeExtra();let c=this.top;c.match=c.match&&c.match.matchType(e);let u=g6(e,o,c.options);c.options&d1&&c.content.length==0&&(u|=d1);let h=Hi.none;return n=n.filter(m=>(c.type?c.type.allowsMarkType(m.type):_6(m.type,e))?(h=m.addToSet(h),!1):!0),this.nodes.push(new hM(e,t,h,r,null,u)),this.open++,n}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=f1)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let n=this.nodes[t].content;for(let r=n.length-1;r>=0;r--)e+=n[r].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==e&&this.find[n].offset==t&&(this.find[n].pos=this.currentPos)}findInside(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].pos==null&&e.nodeType==1&&e.contains(this.find[t].node)&&(this.find[t].pos=this.currentPos)}findAround(e,t,n){if(e!=t&&this.find)for(let r=0;r<this.find.length;r++)this.find[r].pos==null&&e.nodeType==1&&e.contains(this.find[r].node)&&t.compareDocumentPosition(this.find[r].node)&(n?2:4)&&(this.find[r].pos=this.currentPos)}findInText(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].node==e&&(this.find[t].pos=this.currentPos-(e.nodeValue.length-this.find[t].offset))}matchesContext(e){if(e.indexOf("|")>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),n=this.options.context,r=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),o=-(n?n.depth+1:0)+(r?0:1),c=(u,h)=>{for(;u>=0;u--){let m=t[u];if(m==""){if(u==t.length-1||u==0)continue;for(;h>=o;h--)if(c(u-1,h))return!0;return!1}else{let _=h>0||h==0&&r?this.nodes[h].type:n&&h>=o?n.node(h-o).type:null;if(!_||_.name!=m&&!_.isInGroup(m))return!1;h--}}return!0};return c(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let n=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let t in this.parser.schema.nodes){let n=this.parser.schema.nodes[t];if(n.isTextblock&&n.defaultAttrs)return n}}}function PJ(i){for(let e=i.firstChild,t=null;e;e=e.nextSibling){let n=e.nodeType==1?e.nodeName.toLowerCase():null;n&&m6.hasOwnProperty(n)&&t?(t.appendChild(e),e=t):n=="li"?t=e:n&&(t=null)}}function FJ(i,e){return(i.matches||i.msMatchesSelector||i.webkitMatchesSelector||i.mozMatchesSelector).call(i,e)}function y6(i){let e={};for(let t in i)e[t]=i[t];return e}function _6(i,e){let t=e.schema.nodes;for(let n in t){let r=t[n];if(!r.allowsMarkType(i))continue;let o=[],c=u=>{o.push(u);for(let h=0;h<u.edgeCount;h++){let{type:m,next:_}=u.edge(h);if(m==e||o.indexOf(_)<0&&c(_))return!0}};if(c(r.contentMatch))return!0}}class h1{constructor(e,t){this.nodes=e,this.marks=t}serializeFragment(e,t={},n){n||(n=mD(t).createDocumentFragment());let r=n,o=[];return e.forEach(c=>{if(o.length||c.marks.length){let u=0,h=0;for(;u<o.length&&h<c.marks.length;){let m=c.marks[h];if(!this.marks[m.type.name]){h++;continue}if(!m.eq(o[u][0])||m.type.spec.spanning===!1)break;u++,h++}for(;u<o.length;)r=o.pop()[1];for(;h<c.marks.length;){let m=c.marks[h++],_=this.serializeMark(m,c.isInline,t);_&&(o.push([m,r]),r.appendChild(_.dom),r=_.contentDOM||_.dom)}}r.appendChild(this.serializeNodeInner(c,t))}),n}serializeNodeInner(e,t){let{dom:n,contentDOM:r}=pM(mD(t),this.nodes[e.type.name](e),null,e.attrs);if(r){if(e.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(e.content,t,r)}return n}serializeNode(e,t={}){let n=this.serializeNodeInner(e,t);for(let r=e.marks.length-1;r>=0;r--){let o=this.serializeMark(e.marks[r],e.isInline,t);o&&((o.contentDOM||o.dom).appendChild(n),n=o.dom)}return n}serializeMark(e,t,n={}){let r=this.marks[e.type.name];return r&&pM(mD(n),r(e,t),null,e.attrs)}static renderSpec(e,t,n=null,r){return pM(e,t,n,r)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new h1(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=b6(e.nodes);return t.text||(t.text=n=>n.text),t}static marksFromSchema(e){return b6(e.marks)}}function b6(i){let e={};for(let t in i){let n=i[t].spec.toDOM;n&&(e[t]=n)}return e}function mD(i){return i.document||window.document}const x6=new WeakMap;function HJ(i){let e=x6.get(i);return e===void 0&&x6.set(i,e=VJ(i)),e}function VJ(i){let e=null;function t(n){if(n&&typeof n=="object")if(Array.isArray(n))if(typeof n[0]=="string")e||(e=[]),e.push(n);else for(let r=0;r<n.length;r++)t(n[r]);else for(let r in n)t(n[r])}return t(i),e}function pM(i,e,t,n){if(typeof e=="string")return{dom:i.createTextNode(e)};if(e.nodeType!=null)return{dom:e};if(e.dom&&e.dom.nodeType!=null)return e;let r=e[0],o;if(typeof r!="string")throw new RangeError("Invalid array passed to renderSpec");if(n&&(o=HJ(n))&&o.indexOf(e)>-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let c=r.indexOf(" ");c>0&&(t=r.slice(0,c),r=r.slice(c+1));let u,h=t?i.createElementNS(t,r):i.createElement(r),m=e[1],_=1;if(m&&typeof m=="object"&&m.nodeType==null&&!Array.isArray(m)){_=2;for(let p in m)if(m[p]!=null){let y=p.indexOf(" ");y>0?h.setAttributeNS(p.slice(0,y),p.slice(y+1),m[p]):p=="style"&&h.style?h.style.cssText=m[p]:h.setAttribute(p,m[p])}}for(let p=_;p<e.length;p++){let y=e[p];if(y===0){if(p<e.length-1||p>_)throw new RangeError("Content hole must be the only child of its parent node");return{dom:h,contentDOM:h}}else{let{dom:x,contentDOM:T}=pM(i,y,t,n);if(h.appendChild(x),T){if(u)throw new RangeError("Multiple content holes");u=T}}}return{dom:h,contentDOM:u}}const S6=65535,E6=Math.pow(2,16);function GJ(i,e){return i+e*E6}function T6(i){return i&S6}function jJ(i){return(i-(i&S6))/E6}const M6=1,w6=2,mM=4,A6=8;class gD{constructor(e,t,n){this.pos=e,this.delInfo=t,this.recover=n}get deleted(){return(this.delInfo&A6)>0}get deletedBefore(){return(this.delInfo&(M6|mM))>0}get deletedAfter(){return(this.delInfo&(w6|mM))>0}get deletedAcross(){return(this.delInfo&mM)>0}}class Co{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&Co.empty)return Co.empty}recover(e){let t=0,n=T6(e);if(!this.inverted)for(let r=0;r<n;r++)t+=this.ranges[r*3+2]-this.ranges[r*3+1];return this.ranges[n*3]+t+jJ(e)}mapResult(e,t=1){return this._map(e,t,!1)}map(e,t=1){return this._map(e,t,!0)}_map(e,t,n){let r=0,o=this.inverted?2:1,c=this.inverted?1:2;for(let u=0;u<this.ranges.length;u+=3){let h=this.ranges[u]-(this.inverted?r:0);if(h>e)break;let m=this.ranges[u+o],_=this.ranges[u+c],p=h+m;if(e<=p){let y=m?e==h?-1:e==p?1:t:t,x=h+r+(y<0?0:_);if(n)return x;let T=e==(t<0?h:p)?null:GJ(u/3,e-h),M=e==h?w6:e==p?M6:mM;return(t<0?e!=h:e!=p)&&(M|=A6),new gD(x,M,T)}r+=_-m}return n?e+r:new gD(e+r,0,null)}touches(e,t){let n=0,r=T6(t),o=this.inverted?2:1,c=this.inverted?1:2;for(let u=0;u<this.ranges.length;u+=3){let h=this.ranges[u]-(this.inverted?n:0);if(h>e)break;let m=this.ranges[u+o],_=h+m;if(e<=_&&u==r*3)return!0;n+=this.ranges[u+c]-m}return!1}forEach(e){let t=this.inverted?2:1,n=this.inverted?1:2;for(let r=0,o=0;r<this.ranges.length;r+=3){let c=this.ranges[r],u=c-(this.inverted?o:0),h=c+(this.inverted?0:o),m=this.ranges[r+t],_=this.ranges[r+n];e(u,u+m,h,h+_),o+=_-m}}invert(){return new Co(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?Co.empty:new Co(e<0?[0,-e,0]:[0,0,e])}}Co.empty=new Co([]);class p1{constructor(e,t,n=0,r=e?e.length:0){this.mirror=t,this.from=n,this.to=r,this._maps=e||[],this.ownData=!(e||t)}get maps(){return this._maps}slice(e=0,t=this.maps.length){return new p1(this._maps,this.mirror,e,t)}appendMap(e,t){this.ownData||(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0),this.to=this._maps.push(e),t!=null&&this.setMirror(this._maps.length-1,t)}appendMapping(e){for(let t=0,n=this._maps.length;t<e._maps.length;t++){let r=e.getMirror(t);this.appendMap(e._maps[t],r!=null&&r<t?n+r:void 0)}}getMirror(e){if(this.mirror){for(let t=0;t<this.mirror.length;t++)if(this.mirror[t]==e)return this.mirror[t+(t%2?-1:1)]}}setMirror(e,t){this.mirror||(this.mirror=[]),this.mirror.push(e,t)}appendMappingInverted(e){for(let t=e.maps.length-1,n=this._maps.length+e._maps.length;t>=0;t--){let r=e.getMirror(t);this.appendMap(e._maps[t].invert(),r!=null&&r>t?n-r-1:void 0)}}invert(){let e=new p1;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let n=this.from;n<this.to;n++)e=this._maps[n].map(e,t);return e}mapResult(e,t=1){return this._map(e,t,!1)}_map(e,t,n){let r=0;for(let o=this.from;o<this.to;o++){let c=this._maps[o],u=c.mapResult(e,t);if(u.recover!=null){let h=this.getMirror(o);if(h!=null&&h>o&&h<this.to){o=h,e=this._maps[h].recover(u.recover);continue}}r|=u.delInfo,e=u.pos}return n?e:new gD(e,r,null)}}const vD=Object.create(null);class ts{getMap(){return Co.empty}merge(e){return null}static fromJSON(e,t){if(!t||!t.stepType)throw new RangeError("Invalid input for Step.fromJSON");let n=vD[t.stepType];if(!n)throw new RangeError(`No step type ${t.stepType} defined`);return n.fromJSON(e,t)}static jsonID(e,t){if(e in vD)throw new RangeError("Duplicate use of step JSON ID "+e);return vD[e]=t,t.prototype.jsonID=e,t}}class Ar{constructor(e,t){this.doc=e,this.failed=t}static ok(e){return new Ar(e,null)}static fail(e){return new Ar(null,e)}static fromReplace(e,t,n,r){try{return Ar.ok(e.replace(t,n,r))}catch(o){if(o instanceof oM)return Ar.fail(o.message);throw o}}}function yD(i,e,t){let n=[];for(let r=0;r<i.childCount;r++){let o=i.child(r);o.content.size&&(o=o.copy(yD(o.content,e,o))),o.isInline&&(o=e(o,t,r)),n.push(o)}return it.fromArray(n)}class ch extends ts{constructor(e,t,n){super(),this.from=e,this.to=t,this.mark=n}apply(e){let t=e.slice(this.from,this.to),n=e.resolve(this.from),r=n.node(n.sharedDepth(this.to)),o=new St(yD(t.content,(c,u)=>!c.isAtom||!u.type.allowsMarkType(this.mark.type)?c:c.mark(this.mark.addToSet(c.marks)),r),t.openStart,t.openEnd);return Ar.fromReplace(e,this.from,this.to,o)}invert(){return new bc(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return t.deleted&&n.deleted||t.pos>=n.pos?null:new ch(t.pos,n.pos,this.mark)}merge(e){return e instanceof ch&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new ch(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new ch(t.from,t.to,e.markFromJSON(t.mark))}}ts.jsonID("addMark",ch);class bc extends ts{constructor(e,t,n){super(),this.from=e,this.to=t,this.mark=n}apply(e){let t=e.slice(this.from,this.to),n=new St(yD(t.content,r=>r.mark(this.mark.removeFromSet(r.marks)),e),t.openStart,t.openEnd);return Ar.fromReplace(e,this.from,this.to,n)}invert(){return new ch(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return t.deleted&&n.deleted||t.pos>=n.pos?null:new bc(t.pos,n.pos,this.mark)}merge(e){return e instanceof bc&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new bc(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new bc(t.from,t.to,e.markFromJSON(t.mark))}}ts.jsonID("removeMark",bc);class uh extends ts{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Ar.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return Ar.fromReplace(e,this.pos,this.pos+1,new St(it.from(n),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let n=this.mark.addToSet(t.marks);if(n.length==t.marks.length){for(let r=0;r<t.marks.length;r++)if(!t.marks[r].isInSet(n))return new uh(this.pos,t.marks[r]);return new uh(this.pos,this.mark)}}return new Um(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new uh(t.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new uh(t.pos,e.markFromJSON(t.mark))}}ts.jsonID("addNodeMark",uh);class Um extends ts{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Ar.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.removeFromSet(t.marks));return Ar.fromReplace(e,this.pos,this.pos+1,new St(it.from(n),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);return!t||!this.mark.isInSet(t.marks)?this:new uh(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new Um(t.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new Um(t.pos,e.markFromJSON(t.mark))}}ts.jsonID("removeNodeMark",Um);class fa extends ts{constructor(e,t,n,r=!1){super(),this.from=e,this.to=t,this.slice=n,this.structure=r}apply(e){return this.structure&&_D(e,this.from,this.to)?Ar.fail("Structure replace would overwrite content"):Ar.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new Co([this.from,this.to-this.from,this.slice.size])}invert(e){return new fa(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return t.deletedAcross&&n.deletedAcross?null:new fa(t.pos,Math.max(t.pos,n.pos),this.slice,this.structure)}merge(e){if(!(e instanceof fa)||e.structure||this.structure)return null;if(this.from+this.slice.size==e.from&&!this.slice.openEnd&&!e.slice.openStart){let t=this.slice.size+e.slice.size==0?St.empty:new St(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new fa(this.from,this.to+(e.to-e.from),t,this.structure)}else if(e.to==this.from&&!this.slice.openStart&&!e.slice.openEnd){let t=this.slice.size+e.slice.size==0?St.empty:new St(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new fa(e.from,this.to,t,this.structure)}else return null}toJSON(){let e={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new fa(t.from,t.to,St.fromJSON(e,t.slice),!!t.structure)}}ts.jsonID("replace",fa);class da extends ts{constructor(e,t,n,r,o,c,u=!1){super(),this.from=e,this.to=t,this.gapFrom=n,this.gapTo=r,this.slice=o,this.insert=c,this.structure=u}apply(e){if(this.structure&&(_D(e,this.from,this.gapFrom)||_D(e,this.gapTo,this.to)))return Ar.fail("Structure gap-replace would overwrite content");let t=e.slice(this.gapFrom,this.gapTo);if(t.openStart||t.openEnd)return Ar.fail("Gap is not a flat range");let n=this.slice.insertAt(this.insert,t.content);return n?Ar.fromReplace(e,this.from,this.to,n):Ar.fail("Content does not fit in gap")}getMap(){return new Co([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let t=this.gapTo-this.gapFrom;return new da(this.from,this.from+this.slice.size+t,this.from+this.insert,this.from+this.insert+t,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1),r=this.from==this.gapFrom?t.pos:e.map(this.gapFrom,-1),o=this.to==this.gapTo?n.pos:e.map(this.gapTo,1);return t.deletedAcross&&n.deletedAcross||r<t.pos||o>n.pos?null:new da(t.pos,n.pos,r,o,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new da(t.from,t.to,t.gapFrom,t.gapTo,St.fromJSON(e,t.slice),t.insert,!!t.structure)}}ts.jsonID("replaceAround",da);function _D(i,e,t){let n=i.resolve(e),r=t-e,o=n.depth;for(;r>0&&o>0&&n.indexAfter(o)==n.node(o).childCount;)o--,r--;if(r>0){let c=n.node(o).maybeChild(n.indexAfter(o));for(;r>0;){if(!c||c.isLeaf)return!0;c=c.firstChild,r--}}return!1}function XJ(i,e,t,n){let r=[],o=[],c,u;i.doc.nodesBetween(e,t,(h,m,_)=>{if(!h.isInline)return;let p=h.marks;if(!n.isInSet(p)&&_.type.allowsMarkType(n.type)){let y=Math.max(m,e),x=Math.min(m+h.nodeSize,t),T=n.addToSet(p);for(let M=0;M<p.length;M++)p[M].isInSet(T)||(c&&c.to==y&&c.mark.eq(p[M])?c.to=x:r.push(c=new bc(y,x,p[M])));u&&u.to==y?u.to=x:o.push(u=new ch(y,x,n))}}),r.forEach(h=>i.step(h)),o.forEach(h=>i.step(h))}function qJ(i,e,t,n){let r=[],o=0;i.doc.nodesBetween(e,t,(c,u)=>{if(!c.isInline)return;o++;let h=null;if(n instanceof fM){let m=c.marks,_;for(;_=n.isInSet(m);)(h||(h=[])).push(_),m=_.removeFromSet(m)}else n?n.isInSet(c.marks)&&(h=[n]):h=c.marks;if(h&&h.length){let m=Math.min(u+c.nodeSize,t);for(let _=0;_<h.length;_++){let p=h[_],y;for(let x=0;x<r.length;x++){let T=r[x];T.step==o-1&&p.eq(r[x].style)&&(y=T)}y?(y.to=m,y.step=o):r.push({style:p,from:Math.max(u,e),to:m,step:o})}}}),r.forEach(c=>i.step(new bc(c.from,c.to,c.style)))}function bD(i,e,t,n=t.contentMatch,r=!0){let o=i.doc.nodeAt(e),c=[],u=e+1;for(let h=0;h<o.childCount;h++){let m=o.child(h),_=u+m.nodeSize,p=n.matchType(m.type);if(!p)c.push(new fa(u,_,St.empty));else{n=p;for(let y=0;y<m.marks.length;y++)t.allowsMarkType(m.marks[y].type)||i.step(new bc(u,_,m.marks[y]));if(r&&m.isText&&t.whitespace!="pre"){let y,x=/\r?\n|\r/g,T;for(;y=x.exec(m.text);)T||(T=new St(it.from(t.schema.text(" ",t.allowedMarks(m.marks))),0,0)),c.push(new fa(u+y.index,u+y.index+y[0].length,T))}}u=_}if(!n.validEnd){let h=n.fillBefore(it.empty,!0);i.replace(u,u,new St(h,0,0))}for(let h=c.length-1;h>=0;h--)i.step(c[h])}function $J(i,e,t){return(e==0||i.canReplace(e,i.childCount))&&(t==i.childCount||i.canReplace(0,t))}function Uv(i){let t=i.parent.content.cutByIndex(i.startIndex,i.endIndex);for(let n=i.depth,r=0,o=0;;--n){let c=i.$from.node(n),u=i.$from.index(n)+r,h=i.$to.indexAfter(n)-o;if(n<i.depth&&c.canReplace(u,h,t))return n;if(n==0||c.type.spec.isolating||!$J(c,u,h))break;u&&(r=1),h<c.childCount&&(o=1)}return null}function YJ(i,e,t){let{$from:n,$to:r,depth:o}=e,c=n.before(o+1),u=r.after(o+1),h=c,m=u,_=it.empty,p=0;for(let T=o,M=!1;T>t;T--)M||n.index(T)>0?(M=!0,_=it.from(n.node(T).copy(_)),p++):h--;let y=it.empty,x=0;for(let T=o,M=!1;T>t;T--)M||r.after(T+1)<r.end(T)?(M=!0,y=it.from(r.node(T).copy(y)),x++):m++;i.step(new da(h,m,c,u,new St(_.append(y),p,x),_.size-p,!0))}function xD(i,e,t=null,n=i){let r=WJ(i,e),o=r&&ZJ(n,e);return o?r.map(C6).concat({type:e,attrs:t}).concat(o.map(C6)):null}function C6(i){return{type:i,attrs:null}}function WJ(i,e){let{parent:t,startIndex:n,endIndex:r}=i,o=t.contentMatchAt(n).findWrapping(e);if(!o)return null;let c=o.length?o[0]:e;return t.canReplaceWith(n,r,c)?o:null}function ZJ(i,e){let{parent:t,startIndex:n,endIndex:r}=i,o=t.child(n),c=e.contentMatch.findWrapping(o.type);if(!c)return null;let h=(c.length?c[c.length-1]:e).contentMatch;for(let m=n;h&&m<r;m++)h=h.matchType(t.child(m).type);return!h||!h.validEnd?null:c}function KJ(i,e,t){let n=it.empty;for(let c=t.length-1;c>=0;c--){if(n.size){let u=t[c].type.contentMatch.matchFragment(n);if(!u||!u.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}n=it.from(t[c].type.create(t[c].attrs,n))}let r=e.start,o=e.end;i.step(new da(r,o,r,o,new St(n,0,0),t.length,!0))}function JJ(i,e,t,n,r){if(!n.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let o=i.steps.length;i.doc.nodesBetween(e,t,(c,u)=>{let h=typeof r=="function"?r(c):r;if(c.isTextblock&&!c.hasMarkup(n,h)&&QJ(i.doc,i.mapping.slice(o).map(u),n)){let m=null;if(n.schema.linebreakReplacement){let x=n.whitespace=="pre",T=!!n.contentMatch.matchType(n.schema.linebreakReplacement);x&&!T?m=!1:!x&&T&&(m=!0)}m===!1&&D6(i,c,u,o),bD(i,i.mapping.slice(o).map(u,1),n,void 0,m===null);let _=i.mapping.slice(o),p=_.map(u,1),y=_.map(u+c.nodeSize,1);return i.step(new da(p,y,p+1,y-1,new St(it.from(n.create(h,null,c.marks)),0,0),1,!0)),m===!0&&R6(i,c,u,o),!1}})}function R6(i,e,t,n){e.forEach((r,o)=>{if(r.isText){let c,u=/\r?\n|\r/g;for(;c=u.exec(r.text);){let h=i.mapping.slice(n).map(t+1+o+c.index);i.replaceWith(h,h+1,e.type.schema.linebreakReplacement.create())}}})}function D6(i,e,t,n){e.forEach((r,o)=>{if(r.type==r.type.schema.linebreakReplacement){let c=i.mapping.slice(n).map(t+1+o);i.replaceWith(c,c+1,e.type.schema.text(`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bridgeapp-ai-chat-widget",
3
3
  "private": false,
4
- "version": "0.1.4",
4
+ "version": "0.1.5",
5
5
  "description": "Embeddable chat widget for communication with Bridge AI agent",
6
6
  "type": "module",
7
7
  "main": "dist/bridge-ai-chat-widget.umd.js",