@gamepadly/sdk 0.1.0 → 0.2.0

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.
@@ -1 +1 @@
1
- var he=[3302,3570],J=1406,ee=[8201],I=new Uint8Array([0,1,64,64]);function me(a){if(!Number.isFinite(a)||a<=.01)return 0;let e=Math.min(.85,Math.max(0,a));return e>=.23?Math.min(100,Math.round(Math.log2(e*8.7)*32)):e>=.12?Math.round(Math.log2(e*17)*16):Math.max(1,Math.round(e/.12*16))}function N(a){if(!a||a.highAmp<=.01&&a.lowAmp<=.01)return I.slice();let e=Math.max(81.75,Math.min(1252.6,Number.isFinite(a.highFreqHz)?a.highFreqHz:320)),t=Math.max(40.88,Math.min(626.3,Number.isFinite(a.lowFreqHz)?a.lowFreqHz:160)),n=Math.round(Math.log2(e/10)*32),i=Math.round(Math.log2(t/10)*32),r=Math.max(0,Math.min(508,(n-96)*4)),o=Math.max(1,Math.min(127,i-64)),s=me(a.highAmp),c=me(a.lowAmp),l=Math.min(200,s*2),p=(c&1)!==0?128:0,d=Math.min(114,(c>>1)+64);return new Uint8Array([r&255,l+(r>>8&1)&255,(o|p)&255,d&255])}function E(a,e=.06){let t=Math.abs(a);if(t<=e)return 0;let n=(t-e)/(1-e);return Math.sign(a)*Math.max(0,Math.min(1,n))}function ve(a){return(a.match(/vendor:\s*([0-9a-f]{4})/)??a.match(/^([0-9a-f]{1,4})-[0-9a-f]{1,4}-/))?.[1]?.padStart(4,"0")}function Me(a){let e=ve(a);if(e==="054c")return"sony";if(e==="045e")return"xbox";if(e==="057e")return"nintendo";if(!e){if(/xbox|xinput|microsoft/.test(a))return"xbox";if(/dualsense|dualshock|wireless controller/.test(a))return"sony";if(/nintendo|pro controller|joy-con|switch/.test(a))return"nintendo"}}function ne(a){let e=(a||"").toLowerCase(),t=Me(e);return t==="sony"?/0df2|edge/.test(e)?{brand:"sony",model:"dualsense_edge",displayName:"DualSense Edge",rawId:a,vendorId:1356,productId:3570}:/0ce6|dualsense/.test(e)?{brand:"sony",model:"dualsense",displayName:"PlayStation DualSense",rawId:a,vendorId:1356,productId:3302}:/05c4|09cc|dualshock/.test(e)?{brand:"sony",model:"dualshock4",displayName:"DualShock 4",rawId:a,vendorId:1356}:{brand:"sony",model:"dualsense",displayName:"PlayStation Controller",rawId:a,vendorId:1356}:t==="xbox"?/0b12|0b13|0b20|0b21|0b22|series/.test(e)?{brand:"xbox",model:"xbox_series",displayName:"Xbox Wireless Controller",rawId:a,vendorId:1118}:/028e|360/.test(e)?{brand:"xbox",model:"xbox_360",displayName:"Xbox 360 Controller",rawId:a,vendorId:1118}:{brand:"xbox",model:"xbox_series",displayName:"Xbox Controller",rawId:a,vendorId:1118}:t==="nintendo"?/2069|pro 2|switch 2/.test(e)?{brand:"nintendo",model:"switch2_pro",displayName:"Nintendo Switch 2 Pro Controller",rawId:a,vendorId:1406,productId:8297}:/joy-con|2006|2007/.test(e)?{brand:"nintendo",model:"joycon",displayName:"Nintendo Joy-Con",rawId:a,vendorId:1406}:{brand:"nintendo",model:"switch_pro",displayName:"Nintendo Switch Pro Controller",rawId:a,vendorId:1406,productId:8201}:a?{brand:"generic",model:"generic",displayName:a.split("(")[0].trim()||a,rawId:a}:{brand:"none",model:"none",displayName:"No Controller Detected",rawId:""}}var te=(()=>{let a=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;a[e]=t>>>0}return a})();function we(a,e,t){let n=4294967295;n=te[(n^a)&255]^n>>>8,n=te[(n^e)&255]^n>>>8;for(let i=0;i<t.length;i++)n=te[(n^t[i])&255]^n>>>8;return(n^4294967295)>>>0}function R(a){let e=new Uint8Array(11);if(a.type==="off")return e[0]=5,e;if(a.type==="feedback"||a.type==="slope"){e[0]=33;let s=new Array(10).fill(0);if(a.type==="feedback"){let p=Math.max(0,Math.min(9,Math.round(a.startZone))),d=Math.max(1,Math.min(8,Math.round(a.strength)));for(let h=p;h<10;h++)s[h]=d}else{let p=Math.max(0,Math.min(8,Math.round(a.startZone))),d=Math.max(p+1,Math.min(9,Math.round(a.endZone)));for(let h=p;h<=d;h++){let b=(h-p)/(d-p);s[h]=Math.max(1,Math.min(8,Math.round(a.startStrength+b*(a.endStrength-a.startStrength))))}}let c=0,l=0;for(let p=0;p<10;p++){let d=s[p];d>0&&(c|=1<<p,l|=(d-1&7)<<3*p)}return e[1]=c&255,e[2]=c>>8&255,e[3]=l&255,e[4]=l>>8&255,e[5]=l>>16&255,e[6]=l>>24&255,e}if(a.type==="weapon"){let s=Math.max(2,Math.min(7,Math.round(a.startZone))),c=Math.max(s+1,Math.min(8,Math.round(a.endZone))),l=Math.max(1,Math.min(8,Math.round(a.strength))),p=1<<s|1<<c;return e[0]=37,e[1]=p&255,e[2]=p>>8&255,e[3]=l-1&7,e}let t=Math.max(0,Math.min(9,Math.round(a.startZone))),n=Math.max(1,Math.min(8,Math.round(a.amplitude))),i=Math.max(1,Math.min(255,Math.round(a.frequencyHz))),r=0,o=0;for(let s=t;s<10;s++)r|=1<<s,o|=(n-1&7)<<3*s;return e[0]=38,e[1]=r&255,e[2]=r>>8&255,e[3]=o&255,e[4]=o>>8&255,e[5]=o>>16&255,e[6]=o>>24&255,e[9]=i,e}function F(){return{connected:!1,source:"none",deviceName:"",isDualSense:!1,identity:{brand:"none",model:"none",displayName:"No Controller Detected",rawId:"",transport:"disconnected",source:"none"},lx:0,ly:0,rx:0,ry:0,l2:0,r2:0,buttons:{cross:!1,circle:!1,square:!1,triangle:!1,l1:!1,r1:!1,l2Btn:!1,r2Btn:!1,l3:!1,r3:!1,up:!1,down:!1,left:!1,right:!1,create:!1,options:!1,ps:!1,touchpadClick:!1},touch:{active:!1,x:.5,y:.5},touch2:{active:!1,x:.5,y:.5},gyro:{x:0,y:0,z:0},accel:{x:0,y:0,z:0},battery:{percent:0,charging:!1,full:!1,known:!1},observedReportHz:null}}function fe(){let a=()=>({center:2048,minDelta:1500,maxDelta:1500});return{lx:a(),ly:a(),rx:a(),ry:a()}}var ye=[4,10,21,27],ge=[1,3,7,15];function L(a){return new Promise(e=>setTimeout(e,a))}function be(a=0){return{speakerVolume:100,headphoneVolume:100,audioRoute:"speaker",speakerPreamp:7,lightbar:[23,23,23],playerLeds:ye[a%ye.length],leftTrigger:R({type:"off"}),rightTrigger:R({type:"off"}),legacyRumbleActive:!1,legacyLeft:0,legacyRight:0}}var G=class a{hidSessions=new Map;nextHidSeq=1;activeSlotId=null;hidDisconnectAttached=!1;hidConnectAttached=!1;listeners=new Set;gamepadInputs=new Map;gamepadLastActivity=new Map;gamepadPrevBtnMask=new Map;fallbackInput=F();keysDown=new Set;kbmAttached=!1;boundConnect=e=>{this.handleConnect(e)};boundDisconnect=e=>this.handleDisconnect(e);boundKeyDown=e=>{this.keysDown.add(e.code)};boundKeyUp=e=>{this.keysDown.delete(e.code)};boundWindowBlur=()=>{this.keysDown.clear()};get device(){return this.getActiveHidSession()?.device??null}get transport(){return this.getActiveHidSession()?.transport??"disconnected"}get firmwareInfo(){return this.getActiveHidSession()?.firmwareInfo}get hidDeviceCount(){return this.hidSessions.size}static isWebHIDSupported(){return typeof navigator<"u"&&"hid"in navigator}static isGamepadSupported(){return typeof navigator<"u"&&typeof navigator.getGamepads=="function"}isSupportedHidDevice(e){return e.vendorId===1356&&he.includes(e.productId)||e.vendorId===J&&ee.includes(e.productId)}attachHidHotplug(){this.hidConnectAttached||!a.isWebHIDSupported()||(navigator.hid.addEventListener("connect",this.boundConnect),this.hidConnectAttached=!0)}detachHidHotplug(){!this.hidConnectAttached||!a.isWebHIDSupported()||(navigator.hid.removeEventListener("connect",this.boundConnect),this.hidConnectAttached=!1)}async handleConnect(e){if(this.isSupportedHidDevice(e.device))try{await this.attachDevice(e.device)}catch{}}attachKeyboardFallback(){this.kbmAttached||typeof window>"u"||(window.addEventListener("keydown",this.boundKeyDown),window.addEventListener("keyup",this.boundKeyUp),window.addEventListener("blur",this.boundWindowBlur),this.kbmAttached=!0)}detachKeyboardFallback(){!this.kbmAttached||typeof window>"u"||(window.removeEventListener("keydown",this.boundKeyDown),window.removeEventListener("keyup",this.boundKeyUp),window.removeEventListener("blur",this.boundWindowBlur),this.keysDown.clear(),this.kbmAttached=!1)}onStatusChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){for(let t of this.listeners)try{t(e)}catch(n){console.error("[core-hid] listener error:",n)}}getAllRawGamepads(){if(!a.isGamepadSupported())return[];let e=navigator.getGamepads(),t=[];for(let n of e)n&&n.connected&&t.push(n);return t}pollGamepadActivity(e){let t=0,n=Math.min(20,e.buttons.length);for(let r=0;r<n;r++)e.buttons[r]?.pressed&&(t|=1<<r);let i=this.gamepadPrevBtnMask.get(e.index)??0;if(this.gamepadPrevBtnMask.set(e.index,t),(t&~i)!==0){let r=performance.now();return this.gamepadLastActivity.set(e.index,r),r}return this.gamepadLastActivity.get(e.index)??0}getConnectedControllers(){let e=[],t=0,n=0,i=0;for(let s of this.hidSessions.values())s.device.opened&&(s.input.identity.model==="dualsense_edge"?t++:s.input.identity.model==="switch_pro"?i++:n++,e.push({id:s.id,playerNumber:e.length+1,source:"webhid",identity:{...s.input.identity},battery:{...s.input.battery},observedReportHz:s.input.observedReportHz,lastActivityAt:s.lastActivityAt}));let r=this.getAllRawGamepads(),o=new Set;for(let s of r){o.add(s.index);let c=ne(s.id||"");if(c.model==="dualsense_edge"&&t>0){t--;continue}if(c.model==="dualsense"&&n>0){n--;continue}if(c.model==="switch_pro"&&i>0){i--;continue}let l=this.pollGamepadActivity(s);e.push({id:`gp-${s.index}`,playerNumber:e.length+1,source:"gamepad",identity:{...c,transport:"unknown",source:"gamepad"},battery:{percent:0,charging:!1,full:!1,known:!1},observedReportHz:null,lastActivityAt:l})}for(let s of this.gamepadPrevBtnMask.keys())o.has(s)||(this.gamepadPrevBtnMask.delete(s),this.gamepadLastActivity.delete(s));return e.length===0?this.activeSlotId=null:(!this.activeSlotId||!e.some(s=>s.id===this.activeSlotId))&&(this.activeSlotId=e[0].id),e}getActiveSlotId(){return this.getConnectedControllers(),this.activeSlotId}setActiveSlot(e){return this.getConnectedControllers().some(n=>n.id===e)?(this.activeSlotId!==e&&(this.activeSlotId=e,this.emit({type:"slots_changed",slotId:e})),!0):!1}getHidSessionForSlot(e){if(e!==void 0){let r=this.hidSessions.get(e);return r&&r.device.opened?r:null}let t=this.getConnectedControllers(),n=this.activeSlotId??t[0]?.id??null;if(!n)return null;let i=this.hidSessions.get(n);return i&&i.device.opened?i:null}getActiveHidSession(){return this.getHidSessionForSlot()}getGamepadForSlot(e){if(!a.isGamepadSupported())return null;if(e!==void 0){if(!e.startsWith("gp-"))return null;let i=Number(e.slice(3)),r=navigator.getGamepads()[i];return r&&r.connected?r:null}let t=this.getConnectedControllers(),n=this.activeSlotId??t[0]?.id??null;if(n&&n.startsWith("gp-")){let i=Number(n.slice(3)),r=navigator.getGamepads()[i];if(r&&r.connected)return r}if(n&&n.startsWith("hid-"))return null;for(let i of navigator.getGamepads())if(i&&i.connected)return i;return null}getActiveGamepad(){return this.getGamepadForSlot()}getGamepadActuatorEffects(e){let n=this.getGamepadForSlot(e)?.vibrationActuator;return n?Array.isArray(n.effects)&&n.effects.length>0?n.effects:typeof n.playEffect=="function"?["dual-rumble"]:[]:[]}hasTriggerRumbleSupport(e){return this.getGamepadActuatorEffects(e).includes("trigger-rumble")}hasDualRumbleSupport(e){return this.getGamepadActuatorEffects(e).includes("dual-rumble")||!!this.getGamepadForSlot(e)?.vibrationActuator?.playEffect}async connect(){if(!a.isWebHIDSupported())throw new Error("WebHID requires a Chromium browser (Chrome or Edge on desktop).");let e=await navigator.hid.requestDevice({filters:[...he.map(n=>({vendorId:1356,productId:n})),...ee.map(n=>({vendorId:J,productId:n}))]});if(!e.length)return!1;let t=null;for(let n of e)t=await this.attachDevice(n);return t&&(this.activeSlotId=t,this.emit({type:"slots_changed",slotId:t})),!!t}async reconnectAuthorized(){if(!a.isWebHIDSupported())return!1;let t=(await navigator.hid.getDevices()).filter(i=>this.isSupportedHidDevice(i));if(!t.length)return!1;let n=!1;for(let i of t)try{await this.attachDevice(i),n=!0}catch{}return n}async readFirmwareInfoSafe(e){try{let t=await e.receiveFeatureReport(32);if(t.byteLength<44)return;let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=n[0]===32?1:0,r=(d,h)=>{let b="";for(let g=d;g<d+h&&g<n.length;g++){let w=n[g];w>=32&&w<=126&&(b+=String.fromCharCode(w))}return b.trim()},o=r(i+0,11),s=r(i+11,8),c=new DataView(t.buffer,t.byteOffset+i),l=c.byteLength>=28?c.getUint32(24,!0):0,p=c.byteLength>=32?c.getUint32(28,!0):0;return!o&&!l?void 0:{buildDate:o||"Unknown",buildTime:s||"",hwInfoHex:`0x${l.toString(16).padStart(8,"0")}`,fwVersionHex:`0x${p.toString(16).padStart(8,"0")}`}}catch{return}}async attachDevice(e){for(let g of this.hidSessions.values())if(g.device===e&&g.device.opened)return g.id;if(e.opened||await e.open(),e.vendorId===J&&ee.includes(e.productId))return this.attachSwitchProDevice(e);let n=!1,i=!1,r=47,o=77;for(let g of e.collections||[])for(let w of g.outputReports||[]){let M=Math.ceil((w.items||[]).reduce((k,u)=>k+(u.reportSize||0)*(u.reportCount||0),0)/8);w.reportId===2&&(n=!0,M>=47&&(r=M)),w.reportId===49&&(i=!0,M>=77&&(o=M))}let s=n?"usb":i?"bluetooth":"usb",c=e.productId===3570,l=await this.readFirmwareInfoSafe(e),p=`hid-${this.nextHidSeq++}`,d=c?"DualSense Edge":"PlayStation DualSense",h=F();h.connected=!0,h.source="webhid",h.isDualSense=!0,h.deviceName=e.productName||d,h.identity={brand:"sony",model:c?"dualsense_edge":"dualsense",displayName:d,rawId:e.productName||d,vendorId:e.vendorId,productId:e.productId,transport:s,source:"webhid",firmwareInfo:l};let b={id:p,kind:"dualsense",device:e,transport:s,firmwareInfo:l,usbPayloadLength:r,btPayloadLength:o,btSeq:0,switchSubcmdLength:48,switchRumbleLength:9,switchUsb80Length:1,switchPacketNum:0,switchCal:fe(),switchRumbleTimer:null,switchSeqTimers:[],reportTimes:[],input:h,outState:be(this.hidSessions.size),legacyTimer:null,lastActivityAt:performance.now(),prevBtnMask:0,boundInputReport:g=>this.handleInputReport(b,g)};return this.hidSessions.set(p,b),this.activeSlotId||(this.activeSlotId=p),this.getConnectedControllers(),e.addEventListener("inputreport",b.boundInputReport),!this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.addEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!0),await this.flushSessionOutput(b,{includeAudioConfig:!0,includeTriggers:!0,includeLeds:!0}),this.emit({type:"connected",slotId:p,deviceName:h.deviceName,productId:e.productId,transport:s,firmwareInfo:l}),p}async attachSwitchProDevice(e){let t=!1,n=48,i=9,r=1;for(let h of e.collections||[])for(let b of h.outputReports||[]){let g=Math.ceil((b.items||[]).reduce((w,M)=>w+(M.reportSize||0)*(M.reportCount||0),0)/8);b.reportId===128&&(t=!0,g>=1&&(r=g)),b.reportId===1&&g>=10&&(n=g),b.reportId===16&&g>=9&&(i=g)}let o=t?"usb":"bluetooth",s=`hid-${this.nextHidSeq++}`,c="Nintendo Switch Pro Controller",l=F();l.connected=!0,l.source="webhid",l.isDualSense=!1,l.deviceName=e.productName||c,l.identity={brand:"nintendo",model:"switch_pro",displayName:c,rawId:e.productName||c,vendorId:e.vendorId,productId:e.productId,transport:o,source:"webhid"};let p=this.hidSessions.size,d={id:s,kind:"switch_pro",device:e,transport:o,firmwareInfo:void 0,usbPayloadLength:47,btPayloadLength:77,btSeq:0,switchSubcmdLength:n,switchRumbleLength:i,switchUsb80Length:r,switchPacketNum:0,switchCal:fe(),switchRumbleTimer:null,switchSeqTimers:[],reportTimes:[],input:l,outState:be(p),legacyTimer:null,lastActivityAt:performance.now(),prevBtnMask:0,boundInputReport:h=>this.handleSwitchProInputReport(d,h)};return this.hidSessions.set(s,d),this.activeSlotId||(this.activeSlotId=s),this.getConnectedControllers(),e.addEventListener("inputreport",d.boundInputReport),!this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.addEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!0),await this.initSwitchProSession(d,p),this.emit({type:"connected",slotId:s,deviceName:l.deviceName,productId:e.productId,transport:o}),s}async sendSwitchUsbCmd(e,t){if(!e.device.opened)return;let n=new Uint8Array(Math.max(1,e.switchUsb80Length));n[0]=t&255,await e.device.sendReport(128,n)}async sendSwitchSubcommand(e,t,n=[]){if(!e.device.opened)return;let i=Math.max(10+n.length,e.switchSubcmdLength),r=new Uint8Array(i);r[0]=e.switchPacketNum&15,e.switchPacketNum=e.switchPacketNum+1&15,r.set(I,1),r.set(I,5),r[9]=t&255;for(let o=0;o<n.length;o++)r[10+o]=n[o]&255;await e.device.sendReport(1,r)}async sendSwitchRumbleBytes(e,t,n){if(!e.device.opened)return!1;let i=Math.max(9,e.switchRumbleLength),r=new Uint8Array(i);return r[0]=e.switchPacketNum&15,e.switchPacketNum=e.switchPacketNum+1&15,r.set(t.subarray(0,4),1),r.set(n.subarray(0,4),5),await e.device.sendReport(16,r),!0}clearSwitchRumbleTimers(e){e.switchRumbleTimer&&(clearTimeout(e.switchRumbleTimer),e.switchRumbleTimer=null);for(let t of e.switchSeqTimers)clearTimeout(t);e.switchSeqTimers=[]}async initSwitchProSession(e,t){try{e.transport==="usb"&&(await this.sendSwitchUsbCmd(e,2).catch(()=>{}),await L(25),await this.sendSwitchUsbCmd(e,4).catch(()=>{}),await L(25)),await this.sendSwitchSubcommand(e,3,[48]),await L(20),await this.sendSwitchSubcommand(e,64,[1]),await L(20),await this.sendSwitchSubcommand(e,72,[1]),await L(20),await this.sendSwitchSubcommand(e,48,[ge[t%ge.length]]),await L(20),await this.sendSwitchSubcommand(e,16,[61,96,0,0,18]).catch(()=>{})}catch{}}parseSwitchStickCalibration(e,t){if(t.byteLength<37||t.getUint8(13)!==16||t.getUint32(14,!0)!==24637)return;let i=u=>{let y=t.getUint8(u),x=t.getUint8(u+1),v=t.getUint8(u+2);return[y|(x&15)<<8,x>>4&15|v<<4]},[r,o]=i(19),[s,c]=i(22),[l,p]=i(25),[d,h]=i(28),[b,g]=i(31),[w,M]=i(34),k=(u,y,x)=>u>=900&&u<=3200&&y>=400&&y<=2400&&x>=400&&x<=2400;k(s,l,r)&&k(c,p,o)&&(e.switchCal.lx={center:s,minDelta:l,maxDelta:r},e.switchCal.ly={center:c,minDelta:p,maxDelta:o}),k(d,b,w)&&k(h,g,M)&&(e.switchCal.rx={center:d,minDelta:b,maxDelta:w},e.switchCal.ry={center:h,minDelta:g,maxDelta:M})}handleSwitchProInputReport(e,t){let{reportId:n,data:i}=t;if(n===33&&this.parseSwitchStickCalibration(e,i),n!==48&&n!==33||i.byteLength<11)return;let r=e.input,o=performance.now();if(n===48&&(e.reportTimes.push(o),e.reportTimes.length>33&&e.reportTimes.shift(),e.reportTimes.length>=6)){let u=e.reportTimes[e.reportTimes.length-1]-e.reportTimes[0];u>10&&(r.observedReportHz=Math.round((e.reportTimes.length-1)*1e3/u))}let s=i.getUint8(1),c=Math.min(4,s>>5&7);r.battery.percent=c*25,r.battery.charging=!!(s&16),r.battery.full=c>=4,r.battery.known=!0;let l=i.getUint8(2),p=i.getUint8(3),d=i.getUint8(4);r.buttons.square=!!(l&1),r.buttons.triangle=!!(l&2),r.buttons.cross=!!(l&4),r.buttons.circle=!!(l&8),r.buttons.r1=!!(l&64),r.buttons.r2Btn=!!(l&128),r.buttons.create=!!(p&1),r.buttons.options=!!(p&2),r.buttons.r3=!!(p&4),r.buttons.l3=!!(p&8),r.buttons.ps=!!(p&16),r.buttons.touchpadClick=!!(p&32),r.buttons.down=!!(d&1),r.buttons.up=!!(d&2),r.buttons.right=!!(d&4),r.buttons.left=!!(d&8),r.buttons.l1=!!(d&64),r.buttons.l2Btn=!!(d&128),r.l2=r.buttons.l2Btn?1:0,r.r2=r.buttons.r2Btn?1:0;let h=l&207|(p&63)<<8|(d&207)<<16;(h&~e.prevBtnMask)!==0&&(e.lastActivityAt=o),e.prevBtnMask=h;let b=(u,y)=>{let x=u-y.center,v=x>=0?y.maxDelta:y.minDelta,H=v>0?x/v:0;return Math.max(-1,Math.min(1,H))},g=i.getUint8(5)|(i.getUint8(6)&15)<<8,w=i.getUint8(6)>>4&15|i.getUint8(7)<<4,M=i.getUint8(8)|(i.getUint8(9)&15)<<8,k=i.getUint8(9)>>4&15|i.getUint8(10)<<4;if(r.lx=b(g,e.switchCal.lx),r.ly=-b(w,e.switchCal.ly),r.rx=b(M,e.switchCal.rx),r.ry=-b(k,e.switchCal.ry),n===48&&i.byteLength>=48){let u=0,y=0,x=0,v=0,H=0,m=0;for(let D=0;D<3;D++){let q=12+D*12;u+=i.getInt16(q+0,!0),y+=i.getInt16(q+2,!0),x+=i.getInt16(q+4,!0),v+=i.getInt16(q+6,!0),H+=i.getInt16(q+8,!0),m+=i.getInt16(q+10,!0)}let f=u/3,S=y/3,C=x/3,T=v/3,B=H/3,P=m/3,A=D=>Math.max(-1,Math.min(1,D));r.accel.x=A(S/4096),r.accel.y=A(C/4096),r.accel.z=A(-f/4096),r.gyro.x=A(B/8192),r.gyro.y=A(P/8192),r.gyro.z=A(T/8192)}}async disconnect(e){let t=e??this.activeSlotId??Array.from(this.hidSessions.keys())[0];if(!t)return;let n=this.hidSessions.get(t);if(n){n.legacyTimer&&(clearTimeout(n.legacyTimer),n.legacyTimer=null),this.clearSwitchRumbleTimers(n);try{n.kind==="switch_pro"?await this.sendSwitchRumbleBytes(n,I,I):(n.outState.leftTrigger=R({type:"off"}),n.outState.rightTrigger=R({type:"off"}),n.outState.legacyRumbleActive=!1,n.outState.legacyLeft=0,n.outState.legacyRight=0,await this.flushSessionOutput(n,{includeTriggers:!0}))}catch{}n.device.removeEventListener("inputreport",n.boundInputReport);try{n.device.opened&&await n.device.close()}catch{}if(this.hidSessions.delete(t),this.hidSessions.size===0&&this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.removeEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!1),this.activeSlotId===t){let i=this.getConnectedControllers();this.activeSlotId=i[0]?.id??null}this.emit({type:"disconnected",slotId:t})}}async disconnectAll(){let e=Array.from(this.hidSessions.keys());for(let t of e)await this.disconnect(t)}handleDisconnect(e){for(let[t,n]of this.hidSessions.entries())if(n.device===e.device){if(n.legacyTimer&&(clearTimeout(n.legacyTimer),n.legacyTimer=null),this.clearSwitchRumbleTimers(n),n.device.removeEventListener("inputreport",n.boundInputReport),this.hidSessions.delete(t),this.activeSlotId===t){let i=this.getConnectedControllers();this.activeSlotId=i[0]?.id??null}this.emit({type:"disconnected",slotId:t})}this.hidSessions.size===0&&this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.removeEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!1)}handleInputReport(e,t){let{reportId:n,data:i}=t,r=0;if(n===49&&i.byteLength>=40)r=1;else if(n!==1||i.byteLength<10)return;let o=e.input,s=performance.now();if(e.reportTimes.push(s),e.reportTimes.length>33&&e.reportTimes.shift(),e.reportTimes.length>=6){let w=e.reportTimes[e.reportTimes.length-1]-e.reportTimes[0];w>10&&(o.observedReportHz=Math.round((e.reportTimes.length-1)*1e3/w))}let c=w=>{let M=w>=128?(w-128)/127:(w-128)/128;return Math.max(-1,Math.min(1,M))};o.lx=c(i.getUint8(r+0)),o.ly=c(i.getUint8(r+1)),o.rx=c(i.getUint8(r+2)),o.ry=c(i.getUint8(r+3)),o.l2=i.getUint8(r+4)/255,o.r2=i.getUint8(r+5)/255;let l=i.getUint8(r+7),p=i.getUint8(r+8),d=i.getUint8(r+9),h=l&15;o.buttons.up=h===0||h===1||h===7,o.buttons.right=h===1||h===2||h===3,o.buttons.down=h===3||h===4||h===5,o.buttons.left=h===5||h===6||h===7,o.buttons.square=!!(l&16),o.buttons.cross=!!(l&32),o.buttons.circle=!!(l&64),o.buttons.triangle=!!(l&128),o.buttons.l1=!!(p&1),o.buttons.r1=!!(p&2),o.buttons.l2Btn=!!(p&4),o.buttons.r2Btn=!!(p&8),o.buttons.create=!!(p&16),o.buttons.options=!!(p&32),o.buttons.l3=!!(p&64),o.buttons.r3=!!(p&128),o.buttons.ps=!!(d&1),o.buttons.touchpadClick=!!(d&2);let b=l&240|(h<8?1:0)|p<<8|(d&3)<<16;(b&~e.prevBtnMask)!==0&&(e.lastActivityAt=s),e.prevBtnMask=b,i.byteLength>r+26&&(o.gyro.x=Math.max(-1,Math.min(1,i.getInt16(r+15,!0)/16384)),o.gyro.y=Math.max(-1,Math.min(1,i.getInt16(r+17,!0)/16384)),o.gyro.z=Math.max(-1,Math.min(1,i.getInt16(r+19,!0)/16384)),o.accel.x=Math.max(-1,Math.min(1,i.getInt16(r+21,!0)/8192)),o.accel.y=Math.max(-1,Math.min(1,i.getInt16(r+23,!0)/8192)),o.accel.z=Math.max(-1,Math.min(1,i.getInt16(r+25,!0)/8192)));let g=(w,M)=>{if(i.byteLength<=w+3)return;let u=(i.getUint8(w)&128)===0;if(M.active=u,u){let y=i.getUint8(w+1),x=i.getUint8(w+2),v=i.getUint8(w+3),H=y|(x&15)<<8,m=(x&240)>>4|v<<4;M.x=Math.max(0,Math.min(1,H/1919)),M.y=Math.max(0,Math.min(1,m/1079))}};if(g(r+32,o.touch),g(r+36,o.touch2),i.byteLength>r+52){let w=i.getUint8(r+52),M=w&15,k=w>>4&15;o.battery.percent=Math.min(100,Math.round((M+.5)/10*100)),o.battery.charging=k===1,o.battery.full=k===2,o.battery.known=!0}}populateGamepadInput(e,t){let n=r=>Math.max(-1,Math.min(1,Number.isFinite(r)?r:0)),i=ne(e.id||"");return t.connected=!0,t.source="gamepad",t.deviceName=i.displayName,t.isDualSense=i.model==="dualsense"||i.model==="dualsense_edge",t.identity={...i,transport:"unknown",source:"gamepad"},t.lx=n(e.axes[0]??0),t.ly=n(e.axes[1]??0),t.rx=n(e.axes[2]??0),t.ry=n(e.axes[3]??0),t.l2=Math.max(0,Math.min(1,e.buttons[6]?.value??0)),t.r2=Math.max(0,Math.min(1,e.buttons[7]?.value??0)),t.buttons.cross=!!e.buttons[0]?.pressed,t.buttons.circle=!!e.buttons[1]?.pressed,t.buttons.square=!!e.buttons[2]?.pressed,t.buttons.triangle=!!e.buttons[3]?.pressed,t.buttons.l1=!!e.buttons[4]?.pressed,t.buttons.r1=!!e.buttons[5]?.pressed,t.buttons.l2Btn=!!e.buttons[6]?.pressed,t.buttons.r2Btn=!!e.buttons[7]?.pressed,t.buttons.create=!!e.buttons[8]?.pressed,t.buttons.options=!!e.buttons[9]?.pressed,t.buttons.l3=!!e.buttons[10]?.pressed,t.buttons.r3=!!e.buttons[11]?.pressed,t.buttons.up=!!e.buttons[12]?.pressed,t.buttons.down=!!e.buttons[13]?.pressed,t.buttons.left=!!e.buttons[14]?.pressed,t.buttons.right=!!e.buttons[15]?.pressed,t.buttons.ps=!!e.buttons[16]?.pressed,t.buttons.touchpadClick=!!e.buttons[17]?.pressed,t.touch.active=!1,t.touch2.active=!1,t.battery.known=!1,t.observedReportHz=null,t}getInputStateForSlot(e){let t=this.getHidSessionForSlot(e);if(t)return t.input;let n=this.getGamepadForSlot(e);if(n){let i=this.gamepadInputs.get(n.index);return i||(i=F(),this.gamepadInputs.set(n.index,i)),this.populateGamepadInput(n,i)}return F()}getInputState(e){if(e!==void 0)return this.getInputStateForSlot(e);let t=this.getActiveHidSession();if(t)return t.input;let n=this.getActiveGamepad();if(n)return this.populateGamepadInput(n,this.fallbackInput);let i=this.keysDown,r=(i.has("KeyD")||i.has("ArrowRight")?1:0)-(i.has("KeyA")||i.has("ArrowLeft")?1:0),o=(i.has("KeyS")||i.has("ArrowDown")?1:0)-(i.has("KeyW")||i.has("ArrowUp")?1:0),s=this.fallbackInput;return s.connected=!1,s.source="keyboard_mouse",s.deviceName="Keyboard & Mouse",s.isDualSense=!1,s.identity={brand:"none",model:"none",displayName:"Keyboard & Mouse",rawId:"",transport:"disconnected",source:"keyboard_mouse"},s.lx=r,s.ly=o,s.rx=0,s.ry=0,s.l2=i.has("ShiftLeft")||i.has("KeyQ")?1:0,s.r2=i.has("Space")||i.has("KeyE")?1:0,s.buttons.cross=i.has("Space")||i.has("Enter"),s.buttons.circle=i.has("KeyC")||i.has("Escape"),s.buttons.square=i.has("KeyR"),s.buttons.triangle=i.has("KeyF"),s.buttons.l1=i.has("KeyQ"),s.buttons.r1=i.has("KeyE"),s.buttons.l2Btn=s.l2>.5,s.buttons.r2Btn=s.r2>.5,s.buttons.l3=!1,s.buttons.r3=!1,s.buttons.up=i.has("ArrowUp")||i.has("KeyW"),s.buttons.down=i.has("ArrowDown")||i.has("KeyS"),s.buttons.left=i.has("ArrowLeft")||i.has("KeyA"),s.buttons.right=i.has("ArrowRight")||i.has("KeyD"),s.buttons.create=!1,s.buttons.options=!1,s.buttons.ps=!1,s.buttons.touchpadClick=!1,s.touch.active=!1,s.touch2.active=!1,s.battery.known=!1,s.observedReportHz=null,s}getCapabilityMatrixForSlot(e,t={}){let n=this.getInputState(e),i=n.identity,r=this.getHidSessionForSlot(e),o=r?.kind==="dualsense",s=r?.kind==="switch_pro",c=!!r,l=r?.transport??"unknown",p=a.isWebHIDSupported(),d=i.model==="dualsense"||i.model==="dualsense_edge",h=i.brand==="xbox",b=i.model==="switch_pro",g=i.brand==="nintendo",w=n.connected,M=this.hasTriggerRumbleSupport(e),k=this.hasDualRumbleSupport(e);if(!w){let u={inherent:!1,availability:"disconnected"};return{standard_input:u,analog_triggers:u,dual_motor_rumble:u,impulse_triggers:u,hd_rumble:u,adaptive_triggers:u,audio_haptics:u,controller_speaker:u,gyro:u,accelerometer:u,touchpad:u,lightbar:u,battery:u}}return{standard_input:{inherent:!0,availability:"ready"},analog_triggers:{inherent:!g,availability:g?"unsupported":"ready",reason:g?"Nintendo Pro/Joy-Con triggers are digital buttons":void 0},dual_motor_rumble:{inherent:!0,availability:c||k?"ready":"unsupported",reason:!c&&!k?"Browser Gamepad rumble actuator not exposed":void 0},impulse_triggers:{inherent:h,availability:h&&M?"ready":"unsupported",reason:h&&!M?"Requires Chrome/Edge 126+ with USB or Xbox Wireless Adapter (Windows Bluetooth often blocks trigger motors)":void 0},hd_rumble:{inherent:g,availability:g?s?"ready":b?p?"permission_required":"unsupported":"bridge_required":"unsupported",reason:b&&!s?p?"Connect Switch Pro via WebHID to unlock dual-band HD Rumble and 6-axis gyro":"WebHID requires desktop Chrome or Edge":void 0},adaptive_triggers:{inherent:d,availability:d?o?"ready":p?"permission_required":"unsupported":"unsupported",reason:d&&!o?p?"Click Unlock DualSense WebHID (works over USB & Bluetooth)":"WebHID requires desktop Chrome or Edge":void 0},audio_haptics:{inherent:d,availability:d?t.has4ChAudio?"ready":l==="bluetooth"?"configuration_required":"bridge_required":"unsupported",reason:d&&!t.has4ChAudio?l==="bluetooth"?"4-channel audio haptics require a wired USB-C connection on Windows":"Optional Gamepadly Link or USB 4ch audio routing required":void 0},controller_speaker:{inherent:d,availability:d?t.hasControllerSpeaker?"ready":l==="bluetooth"?"configuration_required":"bridge_required":"unsupported",reason:d&&!t.hasControllerSpeaker?"Requires wired USB-C DualSense audio output":void 0},gyro:{inherent:d||g,availability:d?o?"ready":p?"permission_required":"unsupported":b?s?"ready":p?"permission_required":"unsupported":g?"bridge_required":"unsupported"},accelerometer:{inherent:d||g,availability:d?o?"ready":p?"permission_required":"unsupported":b?s?"ready":p?"permission_required":"unsupported":g?"bridge_required":"unsupported"},touchpad:{inherent:d||i.model==="dualshock4",availability:d?o?"ready":p?"permission_required":"unsupported":"unsupported"},lightbar:{inherent:d||i.model==="dualshock4",availability:d?o?"ready":p?"permission_required":"unsupported":"unsupported"},battery:{inherent:!0,availability:d&&o||b&&s?"ready":"unknown"}}}getCapabilityMatrix(e={}){return this.getCapabilityMatrixForSlot(void 0,e)}async playSwitchHdRumble(e,t){let n=this.getHidSessionForSlot(t);if(!n||n.kind!=="switch_pro"||!n.device.opened)return!1;this.clearSwitchRumbleTimers(n);let i=N(e.left),r=N(e.right),o=Math.max(30,Math.min(2500,Math.round(e.durationMs??220)));try{await this.sendSwitchRumbleBytes(n,i,r)}catch{return!1}return n.switchRumbleTimer=setTimeout(()=>{n.switchRumbleTimer=null,this.sendSwitchRumbleBytes(n,I,I).catch(()=>{})},o),!0}async playSwitchHdRumbleSequence(e,t){let n=this.getHidSessionForSlot(t);if(!n||n.kind!=="switch_pro"||!n.device.opened||e.length===0)return!1;this.clearSwitchRumbleTimers(n);let i=0;for(let r of e){let o=Math.max(0,Math.round(r.delayMs)),s=Math.max(30,Math.min(1200,Math.round(r.durationMs??80)));o+s>i&&(i=o+s);let c=N(r.left),l=N(r.right);if(o===0)await this.sendSwitchRumbleBytes(n,c,l).catch(()=>{});else{let p=setTimeout(()=>{this.sendSwitchRumbleBytes(n,c,l).catch(()=>{})},o);n.switchSeqTimers.push(p)}}return n.switchRumbleTimer=setTimeout(()=>{n.switchRumbleTimer=null,n.switchSeqTimers=[],this.sendSwitchRumbleBytes(n,I,I).catch(()=>{})},i+15),!0}stopSwitchHdRumble(e){if(e!==void 0){let t=this.getHidSessionForSlot(e);t&&t.kind==="switch_pro"&&t.device.opened&&(this.clearSwitchRumbleTimers(t),this.sendSwitchRumbleBytes(t,I,I).catch(()=>{}));return}for(let t of this.hidSessions.values())t.kind!=="switch_pro"||!t.device.opened||(this.clearSwitchRumbleTimers(t),this.sendSwitchRumbleBytes(t,I,I).catch(()=>{}))}async playTriggerRumble(e,t,n,i=0,r=0,o){if(this.getHidSessionForSlot(o)?.kind==="switch_pro"){let k=Math.max(e,r),u=Math.max(t,i);return this.playSwitchHdRumble({left:k>.02?{highFreqHz:260,highAmp:k*.65,lowFreqHz:145,lowAmp:k*.7}:void 0,right:u>.02?{highFreqHz:340,highAmp:u*.7,lowFreqHz:170,lowAmp:u*.55}:void 0,durationMs:n},o)}let l=this.getGamepadForSlot(o)?.vibrationActuator;if(!l?.playEffect)return!1;let p=Math.max(20,Math.min(2500,Math.round(n))),d=Math.max(0,Math.min(1,e)),h=Math.max(0,Math.min(1,t)),b=Math.max(0,Math.min(1,i)),g=Math.max(0,Math.min(1,r));if(this.hasTriggerRumbleSupport(o))try{return await l.playEffect("trigger-rumble",{startDelay:0,duration:p,leftTrigger:d,rightTrigger:h,weakMagnitude:b,strongMagnitude:g}),!0}catch{}let w=Math.max(b,h*.65),M=Math.max(g,d*.65);return w>0||M>0?this.playDualRumble(w,M,p,o):!1}async playDualRumble(e,t,n,i){if(this.getHidSessionForSlot(i)?.kind==="switch_pro"){let c={highFreqHz:320,highAmp:Math.max(0,Math.min(.85,e*.8)),lowFreqHz:150,lowAmp:Math.max(0,Math.min(.85,t*.8))};return this.playSwitchHdRumble({left:c,right:c,durationMs:n},i)}let s=this.getGamepadForSlot(i)?.vibrationActuator;if(!s?.playEffect)return!1;try{return await s.playEffect("dual-rumble",{startDelay:0,duration:Math.max(20,Math.min(2500,Math.round(n))),strongMagnitude:Math.max(0,Math.min(1,t)),weakMagnitude:Math.max(0,Math.min(1,e))}),!0}catch{return!1}}stopGamepadRumble(e){if(this.stopSwitchHdRumble(e),!!a.isGamepadSupported()){if(e!==void 0){let t=this.getGamepadForSlot(e);t?.vibrationActuator?.reset&&t.vibrationActuator.reset().catch(()=>{});return}for(let t of this.getAllRawGamepads()){let n=t.vibrationActuator;n?.reset&&n.reset().catch(()=>{})}}}triggerGamepadRumbleFallback(e,t,n,i){let r=this.getHidSessionForSlot(i);if(r?.kind==="switch_pro"){this.playDualRumble(e,t,n,i);return}if(r?.kind==="dualsense"){this.pulseLegacyRumble(Math.round(Math.max(0,Math.min(1,t))*220),Math.round(Math.max(0,Math.min(1,e))*220),Math.max(25,Math.min(350,n)),i);return}this.playDualRumble(e,t,n,i)}buildCommonPayload(e,{includeAudioConfig:t=!1,includeTriggers:n=!1,includeLeds:i=!1}={}){let r=new Uint8Array(47),o=0,s=0;return e.legacyRumbleActive&&(o|=3,r[2]=Math.max(0,Math.min(255,Math.round(e.legacyRight))),r[3]=Math.max(0,Math.min(255,Math.round(e.legacyLeft)))),n&&(o|=12,r.set(e.rightTrigger.subarray(0,11),10),r.set(e.leftTrigger.subarray(0,11),21)),t&&(o|=176,s|=130,r[4]=Math.max(0,Math.min(127,e.headphoneVolume)),r[5]=Math.max(0,Math.min(255,e.speakerVolume)),r[6]=0,r[7]=e.audioRoute==="speaker"?48:e.audioRoute==="both"?32:0,r[9]=0,r[37]=e.speakerPreamp&7),i&&(s|=20,r[38]=2,r[41]=2,r[42]=0,r[43]=e.playerLeds&31,r[44]=e.lightbar[0]&255,r[45]=e.lightbar[1]&255,r[46]=e.lightbar[2]&255),r[0]=o,r[1]=s,r}async flushSessionOutput(e,t={}){if(e.kind!=="dualsense"||!e.device.opened)return!1;let n=this.buildCommonPayload(e.outState,t);if(e.transport==="bluetooth"){let r=new Uint8Array(e.btPayloadLength);r[0]=(e.btSeq&15)<<4,e.btSeq=e.btSeq+1&15,r[1]=16,r.set(n,2);let o=r.length-4,s=we(162,49,r.subarray(0,o));return new DataView(r.buffer).setUint32(o,s,!0),await e.device.sendReport(49,r),!0}let i=new Uint8Array(e.usbPayloadLength);return i.set(n,0),await e.device.sendReport(2,i),!0}async flushOutput(e={}){let t=this.getActiveHidSession();return!t||t.kind!=="dualsense"?!1:this.flushSessionOutput(t,e)}async setAudioConfig(e){let t=this.getActiveHidSession();return!t||t.kind!=="dualsense"?!1:(e.speakerVolume!==void 0&&(t.outState.speakerVolume=e.speakerVolume),e.headphoneVolume!==void 0&&(t.outState.headphoneVolume=e.headphoneVolume),e.audioRoute!==void 0&&(t.outState.audioRoute=e.audioRoute),e.speakerPreamp!==void 0&&(t.outState.speakerPreamp=e.speakerPreamp),this.flushSessionOutput(t,{includeAudioConfig:!0}))}async setTriggers(e,t,n){let i=this.getHidSessionForSlot(n);if(!i||i.kind!=="dualsense")return!1;let r=i.outState.leftTrigger,o=i.outState.rightTrigger,s=e?R(e):void 0,c=t?R(t):void 0;s&&(i.outState.leftTrigger=s),c&&(i.outState.rightTrigger=c);try{let l=await this.flushSessionOutput(i,{includeTriggers:!0});return l||(s&&i.outState.leftTrigger===s&&(i.outState.leftTrigger=r),c&&i.outState.rightTrigger===c&&(i.outState.rightTrigger=o)),l}catch(l){throw s&&i.outState.leftTrigger===s&&(i.outState.leftTrigger=r),c&&i.outState.rightTrigger===c&&(i.outState.rightTrigger=o),l}}async resetTriggers(e){if(this.stopGamepadRumble(e),e!==void 0){let n=this.getHidSessionForSlot(e);return!n||!n.device.opened||n.kind!=="dualsense"?!1:(n.outState.leftTrigger=R({type:"off"}),n.outState.rightTrigger=R({type:"off"}),this.flushSessionOutput(n,{includeTriggers:!0}).catch(()=>!1))}let t=!1;for(let n of this.hidSessions.values()){if(!n.device.opened||n.kind!=="dualsense")continue;n.outState.leftTrigger=R({type:"off"}),n.outState.rightTrigger=R({type:"off"}),await this.flushSessionOutput(n,{includeTriggers:!0}).catch(()=>!1)&&(t=!0)}return t}emergencyReset(){this.stopGamepadRumble();for(let e of this.hidSessions.values())if(e.device.opened){if(e.kind==="switch_pro"){this.clearSwitchRumbleTimers(e),this.sendSwitchRumbleBytes(e,I,I).catch(()=>{});continue}e.outState.leftTrigger=R({type:"off"}),e.outState.rightTrigger=R({type:"off"}),e.outState.legacyRumbleActive=!1,e.outState.legacyLeft=0,e.outState.legacyRight=0,e.outState.lightbar=[23,23,23],this.flushSessionOutput(e,{includeTriggers:!0,includeLeds:!0}).catch(()=>{})}}async setLightbar(e,t,n,i){let r=this.getHidSessionForSlot(i);return!r||r.kind!=="dualsense"?!1:(r.outState.lightbar=[e&255,t&255,n&255],this.flushSessionOutput(r,{includeLeds:!0}))}async pulseLegacyRumble(e=200,t=200,n=250,i){let r=this.getHidSessionForSlot(i);return!r||r.kind!=="dualsense"||!r.device.opened?!1:(r.legacyTimer&&(clearTimeout(r.legacyTimer),r.legacyTimer=null),r.outState.legacyRumbleActive=!0,r.outState.legacyLeft=e,r.outState.legacyRight=t,await this.flushSessionOutput(r,{}),new Promise(o=>{r.legacyTimer=setTimeout(async()=>{r.legacyTimer=null;try{r.outState.legacyLeft=0,r.outState.legacyRight=0,await this.flushSessionOutput(r,{}),r.outState.legacyRumbleActive=!1,await this.flushSessionOutput(r,{includeAudioConfig:!0})}catch{}o(!0)},n)}))}};var O={off:{type:"off"},weapon:{type:"weapon",startZone:2,endZone:5,strength:7},heavy_weapon:{type:"weapon",startZone:3,endZone:6,strength:8},bow:{type:"slope",startZone:1,endZone:8,startStrength:1,endStrength:7},abs:{type:"vibration",startZone:2,amplitude:6,frequencyHz:22},soft_wall:{type:"feedback",startZone:4,strength:4},rapid_pulse:{type:"vibration",startZone:1,amplitude:7,frequencyHz:14},precision_damp:{type:"feedback",startZone:2,strength:3}},ie={click:{freqHz:210,endFreqHz:140,durationMs:26,intensity:.45,wave:"triangle",triggerEmphasis:.65,switchHd:{highFreqHz:340,lowFreqHz:165,highWeight:.75,lowWeight:.25}},ratchet:{freqHz:180,endFreqHz:110,durationMs:22,intensity:.5,wave:"triangle",triggerEmphasis:.75,switchHd:{highFreqHz:320,lowFreqHz:155,highWeight:.8,lowWeight:.2}},wall_hit:{freqHz:135,endFreqHz:58,durationMs:65,intensity:.78,wave:"triangle",triggerEmphasis:.5,switchHd:{highFreqHz:290,lowFreqHz:130,highWeight:.55,lowWeight:.75}},marble_click:{freqHz:290,endFreqHz:210,durationMs:32,intensity:.62,wave:"sine",triggerEmphasis:.85,switchHd:{highFreqHz:380,lowFreqHz:190,highWeight:.85,lowWeight:.18}},recoil:{freqHz:115,endFreqHz:46,durationMs:75,intensity:.88,wave:"triangle",triggerEmphasis:1,switchHd:{highFreqHz:310,lowFreqHz:120,highWeight:.65,lowWeight:.85}},heavy_impact:{freqHz:75,endFreqHz:34,durationMs:140,intensity:.95,wave:"sine",triggerEmphasis:.7,switchHd:{highFreqHz:220,lowFreqHz:95,highWeight:.45,lowWeight:.95}},lock_unlock:{freqHz:95,endFreqHz:220,durationMs:120,intensity:.72,wave:"triangle",triggerEmphasis:.6,switchHd:{highFreqHz:350,lowFreqHz:150,highWeight:.7,lowWeight:.55}},splash:{freqHz:90,endFreqHz:48,durationMs:110,intensity:.6,wave:"sine",triggerEmphasis:.35,switchHd:{highFreqHz:250,lowFreqHz:120,highWeight:.5,lowWeight:.6}},boost:{freqHz:65,endFreqHz:165,durationMs:160,intensity:.75,wave:"sawtooth",triggerEmphasis:.85,switchHd:{highFreqHz:300,lowFreqHz:135,highWeight:.6,lowWeight:.75}},error_buzz:{freqHz:145,endFreqHz:115,durationMs:95,intensity:.65,wave:"square",triggerEmphasis:.45,switchHd:{highFreqHz:260,lowFreqHz:125,highWeight:.55,lowWeight:.65}}};function W(a){let e=Math.max(-1,Math.min(1,a.pan??0)),t=Math.max(0,Math.min(1,a.intensity)),n=Math.min(1,1-Math.max(0,e)),i=Math.min(1,1+Math.min(0,e)),r=a.highFreqHz??Math.max(160,Math.min(620,a.freqHz*1.9)),o=a.lowFreqHz??Math.max(60,Math.min(240,a.freqHz)),s=a.highWeight??(a.freqHz>=140?.78:.42),c=a.lowWeight??(a.freqHz<140?.82:.38),l=p=>{let d=t*p;if(!(d<.02))return{highFreqHz:r,highAmp:Math.min(.85,d*s*.85),lowFreqHz:o,lowAmp:Math.min(.85,d*c*.85)}};return{left:l(n),right:l(i),durationMs:Math.max(30,Math.min(2500,Math.round(a.durationMs)))}}function re(a){return a.allow4ChAudio===!1?!1:!!(a.audio&&a.audio.dsMode!=="none"&&a.audio.dsMaxChannelCount>=4)}function U(a,e){if(re(a)){a.audio.playHapticPulse(e);return}let t=a.hid.getCapabilityMatrixForSlot(a.slotId),n=Math.max(0,Math.min(1,e.intensity)),i=Math.max(25,Math.min(2500,Math.round(e.durationMs))),r=Math.max(-1,Math.min(1,e.pan??0));if(t.hd_rumble?.availability==="ready"){let c=W({pan:r,freqHz:e.freqHz,intensity:n,durationMs:i});a.hid.playSwitchHdRumble(c,a.slotId);return}if(t.impulse_triggers?.availability==="ready"){let c=Math.min(1,1-Math.max(0,r)),l=Math.min(1,1+Math.min(0,r)),p=e.freqHz>=120?.85:.45,d=e.freqHz<120?.78:.35;a.hid.playTriggerRumble(n*c*p,n*l*p,i,n*(e.freqHz>=120?.65:.35),n*d,a.slotId);return}let o=e.freqHz<120?n*.8:n*.3,s=e.freqHz>=120?n*.85:n*.4;a.hid.triggerGamepadRumbleFallback(s,o,i,a.slotId)}function ae(a,e){if(re(a)){a.audio.playHapticSweep(e);return}let t=a.hid.getCapabilityMatrixForSlot(a.slotId),n=Math.max(0,Math.min(1,e.intensity)),i=Math.max(40,Math.min(2500,Math.round(e.durationMs)));if(t.hd_rumble?.availability==="ready"){let r=Math.max(2,Math.min(6,Math.round(i/55))),o=Math.max(30,Math.round(i/r)),s=[];for(let c=0;c<r;c++){let l=r===1?0:c/(r-1),p=e.fromPan+(e.toPan-e.fromPan)*l,d=e.fromHz+(e.toHz-e.fromHz)*l;s.push({...W({pan:p,freqHz:d,intensity:n,durationMs:o}),delayMs:c*o})}a.hid.playSwitchHdRumbleSequence(s,a.slotId);return}if(t.impulse_triggers?.availability==="ready"){let r=(e.fromPan+e.toPan)*.5,o=Math.min(1,1-Math.max(0,r)),s=Math.min(1,1+Math.min(0,r));a.hid.playTriggerRumble(n*o*.7,n*s*.7,i,n*.5,n*.6,a.slotId);return}a.hid.triggerGamepadRumbleFallback(n*.55,n*.65,i,a.slotId)}function oe(a,e,t={}){let n=ie[e];if(!n)return;let i=Math.max(-1,Math.min(1,t.pan??0)),r=Math.max(0,Math.min(1,(t.intensity??1)*n.intensity));if(re(a)){a.audio.playHapticPulse({pan:i,freqHz:n.freqHz,endFreqHz:n.endFreqHz,durationMs:n.durationMs,intensity:r,wave:n.wave});return}let o=a.hid.getCapabilityMatrixForSlot(a.slotId);if(o.hd_rumble?.availability==="ready"&&n.switchHd){let s=W({pan:i,freqHz:n.freqHz,intensity:r,durationMs:n.durationMs,highFreqHz:n.switchHd.highFreqHz,lowFreqHz:n.switchHd.lowFreqHz,highWeight:n.switchHd.highWeight,lowWeight:n.switchHd.lowWeight});a.hid.playSwitchHdRumble(s,a.slotId);return}if(o.impulse_triggers?.availability==="ready"&&n.triggerEmphasis){let s=Math.min(1,1-Math.max(0,i)),c=Math.min(1,1+Math.min(0,i)),l=r*n.triggerEmphasis;a.hid.playTriggerRumble(l*s,l*c,Math.max(30,n.durationMs),r*.45,r*.55,a.slotId);return}U(a,{pan:i,freqHz:n.freqHz,endFreqHz:n.endFreqHz,durationMs:n.durationMs,intensity:r,wave:n.wave})}var Ce=new Set(["cross","circle","square","triangle","l1","r1","l2Btn","r2Btn","l3","r3","up","down","left","right","create","options","ps","touchpadClick"]);function He(a,e,t,n,i){return a==="l2"?e.l2:a==="r2"?e.r2:a==="lx+"?Math.max(0,e.lx):a==="lx-"?Math.max(0,-e.lx):a==="ly+"?Math.max(0,e.ly):a==="ly-"?Math.max(0,-e.ly):a==="rx+"?Math.max(0,e.rx):a==="rx-"?Math.max(0,-e.rx):a==="ry+"?Math.max(0,e.ry):a==="ry-"?Math.max(0,-e.ry):Ce.has(a)?e.buttons[a]?1:0:a==="MouseLeft"||a==="MouseRight"||a==="MouseMiddle"?n.has(a)?1:0:t.has(a)?Math.max(1,i):0}function se(a){let e=a.analogThreshold??.45,t=a.actions??{},n=a.axes??{},i=new Set,r=new Set,o=new Map,s=new Map,c=new Map;for(let u of Object.keys(t))o.set(u,{pressed:!1,justPressed:!1,justReleased:!1,heldMs:0,value:0});for(let u of Object.keys(n))c.set(u,0);let l=u=>u===0?"MouseLeft":u===1?"MouseMiddle":u===2?"MouseRight":null,p=u=>{let y=u;y.code&&i.add(y.code)},d=u=>{let y=u;y.code&&i.delete(y.code)},h=u=>{let x=l(u.button);x&&r.add(x)},b=u=>{let x=l(u.button);x&&r.delete(x)},g=()=>{i.clear(),r.clear()},w=a.attachWindowListeners!==!1&&typeof window<"u",M=a.mouseTarget??(typeof window<"u"?window:void 0);w&&(window.addEventListener("keydown",p),window.addEventListener("keyup",d),window.addEventListener("blur",g),M?.addEventListener("pointerdown",h),window.addEventListener("pointerup",b));let k={pressed:!1,justPressed:!1,justReleased:!1,heldMs:0,value:0};return{update(u,y=typeof performance<"u"?performance.now():Date.now()){for(let[x,v]of Object.entries(t)){let H=0;for(let B of v){let P=He(B,u,i,r,e);P>H&&(H=P)}let m=H>=e,f=o.get(x),S=m&&!f.pressed,C=!m&&f.pressed;S?s.set(x,y):m||s.delete(x);let T=s.get(x);f.pressed=m,f.justPressed=S,f.justReleased=C,f.heldMs=m&&T!==void 0?Math.max(0,y-T):0,f.value=Math.max(0,Math.min(1,H))}for(let[x,v]of Object.entries(n)){let H=0;if(v.stick){let C=u[v.stick],T=v.deadzone??.08;H=E(C,T)}let m=0;v.negativeButtons?.some(C=>u.buttons[C])&&(m-=1),v.positiveButtons?.some(C=>u.buttons[C])&&(m+=1),v.negativeKeys?.some(C=>i.has(C))&&(m-=1),v.positiveKeys?.some(C=>i.has(C))&&(m+=1);let f=Math.abs(m)>Math.abs(H)?m:H,S=Math.max(-1,Math.min(1,f));c.set(x,v.invert?-S:S)}},action(u){return o.get(u)??k},isPressed(u){return o.get(u)?.pressed??!1},justPressed(u){return o.get(u)?.justPressed??!1},justReleased(u){return o.get(u)?.justReleased??!1},axis(u){return c.get(u)??0},setKeyDown(u,y){y?i.add(u):i.delete(u)},setMouseButton(u,y){y?r.add(u):r.delete(u)},dispose(){w&&(window.removeEventListener("keydown",p),window.removeEventListener("keyup",d),window.removeEventListener("blur",g),M?.removeEventListener("pointerdown",h),window.removeEventListener("pointerup",b)),i.clear(),r.clear(),s.clear()}}}var ke={update(){},stop(){}};function ce(a,e,t,n){let i=n&&!!(e&&e.dsMode!=="none"&&e.dsMaxChannelCount>=4),r=n&&!!(e&&e.dsMode!=="none"),o=a.getInputState(t),s=a.getCapabilityMatrixForSlot(t,{has4ChAudio:i,hasControllerSpeaker:r}),c=p=>s[p]?.availability==="ready",l="keyboard_mouse";return c("adaptive_triggers")&&i?l="dualsense_full_4ch":c("adaptive_triggers")?l="dualsense_hid_only":c("hd_rumble")?l="switch_pro_hid":c("impulse_triggers")?l="xbox_impulse":o.source==="gamepad"&&(l="standard_gamepad"),{slotId:t??a.getActiveSlotId(),tier:l,identity:o.identity,matrix:s,has:c,hasAdaptiveTriggers:c("adaptive_triggers"),hasImpulseTriggers:c("impulse_triggers"),hasHdRumble:c("hd_rumble"),hasDualRumble:c("dual_motor_rumble"),has4ChHaptics:i,hasControllerSpeaker:r,hasGyro:c("gyro"),hasTouchpad:c("touchpad")}}function xe(a,e){return[a.map(n=>`${n.id}:${n.source}:${n.identity.model}:${n.identity.transport}`).join(","),e.slotId??"",e.tier,e.hasAdaptiveTriggers?1:0,e.hasImpulseTriggers?1:0,e.hasHdRumble?1:0,e.has4ChHaptics?1:0,e.hasControllerSpeaker?1:0,e.hasGyro?1:0].join("|")}function Te(a={}){let e=!a.hid,t=a.hid??new G,n=a.audio??null,i=!1,r=new Set,o=new Set,s=new Set,c=new Set;a.autoHotplug!==!1&&t.attachHidHotplug(),a.attachKeyboardFallback&&e&&t.attachKeyboardFallback();let l="",p=()=>{if(i)return;let u=t.getConnectedControllers(),y=ce(t,n,void 0,!0),x=xe(u,y);if(x!==l){l=x;for(let v of c)try{v({slots:u,active:y})}catch{}}};l=xe(t.getConnectedControllers(),ce(t,n,void 0,!0));let d=t.onStatusChange(()=>{p()}),h=()=>p(),b=()=>t.emergencyReset();typeof window<"u"&&(a.autoHotplug!==!1&&(window.addEventListener("gamepadconnected",h),window.addEventListener("gamepaddisconnected",h)),a.autoEmergencyReset!==!1&&(window.addEventListener("pagehide",b),window.addEventListener("beforeunload",b)));let g=null,w=a.capabilityPollMs??250;w>0&&typeof setInterval<"u"&&(g=setInterval(p,w));let M=u=>{let y=[23,23,23],x=0,v=()=>{if(u==="active")return{slotId:void 0,connected:!0,isPrimary:!0};if(typeof u=="number"){let S=t.getConnectedControllers()[u];if(!S)return{slotId:`__unassigned_${u}`,connected:!1,isPrimary:u===0};let C=t.getActiveSlotId();return{slotId:S.id,connected:!0,isPrimary:S.id===C||u===0}}let m=t.getActiveSlotId();return{slotId:u,connected:!0,isPrimary:u===m}},H=()=>{let m=v();return{hid:t,audio:n,slotId:m.slotId,allow4ChAudio:m.isPrimary}};return{getSlotId(){let m=v();return m.slotId===void 0?t.getActiveSlotId():m.connected?m.slotId:null},getCapabilities(){let m=v();return ce(t,n,m.slotId,m.isPrimary)},input:{getState:()=>{let m=v();return t.getInputState(m.slotId)},applyDeadzone:E},triggers:{reset:()=>{if(i)return;let m=v();t.resetTriggers(m.slotId).catch(()=>{})},setLeft:m=>{if(i)return;let f=v();t.setTriggers(m,void 0,f.slotId).catch(()=>{})},setRight:m=>{if(i)return;let f=v();t.setTriggers(void 0,m,f.slotId).catch(()=>{})},setBoth:(m,f)=>{if(i)return;let S=v();t.setTriggers(m,f,S.slotId).catch(()=>{})},applyPreset:(m,f="both")=>{if(i)return;let S=O[m];if(!S)return;let C=v();f==="left"?t.setTriggers(S,void 0,C.slotId).catch(()=>{}):f==="right"?t.setTriggers(void 0,S,C.slotId).catch(()=>{}):t.setTriggers(S,S,C.slotId).catch(()=>{})},pulseImpulse:m=>{if(i)return;let f=v();t.playTriggerRumble(m.left??0,m.right??0,m.durationMs??80,m.weakGrip??0,m.strongGrip??0,f.slotId)}},haptics:{pulse:m=>{i||U(H(),m)},sweep:m=>{i||ae(H(),m)},rumble:m=>{if(i)return;let f=v();t.triggerGamepadRumbleFallback(m.weak,m.strong,m.durationMs,f.slotId)},hdRumble:m=>{if(i)return;let f=v();t.playSwitchHdRumble(m,f.slotId)},hdSequence:m=>{if(i)return;let f=v();t.playSwitchHdRumbleSequence(m,f.slotId)},playPreset:(m,f)=>{i||oe(H(),m,f)},createContinuous:m=>{if(i||!n)return ke;let f=n.createContinuous(m);return r.add(f),{update:S=>{i||f.update(S)},stop:()=>{r.delete(f),f.stop()}}},playComboPreset:(m,f=0)=>{if(i)return;let S=v();if(n?.playComboPreset(m,f),!n||!S.isPrimary||n.dsMode==="none"||n.dsMaxChannelCount<4){let C=m==="shotgun"||m==="thunder"?.85:.4,T=m==="ratchet_tick"?30:120;U(H(),{pan:f,freqHz:m==="ratchet_tick"?190:95,durationMs:T,intensity:C})}},stop:()=>{let m=v();t.stopGamepadRumble(m.slotId)}},audio:{playPcTone:m=>{i||n?.playPcTone(m)},playPcNoise:m=>{i||n?.playPcNoiseBurst(m)},playControllerSpeakerTone:m=>{i||n?.playControllerSpeakerTone(m)}},lightbar:{setColor:(m,f,S)=>{if(i)return;let C=typeof performance<"u"?performance.now():Date.now();if(y[0]===m&&y[1]===f&&y[2]===S||C-x<45)return;x=C,y=[m,f,S];let T=v();t.setLightbar(m,f,S,T.slotId).catch(()=>{})},flash:(m,f,S,C=240)=>{if(i)return;let T=[...y],B=v();t.setLightbar(m,f,S,B.slotId).catch(()=>{});let P=setTimeout(()=>{o.delete(P),i||t.setLightbar(T[0],T[1],T[2],B.slotId).catch(()=>{})},C);o.add(P)}},createActions(m){let f=se(m);return s.add(f),{...f,dispose(){s.delete(f),f.dispose()}}}}},k=M("active");return{hid:t,async connectWebHID(){let u=await t.connect();return p(),u},async reconnectAuthorized(){let u=await t.reconnectAuthorized();return p(),u},attachAudio(u){n=u,p()},getSlots(){return t.getConnectedControllers()},get active(){return k},player(u){return u===void 0||u==="active"?k:M(u)},onCapabilitiesChange(u){return c.add(u),()=>{c.delete(u)}},syncCapabilities:p,dispose(){if(!i){i=!0,g!==null&&(clearInterval(g),g=null),d(),c.clear(),typeof window<"u"&&(a.autoHotplug!==!1&&(window.removeEventListener("gamepadconnected",h),window.removeEventListener("gamepaddisconnected",h)),a.autoEmergencyReset!==!1&&(window.removeEventListener("pagehide",b),window.removeEventListener("beforeunload",b)));for(let u of o)clearTimeout(u);o.clear();for(let u of s)try{u.dispose()}catch{}s.clear();for(let u of r)try{u.stop()}catch{}r.clear(),t.stopGamepadRumble(),t.resetTriggers().catch(()=>{}),t.setLightbar(23,23,23).catch(()=>{}),e&&(a.autoHotplug!==!1&&t.detachHidHotplug(),a.attachKeyboardFallback&&t.detachKeyboardFallback())}}}}var le="http://127.0.0.1:5178",de="ws://127.0.0.1:5178",_=class a{httpBase;wsBase;pcCtx=null;pcSinkId="";pcSinkLabel="PC Default Speakers";pcMasterGain=null;pcAnalysers=[];pcNoiseBuffer=null;dsMode="none";dsCtx=null;dsSinkId="";dsSinkLabel="";dsMaxChannelCount=2;dsActiveChannelCount=2;dsWs=null;dsWorklet=null;dsMerger=null;dsChGains=[];dsAnalysers=[];dsNoiseBuffer=null;pcGainValue=.8;dsSpeakerGainValue=.95;dsHapticGainValue=.95;audioMuted=!1;constructor(e={}){this.httpBase=(e.httpBase||le).replace(/\/+$/,""),this.wsBase=(e.wsBase||de).replace(/\/+$/,"")}setAudioMuted(e){if(this.audioMuted=e,this.pcMasterGain&&this.pcCtx&&this.pcMasterGain.gain.setTargetAtTime(e?0:this.pcGainValue,this.pcCtx.currentTime,.015),this.dsChGains.length>=2&&this.dsCtx){let t=e?0:this.dsSpeakerGainValue;this.dsChGains[0].gain.setTargetAtTime(t,this.dsCtx.currentTime,.015),this.dsChGains[1].gain.setTargetAtTime(t,this.dsCtx.currentTime,.015)}}activeContinuous=new Set;companionToken="";intentionalWsClose=!1;reconnectAttempts=0;reconnectTimer=null;streamStateListeners=new Set;onCompanionStreamState(e){return this.streamStateListeners.add(e),()=>this.streamStateListeners.delete(e)}emitStreamState(e,t){for(let n of this.streamStateListeners)try{n(e,t)}catch{}}static isLoopbackOrigin(){if(typeof window>"u")return!0;let e=window.location.hostname;return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}static async getLoopbackPermissionState(){if(a.isLoopbackOrigin())return"local_exempt";if(typeof navigator>"u"||!navigator.permissions?.query)return"unknown";for(let e of["loopback-network","local-network-access"])try{let t=await navigator.permissions.query({name:e});if(t.state==="granted"||t.state==="prompt"||t.state==="denied")return t.state}catch{}return"unknown"}async loopbackFetch(e,t={}){let n={...t,targetAddressSpace:"loopback"};try{return await fetch(e,n)}catch(i){if(i instanceof TypeError&&!String(i.message).toLowerCase().includes("fetch"))return fetch(e,t);throw i}}static checkBrowserCapabilities(){if(typeof window>"u")return{hasWebAudio:!1,hasSetSinkId:!1,hasAudioWorklet:!1,isSecureContext:!0};let e=window.AudioContext||window.webkitAudioContext;return{hasWebAudio:!!e,hasSetSinkId:!!(e&&"setSinkId"in e.prototype),hasAudioWorklet:!!(e&&"audioWorklet"in e.prototype),isSecureContext:!!window.isSecureContext}}async probeCompanion(e=700){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await this.loopbackFetch(`${this.httpBase}/api/health`,{cache:"no-store",signal:t.signal});if(!i.ok)return{online:!1};let r=await i.json();return{online:!!r.ok,version:r.version,protocolVersion:typeof r.protocolVersion=="number"?r.protocolVersion:1,platform:r.platform}}catch{return{online:!1}}finally{clearTimeout(n)}}async acquireCompanionSession(){let e=await this.loopbackFetch(`${this.httpBase}/api/session`,{method:"POST",headers:{"X-Gamepadly-Client":"web"},cache:"no-store"});if(e.status===404)return this.companionToken="","";if(!e.ok)throw new Error(`Gamepadly Link rejected session request (HTTP ${e.status}).`);let t=await e.json();return this.companionToken=typeof t.token=="string"?t.token:"",this.companionToken}async listCompanionDevices(){let e=await this.loopbackFetch(`${this.httpBase}/api/devices`,{cache:"no-store"});if(!e.ok)throw new Error("Gamepadly Link companion did not respond.");let t=await e.json();return Array.isArray(t.devices)?t.devices:[]}async openWindowsSoundPanelViaCompanion(){try{let e=this.companionToken||await this.acquireCompanionSession(),t={};return e&&(t["X-Gamepadly-Token"]=e),(await this.loopbackFetch(`${this.httpBase}/api/open-sound-panel`,{method:"POST",headers:t})).ok}catch{return!1}}async unlockBrowserDeviceLabels(){if(!navigator.mediaDevices?.getUserMedia)return!1;try{let e=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});for(let t of e.getTracks())t.stop();return!0}catch{return!1}}async listBrowserOutputDevices(){return navigator.mediaDevices?.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audiooutput").map(t=>({deviceId:t.deviceId,label:t.label||(t.deviceId==="default"?"System Default":`Audio Output (${t.deviceId.slice(0,8)})`),isLikelyDualSense:/wireless controller|dualsense|ps5|dsx/i.test(t.label||"")})):[]}async initPcOutput(e="",t="PC Default Speakers"){let n=window.AudioContext||window.webkitAudioContext;this.pcCtx||(this.pcCtx=new n({latencyHint:"interactive"}));let i=this.pcCtx;return e&&typeof i.setSinkId=="function"&&await i.setSinkId(e),this.pcCtx.state==="suspended"&&await this.pcCtx.resume(),this.pcMasterGain||this.buildPcGraph(),this.pcSinkId=e,this.pcSinkLabel=t,{sinkId:this.pcSinkId,sinkLabel:this.pcSinkLabel,sampleRate:this.pcCtx.sampleRate}}buildPcGraph(){let e=this.pcCtx;this.pcMasterGain=e.createGain(),this.pcMasterGain.gain.value=this.audioMuted?0:this.pcGainValue;let t=e.createDynamicsCompressor();t.threshold.value=-4,t.knee.value=8,t.ratio.value=6;let n=e.createChannelSplitter(2),i=e.createAnalyser(),r=e.createAnalyser();i.fftSize=256,r.fftSize=256,i.smoothingTimeConstant=.55,r.smoothingTimeConstant=.55,this.pcMasterGain.connect(t),t.connect(e.destination),t.connect(n),n.connect(i,0),n.connect(r,1),this.pcAnalysers=[i,r],this.pcNoiseBuffer=this.createNoiseBuffer(e)}async openCompanionWebSocket(e){let t=await this.acquireCompanionSession(),n=new URLSearchParams;t&&n.set("token",t),e&&n.set("device",e);let i=n.toString(),r=`${this.wsBase}/ws/haptics${i?`?${i}`:""}`;return new Promise((o,s)=>{let c=new WebSocket(r);c.binaryType="arraybuffer";let l=setTimeout(()=>{c.close(),s(new Error("Gamepadly Link WASAPI handshake timeout."))},5e3);c.onmessage=p=>{if(typeof p.data=="string")try{let d=JSON.parse(p.data);d.type==="ready"?(clearTimeout(l),o({ws:c,ready:d})):d.type==="error"&&(clearTimeout(l),c.close(),s(new Error(d.message||"WASAPI renderer failed to initialize.")))}catch{}},c.onerror=()=>{clearTimeout(l),s(new Error("Failed to connect to Gamepadly Link WebSocket (check LNA loopback permission)."))}})}attachWsReconnectHandler(e,t){e.onclose=()=>{if(this.dsWs!==e)return;if(this.dsWs=null,this.intentionalWsClose||this.dsMode!=="companion"){this.emitStreamState("idle");return}if(this.reconnectAttempts>=3){this.emitStreamState("disconnected","Gamepadly Link connection lost. Click Connect to retry.");return}let n=800*Math.pow(2,this.reconnectAttempts);this.reconnectAttempts++,this.emitStreamState("reconnecting",`Reconnecting to Gamepadly Link (${this.reconnectAttempts}/3)...`),this.reconnectTimer=window.setTimeout(async()=>{if(this.reconnectTimer=null,!(this.intentionalWsClose||this.dsMode!=="companion"))try{let{ws:i}=await this.openCompanionWebSocket(t);this.dsWs=i,this.reconnectAttempts=0,this.attachWsReconnectHandler(i,t),this.emitStreamState("connected","Gamepadly Link reconnected.")}catch{this.reconnectAttempts<3?(this.attachWsReconnectHandler(e,t),e.onclose?.(new CloseEvent("close"))):this.emitStreamState("disconnected","Gamepadly Link offline.")}},n)}}async connectDualSenseCompanion(e="",t="DualSense WASAPI"){let n=window.AudioContext||window.webkitAudioContext;await this.teardownDsOutput(),this.intentionalWsClose=!1,this.reconnectAttempts=0;let{ws:i,ready:r}=await this.openCompanionWebSocket(e);this.dsWs=i,this.attachWsReconnectHandler(i,r.id||e),this.emitStreamState("connected");let o=r.sampleRate||48e3;this.dsCtx=new n({sampleRate:o,latencyHint:"interactive"}),this.dsCtx.state==="suspended"&&await this.dsCtx.resume(),await this.dsCtx.audioWorklet.addModule("/haptic-worklet.js"),this.dsMode="companion",this.dsSinkId=r.id||e,this.dsSinkLabel=r.name||t,this.dsMaxChannelCount=r.channels||4,this.dsActiveChannelCount=Math.min(4,this.dsMaxChannelCount),this.buildDsGraph(!1),this.dsWorklet=new AudioWorkletNode(this.dsCtx,"gamepadly-wasapi-capture",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],channelCount:4,channelCountMode:"explicit",channelInterpretation:"discrete"});let s=this.dsCtx.createGain();return s.gain.value=0,this.dsMerger.connect(this.dsWorklet),this.dsWorklet.connect(s),s.connect(this.dsCtx.destination),this.dsWorklet.port.onmessage=c=>{this.dsWs&&this.dsWs.readyState===WebSocket.OPEN&&this.dsWs.send(c.data)},{mode:"companion",sinkId:this.dsSinkId,sinkLabel:this.dsSinkLabel,sampleRate:this.dsCtx.sampleRate,maxChannelCount:this.dsMaxChannelCount,activeChannelCount:this.dsActiveChannelCount,isQuadraphonicReady:this.dsMaxChannelCount>=4,state:this.dsCtx.state}}async connectDualSenseBrowserSink(e,t){if(!e)throw new Error("DualSense audio output device ID is empty.");let n=window.AudioContext||window.webkitAudioContext;await this.teardownDsOutput();try{this.dsCtx=new n({latencyHint:"interactive",sinkId:e})}catch{this.dsCtx=new n({latencyHint:"interactive"})}let i=this.dsCtx;typeof i.setSinkId=="function"&&i.sinkId!==e&&await i.setSinkId(e),this.dsCtx.state==="suspended"&&await this.dsCtx.resume();let r=this.dsCtx.destination;this.dsMaxChannelCount=r.maxChannelCount;let o=this.dsMaxChannelCount>=4?4:Math.min(2,this.dsMaxChannelCount);return r.channelCountMode="explicit",r.channelInterpretation="discrete",r.channelCount=o,this.dsActiveChannelCount=r.channelCount,this.dsMode="setsinkid",this.dsSinkId=e,this.dsSinkLabel=t,this.buildDsGraph(!0),{mode:"setsinkid",sinkId:this.dsSinkId,sinkLabel:this.dsSinkLabel,sampleRate:this.dsCtx.sampleRate,maxChannelCount:this.dsMaxChannelCount,activeChannelCount:this.dsActiveChannelCount,isQuadraphonicReady:this.dsMaxChannelCount>=4,state:this.dsCtx.state}}buildDsGraph(e){let t=this.dsCtx;this.dsMerger=t.createChannelMerger(4),this.dsChGains=[],this.dsAnalysers=[];for(let n=0;n<4;n++){let i=t.createGain();i.gain.value=n<2?this.dsSpeakerGainValue:this.dsHapticGainValue;let r=i;if(n>=2){let c=t.createBiquadFilter();c.type="highpass",c.frequency.value=20,c.Q.value=.707,i.connect(c),r=c}let o=t.createDynamicsCompressor();o.threshold.value=-3,o.knee.value=6,o.ratio.value=12,o.attack.value=.0015,o.release.value=.05;let s=t.createAnalyser();s.fftSize=256,s.smoothingTimeConstant=.5,r.connect(o),o.connect(s),s.connect(this.dsMerger,0,n),this.dsChGains.push(i),this.dsAnalysers.push(s)}e&&this.dsMerger.connect(t.destination),this.dsNoiseBuffer=this.createNoiseBuffer(t)}async teardownDsOutput(){if(this.intentionalWsClose=!0,this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopAllContinuous(),this.dsWorklet){try{this.dsWorklet.port.onmessage=null,this.dsWorklet.disconnect()}catch{}this.dsWorklet=null}if(this.dsWs){try{this.dsWs.close()}catch{}this.dsWs=null}if(this.dsCtx){try{await this.dsCtx.close()}catch{}this.dsCtx=null}this.dsMerger=null,this.dsChGains=[],this.dsAnalysers=[],this.dsNoiseBuffer=null,this.dsMode="none"}createNoiseBuffer(e){let t=e.sampleRate*2,n=e.createBuffer(1,t,e.sampleRate),i=n.getChannelData(0);for(let r=0;r<t;r++)i[r]=Math.random()*2-1;return n}async resumeAll(){this.pcCtx||await this.initPcOutput("",this.pcSinkLabel),this.pcCtx&&this.pcCtx.state==="suspended"&&await this.pcCtx.resume(),this.dsCtx&&this.dsCtx.state==="suspended"&&await this.dsCtx.resume()}setGains(e){e.pc!==void 0&&(this.pcGainValue=Math.max(0,Math.min(1.4,e.pc)),this.pcMasterGain&&this.pcCtx&&this.pcMasterGain.gain.setTargetAtTime(this.pcGainValue,this.pcCtx.currentTime,.02)),e.dsSpeaker!==void 0&&(this.dsSpeakerGainValue=Math.max(0,Math.min(1.3,e.dsSpeaker)),this.dsChGains.length>=2&&this.dsCtx&&(this.dsChGains[0].gain.setTargetAtTime(this.dsSpeakerGainValue,this.dsCtx.currentTime,.02),this.dsChGains[1].gain.setTargetAtTime(this.dsSpeakerGainValue,this.dsCtx.currentTime,.02))),e.dsHaptic!==void 0&&(this.dsHapticGainValue=Math.max(0,Math.min(1.4,e.dsHaptic)),this.dsChGains.length>=4&&this.dsCtx&&(this.dsChGains[2].gain.setTargetAtTime(this.dsHapticGainValue,this.dsCtx.currentTime,.02),this.dsChGains[3].gain.setTargetAtTime(this.dsHapticGainValue,this.dsCtx.currentTime,.02)))}getWaveforms(){let e=t=>{if(!t)return null;let n=new Float32Array(t.fftSize);return t.getFloatTimeDomainData(n),n};return{pcL:e(this.pcAnalysers[0]),pcR:e(this.pcAnalysers[1]),dsCh0:e(this.dsAnalysers[0]),dsCh1:e(this.dsAnalysers[1]),dsCh2:e(this.dsAnalysers[2]),dsCh3:e(this.dsAnalysers[3])}}getHapticEnergy(){if(this.dsAnalysers.length<4)return{left:0,right:0};let e=t=>{let n=new Float32Array(t.fftSize);t.getFloatTimeDomainData(n);let i=0;for(let r=0;r<n.length;r++)i+=n[r]*n[r];return Math.min(1,Math.sqrt(i/n.length)*3.5)};return{left:e(this.dsAnalysers[2]),right:e(this.dsAnalysers[3])}}stopAllContinuous(){for(let e of Array.from(this.activeContinuous))try{e.stop()}catch{}this.activeContinuous.clear()}routePc(e,t=0,n=1){if(!this.pcCtx||!this.pcMasterGain)return;let i=this.pcCtx.createGain();i.gain.value=n;let r=this.pcCtx.createStereoPanner();r.pan.value=Math.max(-1,Math.min(1,t)),e.connect(i),i.connect(r),r.connect(this.pcMasterGain)}routeDsSpeakerMonoSafe(e,t=.9){if(!this.dsCtx||this.dsChGains.length<2)return;let n=this.dsCtx.createGain();n.gain.value=t,e.connect(n),n.connect(this.dsChGains[0]),n.connect(this.dsChGains[1])}routeDsVcm(e,t=0,n=1){if(!this.dsCtx||this.dsChGains.length<4)return;let i=Math.max(-1,Math.min(1,t)),r=this.dsCtx.createGain(),o=this.dsCtx.createGain();r.gain.value=Math.cos((i+1)*Math.PI/4)*n,o.gain.value=Math.sin((i+1)*Math.PI/4)*n,e.connect(r),e.connect(o),r.connect(this.dsChGains[2]),o.connect(this.dsChGains[3])}playPcTone(e){if(!this.pcCtx)return;let t=this.pcCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.015,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"sine",r.frequency.setValueAtTime(Math.max(20,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&r.frequency.exponentialRampToValueAtTime(Math.max(20,e.endFreqHz),n+i);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity??.45));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.012,i*.2)),o.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),this.routePc(o,e.pan??0,1),r.start(n),r.stop(n+i+.02)}playPcNoiseBurst(e){if(!this.pcCtx||!this.pcNoiseBuffer)return;let t=this.pcCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.02,e.durationMs/1e3),r=t.createBufferSource();r.buffer=this.pcNoiseBuffer;let o=t.createBiquadFilter();o.type=e.filterType||"bandpass",o.Q.value=e.q??2,o.frequency.setValueAtTime(e.freqHz,n),e.endFreqHz&&o.frequency.exponentialRampToValueAtTime(Math.max(30,e.endFreqHz),n+i);let s=t.createGain(),c=Math.max(.001,Math.min(1,e.intensity??.5));s.gain.setValueAtTime(1e-4,n),s.gain.linearRampToValueAtTime(c,n+Math.min(.015,i*.15)),s.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),o.connect(s),this.routePc(s,e.pan??0,1),r.start(n),r.stop(n+i+.03)}playControllerSpeakerTone(e){if(!this.dsCtx||this.dsChGains.length<2){this.playPcTone({...e,intensity:(e.intensity??.5)*.45});return}let t=this.dsCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.015,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"triangle",r.frequency.setValueAtTime(Math.max(60,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&r.frequency.exponentialRampToValueAtTime(Math.max(60,e.endFreqHz),n+i);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity??.75));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.006,i*.18)),o.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),this.routeDsSpeakerMonoSafe(o,.95),r.start(n),r.stop(n+i+.02)}playHapticPulse(e){if(!this.dsCtx||this.dsChGains.length<4)return;let t=this.dsCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.012,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"sine",r.frequency.setValueAtTime(Math.max(22,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&r.frequency.exponentialRampToValueAtTime(Math.max(22,e.endFreqHz),n+i);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.004,i*.2)),o.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),this.routeDsVcm(o,e.pan??0,1),r.start(n),r.stop(n+i+.02)}playHapticSweep(e){if(!this.dsCtx||this.dsChGains.length<4)return;let t=this.dsCtx,n=t.currentTime,i=Math.max(.04,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"sine",r.frequency.setValueAtTime(Math.max(25,e.fromHz),n),r.frequency.exponentialRampToValueAtTime(Math.max(25,e.toHz),n+i);let o=Math.max(-1,Math.min(1,e.fromPan)),s=Math.max(-1,Math.min(1,e.toPan)),c=t.createGain(),l=t.createGain();c.gain.setValueAtTime(Math.cos((o+1)*Math.PI/4)*e.intensity,n),c.gain.linearRampToValueAtTime(Math.cos((s+1)*Math.PI/4)*e.intensity,n+i),l.gain.setValueAtTime(Math.sin((o+1)*Math.PI/4)*e.intensity,n),l.gain.linearRampToValueAtTime(Math.sin((s+1)*Math.PI/4)*e.intensity,n+i),r.connect(c),r.connect(l),c.connect(this.dsChGains[2]),l.connect(this.dsChGains[3]),r.start(n),r.stop(n+i+.02)}createContinuous(e){let t=!1,n=null;if(this.dsCtx&&this.dsChGains.length>=4){let o=this.dsCtx,s=o.createOscillator(),c=o.createBiquadFilter(),l=o.createGain(),p=o.createGain(),d=o.createGain(),h=o.createGain();l.gain.value=1e-4,p.gain.value=.7,d.gain.value=.7,h.gain.value=1e-4;let g={ice:{wave:"triangle",f:240,filtF:310,spk:.25},metal:{wave:"sine",f:150,filtF:180,spk:.35},gravel:{wave:"sawtooth",f:82,filtF:150,spk:.2},grass:{wave:"sine",f:65,filtF:110,spk:.1},water:{wave:"sine",f:48,filtF:85,spk:.18},engine:{wave:"sawtooth",f:42,filtF:160,spk:.05},tension:{wave:"sawtooth",f:78,filtF:210,spk:.4}}[e];s.type=g.wave,s.frequency.value=g.f,c.type="lowpass",c.frequency.value=g.filtF;let w;if(this.dsNoiseBuffer&&(e==="water"||e==="gravel"||e==="ice")){w=o.createBufferSource(),w.buffer=this.dsNoiseBuffer,w.loop=!0;let M=o.createGain();M.gain.value=.45,w.connect(M),M.connect(c),w.start()}s.connect(c),c.connect(l),l.connect(p),l.connect(d),p.connect(this.dsChGains[2]),d.connect(this.dsChGains[3]),l.connect(h),h.connect(this.dsChGains[0]),h.connect(this.dsChGains[1]),h.gain.value=g.spk,s.start(),n={osc:s,noise:w,filter:c,master:l,gL:p,gR:d,spkGain:h}}let i=null;if(this.pcCtx&&this.pcMasterGain&&(e==="engine"||e==="tension"||e==="water")){let o=this.pcCtx,s=o.createOscillator();s.type=e==="water"?"sine":"triangle",s.frequency.value=e==="engine"?75:e==="tension"?210:120;let c=o.createGain();c.gain.value=1e-4;let l=o.createStereoPanner();s.connect(c),c.connect(l),l.connect(this.pcMasterGain),s.start(),i={osc:s,gain:c,panner:l}}let r={update:({intensity:o=0,speed:s=.5,pan:c=0,freqScale:l=1}={})=>{if(t)return;let p=Math.max(1e-4,Math.min(1,o)),d=Math.max(-1,Math.min(1,c));if(n&&this.dsCtx){let h=this.dsCtx.currentTime;n.master.gain.setTargetAtTime(p*.85,h,.025),n.gL.gain.setTargetAtTime(Math.cos((d+1)*Math.PI/4),h,.025),n.gR.gain.setTargetAtTime(Math.sin((d+1)*Math.PI/4),h,.025);let b=e==="tension"?68+s*150:e==="engine"?35+s*95:85+s*140;n.osc.frequency.setTargetAtTime(Math.max(25,b*l),h,.03)}if(i&&this.pcCtx){let h=this.pcCtx.currentTime;i.gain.gain.setTargetAtTime(p*.22,h,.03),i.panner.pan.setTargetAtTime(d*.7,h,.03);let b=e==="tension"?180+s*260:70+s*160;i.osc.frequency.setTargetAtTime(Math.max(30,b*l),h,.03)}},stop:()=>{if(!t){t=!0,this.activeContinuous.delete(r);try{n&&(n.osc.stop(),n.noise?.stop(),n.master.disconnect(),n.spkGain.disconnect()),i&&(i.osc.stop(),i.gain.disconnect())}catch{}}}};return this.activeContinuous.add(r),r}playComboPreset(e,t=0){switch(e){case"ratchet_tick":this.playHapticPulse({pan:t,freqHz:215,endFreqHz:115,durationMs:18,intensity:.52,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:2100,endFreqHz:1150,durationMs:16,intensity:.45,wave:"triangle"});break;case"lock_sweet_spot":this.playHapticPulse({pan:-.45,freqHz:145,endFreqHz:68,durationMs:65,intensity:.95,wave:"sine"}),this.playHapticPulse({pan:.45,freqHz:285,endFreqHz:170,durationMs:48,intensity:.75,wave:"triangle",delayMs:14}),this.playControllerSpeakerTone({freqHz:1480,endFreqHz:860,durationMs:75,intensity:.85,wave:"sine"}),this.playPcTone({freqHz:440,endFreqHz:330,durationMs:110,intensity:.28,pan:t,wave:"sine"});break;case"lock_unlock":this.playHapticSweep({fromPan:-.95,toPan:.95,fromHz:65,toHz:185,durationMs:260,intensity:.95}),this.playControllerSpeakerTone({freqHz:980,endFreqHz:1560,durationMs:120,intensity:.85,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:1560,endFreqHz:2093,durationMs:180,intensity:.8,delayMs:120,wave:"sine"}),this.playPcNoiseBurst({durationMs:520,filterType:"lowpass",freqHz:280,endFreqHz:65,intensity:.85}),this.playPcTone({freqHz:523.25,endFreqHz:783.99,durationMs:360,intensity:.38,delayMs:90,wave:"triangle"});break;case"fish_bite":this.playHapticPulse({pan:t,freqHz:95,endFreqHz:42,durationMs:110,intensity:.95,wave:"sine"}),this.playHapticPulse({pan:-t*.5,freqHz:165,endFreqHz:75,durationMs:75,intensity:.8,delayMs:85}),this.playControllerSpeakerTone({freqHz:1250,endFreqHz:780,durationMs:95,intensity:.85,wave:"sawtooth"}),this.playPcNoiseBurst({durationMs:240,filterType:"bandpass",freqHz:1400,endFreqHz:500,intensity:.6,pan:t});break;case"fish_splash":this.playHapticSweep({fromPan:t,toPan:-t,fromHz:140,toHz:52,durationMs:220,intensity:.85}),this.playPcNoiseBurst({durationMs:420,filterType:"bandpass",freqHz:1800,endFreqHz:420,intensity:.72,pan:t}),this.playControllerSpeakerTone({freqHz:1600,endFreqHz:620,durationMs:110,intensity:.55,wave:"triangle"});break;case"pistol":this.playHapticPulse({pan:.2,freqHz:145,endFreqHz:42,durationMs:80,intensity:1}),this.playHapticPulse({pan:.6,freqHz:260,endFreqHz:135,durationMs:36,intensity:.68,delayMs:55,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:1850,endFreqHz:620,durationMs:48,intensity:.85,delayMs:50,wave:"triangle"}),this.playPcNoiseBurst({durationMs:190,filterType:"lowpass",freqHz:3200,endFreqHz:240,intensity:.75});break;case"shotgun":this.playHapticPulse({pan:0,freqHz:115,endFreqHz:28,durationMs:210,intensity:1}),this.playHapticPulse({pan:-.85,freqHz:210,endFreqHz:105,durationMs:50,intensity:.85,delayMs:260,wave:"sawtooth"}),this.playHapticPulse({pan:.85,freqHz:265,endFreqHz:130,durationMs:50,intensity:.85,delayMs:390,wave:"sawtooth"}),this.playControllerSpeakerTone({freqHz:1100,endFreqHz:520,durationMs:55,intensity:.85,delayMs:260,wave:"sawtooth"}),this.playControllerSpeakerTone({freqHz:1450,endFreqHz:740,durationMs:55,intensity:.85,delayMs:390,wave:"sawtooth"}),this.playPcNoiseBurst({durationMs:420,filterType:"lowpass",freqHz:2800,endFreqHz:110,intensity:.95});break;case"bow_release":this.playHapticPulse({pan:-.35,freqHz:240,endFreqHz:72,durationMs:150,intensity:.95,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:920,endFreqHz:360,durationMs:120,intensity:.85,wave:"triangle"}),this.playPcNoiseBurst({durationMs:210,filterType:"bandpass",freqHz:2200,endFreqHz:600,intensity:.55});break;case"thunder":this.playPcNoiseBurst({durationMs:1650,filterType:"lowpass",freqHz:520,endFreqHz:68,intensity:.95,pan:t}),this.playHapticPulse({pan:t,freqHz:82,endFreqHz:28,durationMs:950,intensity:1,wave:"sawtooth"});break}}async testPcSpeakersLoud(){await this.resumeAll(),this.playPcTone({freqHz:523.25,durationMs:240,intensity:.55,pan:-.85,wave:"sine"}),this.playPcTone({freqHz:659.25,durationMs:260,intensity:.55,pan:.85,delayMs:260,wave:"sine"})}async testDualSenseSpeakerLoud(){if(await this.resumeAll(),!this.dsCtx||this.dsChGains.length<2)throw new Error("DualSense 4-channel audio is not connected yet.");[880,1174.66,1318.51].forEach((t,n)=>{this.playControllerSpeakerTone({freqHz:t,durationMs:200,intensity:.95,delayMs:n*210,wave:"triangle"})})}async testDualSenseVcmLoud(){if(await this.resumeAll(),!this.dsCtx||this.dsChGains.length<4)throw new Error("DualSense 4-channel audio is not connected yet.");this.playHapticPulse({pan:-.95,freqHz:55,endFreqHz:180,durationMs:520,intensity:.95}),this.playHapticPulse({pan:.95,freqHz:180,endFreqHz:55,durationMs:520,intensity:.95,delayMs:560})}async runThreeLayerCalibration(e){await this.resumeAll(),e(1),this.playPcTone({freqHz:523.25,durationMs:320,intensity:.5,pan:-.9}),this.playPcTone({freqHz:659.25,durationMs:320,intensity:.5,pan:.9,delayMs:340}),setTimeout(()=>{e(2),this.playControllerSpeakerTone({freqHz:880,endFreqHz:1174.66,durationMs:480,intensity:.95,wave:"triangle"})},760),setTimeout(()=>{e(3),this.playHapticPulse({pan:-1,freqHz:45,endFreqHz:210,durationMs:650,intensity:.95})},1350),setTimeout(()=>{e(4),this.playHapticPulse({pan:1,freqHz:210,endFreqHz:45,durationMs:650,intensity:.95})},2100),setTimeout(()=>{e(5),this.playHapticSweep({fromPan:-1,toPan:1,fromHz:110,toHz:145,durationMs:850,intensity:.95}),this.playPcTone({freqHz:392,endFreqHz:523.25,durationMs:820,intensity:.35,wave:"triangle"})},2850),setTimeout(()=>e(6),3800)}};function Ae(a){return new _(a)}var ue={platformer:{name:"Platformer (WASD / Arrows + Space Jump)",keys:{left:"ArrowLeft",right:"ArrowRight",up:"ArrowUp",down:"ArrowDown","lx-":"ArrowLeft","lx+":"ArrowRight","ly-":"ArrowUp","ly+":"ArrowDown",cross:{code:"Space",hapticOnPress:"click"},square:{code:"KeyZ",hapticOnPress:"recoil",hapticPan:.4},circle:{code:"KeyX",hapticOnPress:"click"},r2:{code:"ShiftLeft",hapticOnPress:"boost",hapticPan:.6},options:"Escape"},triggers:{right:"soft_wall"}},"arcade-4way":{name:"Arcade 4-Way (Grid / Puzzle / Snake / Tetris)",keys:{left:{code:"ArrowLeft",repeatMs:120,hapticOnPress:"ratchet",hapticPan:-.5},right:{code:"ArrowRight",repeatMs:120,hapticOnPress:"ratchet",hapticPan:.5},up:{code:"ArrowUp",repeatMs:120,hapticOnPress:"ratchet"},down:{code:"ArrowDown",repeatMs:90,hapticOnPress:"ratchet"},"lx-":{code:"ArrowLeft",repeatMs:140,hapticOnPress:"ratchet",hapticPan:-.5},"lx+":{code:"ArrowRight",repeatMs:140,hapticOnPress:"ratchet",hapticPan:.5},"ly-":{code:"ArrowUp",repeatMs:140,hapticOnPress:"ratchet"},"ly+":{code:"ArrowDown",repeatMs:100,hapticOnPress:"ratchet"},cross:{code:"Space",hapticOnPress:"click"},circle:"Escape",options:"Enter"}},racing:{name:"Racing (Steer + R2 Gas / L2 ABS Brake)",keys:{left:"ArrowLeft",right:"ArrowRight","lx-":{code:"ArrowLeft",threshold:.25},"lx+":{code:"ArrowRight",threshold:.25},r2:{code:"ArrowUp",threshold:.2},l2:{code:"ArrowDown",threshold:.2},cross:{code:"Space",hapticOnPress:"boost"},square:{code:"ShiftLeft",hapticOnPress:"ratchet"},options:"Escape"},triggers:{left:"abs",right:"bow"}},"twin-stick":{name:"Twin-Stick Shooter (Left Stick Move + Right Stick Aim + R2 Fire)",keys:{"lx-":"KeyA","lx+":"KeyD","ly-":"KeyW","ly+":"KeyS",left:"KeyA",right:"KeyD",up:"KeyW",down:"KeyS",cross:{code:"Space",hapticOnPress:"click"},square:{code:"KeyR",hapticOnPress:"ratchet"},options:"Escape"},pointer:{stick:"right",speedPxPerSec:720,deadzone:.14,clickButton:"r2",secondaryClickButton:"l2",hapticOnClick:"recoil"},triggers:{left:"precision_damp",right:"weapon"}}};var Pe={Space:{key:" ",keyCode:32},Enter:{key:"Enter",keyCode:13},Escape:{key:"Escape",keyCode:27},Tab:{key:"Tab",keyCode:9},Backspace:{key:"Backspace",keyCode:8},ArrowLeft:{key:"ArrowLeft",keyCode:37},ArrowUp:{key:"ArrowUp",keyCode:38},ArrowRight:{key:"ArrowRight",keyCode:39},ArrowDown:{key:"ArrowDown",keyCode:40},ShiftLeft:{key:"Shift",keyCode:16},ShiftRight:{key:"Shift",keyCode:16},ControlLeft:{key:"Control",keyCode:17},AltLeft:{key:"Alt",keyCode:18}};function Ie(a){let e=Pe[a.code];if(e)return{code:a.code,key:a.key??e.key,keyCode:a.keyCode??e.keyCode};if(/^Key[A-Z]$/.test(a.code)){let t=a.code.slice(3);return{code:a.code,key:a.key??t.toLowerCase(),keyCode:a.keyCode??t.charCodeAt(0)}}if(/^Digit[0-9]$/.test(a.code)){let t=a.code.slice(5);return{code:a.code,key:a.key??t,keyCode:a.keyCode??t.charCodeAt(0)}}return{code:a.code,key:a.key??a.code,keyCode:a.keyCode??0}}function Re(a){return(Array.isArray(a)?a:[a]).map(t=>typeof t=="string"?{code:t}:t)}function pe(a,e){return a==="l2"?e.l2:a==="r2"?e.r2:a==="lx+"?Math.max(0,e.lx):a==="lx-"?Math.max(0,-e.lx):a==="ly+"?Math.max(0,e.ly):a==="ly-"?Math.max(0,-e.ly):a==="rx+"?Math.max(0,e.rx):a==="rx-"?Math.max(0,-e.rx):a==="ry+"?Math.max(0,e.ry):a==="ry-"?Math.max(0,-e.ry):e.buttons[a]?1:0}function Se(a){if(a)return typeof a=="string"?O[a]:a}function Be(a){return"active"in a&&"getSlots"in a}function Z(a,e,t,n=!1){if(typeof KeyboardEvent<"u"){let i=new KeyboardEvent(e,{key:t.key,code:t.code,bubbles:!0,cancelable:!0,repeat:n});try{Object.defineProperty(i,"keyCode",{value:t.keyCode}),Object.defineProperty(i,"which",{value:t.keyCode})}catch{}a.dispatchEvent(i);return}if(typeof Event<"u"){let i=new Event(e,{bubbles:!0,cancelable:!0});i.key=t.key,i.code=t.code,i.keyCode=t.keyCode,i.which=t.keyCode,i.repeat=n,a.dispatchEvent(i)}}function V(a,e,t,n,i,r){let o={bubbles:!0,cancelable:!0,clientX:t,clientY:n,button:i,buttons:r,pointerId:1,pointerType:"mouse",isPrimary:!0};typeof PointerEvent<"u"&&a.dispatchEvent(new PointerEvent(e,o));let s=e.replace("pointer","mouse");typeof MouseEvent<"u"&&a.dispatchEvent(new MouseEvent(s,o))}function rt(a){let e=Be(a.player)?a.player:null,t=e?e.active:a.player,n=a.keyTarget??(typeof window<"u"?window:void 0),i=a.pointerTarget!==void 0?a.pointerTarget:typeof document<"u"?document.body:null,r=typeof a.profile=="string"?ue[a.profile]:a.profile,o=!1,s=0,c=0,l=new Map,p=new Map,d={x:0,y:0,down:!1,secondaryDown:!1,visible:!1},h=!1,b=(y,x)=>{typeof y=="string"?t.haptics.playPreset(y,x):t.haptics.pulse({...y,pan:x?.pan??y.pan,intensity:(x?.intensity??1)*y.intensity})},g=()=>{let y=Se(r.triggers?.left),x=Se(r.triggers?.right);y&&x?t.triggers.setBoth(y,x):y?t.triggers.setLeft(y):x?t.triggers.setRight(x):t.triggers.reset()},w=e?e.onCapabilitiesChange(()=>{o&&g()}):null,M=()=>{if(n)for(let{meta:y}of l.values())Z(n,"keyup",y,!1);if(l.clear(),p.clear(),i&&(d.down||d.secondaryDown)){let y=i.getBoundingClientRect?.()??{left:0,top:0};d.down&&V(i,"pointerup",y.left+d.x,y.top+d.y,0,0),d.secondaryDown&&V(i,"pointerup",y.left+d.x,y.top+d.y,2,0)}d.down=!1,d.secondaryDown=!1},k=(y,x=typeof performance<"u"?performance.now():Date.now())=>{let v=y!==void 0?Math.max(0,Math.min(.1,y)):c>0?Math.max(0,Math.min(.1,(x-c)/1e3)):.016666666666666666;c=x;let H=t.input.getState();if(!H.connected||H.source==="keyboard_mouse"){(l.size>0||d.down||d.secondaryDown)&&M();return}let m=new Map;for(let[f,S]of Object.entries(r.keys)){if(!S)continue;let C=f,T=pe(C,H),B=Re(S);for(let P=0;P<B.length;P++){let A=B[P],D=A.threshold??.45,q=T>=D,K=`${C}:${A.code}:${P}`,$=p.get(K)??!1;if(p.set(K,q),q){let z=Ie(A);m.has(z.code)||m.set(z.code,{meta:z,repeatMs:A.repeatMs,repeatDelayMs:A.repeatDelayMs??220}),!$&&A.hapticOnPress&&b(A.hapticOnPress,{pan:A.hapticPan})}}}if(n){for(let[f,S]of l.entries())m.has(f)||(Z(n,"keyup",S.meta,!1),l.delete(f));for(let[f,S]of m.entries()){let C=l.get(f);C?S.repeatMs&&x>=C.nextRepeatAt&&(Z(n,"keydown",S.meta,!0),C.nextRepeatAt=x+S.repeatMs):(Z(n,"keydown",S.meta,!1),l.set(f,{meta:S.meta,nextRepeatAt:S.repeatMs?x+S.repeatDelayMs:Number.POSITIVE_INFINITY}))}}if(r.pointer&&i){let f=r.pointer,S=i.getBoundingClientRect?.()??{left:0,top:0,width:800,height:600},C=Math.max(1,S.width),T=Math.max(1,S.height);h||(d.x=C/2,d.y=T/2,h=!0);let B=f.deadzone??.14,P=E(f.stick==="left"?H.lx:H.rx,B),A=E(f.stick==="left"?H.ly:H.ry,B),D=f.speedPxPerSec??680,q=P!==0||A!==0;q&&(d.x=Math.max(0,Math.min(C,d.x+P*D*v)),d.y=Math.max(0,Math.min(T,d.y+A*D*v)),d.visible=!0);let K=f.clickButton??"r2",$=f.secondaryClickButton??"l2",z=pe(K,H)>=.45,j=pe($,H)>=.45,X=(z?1:0)|(j?2:0),Y=S.left+d.x,Q=S.top+d.y;q&&V(i,"pointermove",Y,Q,-1,X),z!==d.down&&(d.down=z,d.visible=!0,V(i,z?"pointerdown":"pointerup",Y,Q,0,X),z&&f.hapticOnClick&&b(f.hapticOnClick)),j!==d.secondaryDown&&(d.secondaryDown=j,d.visible=!0,V(i,j?"pointerdown":"pointerup",Y,Q,2,X)),a.onCursorUpdate?.({...d})}},u=y=>{o&&(k(void 0,y),s=requestAnimationFrame(u))};return{start(){o||(o=!0,c=0,g(),a.autoRaf!==!1&&typeof requestAnimationFrame<"u"&&(s=requestAnimationFrame(u)))},stop(){o&&(o=!1,s&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(s),s=0,M())},tick:k,setProfile(y){M(),r=typeof y=="string"?ue[y]:y,o&&g()},getCursor(){return{...d}},triggerHaptic:b,dispose(){this.stop(),w?.(),t.triggers.reset()}}}function ot(){let a=new Set,e=!1,t=n=>{if(e){try{n()}catch{}return()=>{}}return a.add(n),()=>{if(a.delete(n))try{n()}catch{}}};return{add:t,on(n,i,r,o){return n.addEventListener(i,r,o),t(()=>n.removeEventListener(i,r,o))},timeout(n,i){let r=setTimeout(()=>{a.delete(o),e||n()},i),o=()=>clearTimeout(r);return a.add(o),r},interval(n,i){let r=setInterval(()=>{e||n()},i);return a.add(()=>clearInterval(r)),r},dispose(){if(e)return;e=!0;let n=Array.from(a).reverse();a.clear();for(let i of n)try{i()}catch{}}}}function st(a,e={}){let t=e.maxDpr??2,n=e.minWidth??320,i=e.minHeight??240,r=document.createElement("canvas");r.style.width="100%",r.style.height="100%",r.style.display="block",r.style.touchAction="none",e.cursor&&(r.style.cursor=e.cursor),a.innerHTML="",a.appendChild(r);let o=r.getContext("2d"),s=n,c=i,l=1,p=()=>{let b=a.getBoundingClientRect(),g=typeof window<"u"&&window.devicePixelRatio||1;l=Math.max(1,Math.min(t,g)),s=Math.max(n,Math.floor(b.width||n)),c=Math.max(i,Math.floor(b.height||i)),r.width=Math.floor(s*l),r.height=Math.floor(c*l),o.setTransform(l,0,0,l,0,0),e.onResize?.(s,c,l)};p();let d=null;typeof ResizeObserver<"u"&&(d=new ResizeObserver(()=>p()),d.observe(a));let h=()=>p();return typeof window<"u"&&window.addEventListener("resize",h),{canvas:r,ctx:o,get width(){return s},get height(){return c},get dpr(){return l},resize:p,dispose(){d?.disconnect(),d=null,typeof window<"u"&&window.removeEventListener("resize",h),r.parentElement===a&&a.removeChild(r)}}}function ct(a){let e=a.maxDelta??.05,t=a.fixedStep,n=a.autoPauseOnHidden!==!1,i=!1,r=!1,o=0,s=0,c=0,l=h=>{if(r){s=h;return}s===0&&(s=h);let b=Math.max(0,(h-s)/1e3);s=h;let g=Math.min(e,b);if(t&&t>0){c+=g;let w=0;for(;c>=t&&w<8;)a.onUpdate(t,h),c-=t,w++;a.onRender?.(c/t,h)}else a.onUpdate(g,h),a.onRender?.(1,h)},p=h=>{i&&(l(h),o=requestAnimationFrame(p))},d=()=>{!n||typeof document>"u"||document.hidden&&(s=0,c=0)};return n&&typeof document<"u"&&document.addEventListener("visibilitychange",d),{start(){i||(i=!0,s=0,c=0,typeof requestAnimationFrame<"u"&&(o=requestAnimationFrame(p)))},stop(){i&&(i=!1,o&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(o),o=0)},pause(){r=!0,s=0},resume(){r=!1,s=0},isPaused(){return r},step:l,dispose(){this.stop(),n&&typeof document<"u"&&document.removeEventListener("visibilitychange",d)}}}export{ue as BUILTIN_BRIDGE_PROFILES,le as COMPANION_HTTP_BASE,de as COMPANION_WS_BASE,G as ControllerManager,G as DualSenseControllerManager,ie as TACTILE_PRESETS,O as TRIGGER_PRESETS,_ as ThreeLayerAudioEngine,E as applyDeadzone,W as buildSwitchHdFromPulse,we as crc32WithSeed,se as createActionTracker,st as createCanvasStage,ot as createDisposables,F as createEmptyInput,ct as createGameLoop,Te as createGamepadly,rt as createKeyMouseBridge,Ae as createLinkAudio,N as encodeSwitchHdRumbleSide,R as encodeTriggerEffect,ne as identifyGamepadFromId,U as routeHapticPulse,ae as routeHapticSweep,oe as routeTactilePreset};
1
+ var fe=[3302,3570],J=1406,ee=[8201],q=new Uint8Array([0,1,64,64]);function me(a){if(!Number.isFinite(a)||a<=.01)return 0;let e=Math.min(.85,Math.max(0,a));return e>=.23?Math.min(100,Math.round(Math.log2(e*8.7)*32)):e>=.12?Math.round(Math.log2(e*17)*16):Math.max(1,Math.round(e/.12*16))}function U(a){if(!a||a.highAmp<=.01&&a.lowAmp<=.01)return q.slice();let e=Math.max(81.75,Math.min(1252.6,Number.isFinite(a.highFreqHz)?a.highFreqHz:320)),t=Math.max(40.88,Math.min(626.3,Number.isFinite(a.lowFreqHz)?a.lowFreqHz:160)),n=Math.round(Math.log2(e/10)*32),i=Math.round(Math.log2(t/10)*32),r=Math.max(0,Math.min(508,(n-96)*4)),o=Math.max(1,Math.min(127,i-64)),s=me(a.highAmp),c=me(a.lowAmp),l=Math.min(200,s*2),u=(c&1)!==0?128:0,d=Math.min(114,(c>>1)+64);return new Uint8Array([r&255,l+(r>>8&1)&255,(o|u)&255,d&255])}function F(a,e=.06){let t=Math.abs(a);if(t<=e)return 0;let n=(t-e)/(1-e);return Math.sign(a)*Math.max(0,Math.min(1,n))}function xe(a){return(a.match(/vendor:\s*([0-9a-f]{4})/)??a.match(/^([0-9a-f]{1,4})-[0-9a-f]{1,4}-/))?.[1]?.padStart(4,"0")}function Ce(a){return(a.match(/product:\s*([0-9a-f]{4})/)??a.match(/^[0-9a-f]{1,4}-([0-9a-f]{1,4})-/))?.[1]?.padStart(4,"0")}function He(a){let e=xe(a);if(e==="054c")return"sony";if(e==="045e")return"xbox";if(e==="057e")return"nintendo";if(!e){if(/xbox|xinput|microsoft/.test(a))return"xbox";if(/dualsense|dualshock|wireless controller/.test(a))return"sony";if(/nintendo|pro controller|joy-con|switch/.test(a))return"nintendo"}}function ne(a){let e=(a||"").toLowerCase(),t=xe(e),n=Ce(e),i=t?Number.parseInt(t,16):void 0,r=n?Number.parseInt(n,16):void 0,o=He(e);return o==="sony"?/0df2|edge/.test(e)?{brand:"sony",model:"dualsense_edge",displayName:"DualSense Edge",rawId:a,vendorId:1356,productId:r??3570}:/0ce6|dualsense/.test(e)?{brand:"sony",model:"dualsense",displayName:"PlayStation DualSense",rawId:a,vendorId:1356,productId:r??3302}:/05c4|09cc|dualshock/.test(e)?{brand:"sony",model:"dualshock4",displayName:"DualShock 4",rawId:a,vendorId:1356,productId:r}:{brand:"sony",model:"dualsense",displayName:"PlayStation Controller",rawId:a,vendorId:1356,productId:r}:o==="xbox"?/0b12|0b13|0b20|0b21|0b22|series/.test(e)?{brand:"xbox",model:"xbox_series",displayName:"Xbox Wireless Controller",rawId:a,vendorId:1118,productId:r}:/028e|360/.test(e)?{brand:"xbox",model:"xbox_360",displayName:"Xbox 360 Controller",rawId:a,vendorId:1118,productId:r}:{brand:"xbox",model:"xbox_series",displayName:"Xbox Controller",rawId:a,vendorId:1118,productId:r}:o==="nintendo"?/2069|pro 2|switch 2/.test(e)?{brand:"nintendo",model:"switch2_pro",displayName:"Nintendo Switch 2 Pro Controller",rawId:a,vendorId:1406,productId:r??8297}:/joy-con|2006|2007/.test(e)?{brand:"nintendo",model:"joycon",displayName:"Nintendo Joy-Con",rawId:a,vendorId:1406,productId:r}:{brand:"nintendo",model:"switch_pro",displayName:"Nintendo Switch Pro Controller",rawId:a,vendorId:1406,productId:r??8201}:a?{brand:"generic",model:"generic",displayName:a.split("(")[0].trim()||a,rawId:a,vendorId:i,productId:r}:{brand:"none",model:"none",displayName:"No Controller Detected",rawId:""}}var te=(()=>{let a=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;a[e]=t>>>0}return a})();function Se(a,e,t){let n=4294967295;n=te[(n^a)&255]^n>>>8,n=te[(n^e)&255]^n>>>8;for(let i=0;i<t.length;i++)n=te[(n^t[i])&255]^n>>>8;return(n^4294967295)>>>0}function z(a){let e=new Uint8Array(11);if(a.type==="off")return e[0]=5,e;if(a.type==="feedback"||a.type==="slope"){e[0]=33;let s=new Array(10).fill(0);if(a.type==="feedback"){let u=Math.max(0,Math.min(9,Math.round(a.startZone))),d=Math.max(1,Math.min(8,Math.round(a.strength)));for(let h=u;h<10;h++)s[h]=d}else{let u=Math.max(0,Math.min(8,Math.round(a.startZone))),d=Math.max(u+1,Math.min(9,Math.round(a.endZone)));for(let h=u;h<=d;h++){let w=(h-u)/(d-u);s[h]=Math.max(1,Math.min(8,Math.round(a.startStrength+w*(a.endStrength-a.startStrength))))}}let c=0,l=0;for(let u=0;u<10;u++){let d=s[u];d>0&&(c|=1<<u,l|=(d-1&7)<<3*u)}return e[1]=c&255,e[2]=c>>8&255,e[3]=l&255,e[4]=l>>8&255,e[5]=l>>16&255,e[6]=l>>24&255,e}if(a.type==="weapon"){let s=Math.max(2,Math.min(7,Math.round(a.startZone))),c=Math.max(s+1,Math.min(8,Math.round(a.endZone))),l=Math.max(1,Math.min(8,Math.round(a.strength))),u=1<<s|1<<c;return e[0]=37,e[1]=u&255,e[2]=u>>8&255,e[3]=l-1&7,e}let t=Math.max(0,Math.min(9,Math.round(a.startZone))),n=Math.max(1,Math.min(8,Math.round(a.amplitude))),i=Math.max(1,Math.min(255,Math.round(a.frequencyHz))),r=0,o=0;for(let s=t;s<10;s++)r|=1<<s,o|=(n-1&7)<<3*s;return e[0]=38,e[1]=r&255,e[2]=r>>8&255,e[3]=o&255,e[4]=o>>8&255,e[5]=o>>16&255,e[6]=o>>24&255,e[9]=i,e}function N(){return{connected:!1,source:"none",deviceName:"",isDualSense:!1,identity:{brand:"none",model:"none",displayName:"No Controller Detected",rawId:"",transport:"disconnected",source:"none"},lx:0,ly:0,rx:0,ry:0,l2:0,r2:0,buttons:{cross:!1,circle:!1,square:!1,triangle:!1,l1:!1,r1:!1,l2Btn:!1,r2Btn:!1,l3:!1,r3:!1,up:!1,down:!1,left:!1,right:!1,create:!1,options:!1,ps:!1,touchpadClick:!1,mute:!1,fnL:!1,fnR:!1,paddleL:!1,paddleR:!1},touch:{active:!1,x:.5,y:.5},touch2:{active:!1,x:.5,y:.5},gyro:{x:0,y:0,z:0},accel:{x:0,y:0,z:0},battery:{percent:0,charging:!1,full:!1,known:!1},observedReportHz:null}}function ye(){let a=()=>({center:2048,minDelta:1500,maxDelta:1500});return{lx:a(),ly:a(),rx:a(),ry:a()}}var ge=[4,10,21,27],be=[1,3,7,15];function _(a){return new Promise(e=>setTimeout(e,a))}function we(a=0){return{speakerVolume:100,headphoneVolume:100,audioRoute:"speaker",speakerPreamp:7,lightbar:[23,23,23],playerLeds:ge[a%ge.length],muteLed:"off",leftTrigger:z({type:"off"}),rightTrigger:z({type:"off"}),legacyRumbleActive:!1,legacyLeft:0,legacyRight:0}}var O=class a{hidSessions=new Map;nextHidSeq=1;activeSlotId=null;hidDisconnectAttached=!1;hidConnectAttached=!1;listeners=new Set;gamepadInputs=new Map;gamepadLastActivity=new Map;gamepadPrevBtnMask=new Map;fallbackInput=N();keysDown=new Set;kbmAttached=!1;boundConnect=e=>{this.handleConnect(e)};boundDisconnect=e=>this.handleDisconnect(e);boundKeyDown=e=>{this.keysDown.add(e.code)};boundKeyUp=e=>{this.keysDown.delete(e.code)};boundWindowBlur=()=>{this.keysDown.clear()};get device(){return this.getActiveHidSession()?.device??null}get transport(){return this.getActiveHidSession()?.transport??"disconnected"}get firmwareInfo(){return this.getActiveHidSession()?.firmwareInfo}get hidDeviceCount(){return this.hidSessions.size}static isWebHIDSupported(){return typeof navigator<"u"&&"hid"in navigator}static isGamepadSupported(){return typeof navigator<"u"&&typeof navigator.getGamepads=="function"}isSupportedHidDevice(e){return e.vendorId===1356&&fe.includes(e.productId)||e.vendorId===J&&ee.includes(e.productId)}attachHidHotplug(){this.hidConnectAttached||!a.isWebHIDSupported()||(navigator.hid.addEventListener("connect",this.boundConnect),this.hidConnectAttached=!0)}detachHidHotplug(){!this.hidConnectAttached||!a.isWebHIDSupported()||(navigator.hid.removeEventListener("connect",this.boundConnect),this.hidConnectAttached=!1)}async handleConnect(e){if(this.isSupportedHidDevice(e.device))try{await this.attachDevice(e.device)}catch{}}attachKeyboardFallback(){this.kbmAttached||typeof window>"u"||(window.addEventListener("keydown",this.boundKeyDown),window.addEventListener("keyup",this.boundKeyUp),window.addEventListener("blur",this.boundWindowBlur),this.kbmAttached=!0)}detachKeyboardFallback(){!this.kbmAttached||typeof window>"u"||(window.removeEventListener("keydown",this.boundKeyDown),window.removeEventListener("keyup",this.boundKeyUp),window.removeEventListener("blur",this.boundWindowBlur),this.keysDown.clear(),this.kbmAttached=!1)}onStatusChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){for(let t of this.listeners)try{t(e)}catch(n){console.error("[core-hid] listener error:",n)}}getAllRawGamepads(){if(!a.isGamepadSupported())return[];let e=navigator.getGamepads(),t=[];for(let n of e)n&&n.connected&&t.push(n);return t}pollGamepadActivity(e){let t=0,n=Math.min(20,e.buttons.length);for(let r=0;r<n;r++)e.buttons[r]?.pressed&&(t|=1<<r);let i=this.gamepadPrevBtnMask.get(e.index)??0;if(this.gamepadPrevBtnMask.set(e.index,t),(t&~i)!==0){let r=performance.now();return this.gamepadLastActivity.set(e.index,r),r}return this.gamepadLastActivity.get(e.index)??0}getConnectedControllers(){let e=[],t=0,n=0,i=0;for(let s of this.hidSessions.values())s.device.opened&&(s.input.identity.model==="dualsense_edge"?t++:s.input.identity.model==="switch_pro"?i++:n++,e.push({id:s.id,playerNumber:e.length+1,source:"webhid",identity:{...s.input.identity},battery:{...s.input.battery},observedReportHz:s.input.observedReportHz,lastActivityAt:s.lastActivityAt}));let r=this.getAllRawGamepads(),o=new Set;for(let s of r){o.add(s.index);let c=ne(s.id||"");if(c.model==="dualsense_edge"&&t>0){t--;continue}if(c.model==="dualsense"&&n>0){n--;continue}if(c.model==="switch_pro"&&i>0){i--;continue}let l=this.pollGamepadActivity(s);e.push({id:`gp-${s.index}`,playerNumber:e.length+1,source:"gamepad",identity:{...c,transport:"unknown",source:"gamepad"},battery:{percent:0,charging:!1,full:!1,known:!1},observedReportHz:null,lastActivityAt:l})}for(let s of this.gamepadPrevBtnMask.keys())o.has(s)||(this.gamepadPrevBtnMask.delete(s),this.gamepadLastActivity.delete(s));return e.length===0?this.activeSlotId=null:(!this.activeSlotId||!e.some(s=>s.id===this.activeSlotId))&&(this.activeSlotId=e[0].id),e}getActiveSlotId(){return this.getConnectedControllers(),this.activeSlotId}setActiveSlot(e){return this.getConnectedControllers().some(n=>n.id===e)?(this.activeSlotId!==e&&(this.activeSlotId=e,this.emit({type:"slots_changed",slotId:e})),!0):!1}getHidSessionForSlot(e){if(e!==void 0){let r=this.hidSessions.get(e);return r&&r.device.opened?r:null}let t=this.getConnectedControllers(),n=this.activeSlotId??t[0]?.id??null;if(!n)return null;let i=this.hidSessions.get(n);return i&&i.device.opened?i:null}getActiveHidSession(){return this.getHidSessionForSlot()}getGamepadForSlot(e){if(!a.isGamepadSupported())return null;if(e!==void 0){if(!e.startsWith("gp-"))return null;let i=Number(e.slice(3)),r=navigator.getGamepads()[i];return r&&r.connected?r:null}let t=this.getConnectedControllers(),n=this.activeSlotId??t[0]?.id??null;if(n&&n.startsWith("gp-")){let i=Number(n.slice(3)),r=navigator.getGamepads()[i];if(r&&r.connected)return r}if(n&&n.startsWith("hid-"))return null;for(let i of navigator.getGamepads())if(i&&i.connected)return i;return null}getActiveGamepad(){return this.getGamepadForSlot()}getGamepadActuatorEffects(e){let n=this.getGamepadForSlot(e)?.vibrationActuator;return n?Array.isArray(n.effects)&&n.effects.length>0?n.effects:typeof n.playEffect=="function"?["dual-rumble"]:[]:[]}hasTriggerRumbleSupport(e){return this.getGamepadActuatorEffects(e).includes("trigger-rumble")}hasDualRumbleSupport(e){return this.getGamepadActuatorEffects(e).includes("dual-rumble")||!!this.getGamepadForSlot(e)?.vibrationActuator?.playEffect}async connect(){if(!a.isWebHIDSupported())throw new Error("WebHID requires a Chromium browser (Chrome or Edge on desktop).");let e=await navigator.hid.requestDevice({filters:[...fe.map(n=>({vendorId:1356,productId:n})),...ee.map(n=>({vendorId:J,productId:n}))]});if(!e.length)return!1;let t=null;for(let n of e)t=await this.attachDevice(n);return t&&(this.activeSlotId=t,this.emit({type:"slots_changed",slotId:t})),!!t}async reconnectAuthorized(){if(!a.isWebHIDSupported())return!1;let t=(await navigator.hid.getDevices()).filter(i=>this.isSupportedHidDevice(i));if(!t.length)return!1;let n=!1;for(let i of t)try{await this.attachDevice(i),n=!0}catch{}return n}async readFirmwareInfoSafe(e){try{let t=await e.receiveFeatureReport(32);if(t.byteLength<44)return;let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=n[0]===32?1:0,r=(d,h)=>{let w="";for(let y=d;y<d+h&&y<n.length;y++){let g=n[y];g>=32&&g<=126&&(w+=String.fromCharCode(g))}return w.trim()},o=r(i+0,11),s=r(i+11,8),c=new DataView(t.buffer,t.byteOffset+i),l=c.byteLength>=28?c.getUint32(24,!0):0,u=c.byteLength>=32?c.getUint32(28,!0):0;return!o&&!l?void 0:{buildDate:o||"Unknown",buildTime:s||"",hwInfoHex:`0x${l.toString(16).padStart(8,"0")}`,fwVersionHex:`0x${u.toString(16).padStart(8,"0")}`}}catch{return}}async attachDevice(e){for(let y of this.hidSessions.values())if(y.device===e&&y.device.opened)return y.id;if(e.opened||await e.open(),e.vendorId===J&&ee.includes(e.productId))return this.attachSwitchProDevice(e);let n=!1,i=!1,r=47,o=77;for(let y of e.collections||[])for(let g of y.outputReports||[]){let v=Math.ceil((g.items||[]).reduce((T,f)=>T+(f.reportSize||0)*(f.reportCount||0),0)/8);g.reportId===2&&(n=!0,v>=47&&(r=v)),g.reportId===49&&(i=!0,v>=77&&(o=v))}let s=n?"usb":i?"bluetooth":"usb",c=e.productId===3570,l=await this.readFirmwareInfoSafe(e),u=`hid-${this.nextHidSeq++}`,d=c?"DualSense Edge":"PlayStation DualSense",h=N();h.connected=!0,h.source="webhid",h.isDualSense=!0,h.deviceName=e.productName||d,h.identity={brand:"sony",model:c?"dualsense_edge":"dualsense",displayName:d,rawId:e.productName||d,vendorId:e.vendorId,productId:e.productId,transport:s,source:"webhid",firmwareInfo:l};let w={id:u,kind:"dualsense",device:e,transport:s,firmwareInfo:l,usbPayloadLength:r,btPayloadLength:o,btSeq:0,switchSubcmdLength:48,switchRumbleLength:9,switchUsb80Length:1,switchPacketNum:0,switchCal:ye(),switchRumbleTimer:null,switchSeqTimers:[],reportTimes:[],input:h,outState:we(this.hidSessions.size),legacyTimer:null,lastActivityAt:performance.now(),prevBtnMask:0,boundInputReport:y=>this.handleInputReport(w,y)};return this.hidSessions.set(u,w),this.activeSlotId||(this.activeSlotId=u),this.getConnectedControllers(),e.addEventListener("inputreport",w.boundInputReport),!this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.addEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!0),await this.flushSessionOutput(w,{includeAudioConfig:!0,includeTriggers:!0,includeLeds:!0}),this.emit({type:"connected",slotId:u,deviceName:h.deviceName,productId:e.productId,transport:s,firmwareInfo:l}),u}async attachSwitchProDevice(e){let t=!1,n=48,i=9,r=1;for(let h of e.collections||[])for(let w of h.outputReports||[]){let y=Math.ceil((w.items||[]).reduce((g,v)=>g+(v.reportSize||0)*(v.reportCount||0),0)/8);w.reportId===128&&(t=!0,y>=1&&(r=y)),w.reportId===1&&y>=10&&(n=y),w.reportId===16&&y>=9&&(i=y)}let o=t?"usb":"bluetooth",s=`hid-${this.nextHidSeq++}`,c="Nintendo Switch Pro Controller",l=N();l.connected=!0,l.source="webhid",l.isDualSense=!1,l.deviceName=e.productName||c,l.identity={brand:"nintendo",model:"switch_pro",displayName:c,rawId:e.productName||c,vendorId:e.vendorId,productId:e.productId,transport:o,source:"webhid"};let u=this.hidSessions.size,d={id:s,kind:"switch_pro",device:e,transport:o,firmwareInfo:void 0,usbPayloadLength:47,btPayloadLength:77,btSeq:0,switchSubcmdLength:n,switchRumbleLength:i,switchUsb80Length:r,switchPacketNum:0,switchCal:ye(),switchRumbleTimer:null,switchSeqTimers:[],reportTimes:[],input:l,outState:we(u),legacyTimer:null,lastActivityAt:performance.now(),prevBtnMask:0,boundInputReport:h=>this.handleSwitchProInputReport(d,h)};return this.hidSessions.set(s,d),this.activeSlotId||(this.activeSlotId=s),this.getConnectedControllers(),e.addEventListener("inputreport",d.boundInputReport),!this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.addEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!0),await this.initSwitchProSession(d,u),this.emit({type:"connected",slotId:s,deviceName:l.deviceName,productId:e.productId,transport:o}),s}async sendSwitchUsbCmd(e,t){if(!e.device.opened)return;let n=new Uint8Array(Math.max(1,e.switchUsb80Length));n[0]=t&255,await e.device.sendReport(128,n)}async sendSwitchSubcommand(e,t,n=[]){if(!e.device.opened)return;let i=Math.max(10+n.length,e.switchSubcmdLength),r=new Uint8Array(i);r[0]=e.switchPacketNum&15,e.switchPacketNum=e.switchPacketNum+1&15,r.set(q,1),r.set(q,5),r[9]=t&255;for(let o=0;o<n.length;o++)r[10+o]=n[o]&255;await e.device.sendReport(1,r)}async sendSwitchRumbleBytes(e,t,n){if(!e.device.opened)return!1;let i=Math.max(9,e.switchRumbleLength),r=new Uint8Array(i);return r[0]=e.switchPacketNum&15,e.switchPacketNum=e.switchPacketNum+1&15,r.set(t.subarray(0,4),1),r.set(n.subarray(0,4),5),await e.device.sendReport(16,r),!0}clearSwitchRumbleTimers(e){e.switchRumbleTimer&&(clearTimeout(e.switchRumbleTimer),e.switchRumbleTimer=null);for(let t of e.switchSeqTimers)clearTimeout(t);e.switchSeqTimers=[]}async initSwitchProSession(e,t){try{e.transport==="usb"&&(await this.sendSwitchUsbCmd(e,2).catch(()=>{}),await _(25),await this.sendSwitchUsbCmd(e,4).catch(()=>{}),await _(25)),await this.sendSwitchSubcommand(e,3,[48]),await _(20),await this.sendSwitchSubcommand(e,64,[1]),await _(20),await this.sendSwitchSubcommand(e,72,[1]),await _(20),await this.sendSwitchSubcommand(e,48,[be[t%be.length]]),await _(20),await this.sendSwitchSubcommand(e,16,[61,96,0,0,18]).catch(()=>{}),await _(20),await this.sendSwitchSubcommand(e,2).catch(()=>{})}catch{}}parseSwitchDeviceInfo(e,t){if(t.byteLength<17||t.getUint8(13)!==2)return;let n=t.getUint8(14),i=t.getUint8(15);if(n===0&&i===0)return;let r={buildDate:"",buildTime:"",hwInfoHex:"",fwVersionHex:`v${n}.${i}`};e.firmwareInfo=r,e.input.identity.firmwareInfo=r}parseSwitchStickCalibration(e,t){if(t.byteLength<37||t.getUint8(13)!==16||t.getUint32(14,!0)!==24637)return;let i=f=>{let x=t.getUint8(f),M=t.getUint8(f+1),A=t.getUint8(f+2);return[x|(M&15)<<8,M>>4&15|A<<4]},[r,o]=i(19),[s,c]=i(22),[l,u]=i(25),[d,h]=i(28),[w,y]=i(31),[g,v]=i(34),T=(f,x,M)=>f>=900&&f<=3200&&x>=400&&x<=2400&&M>=400&&M<=2400;T(s,l,r)&&T(c,u,o)&&(e.switchCal.lx={center:s,minDelta:l,maxDelta:r},e.switchCal.ly={center:c,minDelta:u,maxDelta:o}),T(d,w,g)&&T(h,y,v)&&(e.switchCal.rx={center:d,minDelta:w,maxDelta:g},e.switchCal.ry={center:h,minDelta:y,maxDelta:v})}handleSwitchProInputReport(e,t){let{reportId:n,data:i}=t;if(n===33&&(this.parseSwitchStickCalibration(e,i),this.parseSwitchDeviceInfo(e,i)),n!==48&&n!==33||i.byteLength<11)return;let r=e.input,o=performance.now();if(n===48&&(e.reportTimes.push(o),e.reportTimes.length>33&&e.reportTimes.shift(),e.reportTimes.length>=6)){let f=e.reportTimes[e.reportTimes.length-1]-e.reportTimes[0];f>10&&(r.observedReportHz=Math.round((e.reportTimes.length-1)*1e3/f))}let s=i.getUint8(1),c=Math.min(4,s>>5&7);r.battery.percent=c*25,r.battery.charging=!!(s&16),r.battery.full=c>=4,r.battery.known=!0;let l=i.getUint8(2),u=i.getUint8(3),d=i.getUint8(4);r.buttons.square=!!(l&1),r.buttons.triangle=!!(l&2),r.buttons.cross=!!(l&4),r.buttons.circle=!!(l&8),r.buttons.r1=!!(l&64),r.buttons.r2Btn=!!(l&128),r.buttons.create=!!(u&1),r.buttons.options=!!(u&2),r.buttons.r3=!!(u&4),r.buttons.l3=!!(u&8),r.buttons.ps=!!(u&16),r.buttons.touchpadClick=!!(u&32),r.buttons.down=!!(d&1),r.buttons.up=!!(d&2),r.buttons.right=!!(d&4),r.buttons.left=!!(d&8),r.buttons.l1=!!(d&64),r.buttons.l2Btn=!!(d&128),r.l2=r.buttons.l2Btn?1:0,r.r2=r.buttons.r2Btn?1:0;let h=l&207|(u&63)<<8|(d&207)<<16;(h&~e.prevBtnMask)!==0&&(e.lastActivityAt=o),e.prevBtnMask=h;let w=(f,x)=>{let M=f-x.center,A=M>=0?x.maxDelta:x.minDelta,m=A>0?M/A:0;return Math.max(-1,Math.min(1,m))},y=i.getUint8(5)|(i.getUint8(6)&15)<<8,g=i.getUint8(6)>>4&15|i.getUint8(7)<<4,v=i.getUint8(8)|(i.getUint8(9)&15)<<8,T=i.getUint8(9)>>4&15|i.getUint8(10)<<4;if(r.lx=w(y,e.switchCal.lx),r.ly=-w(g,e.switchCal.ly),r.rx=w(v,e.switchCal.rx),r.ry=-w(T,e.switchCal.ry),n===48&&i.byteLength>=48){let f=0,x=0,M=0,A=0,m=0,S=0;for(let R=0;R<3;R++){let B=12+R*12;f+=i.getInt16(B+0,!0),x+=i.getInt16(B+2,!0),M+=i.getInt16(B+4,!0),A+=i.getInt16(B+6,!0),m+=i.getInt16(B+8,!0),S+=i.getInt16(B+10,!0)}let p=f/3,b=x/3,C=M/3,k=A/3,P=m/3,I=S/3,H=R=>Math.max(-1,Math.min(1,R));r.accel.x=H(b/4096),r.accel.y=H(C/4096),r.accel.z=H(-p/4096),r.gyro.x=H(P/8192),r.gyro.y=H(I/8192),r.gyro.z=H(k/8192)}}async disconnect(e){let t=e??this.activeSlotId??Array.from(this.hidSessions.keys())[0];if(!t)return;let n=this.hidSessions.get(t);if(n){n.legacyTimer&&(clearTimeout(n.legacyTimer),n.legacyTimer=null),this.clearSwitchRumbleTimers(n);try{n.kind==="switch_pro"?await this.sendSwitchRumbleBytes(n,q,q):(n.outState.leftTrigger=z({type:"off"}),n.outState.rightTrigger=z({type:"off"}),n.outState.legacyRumbleActive=!1,n.outState.legacyLeft=0,n.outState.legacyRight=0,await this.flushSessionOutput(n,{includeTriggers:!0}))}catch{}n.device.removeEventListener("inputreport",n.boundInputReport);try{n.device.opened&&await n.device.close()}catch{}if(this.hidSessions.delete(t),this.hidSessions.size===0&&this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.removeEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!1),this.activeSlotId===t){let i=this.getConnectedControllers();this.activeSlotId=i[0]?.id??null}this.emit({type:"disconnected",slotId:t})}}async disconnectAll(){let e=Array.from(this.hidSessions.keys());for(let t of e)await this.disconnect(t)}handleDisconnect(e){for(let[t,n]of this.hidSessions.entries())if(n.device===e.device){if(n.legacyTimer&&(clearTimeout(n.legacyTimer),n.legacyTimer=null),this.clearSwitchRumbleTimers(n),n.device.removeEventListener("inputreport",n.boundInputReport),this.hidSessions.delete(t),this.activeSlotId===t){let i=this.getConnectedControllers();this.activeSlotId=i[0]?.id??null}this.emit({type:"disconnected",slotId:t})}this.hidSessions.size===0&&this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.removeEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!1)}handleInputReport(e,t){let{reportId:n,data:i}=t,r=0;if(n===49&&i.byteLength>=40)r=1;else if(n!==1||i.byteLength<10)return;let o=e.input,s=performance.now();if(e.reportTimes.push(s),e.reportTimes.length>33&&e.reportTimes.shift(),e.reportTimes.length>=6){let g=e.reportTimes[e.reportTimes.length-1]-e.reportTimes[0];g>10&&(o.observedReportHz=Math.round((e.reportTimes.length-1)*1e3/g))}let c=g=>{let v=g>=128?(g-128)/127:(g-128)/128;return Math.max(-1,Math.min(1,v))};o.lx=c(i.getUint8(r+0)),o.ly=c(i.getUint8(r+1)),o.rx=c(i.getUint8(r+2)),o.ry=c(i.getUint8(r+3)),o.l2=i.getUint8(r+4)/255,o.r2=i.getUint8(r+5)/255;let l=i.getUint8(r+7),u=i.getUint8(r+8),d=i.getUint8(r+9),h=l&15;o.buttons.up=h===0||h===1||h===7,o.buttons.right=h===1||h===2||h===3,o.buttons.down=h===3||h===4||h===5,o.buttons.left=h===5||h===6||h===7,o.buttons.square=!!(l&16),o.buttons.cross=!!(l&32),o.buttons.circle=!!(l&64),o.buttons.triangle=!!(l&128),o.buttons.l1=!!(u&1),o.buttons.r1=!!(u&2),o.buttons.l2Btn=!!(u&4),o.buttons.r2Btn=!!(u&8),o.buttons.create=!!(u&16),o.buttons.options=!!(u&32),o.buttons.l3=!!(u&64),o.buttons.r3=!!(u&128),o.buttons.ps=!!(d&1),o.buttons.touchpadClick=!!(d&2),o.buttons.mute=!!(d&4),o.buttons.fnL=!!(d&16),o.buttons.fnR=!!(d&32),o.buttons.paddleL=!!(d&64),o.buttons.paddleR=!!(d&128);let w=l&240|(h<8?1:0)|u<<8|(d&247)<<16;(w&~e.prevBtnMask)!==0&&(e.lastActivityAt=s),e.prevBtnMask=w,i.byteLength>r+26&&(o.gyro.x=Math.max(-1,Math.min(1,i.getInt16(r+15,!0)/16384)),o.gyro.y=Math.max(-1,Math.min(1,i.getInt16(r+17,!0)/16384)),o.gyro.z=Math.max(-1,Math.min(1,i.getInt16(r+19,!0)/16384)),o.accel.x=Math.max(-1,Math.min(1,i.getInt16(r+21,!0)/8192)),o.accel.y=Math.max(-1,Math.min(1,i.getInt16(r+23,!0)/8192)),o.accel.z=Math.max(-1,Math.min(1,i.getInt16(r+25,!0)/8192)));let y=(g,v)=>{if(i.byteLength<=g+3)return;let f=(i.getUint8(g)&128)===0;if(v.active=f,f){let x=i.getUint8(g+1),M=i.getUint8(g+2),A=i.getUint8(g+3),m=x|(M&15)<<8,S=(M&240)>>4|A<<4;v.x=Math.max(0,Math.min(1,m/1919)),v.y=Math.max(0,Math.min(1,S/1079))}};if(y(r+32,o.touch),y(r+36,o.touch2),i.byteLength>r+52){let g=i.getUint8(r+52),v=g&15,T=g>>4&15;o.battery.charging=T===1,o.battery.full=T===2,o.battery.percent=T===2?100:Math.min(100,Math.round((v+.5)/10*100)),o.battery.known=!0}}populateGamepadInput(e,t){let n=r=>Math.max(-1,Math.min(1,Number.isFinite(r)?r:0)),i=ne(e.id||"");return t.connected=!0,t.source="gamepad",t.deviceName=i.displayName,t.isDualSense=i.model==="dualsense"||i.model==="dualsense_edge",t.identity={...i,transport:"unknown",source:"gamepad"},t.lx=n(e.axes[0]??0),t.ly=n(e.axes[1]??0),t.rx=n(e.axes[2]??0),t.ry=n(e.axes[3]??0),t.l2=Math.max(0,Math.min(1,e.buttons[6]?.value??0)),t.r2=Math.max(0,Math.min(1,e.buttons[7]?.value??0)),t.buttons.cross=!!e.buttons[0]?.pressed,t.buttons.circle=!!e.buttons[1]?.pressed,t.buttons.square=!!e.buttons[2]?.pressed,t.buttons.triangle=!!e.buttons[3]?.pressed,t.buttons.l1=!!e.buttons[4]?.pressed,t.buttons.r1=!!e.buttons[5]?.pressed,t.buttons.l2Btn=!!e.buttons[6]?.pressed,t.buttons.r2Btn=!!e.buttons[7]?.pressed,t.buttons.create=!!e.buttons[8]?.pressed,t.buttons.options=!!e.buttons[9]?.pressed,t.buttons.l3=!!e.buttons[10]?.pressed,t.buttons.r3=!!e.buttons[11]?.pressed,t.buttons.up=!!e.buttons[12]?.pressed,t.buttons.down=!!e.buttons[13]?.pressed,t.buttons.left=!!e.buttons[14]?.pressed,t.buttons.right=!!e.buttons[15]?.pressed,t.buttons.ps=!!e.buttons[16]?.pressed,t.buttons.touchpadClick=!!e.buttons[17]?.pressed,t.touch.active=!1,t.touch2.active=!1,t.battery.known=!1,t.observedReportHz=null,t}getInputStateForSlot(e){let t=this.getHidSessionForSlot(e);if(t)return t.input;let n=this.getGamepadForSlot(e);if(n){let i=this.gamepadInputs.get(n.index);return i||(i=N(),this.gamepadInputs.set(n.index,i)),this.populateGamepadInput(n,i)}return N()}getInputState(e){if(e!==void 0)return this.getInputStateForSlot(e);let t=this.getActiveHidSession();if(t)return t.input;let n=this.getActiveGamepad();if(n)return this.populateGamepadInput(n,this.fallbackInput);let i=this.keysDown,r=(i.has("KeyD")||i.has("ArrowRight")?1:0)-(i.has("KeyA")||i.has("ArrowLeft")?1:0),o=(i.has("KeyS")||i.has("ArrowDown")?1:0)-(i.has("KeyW")||i.has("ArrowUp")?1:0),s=this.fallbackInput;return s.connected=!1,s.source="keyboard_mouse",s.deviceName="Keyboard & Mouse",s.isDualSense=!1,s.identity={brand:"none",model:"none",displayName:"Keyboard & Mouse",rawId:"",transport:"disconnected",source:"keyboard_mouse"},s.lx=r,s.ly=o,s.rx=0,s.ry=0,s.l2=i.has("ShiftLeft")||i.has("KeyQ")?1:0,s.r2=i.has("Space")||i.has("KeyE")?1:0,s.buttons.cross=i.has("Space")||i.has("Enter"),s.buttons.circle=i.has("KeyC")||i.has("Escape"),s.buttons.square=i.has("KeyR"),s.buttons.triangle=i.has("KeyF"),s.buttons.l1=i.has("KeyQ"),s.buttons.r1=i.has("KeyE"),s.buttons.l2Btn=s.l2>.5,s.buttons.r2Btn=s.r2>.5,s.buttons.l3=!1,s.buttons.r3=!1,s.buttons.up=i.has("ArrowUp")||i.has("KeyW"),s.buttons.down=i.has("ArrowDown")||i.has("KeyS"),s.buttons.left=i.has("ArrowLeft")||i.has("KeyA"),s.buttons.right=i.has("ArrowRight")||i.has("KeyD"),s.buttons.create=!1,s.buttons.options=!1,s.buttons.ps=!1,s.buttons.touchpadClick=!1,s.touch.active=!1,s.touch2.active=!1,s.battery.known=!1,s.observedReportHz=null,s}getCapabilityMatrixForSlot(e,t={}){let n=this.getInputState(e),i=n.identity,r=this.getHidSessionForSlot(e),o=r?.kind==="dualsense",s=r?.kind==="switch_pro",c=!!r,l=r?.transport??"unknown",u=a.isWebHIDSupported(),d=i.model==="dualsense"||i.model==="dualsense_edge",h=i.brand==="xbox",w=i.model==="switch_pro",y=i.brand==="nintendo",g=n.connected,v=this.hasTriggerRumbleSupport(e),T=this.hasDualRumbleSupport(e);if(!g){let f={inherent:!1,availability:"disconnected"};return{standard_input:f,analog_triggers:f,dual_motor_rumble:f,impulse_triggers:f,hd_rumble:f,adaptive_triggers:f,audio_haptics:f,controller_speaker:f,gyro:f,accelerometer:f,touchpad:f,lightbar:f,battery:f}}return{standard_input:{inherent:!0,availability:"ready"},analog_triggers:{inherent:!y,availability:y?"unsupported":"ready",reason:y?"Nintendo Pro/Joy-Con triggers are digital buttons":void 0},dual_motor_rumble:{inherent:!0,availability:c||T?"ready":"unsupported",reason:!c&&!T?"Browser Gamepad rumble actuator not exposed":void 0},impulse_triggers:{inherent:h,availability:h&&v?"ready":"unsupported",reason:h&&!v?"Requires Chrome/Edge 126+ with USB or Xbox Wireless Adapter (Windows Bluetooth often blocks trigger motors)":void 0},hd_rumble:{inherent:y,availability:y?s?"ready":w?u?"permission_required":"unsupported":"bridge_required":"unsupported",reason:w&&!s?u?"Connect Switch Pro via WebHID to unlock dual-band HD Rumble and 6-axis gyro":"WebHID requires desktop Chrome or Edge":void 0},adaptive_triggers:{inherent:d,availability:d?o?"ready":u?"permission_required":"unsupported":"unsupported",reason:d&&!o?u?"Click Unlock DualSense WebHID (works over USB & Bluetooth)":"WebHID requires desktop Chrome or Edge":void 0},audio_haptics:{inherent:d,availability:d?t.has4ChAudio?"ready":l==="bluetooth"?"configuration_required":"bridge_required":"unsupported",reason:d&&!t.has4ChAudio?l==="bluetooth"?"4-channel audio haptics require a wired USB-C connection on Windows":"Optional Gamepadly Link or USB 4ch audio routing required":void 0},controller_speaker:{inherent:d,availability:d?t.hasControllerSpeaker?"ready":l==="bluetooth"?"configuration_required":"bridge_required":"unsupported",reason:d&&!t.hasControllerSpeaker?"Requires wired USB-C DualSense audio output":void 0},gyro:{inherent:d||y,availability:d?o?"ready":u?"permission_required":"unsupported":w?s?"ready":u?"permission_required":"unsupported":y?"bridge_required":"unsupported"},accelerometer:{inherent:d||y,availability:d?o?"ready":u?"permission_required":"unsupported":w?s?"ready":u?"permission_required":"unsupported":y?"bridge_required":"unsupported"},touchpad:{inherent:d||i.model==="dualshock4",availability:d?o?"ready":u?"permission_required":"unsupported":"unsupported"},lightbar:{inherent:d||i.model==="dualshock4",availability:d?o?"ready":u?"permission_required":"unsupported":"unsupported"},battery:{inherent:!0,availability:d&&o||w&&s?"ready":"unknown"}}}getCapabilityMatrix(e={}){return this.getCapabilityMatrixForSlot(void 0,e)}async playSwitchHdRumble(e,t){let n=this.getHidSessionForSlot(t);if(!n||n.kind!=="switch_pro"||!n.device.opened)return!1;this.clearSwitchRumbleTimers(n);let i=U(e.left),r=U(e.right),o=Math.max(30,Math.min(2500,Math.round(e.durationMs??220)));try{await this.sendSwitchRumbleBytes(n,i,r)}catch{return!1}return n.switchRumbleTimer=setTimeout(()=>{n.switchRumbleTimer=null,this.sendSwitchRumbleBytes(n,q,q).catch(()=>{})},o),!0}async playSwitchHdRumbleSequence(e,t){let n=this.getHidSessionForSlot(t);if(!n||n.kind!=="switch_pro"||!n.device.opened||e.length===0)return!1;this.clearSwitchRumbleTimers(n);let i=0;for(let r of e){let o=Math.max(0,Math.round(r.delayMs)),s=Math.max(30,Math.min(1200,Math.round(r.durationMs??80)));o+s>i&&(i=o+s);let c=U(r.left),l=U(r.right);if(o===0)await this.sendSwitchRumbleBytes(n,c,l).catch(()=>{});else{let u=setTimeout(()=>{this.sendSwitchRumbleBytes(n,c,l).catch(()=>{})},o);n.switchSeqTimers.push(u)}}return n.switchRumbleTimer=setTimeout(()=>{n.switchRumbleTimer=null,n.switchSeqTimers=[],this.sendSwitchRumbleBytes(n,q,q).catch(()=>{})},i+15),!0}stopSwitchHdRumble(e){if(e!==void 0){let t=this.getHidSessionForSlot(e);t&&t.kind==="switch_pro"&&t.device.opened&&(this.clearSwitchRumbleTimers(t),this.sendSwitchRumbleBytes(t,q,q).catch(()=>{}));return}for(let t of this.hidSessions.values())t.kind!=="switch_pro"||!t.device.opened||(this.clearSwitchRumbleTimers(t),this.sendSwitchRumbleBytes(t,q,q).catch(()=>{}))}async playTriggerRumble(e,t,n,i=0,r=0,o){if(this.getHidSessionForSlot(o)?.kind==="switch_pro"){let T=Math.max(e,r),f=Math.max(t,i);return this.playSwitchHdRumble({left:T>.02?{highFreqHz:260,highAmp:T*.65,lowFreqHz:145,lowAmp:T*.7}:void 0,right:f>.02?{highFreqHz:340,highAmp:f*.7,lowFreqHz:170,lowAmp:f*.55}:void 0,durationMs:n},o)}let l=this.getGamepadForSlot(o)?.vibrationActuator;if(!l?.playEffect)return!1;let u=Math.max(20,Math.min(2500,Math.round(n))),d=Math.max(0,Math.min(1,e)),h=Math.max(0,Math.min(1,t)),w=Math.max(0,Math.min(1,i)),y=Math.max(0,Math.min(1,r));if(this.hasTriggerRumbleSupport(o))try{return await l.playEffect("trigger-rumble",{startDelay:0,duration:u,leftTrigger:d,rightTrigger:h,weakMagnitude:w,strongMagnitude:y}),!0}catch{}let g=Math.max(w,h*.65),v=Math.max(y,d*.65);return g>0||v>0?this.playDualRumble(g,v,u,o):!1}async playDualRumble(e,t,n,i){if(this.getHidSessionForSlot(i)?.kind==="switch_pro"){let c={highFreqHz:320,highAmp:Math.max(0,Math.min(.85,e*.8)),lowFreqHz:150,lowAmp:Math.max(0,Math.min(.85,t*.8))};return this.playSwitchHdRumble({left:c,right:c,durationMs:n},i)}let s=this.getGamepadForSlot(i)?.vibrationActuator;if(!s?.playEffect)return!1;try{return await s.playEffect("dual-rumble",{startDelay:0,duration:Math.max(20,Math.min(2500,Math.round(n))),strongMagnitude:Math.max(0,Math.min(1,t)),weakMagnitude:Math.max(0,Math.min(1,e))}),!0}catch{return!1}}stopGamepadRumble(e){if(this.stopSwitchHdRumble(e),!!a.isGamepadSupported()){if(e!==void 0){let t=this.getGamepadForSlot(e);t?.vibrationActuator?.reset&&t.vibrationActuator.reset().catch(()=>{});return}for(let t of this.getAllRawGamepads()){let n=t.vibrationActuator;n?.reset&&n.reset().catch(()=>{})}}}triggerGamepadRumbleFallback(e,t,n,i){let r=this.getHidSessionForSlot(i);if(r?.kind==="switch_pro"){this.playDualRumble(e,t,n,i);return}if(r?.kind==="dualsense"){this.pulseLegacyRumble(Math.round(Math.max(0,Math.min(1,t))*220),Math.round(Math.max(0,Math.min(1,e))*220),Math.max(25,Math.min(350,n)),i);return}this.playDualRumble(e,t,n,i)}buildCommonPayload(e,{includeAudioConfig:t=!1,includeTriggers:n=!1,includeLeds:i=!1}={}){let r=new Uint8Array(47),o=0,s=0;return e.legacyRumbleActive&&(o|=3,r[2]=Math.max(0,Math.min(255,Math.round(e.legacyRight))),r[3]=Math.max(0,Math.min(255,Math.round(e.legacyLeft)))),n&&(o|=12,r.set(e.rightTrigger.subarray(0,11),10),r.set(e.leftTrigger.subarray(0,11),21)),t&&(o|=176,s|=130,r[4]=Math.max(0,Math.min(127,e.headphoneVolume)),r[5]=Math.max(0,Math.min(255,e.speakerVolume)),r[6]=0,r[7]=e.audioRoute==="speaker"?48:e.audioRoute==="both"?32:0,r[9]=0,r[37]=e.speakerPreamp&7),i&&(s|=21,r[8]=e.muteLed==="on"?1:e.muteLed==="pulse"?2:0,r[38]=2,r[41]=2,r[42]=0,r[43]=e.playerLeds&31,r[44]=e.lightbar[0]&255,r[45]=e.lightbar[1]&255,r[46]=e.lightbar[2]&255),r[0]=o,r[1]=s,r}async flushSessionOutput(e,t={}){if(e.kind!=="dualsense"||!e.device.opened)return!1;let n=this.buildCommonPayload(e.outState,t);if(e.transport==="bluetooth"){let r=new Uint8Array(e.btPayloadLength);r[0]=(e.btSeq&15)<<4,e.btSeq=e.btSeq+1&15,r[1]=16,r.set(n,2);let o=r.length-4,s=Se(162,49,r.subarray(0,o));return new DataView(r.buffer).setUint32(o,s,!0),await e.device.sendReport(49,r),!0}let i=new Uint8Array(e.usbPayloadLength);return i.set(n,0),await e.device.sendReport(2,i),!0}async flushOutput(e={}){let t=this.getActiveHidSession();return!t||t.kind!=="dualsense"?!1:this.flushSessionOutput(t,e)}async setAudioConfig(e){let t=this.getActiveHidSession();return!t||t.kind!=="dualsense"?!1:(e.speakerVolume!==void 0&&(t.outState.speakerVolume=e.speakerVolume),e.headphoneVolume!==void 0&&(t.outState.headphoneVolume=e.headphoneVolume),e.audioRoute!==void 0&&(t.outState.audioRoute=e.audioRoute),e.speakerPreamp!==void 0&&(t.outState.speakerPreamp=e.speakerPreamp),this.flushSessionOutput(t,{includeAudioConfig:!0}))}async setTriggers(e,t,n){let i=this.getHidSessionForSlot(n);if(!i||i.kind!=="dualsense")return!1;let r=i.outState.leftTrigger,o=i.outState.rightTrigger,s=e?z(e):void 0,c=t?z(t):void 0;s&&(i.outState.leftTrigger=s),c&&(i.outState.rightTrigger=c);try{let l=await this.flushSessionOutput(i,{includeTriggers:!0});return l||(s&&i.outState.leftTrigger===s&&(i.outState.leftTrigger=r),c&&i.outState.rightTrigger===c&&(i.outState.rightTrigger=o)),l}catch(l){throw s&&i.outState.leftTrigger===s&&(i.outState.leftTrigger=r),c&&i.outState.rightTrigger===c&&(i.outState.rightTrigger=o),l}}async resetTriggers(e){if(this.stopGamepadRumble(e),e!==void 0){let n=this.getHidSessionForSlot(e);return!n||!n.device.opened||n.kind!=="dualsense"?!1:(n.outState.leftTrigger=z({type:"off"}),n.outState.rightTrigger=z({type:"off"}),this.flushSessionOutput(n,{includeTriggers:!0}).catch(()=>!1))}let t=!1;for(let n of this.hidSessions.values()){if(!n.device.opened||n.kind!=="dualsense")continue;n.outState.leftTrigger=z({type:"off"}),n.outState.rightTrigger=z({type:"off"}),await this.flushSessionOutput(n,{includeTriggers:!0}).catch(()=>!1)&&(t=!0)}return t}emergencyReset(){this.stopGamepadRumble();for(let e of this.hidSessions.values())if(e.device.opened){if(e.kind==="switch_pro"){this.clearSwitchRumbleTimers(e),this.sendSwitchRumbleBytes(e,q,q).catch(()=>{});continue}e.outState.leftTrigger=z({type:"off"}),e.outState.rightTrigger=z({type:"off"}),e.outState.legacyRumbleActive=!1,e.outState.legacyLeft=0,e.outState.legacyRight=0,e.outState.lightbar=[23,23,23],e.outState.muteLed="off",this.flushSessionOutput(e,{includeTriggers:!0,includeLeds:!0}).catch(()=>{})}}async setLightbar(e,t,n,i){let r=this.getHidSessionForSlot(i);return!r||r.kind!=="dualsense"?!1:(r.outState.lightbar=[e&255,t&255,n&255],this.flushSessionOutput(r,{includeLeds:!0}))}async setPlayerLeds(e,t){let n=this.getHidSessionForSlot(t);return!n||!n.device.opened?!1:n.kind==="switch_pro"?(await this.sendSwitchSubcommand(n,48,[e&15]),!0):(n.outState.playerLeds=e&31,this.flushSessionOutput(n,{includeLeds:!0}))}async setMuteLed(e,t){let n=this.getHidSessionForSlot(t);return!n||n.kind!=="dualsense"?!1:(n.outState.muteLed=e,this.flushSessionOutput(n,{includeLeds:!0}))}async pulseLegacyRumble(e=200,t=200,n=250,i){let r=this.getHidSessionForSlot(i);return!r||r.kind!=="dualsense"||!r.device.opened?!1:(r.legacyTimer&&(clearTimeout(r.legacyTimer),r.legacyTimer=null),r.outState.legacyRumbleActive=!0,r.outState.legacyLeft=e,r.outState.legacyRight=t,await this.flushSessionOutput(r,{}),new Promise(o=>{r.legacyTimer=setTimeout(async()=>{r.legacyTimer=null;try{r.outState.legacyLeft=0,r.outState.legacyRight=0,await this.flushSessionOutput(r,{}),r.outState.legacyRumbleActive=!1,await this.flushSessionOutput(r,{includeAudioConfig:!0})}catch{}o(!0)},n)}))}};var K={off:{type:"off"},weapon:{type:"weapon",startZone:2,endZone:5,strength:7},heavy_weapon:{type:"weapon",startZone:3,endZone:6,strength:8},bow:{type:"slope",startZone:1,endZone:8,startStrength:1,endStrength:7},abs:{type:"vibration",startZone:2,amplitude:6,frequencyHz:22},soft_wall:{type:"feedback",startZone:4,strength:4},rapid_pulse:{type:"vibration",startZone:1,amplitude:7,frequencyHz:14},precision_damp:{type:"feedback",startZone:2,strength:3}},ie={click:{freqHz:210,endFreqHz:140,durationMs:26,intensity:.45,wave:"triangle",triggerEmphasis:.65,switchHd:{highFreqHz:340,lowFreqHz:165,highWeight:.75,lowWeight:.25}},ratchet:{freqHz:180,endFreqHz:110,durationMs:22,intensity:.5,wave:"triangle",triggerEmphasis:.75,switchHd:{highFreqHz:320,lowFreqHz:155,highWeight:.8,lowWeight:.2}},wall_hit:{freqHz:135,endFreqHz:58,durationMs:65,intensity:.78,wave:"triangle",triggerEmphasis:.5,switchHd:{highFreqHz:290,lowFreqHz:130,highWeight:.55,lowWeight:.75}},marble_click:{freqHz:290,endFreqHz:210,durationMs:32,intensity:.62,wave:"sine",triggerEmphasis:.85,switchHd:{highFreqHz:380,lowFreqHz:190,highWeight:.85,lowWeight:.18}},recoil:{freqHz:115,endFreqHz:46,durationMs:75,intensity:.88,wave:"triangle",triggerEmphasis:1,switchHd:{highFreqHz:310,lowFreqHz:120,highWeight:.65,lowWeight:.85}},heavy_impact:{freqHz:75,endFreqHz:34,durationMs:140,intensity:.95,wave:"sine",triggerEmphasis:.7,switchHd:{highFreqHz:220,lowFreqHz:95,highWeight:.45,lowWeight:.95}},lock_unlock:{freqHz:95,endFreqHz:220,durationMs:120,intensity:.72,wave:"triangle",triggerEmphasis:.6,switchHd:{highFreqHz:350,lowFreqHz:150,highWeight:.7,lowWeight:.55}},splash:{freqHz:90,endFreqHz:48,durationMs:110,intensity:.6,wave:"sine",triggerEmphasis:.35,switchHd:{highFreqHz:250,lowFreqHz:120,highWeight:.5,lowWeight:.6}},boost:{freqHz:65,endFreqHz:165,durationMs:160,intensity:.75,wave:"sawtooth",triggerEmphasis:.85,switchHd:{highFreqHz:300,lowFreqHz:135,highWeight:.6,lowWeight:.75}},error_buzz:{freqHz:145,endFreqHz:115,durationMs:95,intensity:.65,wave:"square",triggerEmphasis:.45,switchHd:{highFreqHz:260,lowFreqHz:125,highWeight:.55,lowWeight:.65}}};function V(a){let e=Math.max(-1,Math.min(1,a.pan??0)),t=Math.max(0,Math.min(1,a.intensity)),n=Math.min(1,1-Math.max(0,e)),i=Math.min(1,1+Math.min(0,e)),r=a.highFreqHz??Math.max(160,Math.min(620,a.freqHz*1.9)),o=a.lowFreqHz??Math.max(60,Math.min(240,a.freqHz)),s=a.highWeight??(a.freqHz>=140?.78:.42),c=a.lowWeight??(a.freqHz<140?.82:.38),l=u=>{let d=t*u;if(!(d<.02))return{highFreqHz:r,highAmp:Math.min(.85,d*s*.85),lowFreqHz:o,lowAmp:Math.min(.85,d*c*.85)}};return{left:l(n),right:l(i),durationMs:Math.max(30,Math.min(2500,Math.round(a.durationMs)))}}function re(a){return a.allow4ChAudio===!1?!1:!!(a.audio&&a.audio.dsMode!=="none"&&a.audio.dsMaxChannelCount>=4)}function j(a,e){if(re(a)){a.audio.playHapticPulse(e);return}let t=a.hid.getCapabilityMatrixForSlot(a.slotId),n=Math.max(0,Math.min(1,e.intensity)),i=Math.max(25,Math.min(2500,Math.round(e.durationMs))),r=Math.max(-1,Math.min(1,e.pan??0));if(t.hd_rumble?.availability==="ready"){let c=V({pan:r,freqHz:e.freqHz,intensity:n,durationMs:i});a.hid.playSwitchHdRumble(c,a.slotId);return}if(t.impulse_triggers?.availability==="ready"){let c=Math.min(1,1-Math.max(0,r)),l=Math.min(1,1+Math.min(0,r)),u=e.freqHz>=120?.85:.45,d=e.freqHz<120?.78:.35;a.hid.playTriggerRumble(n*c*u,n*l*u,i,n*(e.freqHz>=120?.65:.35),n*d,a.slotId);return}let o=e.freqHz<120?n*.8:n*.3,s=e.freqHz>=120?n*.85:n*.4;a.hid.triggerGamepadRumbleFallback(s,o,i,a.slotId)}function ae(a,e){if(re(a)){a.audio.playHapticSweep(e);return}let t=a.hid.getCapabilityMatrixForSlot(a.slotId),n=Math.max(0,Math.min(1,e.intensity)),i=Math.max(40,Math.min(2500,Math.round(e.durationMs)));if(t.hd_rumble?.availability==="ready"){let r=Math.max(2,Math.min(6,Math.round(i/55))),o=Math.max(30,Math.round(i/r)),s=[];for(let c=0;c<r;c++){let l=r===1?0:c/(r-1),u=e.fromPan+(e.toPan-e.fromPan)*l,d=e.fromHz+(e.toHz-e.fromHz)*l;s.push({...V({pan:u,freqHz:d,intensity:n,durationMs:o}),delayMs:c*o})}a.hid.playSwitchHdRumbleSequence(s,a.slotId);return}if(t.impulse_triggers?.availability==="ready"){let r=(e.fromPan+e.toPan)*.5,o=Math.min(1,1-Math.max(0,r)),s=Math.min(1,1+Math.min(0,r));a.hid.playTriggerRumble(n*o*.7,n*s*.7,i,n*.5,n*.6,a.slotId);return}a.hid.triggerGamepadRumbleFallback(n*.55,n*.65,i,a.slotId)}function oe(a,e,t={}){let n=ie[e];if(!n)return;let i=Math.max(-1,Math.min(1,t.pan??0)),r=Math.max(0,Math.min(1,(t.intensity??1)*n.intensity));if(re(a)){a.audio.playHapticPulse({pan:i,freqHz:n.freqHz,endFreqHz:n.endFreqHz,durationMs:n.durationMs,intensity:r,wave:n.wave});return}let o=a.hid.getCapabilityMatrixForSlot(a.slotId);if(o.hd_rumble?.availability==="ready"&&n.switchHd){let s=V({pan:i,freqHz:n.freqHz,intensity:r,durationMs:n.durationMs,highFreqHz:n.switchHd.highFreqHz,lowFreqHz:n.switchHd.lowFreqHz,highWeight:n.switchHd.highWeight,lowWeight:n.switchHd.lowWeight});a.hid.playSwitchHdRumble(s,a.slotId);return}if(o.impulse_triggers?.availability==="ready"&&n.triggerEmphasis){let s=Math.min(1,1-Math.max(0,i)),c=Math.min(1,1+Math.min(0,i)),l=r*n.triggerEmphasis;a.hid.playTriggerRumble(l*s,l*c,Math.max(30,n.durationMs),r*.45,r*.55,a.slotId);return}j(a,{pan:i,freqHz:n.freqHz,endFreqHz:n.endFreqHz,durationMs:n.durationMs,intensity:r,wave:n.wave})}var Te=new Set(["cross","circle","square","triangle","l1","r1","l2Btn","r2Btn","l3","r3","up","down","left","right","create","options","ps","touchpadClick"]),se=new Set(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab"]);function ke(a){if(!a||typeof a!="object")return!1;let e=a;if(e.isContentEditable)return!0;let t=(e.tagName||"").toUpperCase();return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Ae(a,e,t,n,i){let r=e.source!=="keyboard_mouse";return a==="l2"?r?e.l2:0:a==="r2"?r?e.r2:0:a==="lx+"?r?Math.max(0,e.lx):0:a==="lx-"?r?Math.max(0,-e.lx):0:a==="ly+"?r?Math.max(0,e.ly):0:a==="ly-"?r?Math.max(0,-e.ly):0:a==="rx+"?r?Math.max(0,e.rx):0:a==="rx-"?r?Math.max(0,-e.rx):0:a==="ry+"?r?Math.max(0,e.ry):0:a==="ry-"?r?Math.max(0,-e.ry):0:Te.has(a)?r&&e.buttons[a]?1:0:a==="MouseLeft"||a==="MouseRight"||a==="MouseMiddle"?n.has(a)?1:0:t.has(a)?Math.max(1,i):0}function ce(a){let e=a.analogThreshold??.45,t=a.actions??{},n=a.axes??{},i=a.preventDefaultKeys!==!1,r=new Set;for(let m of Object.values(t))for(let S of m)se.has(S)&&r.add(S);for(let m of Object.values(n)){for(let S of m.negativeKeys??[])se.has(S)&&r.add(S);for(let S of m.positiveKeys??[])se.has(S)&&r.add(S)}let o=new Set,s=new Set,c=new Set,l=new Set,u=new Map,d=new Map,h=new Map;for(let m of Object.keys(t))u.set(m,{pressed:!1,justPressed:!1,justReleased:!1,heldMs:0,value:0});for(let m of Object.keys(n))h.set(m,0);let w=m=>m===0?"MouseLeft":m===1?"MouseMiddle":m===2?"MouseRight":null,y=m=>{let S=m;S.code&&(i&&r.has(S.code)&&!S.ctrlKey&&!S.metaKey&&!S.altKey&&!ke(S.target)&&S.preventDefault(),o.has(S.code)||s.add(S.code),o.add(S.code))},g=m=>{let S=m;S.code&&o.delete(S.code)},v=m=>{let p=w(m.button);p&&(c.has(p)||l.add(p),c.add(p))},T=m=>{let p=w(m.button);p&&c.delete(p)},f=()=>{o.clear(),s.clear(),c.clear(),l.clear()},x=a.attachWindowListeners!==!1&&typeof window<"u",M=a.mouseTarget??(typeof window<"u"?window:void 0);x&&(window.addEventListener("keydown",y),window.addEventListener("keyup",g),window.addEventListener("blur",f),M?.addEventListener("pointerdown",v),window.addEventListener("pointerup",T));let A={pressed:!1,justPressed:!1,justReleased:!1,heldMs:0,value:0};return{update(m,S=typeof performance<"u"?performance.now():Date.now()){let p=s.size>0?new Set([...o,...s]):o,b=l.size>0?new Set([...c,...l]):c;s.clear(),l.clear();for(let[k,P]of Object.entries(t)){let I=0;for(let E of P){let G=Ae(E,m,p,b,e);G>I&&(I=G)}let H=I>=e,R=u.get(k),B=H&&!R.pressed,D=!H&&R.pressed;B?d.set(k,S):H||d.delete(k);let L=d.get(k);R.pressed=H,R.justPressed=B,R.justReleased=D,R.heldMs=H&&L!==void 0?Math.max(0,S-L):0,R.value=Math.max(0,Math.min(1,I))}let C=m.source!=="keyboard_mouse";for(let[k,P]of Object.entries(n)){let I=0;if(P.stick&&C){let D=m[P.stick],L=P.deadzone??.08;I=F(D,L)}let H=0;C&&P.negativeButtons?.some(D=>m.buttons[D])&&(H-=1),C&&P.positiveButtons?.some(D=>m.buttons[D])&&(H+=1),P.negativeKeys?.some(D=>p.has(D))&&(H-=1),P.positiveKeys?.some(D=>p.has(D))&&(H+=1);let R=Math.abs(H)>Math.abs(I)?H:I,B=Math.max(-1,Math.min(1,R));h.set(k,P.invert?-B:B)}},action(m){return u.get(m)??A},isPressed(m){return u.get(m)?.pressed??!1},justPressed(m){return u.get(m)?.justPressed??!1},justReleased(m){return u.get(m)?.justReleased??!1},axis(m){return h.get(m)??0},setKeyDown(m,S){S?(o.has(m)||s.add(m),o.add(m)):o.delete(m)},setMouseButton(m,S){S?(c.has(m)||l.add(m),c.add(m)):c.delete(m)},dispose(){x&&(window.removeEventListener("keydown",y),window.removeEventListener("keyup",g),window.removeEventListener("blur",f),M?.removeEventListener("pointerdown",v),window.removeEventListener("pointerup",T)),o.clear(),s.clear(),c.clear(),l.clear(),d.clear()}}}var Pe={update(){},stop(){}};function le(a,e,t,n){let i=n&&!!(e&&e.dsMode!=="none"&&e.dsMaxChannelCount>=4),r=n&&!!(e&&e.dsMode!=="none"),o=a.getInputState(t),s=a.getCapabilityMatrixForSlot(t,{has4ChAudio:i,hasControllerSpeaker:r}),c=u=>s[u]?.availability==="ready",l="keyboard_mouse";return c("adaptive_triggers")&&i?l="dualsense_full_4ch":c("adaptive_triggers")?l="dualsense_hid_only":c("hd_rumble")?l="switch_pro_hid":c("impulse_triggers")?l="xbox_impulse":o.source==="gamepad"&&(l="standard_gamepad"),{slotId:t??a.getActiveSlotId(),tier:l,identity:o.identity,matrix:s,has:c,hasAdaptiveTriggers:c("adaptive_triggers"),hasImpulseTriggers:c("impulse_triggers"),hasHdRumble:c("hd_rumble"),hasDualRumble:c("dual_motor_rumble"),has4ChHaptics:i,hasControllerSpeaker:r,hasGyro:c("gyro"),hasTouchpad:c("touchpad")}}function ve(a,e){return[a.map(n=>`${n.id}:${n.source}:${n.identity.model}:${n.identity.transport}`).join(","),e.slotId??"",e.tier,e.hasAdaptiveTriggers?1:0,e.hasImpulseTriggers?1:0,e.hasHdRumble?1:0,e.has4ChHaptics?1:0,e.hasControllerSpeaker?1:0,e.hasGyro?1:0].join("|")}function Ie(a={}){let e=!a.hid,t=a.hid??new O,n=a.audio??null,i=!1,r=new Set,o=new Set,s=new Set,c=new Set;a.autoHotplug!==!1&&t.attachHidHotplug(),a.attachKeyboardFallback&&e&&t.attachKeyboardFallback();let l="",u=()=>{if(i)return;let f=t.getConnectedControllers(),x=le(t,n,void 0,!0),M=ve(f,x);if(M!==l){l=M;for(let A of c)try{A({slots:f,active:x})}catch{}}};l=ve(t.getConnectedControllers(),le(t,n,void 0,!0));let d=t.onStatusChange(()=>{u()}),h=()=>u(),w=()=>t.emergencyReset();typeof window<"u"&&(a.autoHotplug!==!1&&(window.addEventListener("gamepadconnected",h),window.addEventListener("gamepaddisconnected",h)),a.autoEmergencyReset!==!1&&(window.addEventListener("pagehide",w),window.addEventListener("beforeunload",w)));let y=null,g=a.capabilityPollMs??250;g>0&&typeof setInterval<"u"&&(y=setInterval(u,g));let v=f=>{let x=[23,23,23],M=0,A=null,m=()=>{if(f==="active")return{slotId:void 0,connected:!0,isPrimary:!0};if(typeof f=="number"){let C=t.getConnectedControllers()[f];if(!C)return{slotId:`__unassigned_${f}`,connected:!1,isPrimary:f===0};let k=t.getActiveSlotId();return{slotId:C.id,connected:!0,isPrimary:C.id===k||f===0}}let p=t.getActiveSlotId();return{slotId:f,connected:!0,isPrimary:f===p}},S=()=>{let p=m();return{hid:t,audio:n,slotId:p.slotId,allow4ChAudio:p.isPrimary}};return{getSlotId(){let p=m();return p.slotId===void 0?t.getActiveSlotId():p.connected?p.slotId:null},getCapabilities(){let p=m();return le(t,n,p.slotId,p.isPrimary)},input:{getState:()=>{let p=m();return t.getInputState(p.slotId)},applyDeadzone:F},triggers:{reset:()=>{if(i)return;let p=m();t.resetTriggers(p.slotId).catch(()=>{})},setLeft:p=>{if(i)return;let b=m();t.setTriggers(p,void 0,b.slotId).catch(()=>{})},setRight:p=>{if(i)return;let b=m();t.setTriggers(void 0,p,b.slotId).catch(()=>{})},setBoth:(p,b)=>{if(i)return;let C=m();t.setTriggers(p,b,C.slotId).catch(()=>{})},applyPreset:(p,b="both")=>{if(i)return;let C=K[p];if(!C)return;let k=m();b==="left"?t.setTriggers(C,void 0,k.slotId).catch(()=>{}):b==="right"?t.setTriggers(void 0,C,k.slotId).catch(()=>{}):t.setTriggers(C,C,k.slotId).catch(()=>{})},pulseImpulse:p=>{if(i)return;let b=m();t.playTriggerRumble(p.left??0,p.right??0,p.durationMs??80,p.weakGrip??0,p.strongGrip??0,b.slotId)}},haptics:{pulse:p=>{i||j(S(),p)},sweep:p=>{i||ae(S(),p)},rumble:p=>{if(i)return;let b=m();t.triggerGamepadRumbleFallback(p.weak,p.strong,p.durationMs,b.slotId)},hdRumble:p=>{if(i)return;let b=m();t.playSwitchHdRumble(p,b.slotId)},hdSequence:p=>{if(i)return;let b=m();t.playSwitchHdRumbleSequence(p,b.slotId)},playPreset:(p,b)=>{i||oe(S(),p,b)},createContinuous:p=>{if(i||!n)return Pe;let b=n.createContinuous(p);return r.add(b),{update:C=>{i||b.update(C)},stop:()=>{r.delete(b),b.stop()}}},playComboPreset:(p,b=0)=>{if(i)return;let C=m();if(n?.playComboPreset(p,b),!n||!C.isPrimary||n.dsMode==="none"||n.dsMaxChannelCount<4){let k=p==="shotgun"||p==="thunder"?.85:.4,P=p==="ratchet_tick"?30:120;j(S(),{pan:b,freqHz:p==="ratchet_tick"?190:95,durationMs:P,intensity:k})}},stop:()=>{let p=m();t.stopGamepadRumble(p.slotId)}},audio:{playPcTone:p=>{i||n?.playPcTone(p)},playPcNoise:p=>{i||n?.playPcNoiseBurst(p)},playControllerSpeakerTone:p=>{i||n?.playControllerSpeakerTone(p)}},lightbar:{setColor:(p,b,C)=>{if(i)return;let k=typeof performance<"u"?performance.now():Date.now();if(x[0]===p&&x[1]===b&&x[2]===C)return;if(A!==null){x=[p,b,C];return}if(k-M<30)return;M=k,x=[p,b,C];let P=m();t.setLightbar(p,b,C,P.slotId).catch(()=>{})},flash:(p,b,C,k=240)=>{if(i)return;A!==null&&(clearTimeout(A),o.delete(A),A=null);let P=m();t.setLightbar(p,b,C,P.slotId).catch(()=>{});let I=setTimeout(()=>{if(o.delete(I),A===I&&(A=null),!i){let H=x;t.setLightbar(H[0],H[1],H[2],P.slotId).catch(()=>{})}},k);A=I,o.add(I)}},createActions(p){let b=ce(p);return s.add(b),{...b,dispose(){s.delete(b),b.dispose()}}}}},T=v("active");return{hid:t,async connectWebHID(){let f=await t.connect();return u(),f},async reconnectAuthorized(){let f=await t.reconnectAuthorized();return u(),f},attachAudio(f){n=f,u()},getSlots(){return t.getConnectedControllers()},get active(){return T},player(f){return f===void 0||f==="active"?T:v(f)},onCapabilitiesChange(f){return c.add(f),()=>{c.delete(f)}},syncCapabilities:u,dispose(){if(!i){i=!0,y!==null&&(clearInterval(y),y=null),d(),c.clear(),typeof window<"u"&&(a.autoHotplug!==!1&&(window.removeEventListener("gamepadconnected",h),window.removeEventListener("gamepaddisconnected",h)),a.autoEmergencyReset!==!1&&(window.removeEventListener("pagehide",w),window.removeEventListener("beforeunload",w)));for(let f of o)clearTimeout(f);o.clear();for(let f of s)try{f.dispose()}catch{}s.clear();for(let f of r)try{f.stop()}catch{}r.clear(),t.stopGamepadRumble(),t.resetTriggers().catch(()=>{}),t.setLightbar(23,23,23).catch(()=>{}),e&&(a.autoHotplug!==!1&&t.detachHidHotplug(),a.attachKeyboardFallback&&t.detachKeyboardFallback())}}}}var de="http://127.0.0.1:5178",ue="ws://127.0.0.1:5178",W=class a{httpBase;wsBase;pcCtx=null;pcSinkId="";pcSinkLabel="PC Default Speakers";pcMasterGain=null;pcAnalysers=[];pcNoiseBuffer=null;dsMode="none";dsCtx=null;dsSinkId="";dsSinkLabel="";dsMaxChannelCount=2;dsActiveChannelCount=2;dsWs=null;dsWorklet=null;dsMerger=null;dsChGains=[];dsAnalysers=[];dsNoiseBuffer=null;pcGainValue=.8;dsSpeakerGainValue=.95;dsHapticGainValue=.95;audioMuted=!1;constructor(e={}){this.httpBase=(e.httpBase||de).replace(/\/+$/,""),this.wsBase=(e.wsBase||ue).replace(/\/+$/,"")}setAudioMuted(e){if(this.audioMuted=e,this.pcMasterGain&&this.pcCtx&&this.pcMasterGain.gain.setTargetAtTime(e?0:this.pcGainValue,this.pcCtx.currentTime,.015),this.dsChGains.length>=2&&this.dsCtx){let t=e?0:this.dsSpeakerGainValue;this.dsChGains[0].gain.setTargetAtTime(t,this.dsCtx.currentTime,.015),this.dsChGains[1].gain.setTargetAtTime(t,this.dsCtx.currentTime,.015)}}activeContinuous=new Set;companionToken="";intentionalWsClose=!1;reconnectAttempts=0;reconnectTimer=null;streamStateListeners=new Set;onCompanionStreamState(e){return this.streamStateListeners.add(e),()=>this.streamStateListeners.delete(e)}emitStreamState(e,t){for(let n of this.streamStateListeners)try{n(e,t)}catch{}}static isLoopbackOrigin(){if(typeof window>"u")return!0;let e=window.location.hostname;return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}static async getLoopbackPermissionState(){if(a.isLoopbackOrigin())return"local_exempt";if(typeof navigator>"u"||!navigator.permissions?.query)return"unknown";for(let e of["loopback-network","local-network-access"])try{let t=await navigator.permissions.query({name:e});if(t.state==="granted"||t.state==="prompt"||t.state==="denied")return t.state}catch{}return"unknown"}async loopbackFetch(e,t={}){let n={...t,targetAddressSpace:"loopback"};try{return await fetch(e,n)}catch(i){if(i instanceof TypeError&&!String(i.message).toLowerCase().includes("fetch"))return fetch(e,t);throw i}}static checkBrowserCapabilities(){if(typeof window>"u")return{hasWebAudio:!1,hasSetSinkId:!1,hasAudioWorklet:!1,isSecureContext:!0};let e=window.AudioContext||window.webkitAudioContext;return{hasWebAudio:!!e,hasSetSinkId:!!(e&&"setSinkId"in e.prototype),hasAudioWorklet:!!(e&&"audioWorklet"in e.prototype),isSecureContext:!!window.isSecureContext}}async probeCompanion(e=700){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await this.loopbackFetch(`${this.httpBase}/api/health`,{cache:"no-store",signal:t.signal});if(!i.ok)return{online:!1};let r=await i.json();return{online:!!r.ok,version:r.version,protocolVersion:typeof r.protocolVersion=="number"?r.protocolVersion:1,platform:r.platform}}catch{return{online:!1}}finally{clearTimeout(n)}}async acquireCompanionSession(){let e=await this.loopbackFetch(`${this.httpBase}/api/session`,{method:"POST",headers:{"X-Gamepadly-Client":"web"},cache:"no-store"});if(e.status===404)return this.companionToken="","";if(!e.ok)throw new Error(`Gamepadly Link rejected session request (HTTP ${e.status}).`);let t=await e.json();return this.companionToken=typeof t.token=="string"?t.token:"",this.companionToken}async listCompanionDevices(){let e=await this.loopbackFetch(`${this.httpBase}/api/devices`,{cache:"no-store"});if(!e.ok)throw new Error("Gamepadly Link companion did not respond.");let t=await e.json();return Array.isArray(t.devices)?t.devices:[]}async openWindowsSoundPanelViaCompanion(){try{let e=this.companionToken||await this.acquireCompanionSession(),t={};return e&&(t["X-Gamepadly-Token"]=e),(await this.loopbackFetch(`${this.httpBase}/api/open-sound-panel`,{method:"POST",headers:t})).ok}catch{return!1}}async unlockBrowserDeviceLabels(){if(!navigator.mediaDevices?.getUserMedia)return!1;try{let e=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});for(let t of e.getTracks())t.stop();return!0}catch{return!1}}async listBrowserOutputDevices(){return navigator.mediaDevices?.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audiooutput").map(t=>({deviceId:t.deviceId,label:t.label||(t.deviceId==="default"?"System Default":`Audio Output (${t.deviceId.slice(0,8)})`),isLikelyDualSense:/wireless controller|dualsense|ps5|dsx/i.test(t.label||"")})):[]}async initPcOutput(e="",t="PC Default Speakers"){let n=window.AudioContext||window.webkitAudioContext;this.pcCtx||(this.pcCtx=new n({latencyHint:"interactive"}));let i=this.pcCtx;return e&&typeof i.setSinkId=="function"&&await i.setSinkId(e),this.pcCtx.state==="suspended"&&await this.pcCtx.resume(),this.pcMasterGain||this.buildPcGraph(),this.pcSinkId=e,this.pcSinkLabel=t,{sinkId:this.pcSinkId,sinkLabel:this.pcSinkLabel,sampleRate:this.pcCtx.sampleRate}}buildPcGraph(){let e=this.pcCtx;this.pcMasterGain=e.createGain(),this.pcMasterGain.gain.value=this.audioMuted?0:this.pcGainValue;let t=e.createDynamicsCompressor();t.threshold.value=-4,t.knee.value=8,t.ratio.value=6;let n=e.createChannelSplitter(2),i=e.createAnalyser(),r=e.createAnalyser();i.fftSize=256,r.fftSize=256,i.smoothingTimeConstant=.55,r.smoothingTimeConstant=.55,this.pcMasterGain.connect(t),t.connect(e.destination),t.connect(n),n.connect(i,0),n.connect(r,1),this.pcAnalysers=[i,r],this.pcNoiseBuffer=this.createNoiseBuffer(e)}async openCompanionWebSocket(e){let t=await this.acquireCompanionSession(),n=new URLSearchParams;t&&n.set("token",t),e&&n.set("device",e);let i=n.toString(),r=`${this.wsBase}/ws/haptics${i?`?${i}`:""}`;return new Promise((o,s)=>{let c=new WebSocket(r);c.binaryType="arraybuffer";let l=setTimeout(()=>{c.close(),s(new Error("Gamepadly Link WASAPI handshake timeout."))},5e3);c.onmessage=u=>{if(typeof u.data=="string")try{let d=JSON.parse(u.data);d.type==="ready"?(clearTimeout(l),o({ws:c,ready:d})):d.type==="error"&&(clearTimeout(l),c.close(),s(new Error(d.message||"WASAPI renderer failed to initialize.")))}catch{}},c.onerror=()=>{clearTimeout(l),s(new Error("Failed to connect to Gamepadly Link WebSocket (check LNA loopback permission)."))}})}attachWsReconnectHandler(e,t){e.onclose=()=>{if(this.dsWs!==e)return;if(this.dsWs=null,this.intentionalWsClose||this.dsMode!=="companion"){this.emitStreamState("idle");return}if(this.reconnectAttempts>=3){this.emitStreamState("disconnected","Gamepadly Link connection lost. Click Connect to retry.");return}let n=800*Math.pow(2,this.reconnectAttempts);this.reconnectAttempts++,this.emitStreamState("reconnecting",`Reconnecting to Gamepadly Link (${this.reconnectAttempts}/3)...`),this.reconnectTimer=window.setTimeout(async()=>{if(this.reconnectTimer=null,!(this.intentionalWsClose||this.dsMode!=="companion"))try{let{ws:i}=await this.openCompanionWebSocket(t);this.dsWs=i,this.reconnectAttempts=0,this.attachWsReconnectHandler(i,t),this.emitStreamState("connected","Gamepadly Link reconnected.")}catch{this.reconnectAttempts<3?(this.attachWsReconnectHandler(e,t),e.onclose?.(new CloseEvent("close"))):this.emitStreamState("disconnected","Gamepadly Link offline.")}},n)}}async connectDualSenseCompanion(e="",t="DualSense WASAPI"){let n=window.AudioContext||window.webkitAudioContext;await this.teardownDsOutput(),this.intentionalWsClose=!1,this.reconnectAttempts=0;let{ws:i,ready:r}=await this.openCompanionWebSocket(e);this.dsWs=i,this.attachWsReconnectHandler(i,r.id||e),this.emitStreamState("connected");let o=r.sampleRate||48e3;this.dsCtx=new n({sampleRate:o,latencyHint:"interactive"}),this.dsCtx.state==="suspended"&&await this.dsCtx.resume(),await this.dsCtx.audioWorklet.addModule("/haptic-worklet.js"),this.dsMode="companion",this.dsSinkId=r.id||e,this.dsSinkLabel=r.name||t,this.dsMaxChannelCount=r.channels||4,this.dsActiveChannelCount=Math.min(4,this.dsMaxChannelCount),this.buildDsGraph(!1),this.dsWorklet=new AudioWorkletNode(this.dsCtx,"gamepadly-wasapi-capture",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],channelCount:4,channelCountMode:"explicit",channelInterpretation:"discrete"});let s=this.dsCtx.createGain();return s.gain.value=0,this.dsMerger.connect(this.dsWorklet),this.dsWorklet.connect(s),s.connect(this.dsCtx.destination),this.dsWorklet.port.onmessage=c=>{this.dsWs&&this.dsWs.readyState===WebSocket.OPEN&&this.dsWs.send(c.data)},{mode:"companion",sinkId:this.dsSinkId,sinkLabel:this.dsSinkLabel,sampleRate:this.dsCtx.sampleRate,maxChannelCount:this.dsMaxChannelCount,activeChannelCount:this.dsActiveChannelCount,isQuadraphonicReady:this.dsMaxChannelCount>=4,state:this.dsCtx.state}}async connectDualSenseBrowserSink(e,t){if(!e)throw new Error("DualSense audio output device ID is empty.");let n=window.AudioContext||window.webkitAudioContext;await this.teardownDsOutput();try{this.dsCtx=new n({latencyHint:"interactive",sinkId:e})}catch{this.dsCtx=new n({latencyHint:"interactive"})}let i=this.dsCtx;typeof i.setSinkId=="function"&&i.sinkId!==e&&await i.setSinkId(e),this.dsCtx.state==="suspended"&&await this.dsCtx.resume();let r=this.dsCtx.destination;this.dsMaxChannelCount=r.maxChannelCount;let o=this.dsMaxChannelCount>=4?4:Math.min(2,this.dsMaxChannelCount);return r.channelCountMode="explicit",r.channelInterpretation="discrete",r.channelCount=o,this.dsActiveChannelCount=r.channelCount,this.dsMode="setsinkid",this.dsSinkId=e,this.dsSinkLabel=t,this.buildDsGraph(!0),{mode:"setsinkid",sinkId:this.dsSinkId,sinkLabel:this.dsSinkLabel,sampleRate:this.dsCtx.sampleRate,maxChannelCount:this.dsMaxChannelCount,activeChannelCount:this.dsActiveChannelCount,isQuadraphonicReady:this.dsMaxChannelCount>=4,state:this.dsCtx.state}}buildDsGraph(e){let t=this.dsCtx;this.dsMerger=t.createChannelMerger(4),this.dsChGains=[],this.dsAnalysers=[];for(let n=0;n<4;n++){let i=t.createGain();i.gain.value=n<2?this.dsSpeakerGainValue:this.dsHapticGainValue;let r=i;if(n>=2){let c=t.createBiquadFilter();c.type="highpass",c.frequency.value=20,c.Q.value=.707,i.connect(c),r=c}let o=t.createDynamicsCompressor();o.threshold.value=-3,o.knee.value=6,o.ratio.value=12,o.attack.value=.0015,o.release.value=.05;let s=t.createAnalyser();s.fftSize=256,s.smoothingTimeConstant=.5,r.connect(o),o.connect(s),s.connect(this.dsMerger,0,n),this.dsChGains.push(i),this.dsAnalysers.push(s)}e&&this.dsMerger.connect(t.destination),this.dsNoiseBuffer=this.createNoiseBuffer(t)}async teardownDsOutput(){if(this.intentionalWsClose=!0,this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopAllContinuous(),this.dsWorklet){try{this.dsWorklet.port.onmessage=null,this.dsWorklet.disconnect()}catch{}this.dsWorklet=null}if(this.dsWs){try{this.dsWs.close()}catch{}this.dsWs=null}if(this.dsCtx){try{await this.dsCtx.close()}catch{}this.dsCtx=null}this.dsMerger=null,this.dsChGains=[],this.dsAnalysers=[],this.dsNoiseBuffer=null,this.dsMode="none"}createNoiseBuffer(e){let t=e.sampleRate*2,n=e.createBuffer(1,t,e.sampleRate),i=n.getChannelData(0);for(let r=0;r<t;r++)i[r]=Math.random()*2-1;return n}async resumeAll(){this.pcCtx||await this.initPcOutput("",this.pcSinkLabel),this.pcCtx&&this.pcCtx.state==="suspended"&&await this.pcCtx.resume(),this.dsCtx&&this.dsCtx.state==="suspended"&&await this.dsCtx.resume()}setGains(e){e.pc!==void 0&&(this.pcGainValue=Math.max(0,Math.min(1.4,e.pc)),this.pcMasterGain&&this.pcCtx&&this.pcMasterGain.gain.setTargetAtTime(this.pcGainValue,this.pcCtx.currentTime,.02)),e.dsSpeaker!==void 0&&(this.dsSpeakerGainValue=Math.max(0,Math.min(1.3,e.dsSpeaker)),this.dsChGains.length>=2&&this.dsCtx&&(this.dsChGains[0].gain.setTargetAtTime(this.dsSpeakerGainValue,this.dsCtx.currentTime,.02),this.dsChGains[1].gain.setTargetAtTime(this.dsSpeakerGainValue,this.dsCtx.currentTime,.02))),e.dsHaptic!==void 0&&(this.dsHapticGainValue=Math.max(0,Math.min(1.4,e.dsHaptic)),this.dsChGains.length>=4&&this.dsCtx&&(this.dsChGains[2].gain.setTargetAtTime(this.dsHapticGainValue,this.dsCtx.currentTime,.02),this.dsChGains[3].gain.setTargetAtTime(this.dsHapticGainValue,this.dsCtx.currentTime,.02)))}getWaveforms(){let e=t=>{if(!t)return null;let n=new Float32Array(t.fftSize);return t.getFloatTimeDomainData(n),n};return{pcL:e(this.pcAnalysers[0]),pcR:e(this.pcAnalysers[1]),dsCh0:e(this.dsAnalysers[0]),dsCh1:e(this.dsAnalysers[1]),dsCh2:e(this.dsAnalysers[2]),dsCh3:e(this.dsAnalysers[3])}}getHapticEnergy(){if(this.dsAnalysers.length<4)return{left:0,right:0};let e=t=>{let n=new Float32Array(t.fftSize);t.getFloatTimeDomainData(n);let i=0;for(let r=0;r<n.length;r++)i+=n[r]*n[r];return Math.min(1,Math.sqrt(i/n.length)*3.5)};return{left:e(this.dsAnalysers[2]),right:e(this.dsAnalysers[3])}}stopAllContinuous(){for(let e of Array.from(this.activeContinuous))try{e.stop()}catch{}this.activeContinuous.clear()}routePc(e,t=0,n=1){if(!this.pcCtx||!this.pcMasterGain)return;let i=this.pcCtx.createGain();i.gain.value=n;let r=this.pcCtx.createStereoPanner();r.pan.value=Math.max(-1,Math.min(1,t)),e.connect(i),i.connect(r),r.connect(this.pcMasterGain)}routeDsSpeakerMonoSafe(e,t=.9){if(!this.dsCtx||this.dsChGains.length<2)return;let n=this.dsCtx.createGain();n.gain.value=t,e.connect(n),n.connect(this.dsChGains[0]),n.connect(this.dsChGains[1])}routeDsVcm(e,t=0,n=1){if(!this.dsCtx||this.dsChGains.length<4)return;let i=Math.max(-1,Math.min(1,t)),r=this.dsCtx.createGain(),o=this.dsCtx.createGain();r.gain.value=Math.cos((i+1)*Math.PI/4)*n,o.gain.value=Math.sin((i+1)*Math.PI/4)*n,e.connect(r),e.connect(o),r.connect(this.dsChGains[2]),o.connect(this.dsChGains[3])}playPcTone(e){if(!this.pcCtx)return;let t=this.pcCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.015,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"sine",r.frequency.setValueAtTime(Math.max(20,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&r.frequency.exponentialRampToValueAtTime(Math.max(20,e.endFreqHz),n+i);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity??.45));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.012,i*.2)),o.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),this.routePc(o,e.pan??0,1),r.start(n),r.stop(n+i+.02)}playPcNoiseBurst(e){if(!this.pcCtx||!this.pcNoiseBuffer)return;let t=this.pcCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.02,e.durationMs/1e3),r=t.createBufferSource();r.buffer=this.pcNoiseBuffer;let o=t.createBiquadFilter();o.type=e.filterType||"bandpass",o.Q.value=e.q??2,o.frequency.setValueAtTime(e.freqHz,n),e.endFreqHz&&o.frequency.exponentialRampToValueAtTime(Math.max(30,e.endFreqHz),n+i);let s=t.createGain(),c=Math.max(.001,Math.min(1,e.intensity??.5));s.gain.setValueAtTime(1e-4,n),s.gain.linearRampToValueAtTime(c,n+Math.min(.015,i*.15)),s.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),o.connect(s),this.routePc(s,e.pan??0,1),r.start(n),r.stop(n+i+.03)}playControllerSpeakerTone(e){if(!this.dsCtx||this.dsChGains.length<2){this.playPcTone({...e,intensity:(e.intensity??.5)*.45});return}let t=this.dsCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.015,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"triangle",r.frequency.setValueAtTime(Math.max(60,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&r.frequency.exponentialRampToValueAtTime(Math.max(60,e.endFreqHz),n+i);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity??.75));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.006,i*.18)),o.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),this.routeDsSpeakerMonoSafe(o,.95),r.start(n),r.stop(n+i+.02)}playHapticPulse(e){if(!this.dsCtx||this.dsChGains.length<4)return;let t=this.dsCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.012,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"sine",r.frequency.setValueAtTime(Math.max(22,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&r.frequency.exponentialRampToValueAtTime(Math.max(22,e.endFreqHz),n+i);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.004,i*.2)),o.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),this.routeDsVcm(o,e.pan??0,1),r.start(n),r.stop(n+i+.02)}playHapticSweep(e){if(!this.dsCtx||this.dsChGains.length<4)return;let t=this.dsCtx,n=t.currentTime,i=Math.max(.04,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"sine",r.frequency.setValueAtTime(Math.max(25,e.fromHz),n),r.frequency.exponentialRampToValueAtTime(Math.max(25,e.toHz),n+i);let o=Math.max(-1,Math.min(1,e.fromPan)),s=Math.max(-1,Math.min(1,e.toPan)),c=t.createGain(),l=t.createGain();c.gain.setValueAtTime(Math.cos((o+1)*Math.PI/4)*e.intensity,n),c.gain.linearRampToValueAtTime(Math.cos((s+1)*Math.PI/4)*e.intensity,n+i),l.gain.setValueAtTime(Math.sin((o+1)*Math.PI/4)*e.intensity,n),l.gain.linearRampToValueAtTime(Math.sin((s+1)*Math.PI/4)*e.intensity,n+i),r.connect(c),r.connect(l),c.connect(this.dsChGains[2]),l.connect(this.dsChGains[3]),r.start(n),r.stop(n+i+.02)}createContinuous(e){let t=!1,n=null,i=null,r=()=>{if(n){try{n.osc.stop(),n.noise?.stop(),n.master.disconnect(),n.spkGain.disconnect()}catch{}n=null}},o=()=>{if(i){try{i.osc.stop(),i.gain.disconnect()}catch{}i=null}},s=()=>{if(!t){if(n&&n.ctx!==this.dsCtx&&r(),!n&&this.dsCtx&&this.dsChGains.length>=4){let l=this.dsCtx,u=l.createOscillator(),d=l.createBiquadFilter(),h=l.createGain(),w=l.createGain(),y=l.createGain(),g=l.createGain();h.gain.value=1e-4,w.gain.value=.7,y.gain.value=.7,g.gain.value=1e-4;let T={ice:{wave:"triangle",f:240,filtF:310,spk:.25},metal:{wave:"sine",f:150,filtF:180,spk:.35},gravel:{wave:"sawtooth",f:82,filtF:150,spk:.2},grass:{wave:"sine",f:65,filtF:110,spk:.1},water:{wave:"sine",f:48,filtF:85,spk:.18},engine:{wave:"sawtooth",f:42,filtF:160,spk:.05},tension:{wave:"sawtooth",f:78,filtF:210,spk:.4}}[e];u.type=T.wave,u.frequency.value=T.f,d.type="lowpass",d.frequency.value=T.filtF;let f;if(this.dsNoiseBuffer&&(e==="water"||e==="gravel"||e==="ice")){f=l.createBufferSource(),f.buffer=this.dsNoiseBuffer,f.loop=!0;let x=l.createGain();x.gain.value=.45,f.connect(x),x.connect(d),f.start()}u.connect(d),d.connect(h),h.connect(w),h.connect(y),w.connect(this.dsChGains[2]),y.connect(this.dsChGains[3]),h.connect(g),g.connect(this.dsChGains[0]),g.connect(this.dsChGains[1]),g.gain.value=T.spk,u.start(),n={ctx:l,osc:u,noise:f,filter:d,master:h,gL:w,gR:y,spkGain:g}}if(i&&i.ctx!==this.pcCtx&&o(),!i&&this.pcCtx&&this.pcMasterGain&&(e==="engine"||e==="tension"||e==="water")){let l=this.pcCtx,u=l.createOscillator();u.type=e==="water"?"sine":"triangle",u.frequency.value=e==="engine"?75:e==="tension"?210:120;let d=l.createGain();d.gain.value=1e-4;let h=l.createStereoPanner();u.connect(d),d.connect(h),h.connect(this.pcMasterGain),u.start(),i={ctx:l,osc:u,gain:d,panner:h}}}};s();let c={update:({intensity:l=0,speed:u=.5,pan:d=0,freqScale:h=1}={})=>{if(t)return;l>.005&&s();let w=Math.max(1e-4,Math.min(1,l)),y=Math.max(-1,Math.min(1,d));if(n&&this.dsCtx&&n.ctx===this.dsCtx){let g=this.dsCtx.currentTime;n.master.gain.setTargetAtTime(w*.85,g,.025),n.gL.gain.setTargetAtTime(Math.cos((y+1)*Math.PI/4),g,.025),n.gR.gain.setTargetAtTime(Math.sin((y+1)*Math.PI/4),g,.025);let v=e==="tension"?68+u*150:e==="engine"?35+u*95:85+u*140;n.osc.frequency.setTargetAtTime(Math.max(25,v*h),g,.03)}if(i&&this.pcCtx&&i.ctx===this.pcCtx){let g=this.pcCtx.currentTime;i.gain.gain.setTargetAtTime(w*.22,g,.03),i.panner.pan.setTargetAtTime(y*.7,g,.03);let v=e==="tension"?180+u*260:70+u*160;i.osc.frequency.setTargetAtTime(Math.max(30,v*h),g,.03)}},stop:()=>{t||(t=!0,this.activeContinuous.delete(c),r(),o())}};return this.activeContinuous.add(c),c}playComboPreset(e,t=0){switch(e){case"ratchet_tick":this.playHapticPulse({pan:t,freqHz:215,endFreqHz:115,durationMs:18,intensity:.52,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:2100,endFreqHz:1150,durationMs:16,intensity:.45,wave:"triangle"});break;case"lock_sweet_spot":this.playHapticPulse({pan:-.45,freqHz:145,endFreqHz:68,durationMs:65,intensity:.95,wave:"sine"}),this.playHapticPulse({pan:.45,freqHz:285,endFreqHz:170,durationMs:48,intensity:.75,wave:"triangle",delayMs:14}),this.playControllerSpeakerTone({freqHz:1480,endFreqHz:860,durationMs:75,intensity:.85,wave:"sine"}),this.playPcTone({freqHz:440,endFreqHz:330,durationMs:110,intensity:.28,pan:t,wave:"sine"});break;case"lock_unlock":this.playHapticSweep({fromPan:-.95,toPan:.95,fromHz:65,toHz:185,durationMs:260,intensity:.95}),this.playControllerSpeakerTone({freqHz:980,endFreqHz:1560,durationMs:120,intensity:.85,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:1560,endFreqHz:2093,durationMs:180,intensity:.8,delayMs:120,wave:"sine"}),this.playPcNoiseBurst({durationMs:520,filterType:"lowpass",freqHz:280,endFreqHz:65,intensity:.85}),this.playPcTone({freqHz:523.25,endFreqHz:783.99,durationMs:360,intensity:.38,delayMs:90,wave:"triangle"});break;case"fish_bite":this.playHapticPulse({pan:t,freqHz:95,endFreqHz:42,durationMs:110,intensity:.95,wave:"sine"}),this.playHapticPulse({pan:-t*.5,freqHz:165,endFreqHz:75,durationMs:75,intensity:.8,delayMs:85}),this.playControllerSpeakerTone({freqHz:1250,endFreqHz:780,durationMs:95,intensity:.85,wave:"sawtooth"}),this.playPcNoiseBurst({durationMs:240,filterType:"bandpass",freqHz:1400,endFreqHz:500,intensity:.6,pan:t});break;case"fish_splash":this.playHapticSweep({fromPan:t,toPan:-t,fromHz:140,toHz:52,durationMs:220,intensity:.85}),this.playPcNoiseBurst({durationMs:420,filterType:"bandpass",freqHz:1800,endFreqHz:420,intensity:.72,pan:t}),this.playControllerSpeakerTone({freqHz:1600,endFreqHz:620,durationMs:110,intensity:.55,wave:"triangle"});break;case"pistol":this.playHapticPulse({pan:.2,freqHz:145,endFreqHz:42,durationMs:80,intensity:1}),this.playHapticPulse({pan:.6,freqHz:260,endFreqHz:135,durationMs:36,intensity:.68,delayMs:55,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:1850,endFreqHz:620,durationMs:48,intensity:.85,delayMs:50,wave:"triangle"}),this.playPcNoiseBurst({durationMs:190,filterType:"lowpass",freqHz:3200,endFreqHz:240,intensity:.75});break;case"shotgun":this.playHapticPulse({pan:0,freqHz:115,endFreqHz:28,durationMs:210,intensity:1}),this.playHapticPulse({pan:-.85,freqHz:210,endFreqHz:105,durationMs:50,intensity:.85,delayMs:260,wave:"sawtooth"}),this.playHapticPulse({pan:.85,freqHz:265,endFreqHz:130,durationMs:50,intensity:.85,delayMs:390,wave:"sawtooth"}),this.playControllerSpeakerTone({freqHz:1100,endFreqHz:520,durationMs:55,intensity:.85,delayMs:260,wave:"sawtooth"}),this.playControllerSpeakerTone({freqHz:1450,endFreqHz:740,durationMs:55,intensity:.85,delayMs:390,wave:"sawtooth"}),this.playPcNoiseBurst({durationMs:420,filterType:"lowpass",freqHz:2800,endFreqHz:110,intensity:.95});break;case"bow_release":this.playHapticPulse({pan:-.35,freqHz:240,endFreqHz:72,durationMs:150,intensity:.95,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:920,endFreqHz:360,durationMs:120,intensity:.85,wave:"triangle"}),this.playPcNoiseBurst({durationMs:210,filterType:"bandpass",freqHz:2200,endFreqHz:600,intensity:.55});break;case"thunder":this.playPcNoiseBurst({durationMs:1650,filterType:"lowpass",freqHz:520,endFreqHz:68,intensity:.95,pan:t}),this.playHapticPulse({pan:t,freqHz:82,endFreqHz:28,durationMs:950,intensity:1,wave:"sawtooth"});break}}async testPcSpeakersLoud(){await this.resumeAll(),this.playPcTone({freqHz:523.25,durationMs:240,intensity:.55,pan:-.85,wave:"sine"}),this.playPcTone({freqHz:659.25,durationMs:260,intensity:.55,pan:.85,delayMs:260,wave:"sine"})}async testDualSenseSpeakerLoud(){if(await this.resumeAll(),!this.dsCtx||this.dsChGains.length<2)throw new Error("DualSense 4-channel audio is not connected yet.");[880,1174.66,1318.51].forEach((t,n)=>{this.playControllerSpeakerTone({freqHz:t,durationMs:200,intensity:.95,delayMs:n*210,wave:"triangle"})})}async testDualSenseVcmLoud(){if(await this.resumeAll(),!this.dsCtx||this.dsChGains.length<4)throw new Error("DualSense 4-channel audio is not connected yet.");this.playHapticPulse({pan:-.95,freqHz:55,endFreqHz:180,durationMs:520,intensity:.95}),this.playHapticPulse({pan:.95,freqHz:180,endFreqHz:55,durationMs:520,intensity:.95,delayMs:560})}async runThreeLayerCalibration(e){await this.resumeAll(),e(1),this.playPcTone({freqHz:523.25,durationMs:320,intensity:.5,pan:-.9}),this.playPcTone({freqHz:659.25,durationMs:320,intensity:.5,pan:.9,delayMs:340}),setTimeout(()=>{e(2),this.playControllerSpeakerTone({freqHz:880,endFreqHz:1174.66,durationMs:480,intensity:.95,wave:"triangle"})},760),setTimeout(()=>{e(3),this.playHapticPulse({pan:-1,freqHz:45,endFreqHz:210,durationMs:650,intensity:.95})},1350),setTimeout(()=>{e(4),this.playHapticPulse({pan:1,freqHz:210,endFreqHz:45,durationMs:650,intensity:.95})},2100),setTimeout(()=>{e(5),this.playHapticSweep({fromPan:-1,toPan:1,fromHz:110,toHz:145,durationMs:850,intensity:.95}),this.playPcTone({freqHz:392,endFreqHz:523.25,durationMs:820,intensity:.35,wave:"triangle"})},2850),setTimeout(()=>e(6),3800)}};function Re(a){return new W(a)}var pe={platformer:{name:"Platformer (WASD / Arrows + Space Jump)",keys:{left:"ArrowLeft",right:"ArrowRight",up:"ArrowUp",down:"ArrowDown","lx-":"ArrowLeft","lx+":"ArrowRight","ly-":"ArrowUp","ly+":"ArrowDown",cross:{code:"Space",hapticOnPress:"click"},square:{code:"KeyZ",hapticOnPress:"recoil",hapticPan:.4},circle:{code:"KeyX",hapticOnPress:"click"},r2:{code:"ShiftLeft",hapticOnPress:"boost",hapticPan:.6},options:"Escape"},triggers:{right:"soft_wall"}},"arcade-4way":{name:"Arcade 4-Way (Grid / Puzzle / Snake / Tetris)",keys:{left:{code:"ArrowLeft",repeatMs:120,hapticOnPress:"ratchet",hapticPan:-.5},right:{code:"ArrowRight",repeatMs:120,hapticOnPress:"ratchet",hapticPan:.5},up:{code:"ArrowUp",repeatMs:120,hapticOnPress:"ratchet"},down:{code:"ArrowDown",repeatMs:90,hapticOnPress:"ratchet"},"lx-":{code:"ArrowLeft",repeatMs:140,hapticOnPress:"ratchet",hapticPan:-.5},"lx+":{code:"ArrowRight",repeatMs:140,hapticOnPress:"ratchet",hapticPan:.5},"ly-":{code:"ArrowUp",repeatMs:140,hapticOnPress:"ratchet"},"ly+":{code:"ArrowDown",repeatMs:100,hapticOnPress:"ratchet"},cross:{code:"Space",hapticOnPress:"click"},circle:"Escape",options:"Enter"}},racing:{name:"Racing (Steer + R2 Gas / L2 ABS Brake)",keys:{left:"ArrowLeft",right:"ArrowRight","lx-":{code:"ArrowLeft",threshold:.25},"lx+":{code:"ArrowRight",threshold:.25},r2:{code:"ArrowUp",threshold:.2},l2:{code:"ArrowDown",threshold:.2},cross:{code:"Space",hapticOnPress:"boost"},square:{code:"ShiftLeft",hapticOnPress:"ratchet"},options:"Escape"},triggers:{left:"abs",right:"bow"}},"twin-stick":{name:"Twin-Stick Shooter (Left Stick Move + Right Stick Aim + R2 Fire)",keys:{"lx-":"KeyA","lx+":"KeyD","ly-":"KeyW","ly+":"KeyS",left:"KeyA",right:"KeyD",up:"KeyW",down:"KeyS",cross:{code:"Space",hapticOnPress:"click"},square:{code:"KeyR",hapticOnPress:"ratchet"},options:"Escape"},pointer:{stick:"right",speedPxPerSec:720,deadzone:.14,clickButton:"r2",secondaryClickButton:"l2",hapticOnClick:"recoil"},triggers:{left:"precision_damp",right:"weapon"}}};var Be={Space:{key:" ",keyCode:32},Enter:{key:"Enter",keyCode:13},Escape:{key:"Escape",keyCode:27},Tab:{key:"Tab",keyCode:9},Backspace:{key:"Backspace",keyCode:8},ArrowLeft:{key:"ArrowLeft",keyCode:37},ArrowUp:{key:"ArrowUp",keyCode:38},ArrowRight:{key:"ArrowRight",keyCode:39},ArrowDown:{key:"ArrowDown",keyCode:40},ShiftLeft:{key:"Shift",keyCode:16},ShiftRight:{key:"Shift",keyCode:16},ControlLeft:{key:"Control",keyCode:17},AltLeft:{key:"Alt",keyCode:18}};function De(a){let e=Be[a.code];if(e)return{code:a.code,key:a.key??e.key,keyCode:a.keyCode??e.keyCode};if(/^Key[A-Z]$/.test(a.code)){let t=a.code.slice(3);return{code:a.code,key:a.key??t.toLowerCase(),keyCode:a.keyCode??t.charCodeAt(0)}}if(/^Digit[0-9]$/.test(a.code)){let t=a.code.slice(5);return{code:a.code,key:a.key??t,keyCode:a.keyCode??t.charCodeAt(0)}}return{code:a.code,key:a.key??a.code,keyCode:a.keyCode??0}}function qe(a){return(Array.isArray(a)?a:[a]).map(t=>typeof t=="string"?{code:t}:t)}function he(a,e){return a==="l2"?e.l2:a==="r2"?e.r2:a==="lx+"?Math.max(0,e.lx):a==="lx-"?Math.max(0,-e.lx):a==="ly+"?Math.max(0,e.ly):a==="ly-"?Math.max(0,-e.ly):a==="rx+"?Math.max(0,e.rx):a==="rx-"?Math.max(0,-e.rx):a==="ry+"?Math.max(0,e.ry):a==="ry-"?Math.max(0,-e.ry):e.buttons[a]?1:0}function Me(a){if(a)return typeof a=="string"?K[a]:a}function ze(a){return"active"in a&&"getSlots"in a}function Z(a,e,t,n=!1){if(typeof KeyboardEvent<"u"){let i=new KeyboardEvent(e,{key:t.key,code:t.code,bubbles:!0,cancelable:!0,repeat:n});try{Object.defineProperty(i,"keyCode",{value:t.keyCode}),Object.defineProperty(i,"which",{value:t.keyCode})}catch{}a.dispatchEvent(i);return}if(typeof Event<"u"){let i=new Event(e,{bubbles:!0,cancelable:!0});i.key=t.key,i.code=t.code,i.keyCode=t.keyCode,i.which=t.keyCode,i.repeat=n,a.dispatchEvent(i)}}function $(a,e,t,n,i,r){let o={bubbles:!0,cancelable:!0,clientX:t,clientY:n,button:i,buttons:r,pointerId:1,pointerType:"mouse",isPrimary:!0};typeof PointerEvent<"u"&&a.dispatchEvent(new PointerEvent(e,o));let s=e.replace("pointer","mouse");typeof MouseEvent<"u"&&a.dispatchEvent(new MouseEvent(s,o))}function st(a){let e=ze(a.player)?a.player:null,t=e?e.active:a.player,n=a.keyTarget??(typeof window<"u"?window:void 0),i=a.pointerTarget!==void 0?a.pointerTarget:typeof document<"u"?document.body:null,r=typeof a.profile=="string"?pe[a.profile]:a.profile,o=!1,s=0,c=0,l=new Map,u=new Map,d={x:0,y:0,down:!1,secondaryDown:!1,visible:!1},h=!1,w=(x,M)=>{typeof x=="string"?t.haptics.playPreset(x,M):t.haptics.pulse({...x,pan:M?.pan??x.pan,intensity:(M?.intensity??1)*x.intensity})},y=()=>{let x=Me(r.triggers?.left),M=Me(r.triggers?.right);x&&M?t.triggers.setBoth(x,M):x?t.triggers.setLeft(x):M?t.triggers.setRight(M):t.triggers.reset()},g=e?e.onCapabilitiesChange(()=>{o&&y()}):null,v=()=>{if(n)for(let{meta:x}of l.values())Z(n,"keyup",x,!1);if(l.clear(),u.clear(),i&&(d.down||d.secondaryDown)){let x=i.getBoundingClientRect?.()??{left:0,top:0};d.down&&$(i,"pointerup",x.left+d.x,x.top+d.y,0,0),d.secondaryDown&&$(i,"pointerup",x.left+d.x,x.top+d.y,2,0)}d.down=!1,d.secondaryDown=!1},T=(x,M=typeof performance<"u"?performance.now():Date.now())=>{let A=x!==void 0?Math.max(0,Math.min(.1,x)):c>0?Math.max(0,Math.min(.1,(M-c)/1e3)):.016666666666666666;c=M;let m=t.input.getState();if(!m.connected||m.source==="keyboard_mouse"){(l.size>0||d.down||d.secondaryDown)&&v();return}let S=new Map;for(let[p,b]of Object.entries(r.keys)){if(!b)continue;let C=p,k=he(C,m),P=qe(b);for(let I=0;I<P.length;I++){let H=P[I],R=H.threshold??.45,B=k>=R,D=`${C}:${H.code}:${I}`,L=u.get(D)??!1;if(u.set(D,B),B){let E=De(H);S.has(E.code)||S.set(E.code,{meta:E,repeatMs:H.repeatMs,repeatDelayMs:H.repeatDelayMs??220}),!L&&H.hapticOnPress&&w(H.hapticOnPress,{pan:H.hapticPan})}}}if(n){for(let[p,b]of l.entries())S.has(p)||(Z(n,"keyup",b.meta,!1),l.delete(p));for(let[p,b]of S.entries()){let C=l.get(p);C?b.repeatMs&&M>=C.nextRepeatAt&&(Z(n,"keydown",b.meta,!0),C.nextRepeatAt=M+b.repeatMs):(Z(n,"keydown",b.meta,!1),l.set(p,{meta:b.meta,nextRepeatAt:b.repeatMs?M+b.repeatDelayMs:Number.POSITIVE_INFINITY}))}}if(r.pointer&&i){let p=r.pointer,b=i.getBoundingClientRect?.()??{left:0,top:0,width:800,height:600},C=Math.max(1,b.width),k=Math.max(1,b.height);h||(d.x=C/2,d.y=k/2,h=!0);let P=p.deadzone??.14,I=F(p.stick==="left"?m.lx:m.rx,P),H=F(p.stick==="left"?m.ly:m.ry,P),R=p.speedPxPerSec??680,B=I!==0||H!==0;B&&(d.x=Math.max(0,Math.min(C,d.x+I*R*A)),d.y=Math.max(0,Math.min(k,d.y+H*R*A)),d.visible=!0);let D=p.clickButton??"r2",L=p.secondaryClickButton??"l2",E=he(D,m)>=.45,G=he(L,m)>=.45,X=(E?1:0)|(G?2:0),Y=b.left+d.x,Q=b.top+d.y;B&&$(i,"pointermove",Y,Q,-1,X),E!==d.down&&(d.down=E,d.visible=!0,$(i,E?"pointerdown":"pointerup",Y,Q,0,X),E&&p.hapticOnClick&&w(p.hapticOnClick)),G!==d.secondaryDown&&(d.secondaryDown=G,d.visible=!0,$(i,G?"pointerdown":"pointerup",Y,Q,2,X)),a.onCursorUpdate?.({...d})}},f=x=>{o&&(T(void 0,x),s=requestAnimationFrame(f))};return{start(){o||(o=!0,c=0,y(),a.autoRaf!==!1&&typeof requestAnimationFrame<"u"&&(s=requestAnimationFrame(f)))},stop(){o&&(o=!1,s&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(s),s=0,v())},tick:T,setProfile(x){v(),r=typeof x=="string"?pe[x]:x,o&&y()},getCursor(){return{...d}},triggerHaptic:w,dispose(){this.stop(),g?.(),t.triggers.reset()}}}function lt(){let a=new Set,e=!1,t=n=>{if(e){try{n()}catch{}return()=>{}}return a.add(n),()=>{if(a.delete(n))try{n()}catch{}}};return{add:t,on(n,i,r,o){return n.addEventListener(i,r,o),t(()=>n.removeEventListener(i,r,o))},timeout(n,i){let r=setTimeout(()=>{a.delete(o),e||n()},i),o=()=>clearTimeout(r);return a.add(o),r},interval(n,i){let r=setInterval(()=>{e||n()},i);return a.add(()=>clearInterval(r)),r},dispose(){if(e)return;e=!0;let n=Array.from(a).reverse();a.clear();for(let i of n)try{i()}catch{}}}}function dt(a,e={}){let t=e.maxDpr??2,n=e.minWidth??320,i=e.minHeight??240,r=document.createElement("canvas");r.style.width="100%",r.style.height="100%",r.style.display="block",r.style.touchAction="none",e.cursor&&(r.style.cursor=e.cursor),a.innerHTML="",a.appendChild(r);let o=r.getContext("2d"),s=n,c=i,l=1,u=()=>{let w=a.getBoundingClientRect(),y=typeof window<"u"&&window.devicePixelRatio||1;l=Math.max(1,Math.min(t,y)),s=Math.max(n,Math.floor(w.width||n)),c=Math.max(i,Math.floor(w.height||i)),r.width=Math.floor(s*l),r.height=Math.floor(c*l),o.setTransform(l,0,0,l,0,0),e.onResize?.(s,c,l)};u();let d=null;typeof ResizeObserver<"u"&&(d=new ResizeObserver(()=>u()),d.observe(a));let h=()=>u();return typeof window<"u"&&window.addEventListener("resize",h),{canvas:r,ctx:o,get width(){return s},get height(){return c},get dpr(){return l},resize:u,dispose(){d?.disconnect(),d=null,typeof window<"u"&&window.removeEventListener("resize",h),r.parentElement===a&&a.removeChild(r)}}}function ut(a){let e=a.maxDelta??.05,t=a.fixedStep,n=a.autoPauseOnHidden!==!1,i=!1,r=!1,o=0,s=0,c=0,l=h=>{if(r){s=h;return}s===0&&(s=h);let w=Math.max(0,(h-s)/1e3);s=h;let y=Math.min(e,w);if(t&&t>0){c+=y;let g=0;for(;c>=t&&g<8;)a.onUpdate(t,h),c-=t,g++;a.onRender?.(c/t,h)}else a.onUpdate(y,h),a.onRender?.(1,h)},u=h=>{i&&(l(h),o=requestAnimationFrame(u))},d=()=>{!n||typeof document>"u"||document.hidden&&(s=0,c=0)};return n&&typeof document<"u"&&document.addEventListener("visibilitychange",d),{start(){i||(i=!0,s=0,c=0,typeof requestAnimationFrame<"u"&&(o=requestAnimationFrame(u)))},stop(){i&&(i=!1,o&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(o),o=0)},pause(){r=!0,s=0},resume(){r=!1,s=0},isPaused(){return r},step:l,dispose(){this.stop(),n&&typeof document<"u"&&document.removeEventListener("visibilitychange",d)}}}export{pe as BUILTIN_BRIDGE_PROFILES,de as COMPANION_HTTP_BASE,ue as COMPANION_WS_BASE,O as ControllerManager,O as DualSenseControllerManager,ie as TACTILE_PRESETS,K as TRIGGER_PRESETS,W as ThreeLayerAudioEngine,F as applyDeadzone,V as buildSwitchHdFromPulse,Se as crc32WithSeed,ce as createActionTracker,dt as createCanvasStage,lt as createDisposables,N as createEmptyInput,ut as createGameLoop,Ie as createGamepadly,st as createKeyMouseBridge,Re as createLinkAudio,U as encodeSwitchHdRumbleSide,z as encodeTriggerEffect,ne as identifyGamepadFromId,j as routeHapticPulse,ae as routeHapticSweep,oe as routeTactilePreset};