brilliantsole 0.0.20 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,5 +2,5 @@
2
2
  * @copyright Zack Qattan 2024
3
3
  * @license MIT
4
4
  */
5
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BS={})}(this,(function(e){"use strict";function t(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)}function s(e,t,s,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,s):n?n.value=s:t.set(e,s),s}"function"==typeof SuppressedError&&SuppressedError;const i=!1,n="undefined"!=typeof window&&void 0!==window?.document,r="undefined"!=typeof process&&null!=process?.versions?.node,a=n&&navigator.userAgent||"";let o=!1;n?o=Boolean(navigator.bluetooth):r&&(o=!0);const c=n&&/Bluefy/i.test(a),h=n&&/WebBLE/i.test(a),l=n&&/Android/i.test(a),g=n&&/Safari/i.test(a)&&!/Chrome/i.test(a),f=n&&/iPad|iPhone|iPod/i.test(a),u=n&&/Macintosh/i.test(a),d=!n&&!r&&"undefined"!=typeof global&&"undefined"!=typeof Studio;var m,p,v,w,y=Object.freeze({__proto__:null,isAndroid:l,get isBluetoothSupported(){return o},isIOS:f,isInBluefy:c,isInBrowser:n,isInDev:i,isInLensStudio:d,isInNode:r,isInProduction:!0,isInWebBLE:h,isMac:u,isSafari:g});if(d){const e=function(...e){Studio.log(e.map((e=>new String(e))).join(","))};(w={}).log=e,w.warn=e.bind(w,"WARNING"),w.error=e.bind(w,"ERROR")}else w=console;if(!w.assert){const e=(e,...t)=>{e||w.warn(...t)};w.assert=e}if(!w.table){const e=(...e)=>{w.log(...e)};w.table=e}function b(){}const S=w.log.bind(w),E=w.warn.bind(w),M=w.error.bind(w),C=w.table.bind(w),D=w.assert.bind(w);class k{constructor(e){if(v.set(this,{log:i,warn:i,assert:!0,error:!0,table:!0}),t(m,m,"f",p)[e])throw new Error(`"${e}" console already exists`);t(m,m,"f",p)[e]=this}setLevelFlags(e){Object.assign(t(this,v,"f"),e)}static setLevelFlagsForType(e,s){if(!t(this,m,"f",p)[e])throw new Error(`no console found with type "${e}"`);t(this,m,"f",p)[e].setLevelFlags(s)}static setAllLevelFlags(e){for(const s in t(this,m,"f",p))t(this,m,"f",p)[s].setLevelFlags(e)}static create(e,s){return t(this,m,"f",p)[e]||new m(e)}get log(){return t(this,v,"f").log?S:b}get warn(){return t(this,v,"f").warn?E:b}get error(){return t(this,v,"f").error?M:b}get assert(){return t(this,v,"f").assert?D:b}get table(){return t(this,v,"f").table?C:b}assertWithError(e,t){if(!Boolean(e))throw new Error(t)}assertTypeWithError(e,t){this.assertWithError(typeof e==t,`value ${e} of type "${typeof e}" not of type "${t}"`)}assertEnumWithError(e,t){this.assertWithError(t.includes(e),`invalid enum "${e}"`)}}function T(e,t){return k.create(e,t)}m=k,v=new WeakMap,p={value:{}};const W=T("EventDispatcher",{log:!1});class _{constructor(e,t){this.target=e,this.validEventTypes=t,this.listeners={},this.addEventListener=this.addEventListener.bind(this),this.removeEventListener=this.removeEventListener.bind(this),this.removeEventListeners=this.removeEventListeners.bind(this),this.removeAllEventListeners=this.removeAllEventListeners.bind(this),this.dispatchEvent=this.dispatchEvent.bind(this),this.waitForEvent=this.waitForEvent.bind(this)}isValidEventType(e){return this.validEventTypes.includes(e)}updateEventListeners(e){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter((t=>(t.shouldRemove&&W.log(`removing "${e}" eventListener`,t),!t.shouldRemove))))}addEventListener(e,t,s={once:!1}){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]||(this.listeners[e]=[],W.log(`creating "${e}" listeners array`,this.listeners[e]));this.listeners[e].find((e=>e.listener==t&&e.once==s.once))?W.log("already added listener"):(W.log(`adding "${e}" listener`,t,s),this.listeners[e].push({listener:t,once:s.once}),W.log(`currently have ${this.listeners[e].length} "${e}" listeners`))}removeEventListener(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(W.log(`removing "${e}" listener...`,t),this.listeners[e].forEach((s=>{s.listener===t&&(W.log(`flagging "${e}" listener`,t),s.shouldRemove=!0)})),this.updateEventListeners(e))}removeEventListeners(e){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(W.log(`removing "${e}" listeners...`),this.listeners[e]=[])}removeAllEventListeners(){W.log("removing listeners..."),this.listeners={}}dispatchEvent(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(this.listeners[e].forEach((s=>{s.shouldRemove||(W.log(`dispatching "${e}" listener`,s),s.listener({type:e,target:this.target,message:t}),s.once&&(W.log(`flagging "${e}" listener`,s),s.shouldRemove=!0))})),this.updateEventListeners(e))}waitForEvent(e){return new Promise((t=>{this.addEventListener(e,(e=>{t(e)}),{once:!0})}))}}var I,L,F;const U=T("Timer",{log:!1});class R{get callback(){return t(this,I,"f")}set callback(e){U.assertTypeWithError(e,"function"),U.log({newCallback:e}),s(this,I,e,"f"),this.isRunning&&this.restart()}get interval(){return t(this,L,"f")}set interval(e){U.assertTypeWithError(e,"number"),U.assertWithError(e>0,"interval must be above 0"),U.log({newInterval:e}),s(this,L,e,"f"),this.isRunning&&this.restart()}constructor(e,t){I.set(this,void 0),L.set(this,void 0),F.set(this,void 0),this.interval=t,this.callback=e}get isRunning(){return null!=t(this,F,"f")}start(e=!1){this.isRunning?U.log("interval already running"):(U.log("starting interval"),s(this,F,setInterval(t(this,I,"f"),t(this,L,"f")),"f"),e&&t(this,I,"f").call(this))}stop(){this.isRunning?(U.log("stopping interval"),clearInterval(t(this,F,"f")),s(this,F,void 0,"f")):U.log("interval already not running")}restart(e=!1){this.stop(),this.start(e)}}function x(e){for(let t=0;t<8;++t)e=(1&e?0:3988292384)^e>>>1;return 4278190080^e}I=new WeakMap,L=new WeakMap,F=new WeakMap,T("checksum",{log:!0});const A=new Uint32Array(256);for(let e=0;e<256;++e)A[e]=x(e);function O(e){let t=new Uint8Array(e),s=0;for(let e=0;e<t.byteLength;++e){const i=255&s,n=t[e];s=(A[i^n]^s>>>8)>>>0}return s}var $,B;$="undefined"==typeof TextEncoder?class{encode(e){const t=Array.from(e).map((e=>e.charCodeAt(0)));return Uint8Array.from(t)}}:TextEncoder,B="undefined"==typeof TextDecoder?class{decode(e){return Array.from(new Uint8Array(e)).map((e=>String.fromCharCode(e))).join("")}}:TextDecoder;const N=new $,P=new B,V=T("ArrayBufferUtils",{log:!1});function z(...e){const t=(e=(e=(e=e.filter((e=>null!=e||null!=e))).map((e=>{if("number"==typeof e){const t=e;return Uint8Array.from([Math.floor(t)])}if("boolean"==typeof e){const t=e;return Uint8Array.from([t?1:0])}if("string"==typeof e){return j(e)}if(e instanceof Array){return z(...e)}if(e instanceof ArrayBuffer)return e;if("buffer"in e&&e.buffer instanceof ArrayBuffer){return e.buffer}if(e instanceof DataView){return e.buffer}if("object"==typeof e){return function(e){return j(JSON.stringify(e))}(e)}return e}))).filter((e=>e&&"byteLength"in e))).reduce(((e,t)=>e+t.byteLength),0),s=new Uint8Array(t);let i=0;return e.forEach((e=>{s.set(new Uint8Array(e),i),i+=e.byteLength})),s.buffer}function j(e){const t=N.encode(e);return z(t.byteLength,t)}function q(e,t,s){let i;return null!=s&&(i=e.byteOffset+t+s),V.log({dataView:e,begin:t,end:i,length:s}),new DataView(e.buffer.slice(e.byteOffset+t,i))}async function G(e){let t;if(e instanceof Array)t=Uint8Array.from(e);else if(e instanceof DataView)t=e.buffer;else if("string"==typeof e||e instanceof URL){const s=await fetch(e);t=await s.arrayBuffer()}else if(e instanceof File)t=await e.arrayBuffer();else{if(!(e instanceof ArrayBuffer))throw{error:"invalid file type",file:e};t=e}return t}function H(e,{include:t,exclude:s}={}){const i=e=>{const i=t=>"string"==typeof t?e===t:t.test(e);return t?t.some(i):!s||!s.some(i)};for(const[t,s]of(e=>{const t=new Set;do{for(const s of Reflect.ownKeys(e))t.add([e,s])}while((e=Reflect.getPrototypeOf(e))&&e!==Object.prototype);return t})(e.constructor.prototype)){if("constructor"===s||!i(s))continue;const n=Reflect.getOwnPropertyDescriptor(t,s);n&&"function"==typeof n.value&&(e[s]=e[s].bind(e))}return e}var J,Q,K,Z,X,Y,ee,te,se,ie,ne,re,ae,oe,ce,he,le,ge,fe,ue,de,me,pe,ve,we,ye,be,Se,Ee,Me,Ce,De,ke,Te,We,_e,Ie,Le;const Fe=T("FileTransferManager",{log:!0}),Ue=["maxFileLength","getFileType","setFileType","getFileLength","setFileLength","getFileChecksum","setFileChecksum","setFileTransferCommand","fileTransferStatus","getFileBlock","setFileBlock","fileBytesTransferred"],Re=["tflite"],xe=["idle","sending","receiving"],Ae=["startSend","startReceive","cancel"],Oe=[...Ue,"fileTransferProgress","fileTransferComplete","fileReceived"];class $e{constructor(){J.add(this),se.set(this,Q.MaxLength),ae.set(this,void 0),le.set(this,0),de.set(this,0),ye.set(this,"idle"),Ce.set(this,[]),ke.set(this,void 0),Te.set(this,0),Le.set(this,!1),H(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}static get MaxLength(){return t(this,Q,"f",te)}get maxLength(){return t(this,se,"f")}get type(){return t(this,ae,"f")}get length(){return t(this,le,"f")}get checksum(){return t(this,de,"f")}get status(){return t(this,ye,"f")}parseMessage(e,s){switch(Fe.log({messageType:e}),e){case"maxFileLength":t(this,J,"m",ie).call(this,s);break;case"getFileType":case"setFileType":t(this,J,"m",oe).call(this,s);break;case"getFileLength":case"setFileLength":t(this,J,"m",ge).call(this,s);break;case"getFileChecksum":case"setFileChecksum":t(this,J,"m",me).call(this,s);break;case"fileTransferStatus":t(this,J,"m",be).call(this,s);break;case"getFileBlock":t(this,J,"m",De).call(this,s);break;case"fileBytesTransferred":t(this,J,"m",Ie).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}async send(e,s){t(this,J,"m",Ee).call(this),t(this,J,"m",Z).call(this,e);const i=await G(s),n=[];n.push(t(this,J,"m",he).call(this,e,!1));const r=i.byteLength;n.push(t(this,J,"m",ue).call(this,r,!1));const a=O(i);n.push(t(this,J,"m",ve).call(this,a,!1)),n.push(t(this,J,"m",we).call(this,"startSend",!1)),this.sendMessage(),await Promise.all(n),await t(this,J,"m",We).call(this,i)}async receive(e){t(this,J,"m",Ee).call(this),t(this,J,"m",Z).call(this,e),await t(this,J,"m",he).call(this,e),await t(this,J,"m",we).call(this,"startReceive")}async cancel(){t(this,J,"m",Me).call(this),await t(this,J,"m",we).call(this,"cancel")}get isServerSide(){return t(this,Le,"f")}set isServerSide(e){t(this,Le,"f")!=e?(Fe.log({newIsServerSide:e}),s(this,Le,e,"f")):Fe.log("redundant isServerSide assignment")}}Q=$e,se=new WeakMap,ae=new WeakMap,le=new WeakMap,de=new WeakMap,ye=new WeakMap,Ce=new WeakMap,ke=new WeakMap,Te=new WeakMap,Le=new WeakMap,J=new WeakSet,K=function(){return this.eventDispatcher.dispatchEvent},Z=function(e){Fe.assertEnumWithError(e,Re)},X=function(e){Fe.assertWithError(e in Re,`invalid typeEnum ${e}`)},Y=function(e){Fe.assertWithError(e in xe,`invalid statusEnum ${e}`)},ee=function(e){Fe.assertEnumWithError(e,Ae)},ie=function(e){Fe.log("parseFileMaxLength",e);const s=e.getUint32(0,!0);Fe.log(`maxLength: ${s/1024}kB`),t(this,J,"m",ne).call(this,s)},ne=function(e){Fe.log({maxLength:e}),s(this,se,e,"f"),t(this,J,"a",K).call(this,"maxFileLength",{maxFileLength:e})},re=function(e){Fe.assertWithError(e<=this.maxLength,`file length ${e}kB too large - must be ${this.maxLength}kB or less`)},oe=function(e){Fe.log("parseFileType",e);const s=e.getUint8(0);t(this,J,"m",X).call(this,s);const i=Re[s];t(this,J,"m",ce).call(this,i)},ce=function(e){Fe.log({fileTransferType:e}),s(this,ae,e,"f"),t(this,J,"a",K).call(this,"getFileType",{fileType:e})},he=async function(e,s){if(t(this,J,"m",Z).call(this,e),this.type==e)return void Fe.log(`redundant type assignment ${e}`);const i=this.waitForEvent("getFileType"),n=Re.indexOf(e);this.sendMessage([{type:"setFileType",data:Uint8Array.from([n]).buffer}],s),await i},ge=function(e){Fe.log("parseFileLength",e);const s=e.getUint32(0,!0);t(this,J,"m",fe).call(this,s)},fe=function(e){Fe.log(`length: ${e/1024}kB`),s(this,le,e,"f"),t(this,J,"a",K).call(this,"getFileLength",{fileLength:e})},ue=async function(e,s){if(Fe.assertTypeWithError(e,"number"),t(this,J,"m",re).call(this,e),this.length==e)return void Fe.log(`redundant length assignment ${e}`);const i=this.waitForEvent("getFileLength"),n=new DataView(new ArrayBuffer(4));n.setUint32(0,e,!0),this.sendMessage([{type:"setFileLength",data:n.buffer}],s),await i},me=function(e){Fe.log("checksum",e);const s=e.getUint32(0,!0);t(this,J,"m",pe).call(this,s)},pe=function(e){Fe.log({checksum:e}),s(this,de,e,"f"),t(this,J,"a",K).call(this,"getFileChecksum",{fileChecksum:e})},ve=async function(e,t){if(Fe.assertTypeWithError(e,"number"),this.checksum==e)return void Fe.log(`redundant checksum assignment ${e}`);const s=this.waitForEvent("getFileChecksum"),i=new DataView(new ArrayBuffer(4));i.setUint32(0,e,!0),this.sendMessage([{type:"setFileChecksum",data:i.buffer}],t),await s},we=async function(e,s){t(this,J,"m",ee).call(this,e);const i=this.waitForEvent("fileTransferStatus"),n=Ae.indexOf(e);this.sendMessage([{type:"setFileTransferCommand",data:Uint8Array.from([n]).buffer}],s),await i},be=function(e){Fe.log("parseFileStatus",e);const s=e.getUint8(0);t(this,J,"m",Y).call(this,s);const i=xe[s];t(this,J,"m",Se).call(this,i)},Se=function(e){Fe.log({status:e}),s(this,ye,e,"f"),t(this,J,"a",K).call(this,"fileTransferStatus",{fileTransferStatus:e}),t(this,Ce,"f").length=0},Ee=function(){Fe.assertWithError("idle"==t(this,ye,"f"),"status is not idle")},Me=function(){Fe.assertWithError("idle"!=t(this,ye,"f"),"status is idle")},De=async function(e){Fe.log("parseFileBlock",e),t(this,Ce,"f").push(e.buffer);const s=t(this,Ce,"f").reduce(((e,t)=>e+t.byteLength),0),i=s/t(this,le,"f");if(Fe.log(`received ${s} of ${t(this,le,"f")} bytes (${100*i}%)`),t(this,J,"a",K).call(this,"fileTransferProgress",{progress:i}),s!=t(this,le,"f")){const e=new DataView(new ArrayBuffer(4));if(e.setUint32(0,s,!0),this.isServerSide)return;return void await this.sendMessage([{type:"fileBytesTransferred",data:e.buffer}])}Fe.log("file transfer complete");let n,r=(new Date).toLocaleString();if("tflite"===this.type)r+=".tflite";n="undefined"!=typeof File?new File(t(this,Ce,"f"),r):new Blob(t(this,Ce,"f"));const a=O(await n.arrayBuffer());Fe.log({checksum:a}),a==t(this,de,"f")?(Fe.log("received file",n),t(this,J,"a",K).call(this,"getFileBlock",{fileTransferBlock:e}),t(this,J,"a",K).call(this,"fileTransferComplete",{direction:"receiving"}),t(this,J,"a",K).call(this,"fileReceived",{file:n})):Fe.error(`wrong checksum - expected ${t(this,de,"f")}, got ${a}`)},We=async function(e){return s(this,ke,e,"f"),s(this,Te,0,"f"),t(this,J,"m",_e).call(this)},_e=async function(){if("sending"!=this.status)return;if(!t(this,ke,"f"))return void(this.isServerSide||Fe.error("no buffer defined"));const e=t(this,ke,"f");let i=t(this,Te,"f");const n=e.slice(i,i+(this.mtu-3-3));Fe.log("slicedBuffer",n);const r=1-(e.byteLength-i)/e.byteLength;Fe.log(`sending bytes ${i}-${i+n.byteLength} of ${e.byteLength} bytes (${100*r}%)`),t(this,J,"a",K).call(this,"fileTransferProgress",{progress:r}),0==n.byteLength?(Fe.log("finished sending buffer"),t(this,J,"a",K).call(this,"fileTransferComplete",{direction:"sending"})):(await this.sendMessage([{type:"setFileBlock",data:n}]),s(this,Te,i+n.byteLength,"f"))},Ie=async function(e){Fe.log("parseBytesTransferred",e);const s=e.getUint32(0,!0);if(Fe.log({bytesTransferred:s}),"sending"==this.status)return this.isServerSide||t(this,Te,"f")==s?void t(this,J,"m",_e).call(this):(Fe.error(`bytesTransferred are not equal - got ${s}, expected ${t(this,Te,"f")}`),void this.cancel());Fe.error("not currently sending file")},te={value:0};const Be=T("MathUtils",{log:!0});const Ne=65536;function Pe(e,t){const s=Date.now();var i;let n=(i=s)-i%Ne+e.getUint16(t,!0);return Math.abs(s-n)>6e4&&(Be.log("correcting timestamp delta"),n+=Ne*Math.sign(s-n)),n}var Ve,ze,je;const qe={min:1/0,max:-1/0,span:0};class Ge{constructor(){Ve.add(this),ze.set(this,Object.assign({},qe))}get min(){return t(this,ze,"f").min}get max(){return t(this,ze,"f").max}set min(e){t(this,ze,"f").min=e,t(this,ze,"f").max=Math.max(e,t(this,ze,"f").max),t(this,Ve,"m",je).call(this)}set max(e){t(this,ze,"f").max=e,t(this,ze,"f").min=Math.min(e,t(this,ze,"f").min),t(this,Ve,"m",je).call(this)}reset(){Object.assign(t(this,ze,"f"),qe)}update(e){t(this,ze,"f").min=Math.min(e,t(this,ze,"f").min),t(this,ze,"f").max=Math.max(e,t(this,ze,"f").max),t(this,Ve,"m",je).call(this)}getNormalization(e,s){let i=function(e,t,s,i){return null==i&&(i=s-t),(e-t)/i}(e,t(this,ze,"f").min,t(this,ze,"f").max,t(this,ze,"f").span);return s&&(i*=t(this,ze,"f").span),i||0}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}var He,Je,Qe,Ke;ze=new WeakMap,Ve=new WeakSet,je=function(){t(this,ze,"f").span=t(this,ze,"f").max-t(this,ze,"f").min};class Ze{constructor(){He.set(this,{x:new Ge,y:new Ge})}reset(){t(this,He,"f").x.reset(),t(this,He,"f").y.reset()}update(e){t(this,He,"f").x.update(e.x),t(this,He,"f").y.update(e.y)}getNormalization(e){return{x:t(this,He,"f").x.getNormalization(e.x,!1),y:t(this,He,"f").y.getNormalization(e.y,!1)}}updateAndGetNormalization(e){return this.update(e),this.getNormalization(e)}}He=new WeakMap;const Xe=T("PressureDataManager",{log:!0}),Ye=["pressure"],et=Ye;class tt{constructor(){Je.set(this,[]),Qe.set(this,void 0),Ke.set(this,new Ze)}get positions(){return t(this,Je,"f")}get numberOfSensors(){return this.positions.length}parsePositions(e){const t=[];for(let s=0,i=0;i<e.byteLength;s++,i+=2)t.push({x:e.getUint8(i)/256,y:e.getUint8(i+1)/256});var i,n;Xe.log({positions:t}),s(this,Je,t,"f"),s(this,Qe,(i=this.numberOfSensors,n=()=>new Ge,new Array(i).fill(1).map(((e,t)=>{if("function"==typeof n)return n(t);{const e=n;return Object.assign({},e)}}))),"f"),this.resetRange()}resetRange(){t(this,Qe,"f").forEach((e=>e.reset())),t(this,Ke,"f").reset()}parseData(e,s){const i={sensors:[],scaledSum:0,normalizedSum:0};for(let n=0,r=0;r<e.byteLength;n++,r+=2){const a=e.getUint16(r,!0),o=a*s,c=t(this,Qe,"f")[n].updateAndGetNormalization(o,!0),h=this.positions[n];i.sensors[n]={rawValue:a,scaledValue:o,normalizedValue:c,position:h,weightedValue:0},i.scaledSum+=o,i.normalizedSum+=c/this.numberOfSensors}return i.scaledSum>0&&i.normalizedSum>.001&&(i.center={x:0,y:0},i.sensors.forEach((e=>{e.weightedValue=e.scaledValue/i.scaledSum,i.center.x+=e.position.x*e.weightedValue,i.center.y+=e.position.y*e.weightedValue})),i.normalizedCenter=t(this,Ke,"f").updateAndGetNormalization(i.center)),Xe.log({pressure:i}),i}}Je=new WeakMap,Qe=new WeakMap,Ke=new WeakMap;const st=T("MotionSensorDataManager",{log:!0}),it=["still","walking","running","bicycle","vehicle","tilting"],nt=["portraitUpright","landscapeLeft","portraitUpsideDown","landscapeRight","unknown"];class rt{parseVector3(e,t){let[s,i,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));const r={x:s,y:i,z:n};return st.log({vector:r}),r}parseQuaternion(e,t){let[s,i,n,r]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0),e.getInt16(6,!0)].map((e=>e*t));const a={x:s,y:i,z:n,w:r};return st.log({quaternion:a}),a}parseEuler(e,t){let[s,i,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));i*=-1,s*=-1,s+=360;const r={heading:s,pitch:i,roll:n};return st.log({euler:r}),r}parseStepCounter(e){st.log("parseStepCounter",e);const t=e.getUint32(0,!0);return st.log({stepCount:t}),t}parseActivity(e){st.log("parseActivity",e);const t={},s=e.getUint8(0);return st.log("activityBitfield",s.toString(2)),it.forEach(((e,i)=>{t[e]=Boolean(s&1<<i)})),st.log("activity",t),t}parseDeviceOrientation(e){st.log("parseDeviceOrientation",e);const t=e.getUint8(0),s=nt[t];return st.assertWithError(s,"undefined deviceOrientation"),st.log({deviceOrientation:s}),s}}var at,ot;const ct=["barometer"],ht=ct,lt=T("BarometerSensorDataManager",{log:!0});class gt{constructor(){at.add(this)}parseData(e,s){const i=e.getUint32(0,!0)*s,n=t(this,at,"m",ot).call(this,i);return lt.log({pressure:i,altitude:n}),{pressure:i}}}at=new WeakSet,ot=function(e){const t=.0065;return 288.15/t*(1-Math.pow(e/101325,.19026643566373183))};const ft=T("ParseUtils",{log:!0});function ut(e,t=0){const s=e.getUint8(t++);return{string:P.decode(e.buffer.slice(e.byteOffset+t,e.byteOffset+t+s)),byteOffset:t+=s}}function dt(e,t,s,i,n=!1){let r=0;for(;r<e.byteLength;){const a=e.getUint8(r++);ft.assertWithError(a in t,`invalid messageTypeEnum ${a}`);const o=t[a];let c;n?(c=e.getUint16(r,!0),r+=2):c=e.getUint8(r++),ft.log({messageTypeEnum:a,messageType:o,messageLength:c,dataView:e,byteOffset:r});const h=q(e,r,c);ft.log({_dataView:h}),s(o,h,i),r+=c}}var mt;const pt=T("SensorDataManager",{log:!0}),vt=[...Ye,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation","activity","stepCounter","stepDetector","deviceOrientation",...ct],wt=[...et,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation",...ht],yt=["getPressurePositions","getSensorScalars","sensorData"],bt=[...yt,...vt];class St{constructor(){this.pressureSensorDataManager=new tt,this.motionSensorDataManager=new rt,this.barometerSensorDataManager=new gt,mt.set(this,new Map)}static AssertValidSensorType(e){pt.assertEnumWithError(e,vt)}static AssertValidSensorTypeEnum(e){pt.assertTypeWithError(e,"number"),pt.assertWithError(e in vt,`invalid sensorTypeEnum ${e}`)}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}parseMessage(e,t){switch(pt.log({messageType:e}),e){case"getSensorScalars":this.parseScalars(t);break;case"getPressurePositions":this.pressureSensorDataManager.parsePositions(t);break;case"sensorData":this.parseData(t);break;default:throw Error(`uncaught messageType ${e}`)}}parseScalars(e){for(let s=0;s<e.byteLength;s+=5){const i=e.getUint8(s),n=vt[i];if(!n){pt.warn(`unknown sensorType index ${i}`);continue}const r=e.getFloat32(s+1,!0);pt.log({sensorType:n,sensorScalar:r}),t(this,mt,"f").set(n,r)}}parseData(e){pt.log("sensorData",Array.from(new Uint8Array(e.buffer)));let t=0;const s=Pe(e,t);t+=2;dt(new DataView(e.buffer,t),vt,this.parseDataCallback.bind(this),{timestamp:s})}parseDataCallback(e,s,{timestamp:i}){const n=t(this,mt,"f").get(e)||1;let r=null;switch(e){case"pressure":r=this.pressureSensorDataManager.parseData(s,n);break;case"acceleration":case"gravity":case"linearAcceleration":case"gyroscope":case"magnetometer":r=this.motionSensorDataManager.parseVector3(s,n);break;case"gameRotation":case"rotation":r=this.motionSensorDataManager.parseQuaternion(s,n);break;case"orientation":r=this.motionSensorDataManager.parseEuler(s,n);break;case"stepCounter":r=this.motionSensorDataManager.parseStepCounter(s);break;case"stepDetector":r={};break;case"activity":r=this.motionSensorDataManager.parseActivity(s);break;case"deviceOrientation":r=this.motionSensorDataManager.parseDeviceOrientation(s);break;case"barometer":r=this.barometerSensorDataManager.parseData(s,n);break;default:pt.error(`uncaught sensorType "${e}"`)}pt.assertWithError(null!=r,`no sensorData defined for sensorType "${e}"`),pt.log({sensorType:e,sensorData:r}),this.dispatchEvent(e,{sensorType:e,[e]:r,timestamp:i}),this.dispatchEvent("sensorData",{sensorType:e,[e]:r,timestamp:i})}}var Et,Mt,Ct,Dt,kt,Tt,Wt,_t,It,Lt,Ft,Ut,Rt;mt=new WeakMap;const xt=T("SensorConfigurationManager",{log:!0}),At=["getSensorConfiguration","setSensorConfiguration"],Ot=At;class $t{constructor(){Et.add(this),Dt.set(this,void 0),Tt.set(this,void 0),H(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get configuration(){return t(this,Tt,"f")}async setConfiguration(e,s){if(s&&(e=Object.assign({...this.zeroSensorConfiguration},e)),xt.log({newSensorConfiguration:e}),t(this,Et,"m",_t).call(this,e))return void xt.log("redundant sensor configuration");const i=t(this,Et,"m",Ut).call(this,e);xt.log({setSensorConfigurationData:i});const n=this.waitForEvent("getSensorConfiguration");this.sendMessage([{type:"setSensorConfiguration",data:i.buffer}]),await n}static get ZeroSensorConfiguration(){return t(this,Mt,"f",Rt)}get zeroSensorConfiguration(){const e={};return vt.forEach((t=>{e[t]=0})),e}async clearSensorConfiguration(){return this.setConfiguration(this.zeroSensorConfiguration)}parseMessage(e,s){switch(xt.log({messageType:e}),e){case"getSensorConfiguration":case"setSensorConfiguration":const i=t(this,Et,"m",It).call(this,s);t(this,Et,"m",Wt).call(this,i);break;default:throw Error(`uncaught messageType ${e}`)}}}var Bt,Nt,Pt,Vt,zt,jt,qt,Gt,Ht,Jt,Qt,Kt,Zt,Xt,Yt,es,ts,ss,is,ns,rs,as,os,cs,hs,ls,gs,fs,us,ds;Mt=$t,Dt=new WeakMap,Tt=new WeakMap,Et=new WeakSet,Ct=function(){return this.eventDispatcher.dispatchEvent},kt=function(e){xt.assertWithError(t(this,Dt,"f"),"must get initial sensorConfiguration");const s=t(this,Dt,"f")?.includes(e);return xt.assert(s,`unavailable sensor type "${e}"`),s},Wt=function(e){s(this,Tt,e,"f"),xt.log({updatedConfiguration:t(this,Tt,"f")}),t(this,Et,"a",Ct).call(this,"getSensorConfiguration",{sensorConfiguration:this.configuration})},_t=function(e){return Object.keys(e).every((t=>this.configuration[t]==e[t]))},It=function(e){const t={};for(let s=0;s<e.byteLength;s+=3){const i=e.getUint8(s),n=vt[i];if(!n){xt.warn(`unknown sensorType index ${i}`);continue}const r=e.getUint16(s+1,!0);xt.log({sensorType:n,sensorRate:r}),t[n]=r}return xt.log({parsedSensorConfiguration:t}),s(this,Dt,Object.keys(t),"f"),t},Lt=function(e){xt.assertTypeWithError(e,"number"),xt.assertWithError(e>=0,`sensorRate must be 0 or greater (got ${e})`),xt.assertWithError(e<65535,`sensorRate must be 0 or greater (got ${e})`),xt.assertWithError(e%5==0,"sensorRate must be multiple of 5")},Ft=function(e){t(Mt,Mt,"m",Lt).call(Mt,e)},Ut=function(e){let s=Object.keys(e);s=s.filter((e=>t(this,Et,"m",kt).call(this,e)));const i=new DataView(new ArrayBuffer(3*s.length));return s.forEach(((s,n)=>{St.AssertValidSensorType(s);const r=vt.indexOf(s);i.setUint8(3*n,r);const a=e[s];t(this,Et,"m",Ft).call(this,a),i.setUint16(3*n+1,a,!0)})),xt.log({sensorConfigurationData:i}),i},Rt={value:{}},vt.forEach((e=>{t(Mt,Mt,"f",Rt)[e]=0}));const ms=T("TfliteManager",{log:!0}),ps=["getTfliteName","setTfliteName","getTfliteTask","setTfliteTask","getTfliteSampleRate","setTfliteSampleRate","getTfliteSensorTypes","setTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","setTfliteCaptureDelay","getTfliteThreshold","setTfliteThreshold","getTfliteInferencingEnabled","setTfliteInferencingEnabled","tfliteInference"],vs=ps,ws=["classification","regression"],ys=["pressure","linearAcceleration","gyroscope","magnetometer"];class bs{constructor(){Bt.add(this),zt.set(this,void 0),Gt.set(this,void 0),Qt.set(this,void 0),Xt.set(this,[]),ts.set(this,void 0),rs.set(this,void 0),cs.set(this,void 0),gs.set(this,void 0),H(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get name(){return t(this,zt,"f")}async setName(e,t){if(ms.assertTypeWithError(e,"string"),this.name==e)return void ms.log(`redundant name assignment ${e}`);const s=this.waitForEvent("getTfliteName"),i=N.encode(e);this.sendMessage([{type:"setTfliteName",data:i.buffer}],t),await s}get task(){return t(this,Gt,"f")}async setTask(e,s){if(t(this,Bt,"m",Nt).call(this,e),this.task==e)return void ms.log(`redundant task assignment ${e}`);const i=this.waitForEvent("getTfliteTask"),n=ws.indexOf(e);this.sendMessage([{type:"setTfliteTask",data:Uint8Array.from([n]).buffer}],s),await i}get sampleRate(){return t(this,Qt,"f")}async setSampleRate(e,s){if(ms.assertTypeWithError(e,"number"),e-=e%5,ms.assertWithError(e>=5,`sampleRate must be multiple of 5 greater than 0 (got ${e})`),t(this,Qt,"f")==e)return void ms.log(`redundant sampleRate assignment ${e}`);const i=this.waitForEvent("getTfliteSampleRate"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteSampleRate",data:n.buffer}],s),await i}static AssertValidSensorType(e){St.AssertValidSensorType(e),ms.assertWithError(ys.includes(e),`invalid tflite sensorType "${e}"`)}get sensorTypes(){return t(this,Xt,"f").slice()}async setSensorTypes(e,t){e.forEach((e=>{bs.AssertValidSensorType(e)}));const s=this.waitForEvent("getTfliteSensorTypes");var i;const n=(e=(i=e).filter(((e,t)=>i.indexOf(e)==t))).map((e=>vt.indexOf(e))).sort();ms.log(e,n),this.sendMessage([{type:"setTfliteSensorTypes",data:Uint8Array.from(n).buffer}],t),await s}get isReady(){return t(this,ts,"f")}get captureDelay(){return t(this,rs,"f")}async setCaptureDelay(e,s){if(ms.assertTypeWithError(e,"number"),t(this,rs,"f")==e)return void ms.log(`redundant captureDelay assignment ${e}`);const i=this.waitForEvent("getTfliteCaptureDelay"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteCaptureDelay",data:n.buffer}],s),await i}get threshold(){return t(this,cs,"f")}async setThreshold(e,s){if(ms.assertTypeWithError(e,"number"),ms.assertWithError(e>=0,`threshold must be positive (got ${e})`),t(this,cs,"f")==e)return void ms.log(`redundant threshold assignment ${e}`);const i=this.waitForEvent("getTfliteThreshold"),n=new DataView(new ArrayBuffer(4));n.setFloat32(0,e,!0),this.sendMessage([{type:"setTfliteThreshold",data:n.buffer}],s),await i}get inferencingEnabled(){return t(this,gs,"f")}async setInferencingEnabled(e,s=!0){if(ms.assertTypeWithError(e,"boolean"),!e&&!this.isReady)return;if(t(this,Bt,"m",ns).call(this),t(this,gs,"f")==e)return void ms.log(`redundant inferencingEnabled assignment ${e}`);const i=this.waitForEvent("getTfliteInferencingEnabled");this.sendMessage([{type:"setTfliteInferencingEnabled",data:Uint8Array.from([Number(e)]).buffer}],s),await i}async toggleInferencingEnabled(){return this.setInferencingEnabled(!this.inferencingEnabled)}async enableInferencing(){this.inferencingEnabled||this.setInferencingEnabled(!0)}async disableInferencing(){this.inferencingEnabled&&this.setInferencingEnabled(!1)}parseMessage(e,s){switch(ms.log({messageType:e}),e){case"getTfliteName":case"setTfliteName":t(this,Bt,"m",jt).call(this,s);break;case"getTfliteTask":case"setTfliteTask":t(this,Bt,"m",Ht).call(this,s);break;case"getTfliteSampleRate":case"setTfliteSampleRate":t(this,Bt,"m",Kt).call(this,s);break;case"getTfliteSensorTypes":case"setTfliteSensorTypes":t(this,Bt,"m",Yt).call(this,s);break;case"tfliteIsReady":t(this,Bt,"m",ss).call(this,s);break;case"getTfliteCaptureDelay":case"setTfliteCaptureDelay":t(this,Bt,"m",as).call(this,s);break;case"getTfliteThreshold":case"setTfliteThreshold":t(this,Bt,"m",hs).call(this,s);break;case"getTfliteInferencingEnabled":case"setTfliteInferencingEnabled":t(this,Bt,"m",fs).call(this,s);break;case"tfliteInference":t(this,Bt,"m",ds).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}}var Ss,Es,Ms,Cs,Ds;zt=new WeakMap,Gt=new WeakMap,Qt=new WeakMap,Xt=new WeakMap,ts=new WeakMap,rs=new WeakMap,cs=new WeakMap,gs=new WeakMap,Bt=new WeakSet,Nt=function(e){ms.assertEnumWithError(e,ws)},Pt=function(e){ms.assertWithError(e in ws,`invalid taskEnum ${e}`)},Vt=function(){return this.eventDispatcher.dispatchEvent},jt=function(e){ms.log("parseName",e);const s=P.decode(e.buffer);t(this,Bt,"m",qt).call(this,s)},qt=function(e){ms.log({name:e}),s(this,zt,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteName",{tfliteName:e})},Ht=function(e){ms.log("parseTask",e);const s=e.getUint8(0);t(this,Bt,"m",Pt).call(this,s);const i=ws[s];t(this,Bt,"m",Jt).call(this,i)},Jt=function(e){ms.log({task:e}),s(this,Gt,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteTask",{tfliteTask:e})},Kt=function(e){ms.log("parseSampleRate",e);const s=e.getUint16(0,!0);t(this,Bt,"m",Zt).call(this,s)},Zt=function(e){ms.log({sampleRate:e}),s(this,Qt,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteSampleRate",{tfliteSampleRate:e})},Yt=function(e){ms.log("parseSensorTypes",e);const s=[];for(let t=0;t<e.byteLength;t++){const i=e.getUint8(t),n=vt[i];n?s.push(n):ms.error(`invalid sensorTypeEnum ${i}`)}t(this,Bt,"m",es).call(this,s)},es=function(e){ms.log({sensorTypes:e}),s(this,Xt,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteSensorTypes",{tfliteSensorTypes:e})},ss=function(e){ms.log("parseIsReady",e);const s=Boolean(e.getUint8(0));t(this,Bt,"m",is).call(this,s)},is=function(e){ms.log({isReady:e}),s(this,ts,e,"f"),t(this,Bt,"a",Vt).call(this,"tfliteIsReady",{tfliteIsReady:e})},ns=function(){ms.assertWithError(this.isReady,"tflite is not ready")},as=function(e){ms.log("parseCaptureDelay",e);const s=e.getUint16(0,!0);t(this,Bt,"m",os).call(this,s)},os=function(e){ms.log({captureDelay:e}),s(this,rs,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteCaptureDelay",{tfliteCaptureDelay:e})},hs=function(e){ms.log("parseThreshold",e);const s=e.getFloat32(0,!0);t(this,Bt,"m",ls).call(this,s)},ls=function(e){ms.log({threshold:e}),s(this,cs,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteThreshold",{tfliteThreshold:e})},fs=function(e){ms.log("parseInferencingEnabled",e);const s=Boolean(e.getUint8(0));t(this,Bt,"m",us).call(this,s)},us=function(e){ms.log({inferencingEnabled:e}),s(this,gs,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteInferencingEnabled",{tfliteInferencingEnabled:e})},ds=function(e){ms.log("parseInference",e);const s=Pe(e,0);ms.log({timestamp:s});const i=[];for(let t=0,s=2;s<e.byteLength;t++,s+=4){const t=e.getFloat32(s,!0);i.push(t)}ms.log("values",i);const n={timestamp:s,values:i};if("classification"==this.task){let e=0,t=0;i.forEach(((s,i)=>{s>e&&(e=s,t=i)})),ms.log({maxIndex:t,maxValue:e}),n.maxIndex=t,n.maxValue=e}t(this,Bt,"a",Vt).call(this,"tfliteInference",{tfliteInference:n})};const ks=T("DeviceInformationManager",{log:!0}),Ts=["manufacturerName","modelNumber","softwareRevision","hardwareRevision","firmwareRevision","pnpId","serialNumber"],Ws=[...Ts,"deviceInformation"];class _s{constructor(){Ss.add(this),Ms.set(this,{})}get information(){return t(this,Ms,"f")}clear(){s(this,Ms,{},"f")}parseMessage(e,s){switch(ks.log({messageType:e}),e){case"manufacturerName":const i=P.decode(s.buffer);ks.log({manufacturerName:i}),t(this,Ss,"m",Ds).call(this,{manufacturerName:i});break;case"modelNumber":const n=P.decode(s.buffer);ks.log({modelNumber:n}),t(this,Ss,"m",Ds).call(this,{modelNumber:n});break;case"softwareRevision":const r=P.decode(s.buffer);ks.log({softwareRevision:r}),t(this,Ss,"m",Ds).call(this,{softwareRevision:r});break;case"hardwareRevision":const a=P.decode(s.buffer);ks.log({hardwareRevision:a}),t(this,Ss,"m",Ds).call(this,{hardwareRevision:a});break;case"firmwareRevision":const o=P.decode(s.buffer);ks.log({firmwareRevision:o}),t(this,Ss,"m",Ds).call(this,{firmwareRevision:o});break;case"pnpId":const c={source:1===s.getUint8(0)?"Bluetooth":"USB",productId:s.getUint16(3,!0),productVersion:s.getUint16(5,!0),vendorId:0};"Bluetooth"==c.source&&(c.vendorId=s.getUint16(1,!0)),ks.log({pnpId:c}),t(this,Ss,"m",Ds).call(this,{pnpId:c});break;case"serialNumber":const h=P.decode(s.buffer);ks.log({serialNumber:h});break;default:throw Error(`uncaught messageType ${e}`)}}}var Is,Ls,Fs,Us,Rs,xs,As,Os,$s,Bs,Ns,Ps,Vs,zs,js,qs,Gs,Hs;Ms=new WeakMap,Ss=new WeakSet,Es=function(){return this.eventDispatcher.dispatchEvent},Cs=function(){return Ts.every((e=>e in t(this,Ms,"f")))},Ds=function(e){ks.log({partialDeviceInformation:e});Object.keys(e).forEach((s=>{t(this,Ss,"a",Es).call(this,s,{[s]:e[s]})})),Object.assign(t(this,Ms,"f"),e),ks.log({deviceInformation:t(this,Ms,"f")}),t(this,Ss,"a",Cs)&&(ks.log("completed deviceInformation"),t(this,Ss,"a",Es).call(this,"deviceInformation",{deviceInformation:this.information}))};const Js=T("InformationManager",{log:!0}),Qs=["leftInsole","rightInsole"],Ks=["left","right"],Zs=["isCharging","getBatteryCurrent","getMtu","getId","getName","setName","getType","setType","getCurrentTime","setCurrentTime"],Xs=Zs;class Ys{constructor(){Is.add(this),Fs.set(this,!1),Rs.set(this,void 0),As.set(this,void 0),$s.set(this,""),Bs.set(this,void 0),zs.set(this,0),qs.set(this,!1),H(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}get isCharging(){return t(this,Fs,"f")}get batteryCurrent(){return t(this,Rs,"f")}async getBatteryCurrent(){Js.log("getting battery current...");const e=this.waitForEvent("getBatteryCurrent");this.sendMessage([{type:"getBatteryCurrent"}]),await e}get id(){return t(this,As,"f")}get name(){return t(this,$s,"f")}updateName(e){Js.assertTypeWithError(e,"string"),s(this,$s,e,"f"),Js.log({updatedName:t(this,$s,"f")}),t(this,Is,"a",Ls).call(this,"getName",{name:t(this,$s,"f")})}async setName(e){Js.assertTypeWithError(e,"string"),Js.assertWithError(e.length>=2,`name must be greater than 2 characters long ("${e}" is ${e.length} characters long)`),Js.assertWithError(e.length<30,`name must be less than 30 characters long ("${e}" is ${e.length} characters long)`);const t=N.encode(e);Js.log({setNameData:t});const s=this.waitForEvent("getName");this.sendMessage([{type:"setName",data:t.buffer}]),await s}get type(){return t(this,Bs,"f")}get typeEnum(){return Qs.indexOf(this.type)}updateType(e){t(this,Is,"m",Ns).call(this,e),e!=this.type?(s(this,Bs,e,"f"),Js.log({updatedType:t(this,Bs,"f")}),t(this,Is,"a",Ls).call(this,"getType",{type:t(this,Bs,"f")})):Js.log("redundant type assignment")}async setType(e){t(this,Is,"m",Ns).call(this,e);const s=Qs.indexOf(e);t(this,Is,"m",Vs).call(this,s)}get isInsole(){switch(this.type){case"leftInsole":case"rightInsole":return!0;default:return!1}}get insoleSide(){switch(this.type){case"leftInsole":return"left";case"rightInsole":return"right"}}get mtu(){return t(this,zs,"f")}get isCurrentTimeSet(){return t(this,qs,"f")}parseMessage(e,s){switch(Js.log({messageType:e}),e){case"isCharging":const i=Boolean(s.getUint8(0));Js.log({isCharging:i}),t(this,Is,"m",Us).call(this,i);break;case"getBatteryCurrent":const n=s.getFloat32(0,!0);Js.log({batteryCurrent:n}),t(this,Is,"m",xs).call(this,n);break;case"getId":const r=P.decode(s.buffer);Js.log({id:r}),t(this,Is,"m",Os).call(this,r);break;case"getName":case"setName":const a=P.decode(s.buffer);Js.log({name:a}),this.updateName(a);break;case"getType":case"setType":const o=s.getUint8(0),c=Qs[o];Js.log({typeEnum:o,type:c}),this.updateType(c);break;case"getMtu":const h=s.getUint16(0,!0);Js.log({mtu:h}),t(this,Is,"m",js).call(this,h);break;case"getCurrentTime":case"setCurrentTime":const l=Number(s.getBigUint64(0,!0));t(this,Is,"m",Gs).call(this,l);break;default:throw Error(`uncaught messageType ${e}`)}}clear(){s(this,qs,!1,"f")}}Fs=new WeakMap,Rs=new WeakMap,As=new WeakMap,$s=new WeakMap,Bs=new WeakMap,zs=new WeakMap,qs=new WeakMap,Is=new WeakSet,Ls=function(){return this.eventDispatcher.dispatchEvent},Us=function(e){Js.assertTypeWithError(e,"boolean"),s(this,Fs,e,"f"),Js.log({isCharging:t(this,Fs,"f")}),t(this,Is,"a",Ls).call(this,"isCharging",{isCharging:t(this,Fs,"f")})},xs=function(e){Js.assertTypeWithError(e,"number"),s(this,Rs,e,"f"),Js.log({batteryCurrent:t(this,Rs,"f")}),t(this,Is,"a",Ls).call(this,"getBatteryCurrent",{batteryCurrent:t(this,Rs,"f")})},Os=function(e){Js.assertTypeWithError(e,"string"),s(this,As,e,"f"),Js.log({id:t(this,As,"f")}),t(this,Is,"a",Ls).call(this,"getId",{id:t(this,As,"f")})},Ns=function(e){Js.assertEnumWithError(e,Qs)},Ps=function(e){Js.assertTypeWithError(e,"number"),Js.assertWithError(e in Qs,`invalid typeEnum ${e}`)},Vs=async function(e){t(this,Is,"m",Ps).call(this,e);const s=Uint8Array.from([e]);Js.log({setTypeData:s});const i=this.waitForEvent("getType");this.sendMessage([{type:"setType",data:s.buffer}]),await i},js=function(e){Js.assertTypeWithError(e,"number"),t(this,zs,"f")!=e?(s(this,zs,e,"f"),t(this,Is,"a",Ls).call(this,"getMtu",{mtu:t(this,zs,"f")})):Js.log("redundant mtu assignment",e)},Gs=function(e){Js.log({currentTime:e}),s(this,qs,0!=e||Math.abs(Date.now()-e)<Ne,"f"),t(this,qs,"f")||t(this,Is,"m",Hs).call(this,!1)},Hs=async function(e){Js.log("setting current time...");const t=new DataView(new ArrayBuffer(8));t.setBigUint64(0,BigInt(Date.now()),!0);const s=this.waitForEvent("getCurrentTime");this.sendMessage([{type:"setCurrentTime",data:t.buffer}],e),await s};const ei=["none","strongClick100","strongClick60","strongClick30","sharpClick100","sharpClick60","sharpClick30","softBump100","softBump60","softBump30","doubleClick100","doubleClick60","tripleClick100","softFuzz60","strongBuzz100","alert750ms","alert1000ms","strongClick1_100","strongClick2_80","strongClick3_60","strongClick4_30","mediumClick100","mediumClick80","mediumClick60","sharpTick100","sharpTick80","sharpTick60","shortDoubleClickStrong100","shortDoubleClickStrong80","shortDoubleClickStrong60","shortDoubleClickStrong30","shortDoubleClickMedium100","shortDoubleClickMedium80","shortDoubleClickMedium60","shortDoubleSharpTick100","shortDoubleSharpTick80","shortDoubleSharpTick60","longDoubleSharpClickStrong100","longDoubleSharpClickStrong80","longDoubleSharpClickStrong60","longDoubleSharpClickStrong30","longDoubleSharpClickMedium100","longDoubleSharpClickMedium80","longDoubleSharpClickMedium60","longDoubleSharpTick100","longDoubleSharpTick80","longDoubleSharpTick60","buzz100","buzz80","buzz60","buzz40","buzz20","pulsingStrong100","pulsingStrong60","pulsingMedium100","pulsingMedium60","pulsingSharp100","pulsingSharp60","transitionClick100","transitionClick80","transitionClick60","transitionClick40","transitionClick20","transitionClick10","transitionHum100","transitionHum80","transitionHum60","transitionHum40","transitionHum20","transitionHum10","transitionRampDownLongSmooth2_100","transitionRampDownLongSmooth1_100","transitionRampDownMediumSmooth1_100","transitionRampDownMediumSmooth2_100","transitionRampDownShortSmooth1_100","transitionRampDownShortSmooth2_100","transitionRampDownLongSharp1_100","transitionRampDownLongSharp2_100","transitionRampDownMediumSharp1_100","transitionRampDownMediumSharp2_100","transitionRampDownShortSharp1_100","transitionRampDownShortSharp2_100","transitionRampUpLongSmooth1_100","transitionRampUpLongSmooth2_100","transitionRampUpMediumSmooth1_100","transitionRampUpMediumSmooth2_100","transitionRampUpShortSmooth1_100","transitionRampUpShortSmooth2_100","transitionRampUpLongSharp1_100","transitionRampUpLongSharp2_100","transitionRampUpMediumSharp1_100","transitionRampUpMediumSharp2_100","transitionRampUpShortSharp1_100","transitionRampUpShortSharp2_100","transitionRampDownLongSmooth1_50","transitionRampDownLongSmooth2_50","transitionRampDownMediumSmooth1_50","transitionRampDownMediumSmooth2_50","transitionRampDownShortSmooth1_50","transitionRampDownShortSmooth2_50","transitionRampDownLongSharp1_50","transitionRampDownLongSharp2_50","transitionRampDownMediumSharp1_50","transitionRampDownMediumSharp2_50","transitionRampDownShortSharp1_50","transitionRampDownShortSharp2_50","transitionRampUpLongSmooth1_50","transitionRampUpLongSmooth2_50","transitionRampUpMediumSmooth1_50","transitionRampUpMediumSmooth2_50","transitionRampUpShortSmooth1_50","transitionRampUpShortSmooth2_50","transitionRampUpLongSharp1_50","transitionRampUpLongSharp2_50","transitionRampUpMediumSharp1_50","transitionRampUpMediumSharp2_50","transitionRampUpShortSharp1_50","transitionRampUpShortSharp2_50","longBuzz100","smoothHum50","smoothHum40","smoothHum30","smoothHum20","smoothHum10"];var ti,si,ii,ni,ri,ai,oi,ci,hi,li,gi,fi,ui,di,mi,pi;const vi=T("VibrationManager"),wi=["front","rear"],yi=["waveformEffect","waveform"],bi=2550,Si=1270;class Ei{constructor(){ti.add(this),H(this)}async triggerVibration(e,s=!0){let i;e.forEach((e=>{const{type:s}=e;let n,{locations:r}=e;switch(r=r||wi.slice(),s){case"waveformEffect":{const{segments:s,loopCount:i}=e;n=t(this,ti,"m",ui).call(this,r,s,i)}break;case"waveform":{const{segments:s}=e;n=t(this,ti,"m",di).call(this,r,s)}break;default:throw Error(`invalid vibration type "${s}"`)}vi.log({type:s,arrayBuffer:n}),i=z(i,n)})),await this.sendMessage([{type:"triggerVibration",data:i}],s)}}var Mi,Ci,Di,ki,Ti,Wi,_i,Ii,Li,Fi,Ui,Ri,xi,Ai,Oi;ti=new WeakSet,si=function(e){vi.assertTypeWithError(e,"string"),vi.assertWithError(wi.includes(e),`invalid location "${e}"`)},ii=function(e){t(this,ti,"m",ri).call(this,e),e.forEach((e=>{t(this,ti,"m",si).call(this,e)}))},ni=function(e){t(this,ti,"m",ii).call(this,e);let s=0;return e.forEach((e=>{const t=wi.indexOf(e);s|=1<<t})),vi.log({locationsBitmask:s}),vi.assertWithError(s>0,"locationsBitmask must not be zero"),s},ri=function(e){vi.assertWithError(Array.isArray(e),"passed non-array"),vi.assertWithError(e.length>0,"passed empty array")},ai=function(e){vi.assertWithError(ei.includes(e),`invalid waveformEffect "${e}"`)},oi=function(e){if(null!=e.effect){const s=e.effect;t(this,ti,"m",ai).call(this,s)}else{if(null==e.delay)throw Error("no effect or delay found in waveformEffectSegment");{const{delay:t}=e;vi.assertWithError(t>=0,`delay must be 0ms or greater (got ${t})`),vi.assertWithError(t<=Si,`delay must be 1270ms or less (got ${t})`)}}if(null!=e.loopCount){const{loopCount:s}=e;t(this,ti,"m",ci).call(this,s)}},ci=function(e){vi.assertTypeWithError(e,"number"),vi.assertWithError(e>=0,`waveformEffectSegmentLoopCount must be 0 or greater (got ${e})`),vi.assertWithError(e<=3,`waveformEffectSegmentLoopCount must be 3 or fewer (got ${e})`)},hi=function(e){t(this,ti,"m",ri).call(this,e),vi.assertWithError(e.length<=8,`must have 8 waveformEffectSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,ti,"m",oi).call(this,e)}))},li=function(e){vi.assertTypeWithError(e,"number"),vi.assertWithError(e>=0,`waveformEffectSequenceLoopCount must be 0 or greater (got ${e})`),vi.assertWithError(e<=6,`waveformEffectSequenceLoopCount must be 6 or fewer (got ${e})`)},gi=function(e){vi.assertTypeWithError(e.amplitude,"number"),vi.assertWithError(e.amplitude>=0,`amplitude must be 0 or greater (got ${e.amplitude})`),vi.assertWithError(e.amplitude<=1,`amplitude must be 1 or less (got ${e.amplitude})`),vi.assertTypeWithError(e.duration,"number"),vi.assertWithError(e.duration>0,`duration must be greater than 0ms (got ${e.duration}ms)`),vi.assertWithError(e.duration<=bi,`duration must be 2550ms or less (got ${e.duration}ms)`)},fi=function(e){t(this,ti,"m",ri).call(this,e),vi.assertWithError(e.length<=20,`must have 20 waveformSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,ti,"m",gi).call(this,e)}))},ui=function(e,s,i=0){t(this,ti,"m",hi).call(this,s),t(this,ti,"m",li).call(this,i);let n=[],r=0;const a=s.some((e=>{const{loopCount:t}=e;return null!=t&&t>0}))||0!=i;for(let e=0;e<s.length||a&&e<8;e++){const t=s[e]||{effect:"none"};if(null!=t.effect){const e=t.effect;n[r++]=ei.indexOf(e)}else{if(null==t.delay)throw Error("invalid waveformEffectSegment");{const{delay:e}=t;n[r++]=128|Math.floor(e/10)}}}const o=0!=i;for(let e=0;e<s.length||o&&e<8;e++){const t=s[e]?.loopCount||0;0!=e&&4!=e||(n[r]=0);const i=e%4*2;n[r]|=t<<i,3!=e&&7!=e||r++}0!=i&&(n[r++]=i);const c=new DataView(Uint8Array.from(n).buffer);return vi.log({dataArray:n,dataView:c}),t(this,ti,"m",pi).call(this,e,"waveformEffect",c)},di=function(e,s){t(this,ti,"m",fi).call(this,s);const i=new DataView(new ArrayBuffer(2*s.length));return s.forEach(((e,t)=>{i.setUint8(2*t,Math.floor(127*e.amplitude)),i.setUint8(2*t+1,Math.floor(e.duration/10))})),vi.log({dataView:i}),t(this,ti,"m",pi).call(this,e,"waveform",i)},mi=function(e){vi.assertTypeWithError(e,"string"),vi.assertWithError(yi.includes(e),`invalid vibrationType "${e}"`)},pi=function(e,s,i){vi.assertWithError(i?.byteLength>0,"no data received");const n=t(this,ti,"m",ni).call(this,e);t(this,ti,"m",mi).call(this,s);const r=yi.indexOf(s);vi.log({locationsBitmask:n,vibrationTypeIndex:r,dataView:i});const a=z(n,r,i.byteLength,i);return vi.log({data:a}),a};const $i=T("BaseConnectionManager",{log:!0}),Bi=["notConnected","connecting","connected","disconnecting"],Ni=[...Bi,"connectionStatus","isConnected"],Pi=[...Zs,...At,...yt,"triggerVibration",...ps,...Ue],Vi=["batteryLevel"],zi=["rx","tx"],ji=[...Vi,...Ts,...zi,...Pi,"smp"];class qi{get baseConstructor(){return this.constructor}static get isSupported(){return!1}get isSupported(){return this.baseConstructor.isSupported}get type(){return this.baseConstructor.type}constructor(){Mi.add(this),Ti.set(this,"notConnected"),Ui.set(this,[]),Ri.set(this,!1),Ai.set(this,new R(t(this,Mi,"m",Oi).bind(this),5e3)),t(this,Mi,"m",ki).call(this)}get status(){return t(this,Ti,"f")}set status(e){$i.assertEnumWithError(e,Bi),t(this,Ti,"f")!=e?($i.log(`new connection status "${e}"`),s(this,Ti,e,"f"),this.onStatusUpdated(this.status),this.isConnected?t(this,Ai,"f").start():t(this,Ai,"f").stop(),"notConnected"==t(this,Ti,"f")&&(this.mtu=void 0)):$i.log(`tried to assign same connection status "${e}"`)}get isConnected(){return"connected"==this.status}async connect(){t(this,Mi,"m",Wi).call(this),t(this,Mi,"m",_i).call(this),this.status="connecting"}get canReconnect(){return!1}async reconnect(){t(this,Mi,"m",Wi).call(this),t(this,Mi,"m",_i).call(this),$i.assert(this.canReconnect,"unable to reconnect")}async disconnect(){t(this,Mi,"m",Ii).call(this),t(this,Mi,"m",Li).call(this),this.status="disconnecting",$i.log("disconnecting from device...")}async sendSmpMessage(e){t(this,Mi,"m",Fi).call(this),$i.log("sending smp message",e)}async sendTxMessages(e,i=!0){if(t(this,Mi,"m",Fi).call(this),e&&t(this,Ui,"f").push(...e),!i)return;if(t(this,Ri,"f"))return;s(this,Ri,!0,"f"),$i.log("sendTxMessages",t(this,Ui,"f").slice());const n=t(this,Ui,"f").map((e=>{t(Ci,Ci,"m",Di).call(Ci,e.type);const s=Pi.indexOf(e.type),i=new DataView(new ArrayBuffer(2));return i.setUint16(0,e.data?.byteLength||0,!0),z(s,i,e.data)}));if(this.mtu)for(;n.length>0;){let e=0,t=0;n.some((s=>{if(e+s.byteLength>this.mtu-3)return!0;t++,e+=s.byteLength}));const s=n.splice(0,t);$i.log({arrayBufferCount:t,arrayBuffersToSend:s});const i=z(...s);$i.log("sending arrayBuffer",i),await this.sendTxData(i)}else{const e=z(...n);$i.log("sending arrayBuffer",e),await this.sendTxData(e)}t(this,Ui,"f").length=0,s(this,Ri,!1,"f")}async sendTxData(e){$i.log("sendTxData",e)}parseRxMessage(e){dt(e,Pi,t(this,Mi,"m",xi).bind(this),null,!0),this.onMessagesReceived()}}Ci=qi,Ti=new WeakMap,Ui=new WeakMap,Ri=new WeakMap,Ai=new WeakMap,Mi=new WeakSet,Di=function(e){$i.assertEnumWithError(e,Pi)},ki=function(){$i.assertWithError(this.isSupported,`${this.constructor.name} is not supported`)},Wi=function(){$i.assertWithError(!this.isConnected,"device is already connected")},_i=function(){$i.assertWithError("connecting"!=this.status,"device is already connecting")},Ii=function(){$i.assertWithError(this.isConnected,"device is not connected")},Li=function(){$i.assertWithError("disconnecting"!=this.status,"device is already disconnecting")},Fi=function(){t(this,Mi,"m",Ii).call(this),t(this,Mi,"m",Li).call(this)},xi=function(e,t){$i.log({messageType:e,dataView:t}),this.onMessageReceived(e,t)},Oi=function(){this.isConnected||($i.log("timer detected disconnection"),this.status="notConnected")};const Gi=T("EventUtils",{log:!1});function Hi(e,t){let s=e.addEventListener||e.addListener||e.on||e.AddEventListener;Gi.assertWithError(s,"no add listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}function Ji(e,t){let s=e.removeEventListener||e.removeListener||e.RemoveEventListener;Gi.assertWithError(s,"no remove listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}const Qi=T("bluetoothUUIDs",{log:!1});if(n)var Ki=window.BluetoothUUID;function Zi(e){return Qi.assertTypeWithError(e,"string"),Qi.assertWithError(4==e.length,"value must be 4 characters long"),`ea6da725-${e}-4f9b-893d-c3913e33b39f`}function Xi(e){return Ki?.getCharacteristic?.(e)}function Yi(e){return Ki?.getService?.(e)}const en=Object.freeze({services:{deviceInformation:{uuid:Yi("device_information"),characteristics:{manufacturerName:{uuid:Xi("manufacturer_name_string")},modelNumber:{uuid:Xi("model_number_string")},hardwareRevision:{uuid:Xi("hardware_revision_string")},firmwareRevision:{uuid:Xi("firmware_revision_string")},softwareRevision:{uuid:Xi("software_revision_string")},pnpId:{uuid:Xi("pnp_id")},serialNumber:{uuid:Xi("serial_number_string")}}},battery:{uuid:Yi("battery_service"),characteristics:{batteryLevel:{uuid:Xi("battery_level")}}},main:{uuid:Zi("0000"),characteristics:{rx:{uuid:Zi("1000")},tx:{uuid:Zi("1001")}}},smp:{uuid:"8d53dc1d-1db7-4cd3-868b-8a527460aa84",characteristics:{smp:{uuid:"da2e7828-fbce-4e01-ae9e-261174997c48"}}}}}),tn=[en.services.main.uuid],sn=[en.services.deviceInformation.uuid,en.services.battery.uuid,en.services.smp.uuid];function nn(e){e=e.toString().toLowerCase();return Object.keys(en.services).find((t=>{let s=en.services[t].uuid.toString();return 4==e.length&&(s=s.slice(4,8)),e.includes("-")||(s=s.replaceAll("-","")),e==s}))}const rn=[],an=[];function on(e){var t;return e=e.toString().toLowerCase(),Object.values(en.services).some((s=>{const i=Object.keys(s.characteristics);return t=i.find((t=>{let i=s.characteristics[t].uuid.toString();return 4==e.length&&(i=i.slice(4,8)),e.includes("-")||(i=i.replaceAll("-","")),e==i}))})),t}function cn(e){const t={broadcast:!1,read:!0,writeWithoutResponse:!1,write:!1,notify:!1,indicate:!1,authenticatedSignedWrites:!1,reliableWrite:!1,writableAuxiliaries:!1};switch(e){case"rx":case"tx":case"smp":t.read=!1}switch(e){case"batteryLevel":case"rx":case"smp":t.notify=!0}if("smp"===e)t.writeWithoutResponse=!0;if("tx"===e)t.write=!0;return t}Object.values(en.services).forEach((e=>{if(!e.characteristics)return;const t=Object.keys(e.characteristics);t.forEach((s=>{const i=e.characteristics[s];tn.includes(e.uuid)&&(rn.push(i.uuid),t.push(s)),an.push(i.uuid)}))}),[]);const hn=T("BluetoothConnectionManager",{log:!0});class ln extends qi{constructor(){super(...arguments),this.isInRange=!0}onCharacteristicValueChanged(e,t){"rx"==e?this.parseRxMessage(t):this.onMessageReceived?.(e,t)}async writeCharacteristic(e,t){hn.log("writeCharacteristic",...arguments)}async sendSmpMessage(e){super.sendSmpMessage(e),await this.writeCharacteristic("smp",e)}async sendTxData(e){super.sendTxData(e),0!=e.byteLength&&await this.writeCharacteristic("tx",e)}}var gn,fn,un,dn,mn,pn,vn,wn,yn,bn,Sn;const En=T("WebBluetoothConnectionManager",{log:!0});var Mn;n&&(Mn=window.navigator.bluetooth);class Cn extends ln{constructor(){super(...arguments),gn.add(this),fn.set(this,{characteristicvaluechanged:t(this,gn,"m",yn).bind(this)}),un.set(this,{gattserverdisconnected:t(this,gn,"m",Sn).bind(this)}),dn.set(this,void 0),mn.set(this,new Map),pn.set(this,new Map)}get bluetoothId(){return this.device.id}static get isSupported(){return Boolean(Mn)}static get type(){return"webBluetooth"}get device(){return t(this,dn,"f")}set device(e){t(this,dn,"f")!=e?(t(this,dn,"f")&&Ji(t(this,dn,"f"),t(this,un,"f")),e&&Hi(e,t(this,un,"f")),s(this,dn,e,"f")):En.log("tried to assign the same BluetoothDevice")}get server(){return t(this,dn,"f")?.gatt}get isConnected(){return this.server?.connected||!1}async connect(){await super.connect();try{const e=await Mn.requestDevice({filters:[{services:tn}],optionalServices:n?sn:[]});En.log("got BluetoothDevice"),this.device=e,En.log("connecting to device...");const s=await this.server.connect();En.log(`connected to device? ${s.connected}`),await t(this,gn,"m",vn).call(this),En.log("fully connected"),this.status="connected"}catch(e){En.error(e),this.status="notConnected",this.server?.disconnect(),t(this,gn,"m",wn).call(this)}}async disconnect(){await t(this,gn,"m",wn).call(this),await super.disconnect(),this.server?.disconnect(),this.status="notConnected"}async writeCharacteristic(e,s){super.writeCharacteristic(e,s);const i=t(this,pn,"f").get(e);En.assertWithError(i,`${e} characteristic not found`),En.log("writing characteristic",i,s);const n=i.properties||cn(e);n.writeWithoutResponse?(En.log("writing without response"),await i.writeValueWithoutResponse(s)):(En.log("writing with response"),await i.writeValueWithResponse(s)),En.log("wrote characteristic"),n.read&&!n.notify&&(En.log("reading value after write..."),await i.readValue(),(c||h)&&t(this,gn,"m",bn).call(this,i))}get canReconnect(){return Boolean(this.server&&!this.server.connected&&this.isInRange)}async reconnect(){await super.reconnect(),En.log("attempting to reconnect..."),this.status="connecting";try{await this.server.connect()}catch(e){En.error(e),this.isInRange=!1}this.isConnected?(En.log("successfully reconnected!"),await t(this,gn,"m",vn).call(this),this.status="connected"):(En.log("unable to reconnect"),this.status="notConnected")}}fn=new WeakMap,un=new WeakMap,dn=new WeakMap,mn=new WeakMap,pn=new WeakMap,gn=new WeakSet,vn=async function(){t(this,gn,"m",wn).call(this),En.log("getting services...");const e=await this.server.getPrimaryServices();En.log("got services",e.length),En.log("getting characteristics...");for(const s in e){const i=e[s];En.log({service:i});const n=nn(i.uuid);En.assertWithError(n,`no name found for service uuid "${i.uuid}"`),En.log(`got "${n}" service`),i.name=n,t(this,mn,"f").set(n,i),En.log(`getting characteristics for "${n}" service`);const r=await i.getCharacteristics();En.log(`got characteristics for "${n}" service`);for(const e in r){const s=r[e];En.log({characteristic:s});const i=on(s.uuid);En.assertWithError(Boolean(i),`no name found for characteristic uuid "${s.uuid}" in "${n}" service`),En.log(`got "${i}" characteristic in "${n}" service`),s.name=i,t(this,pn,"f").set(i,s),Hi(s,t(this,fn,"f"));const a=s.properties||cn(i);a.notify&&(En.log(`starting notifications for "${i}" characteristic`),await s.startNotifications()),a.read&&(En.log(`reading "${i}" characteristic...`),await s.readValue(),(c||h)&&t(this,gn,"m",bn).call(this,s))}}},wn=async function(){this.device&&Ji(this.device,t(this,un,"f"));const e=Array.from(t(this,pn,"f").keys()).map((e=>{const s=t(this,pn,"f").get(e);Ji(s,t(this,fn,"f"));if((s.properties||cn(e)).notify)return En.log(`stopping notifications for "${e}" characteristic`),s.stopNotifications()}));return Promise.allSettled(e)},yn=function(e){En.log("oncharacteristicvaluechanged");const s=e.target;t(this,gn,"m",bn).call(this,s)},bn=function(e){En.log("onCharacteristicValue");const t=e.name;En.assertWithError(Boolean(t),`no name found for characteristic with uuid "${e.uuid}"`),En.log(`oncharacteristicvaluechanged for "${t}" characteristic`);const s=e.value;En.assertWithError(s,`no data found for "${t}" characteristic`),En.log(`data for "${t}" characteristic`,Array.from(new Uint8Array(s.buffer)));try{this.onCharacteristicValueChanged(t,s)}catch(e){En.error(e)}},Sn=function(){En.log("gattserverdisconnected"),this.status="notConnected"};const Dn=4294967296,kn=9007199254740992;const Tn={encode:function(e){let t,s=new ArrayBuffer(256),i=new DataView(s),n=0;function r(e){let r=s.byteLength;const a=n+e;for(;r<a;)r<<=1;if(r!==s.byteLength){const e=i;s=new ArrayBuffer(r),i=new DataView(s);const t=n+3>>2;for(let s=0;s<t;++s)i.setUint32(s<<2,e.getUint32(s<<2))}return t=e,i}function a(){n+=t}function o(e){a(r(1).setUint8(n,e))}function c(e){const t=r(e.length);for(let s=0;s<e.length;++s)t.setUint8(n+s,e[s]);a()}function h(e,t){t<24?o(e<<5|t):t<256?(o(e<<5|24),o(t)):t<65536?(o(e<<5|25),function(e){a(r(2).setUint16(n,e))}(t)):t<4294967296?(o(e<<5|26),function(e){a(r(4).setUint32(n,e))}(t)):(o(e<<5|27),function(e){const t=e%Dn,s=(e-t)/Dn,i=r(8);i.setUint32(n,s),i.setUint32(n+4,t),a()}(t))}if(function e(t){let s;const i=[];let l;if(!1===t)return o(244);if(!0===t)return o(245);if(null===t)return o(246);if(void 0===t)return o(247);switch(typeof t){case"number":if(Math.floor(t)===t){if(t>=0&&t<=kn)return h(0,t);if(-kn<=t&&t<0)return h(1,-(t+1))}return o(251),function(e){a(r(8).setFloat64(n,e))}(t);case"string":for(s=0;s<t.length;++s){let e=t.charCodeAt(s);e<128?i.push(e):e<2048?(i.push(192|e>>6),i.push(128|63&e)):e<55296?(i.push(224|e>>12),i.push(128|e>>6&63),i.push(128|63&e)):(e=(1023&e)<<10,e|=1023&t.charCodeAt(++s),e+=65536,i.push(240|e>>18),i.push(128|e>>12&63),i.push(128|e>>6&63),i.push(128|63&e))}return h(3,i.length),c(i);default:if(Array.isArray(t))for(l=t.length,h(4,l),s=0;s<l;++s)e(t[s]);else if(t instanceof Uint8Array)h(2,t.length),c(t);else{const i=Object.keys(t);for(l=i.length,h(5,l),s=0;s<l;++s){const n=i[s];e(n),e(t[n])}}}}(e),"slice"in s)return s.slice(0,n);const l=new ArrayBuffer(n),g=new DataView(l);for(let e=0;e<n;++e)g.setUint8(e,i.getUint8(e));return l},decode:function(e,t,s){const i=new DataView(e);let n=0;function r(e,t){return n+=e,t}function a(t){return r(t,new Uint8Array(e,n,t))}function o(){return r(1,i.getUint8(n))}function c(){return r(2,i.getUint16(n))}function h(){return r(4,i.getUint32(n))}function l(){return 255===i.getUint8(n)&&(n+=1,!0)}function g(e){if(e<24)return e;if(24===e)return o();if(25===e)return c();if(26===e)return h();if(27===e)return h()*Dn+h();if(31===e)return-1;throw new Error("Invalid length encoding")}function f(e){const t=o();if(255===t)return-1;const s=g(31&t);if(s<0||t>>5!==e)throw new Error("Invalid indefinite length element");return s}function u(e,t){for(let s=0;s<t;++s){let s=o();128&s&&(s<224?(s=(31&s)<<6|63&o(),t-=1):s<240?(s=(15&s)<<12|(63&o())<<6|63&o(),t-=2):(s=(15&s)<<18|(63&o())<<12|(63&o())<<6|63&o(),t-=3)),s<65536?e.push(s):(s-=65536,e.push(55296|s>>10),e.push(56320|1023&s))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof s&&(s=function(){});const d=function e(){const h=o(),d=h>>5,m=31&h;let p,v;if(7===d)switch(m){case 25:return function(){const e=new ArrayBuffer(4),t=new DataView(e),s=c(),i=32768&s;let n=31744&s;const r=1023&s;if(31744===n)n=261120;else if(0!==n)n+=114688;else if(0!==r)return(i?-1:1)*r*5.960464477539063e-8;return t.setUint32(0,i<<16|n<<13|r<<13),t.getFloat32(0)}();case 26:return r(4,i.getFloat32(n));case 27:return r(8,i.getFloat64(n))}if(v=g(m),v<0&&(d<2||d>6))throw new Error("Invalid length");const w=[];let y;const b={};switch(d){case 0:return v;case 1:return-1-v;case 2:if(v<0){const e=[];let t=0;for(;(v=f(d))>=0;)t+=v,e.push(a(v));const s=new Uint8Array(t);let i=0;for(p=0;p<e.length;++p)s.set(e[p],i),i+=e[p].length;return s}return a(v);case 3:if(v<0)for(;(v=f(d))>=0;)u(w,v);else u(w,v);return String.fromCharCode.apply(null,w);case 4:if(v<0)for(y=[];!l();)y.push(e());else for(y=new Array(v),p=0;p<v;++p)y[p]=e();return y;case 5:for(p=0;p<v||v<0&&!l();++p){b[e()]=e()}return b;case 6:return t(e(),v);case 7:switch(v){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:return s(v)}}}();if(n!==e.byteLength)throw new Error("Remaining bytes");return d}},Wn=T("mcumgr",{log:!0}),_n=0,In=1,Ln=2,Fn=3,Un=0,Rn=1,xn=8,An=0,On=2,$n=3,Bn=5,Nn=0,Pn=1,Vn=5,zn=0;class jn{constructor(){this._mtu=256,this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}onMessage(e){return this._messageCallback=e,this}onImageUploadNext(e){return this._imageUploadNextCallback=e,this}onImageUploadProgress(e){return this._imageUploadProgressCallback=e,this}onImageUploadFinished(e){return this._imageUploadFinishedCallback=e,this}onFileUploadNext(e){return this._fileUploadNextCallback=e,this}onFileUploadProgress(e){return this._fileUploadProgressCallback=e,this}onFileUploadFinished(e){return this._fileUploadFinishedCallback=e,this}onFileDownloadNext(e){return this._fileDownloadNextCallback=e,this}onFileDownloadProgress(e){return this._fileDownloadProgressCallback=e,this}onFileDownloadFinished(e){return this._fileDownloadFinishedCallback=e,this}_getMessage(e,t,s,i){let n=[];void 0!==i&&(n=[...new Uint8Array(Tn.encode(i))]);const r=255&n.length,a=[e,0,n.length>>8,r,t>>8,255&t,this._seq,s,...n];return this._seq=(this._seq+1)%256,a}_notification(e){Wn.log("mcumgr - message received");const t=new Uint8Array(e);this._buffer=new Uint8Array([...this._buffer,...t]);const s=256*this._buffer[2]+this._buffer[3];this._buffer.length<s+8||(this._processMessage(this._buffer.slice(0,s+8)),this._buffer=this._buffer.slice(s+8))}_processMessage(e){const[t,,s,i,n,r,,a]=e,o=Tn.decode(e.slice(8).buffer),c=256*s+i,h=256*n+r;return Wn.log("mcumgr - Process Message - Group: "+h+", Id: "+a+", Off: "+o.off),h===Rn&&a===Pn&&o.off?(this._uploadOffset=o.off,void this._uploadNext()):t===Fn&&h===xn&&a===zn&&o.off?(this._uploadFileOffset=o.off,void this._uploadFileNext()):t===In&&h===xn&&a===zn?(this._downloadFileOffset+=o.data.length,null!=o.len&&(this._downloadFileLength=o.len),Wn.log("downloaded "+this._downloadFileOffset+" bytes of "+this._downloadFileLength),this._downloadFileLength>0&&this._fileDownloadProgressCallback({percentage:Math.floor(this._downloadFileOffset/this._downloadFileLength*100)}),this._messageCallback&&this._messageCallback({op:t,group:h,id:a,data:o,length:c}),void this._downloadFileNext()):void(this._messageCallback&&this._messageCallback({op:t,group:h,id:a,data:o,length:c}))}cmdReset(){return this._getMessage(Ln,Un,Bn)}smpEcho(e){return this._getMessage(Ln,Un,An,{d:e})}cmdImageState(){return this._getMessage(_n,Rn,Nn)}cmdImageErase(){return this._getMessage(Ln,Rn,Vn,{})}cmdImageTest(e){return this._getMessage(Ln,Rn,Nn,{hash:e,confirm:!1})}cmdImageConfirm(e){return this._getMessage(Ln,Rn,Nn,{hash:e,confirm:!0})}_hash(e){return crypto.subtle.digest("SHA-256",e)}async _uploadNext(){if(!this._uploadImage)return;if(this._uploadOffset>=this._uploadImage.byteLength)return this._uploadIsInProgress=!1,void this._imageUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadOffset};0===this._uploadOffset&&(e.len=this._uploadImage.byteLength,e.sha=new Uint8Array(await this._hash(this._uploadImage))),this._imageUploadProgressCallback({percentage:Math.floor(this._uploadOffset/this._uploadImage.byteLength*100)});const t=this._mtu-Tn.encode(e).byteLength-8-3-5;e.data=new Uint8Array(this._uploadImage.slice(this._uploadOffset,this._uploadOffset+t)),this._uploadOffset+=t;const s=this._getMessage(Ln,Rn,Pn,e);Wn.log("mcumgr - _uploadNext: Message Length: "+s.length),this._imageUploadNextCallback({packet:s})}async reset(){this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}async cmdUpload(e,t=0){this._uploadIsInProgress?Wn.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadOffset=0,this._uploadImage=e,this._uploadSlot=t,this._uploadNext())}async cmdUploadFile(e,t){this._uploadIsInProgress?Wn.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadFileOffset=0,this._uploadFile=e,this._uploadFilename=t,this._uploadFileNext())}async _uploadFileNext(){if(Wn.log("uploadFileNext - offset: "+this._uploadFileOffset+", length: "+this._uploadFile.byteLength),this._uploadFileOffset>=this._uploadFile.byteLength)return this._uploadIsInProgress=!1,void this._fileUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadFileOffset};0===this._uploadFileOffset&&(e.len=this._uploadFile.byteLength),e.name=this._uploadFilename,this._fileUploadProgressCallback({percentage:Math.floor(this._uploadFileOffset/this._uploadFile.byteLength*100)});const t=this._mtu-Tn.encode(e).byteLength-8;e.data=new Uint8Array(this._uploadFile.slice(this._uploadFileOffset,this._uploadFileOffset+t)),this._uploadFileOffset+=t;const s=this._getMessage(Ln,xn,zn,e);Wn.log("mcumgr - _uploadNext: Message Length: "+s.length),this._fileUploadNextCallback({packet:s})}async cmdDownloadFile(e,t){this._downloadIsInProgress?Wn.error("Download is already in progress."):(this._downloadIsInProgress=!0,this._downloadFileOffset=0,this._downloadFileLength=0,this._downloadRemoteFilename=e,this._downloadLocalFilename=t,this._downloadFileNext())}async _downloadFileNext(){if(this._downloadFileLength>0&&this._downloadFileOffset>=this._downloadFileLength)return this._downloadIsInProgress=!1,void this._fileDownloadFinishedCallback();const e={off:this._downloadFileOffset};0===this._downloadFileOffset&&(e.name=this._downloadRemoteFilename);const t=this._getMessage(_n,xn,zn,e);Wn.log("mcumgr - _downloadNext: Message Length: "+t.length),this._fileDownloadNextCallback({packet:t})}async imageInfo(e){const t={},s=new Uint8Array(e);if(s.length<32)throw new Error("Invalid image (too short file)");if(61!==s[0]||184!==s[1]||243!==s[2]||150!==s[3])throw new Error("Invalid image (wrong magic bytes)");if(0!==s[4]||0!==s[5]||0!==s[6]||0!==s[7])throw new Error("Invalid image (wrong load address)");const i=s[8]+256*s[9];if(0!==s[10]||0!==s[11])throw new Error("Invalid image (wrong protected TLV area size)");const n=s[12]+256*s[13]+65536*s[14]+s[15]*2**24;if(t.imageSize=n,s.length<n+i)throw new Error("Invalid image (wrong image size)");if(0!==s[16]||0!==s[17]||0!==s[18]||0!==s[19])throw new Error("Invalid image (wrong flags)");const r=`${s[20]}.${s[21]}.${s[22]+256*s[23]}`;return t.version=r,t.hash=[...new Uint8Array(await this._hash(e.slice(0,n+32)))].map((e=>e.toString(16).padStart(2,"0"))).join(""),t}}var qn,Gn,Hn,Jn,Qn,Kn,Zn,Xn,Yn,er,tr,sr,ir,nr,rr,ar,or,cr,hr,lr,gr;const fr=T("FirmwareManager",{log:!0}),ur=["smp"],dr=[...ur,"firmwareImages","firmwareUploadProgress","firmwareStatus","firmwareUploadComplete"],mr=["idle","uploading","uploaded","pending","testing","erasing"];class pr{constructor(){qn.add(this),Hn.set(this,"idle"),Qn.set(this,void 0),Xn.set(this,void 0),Yn.set(this,new jn),t(this,qn,"m",er).call(this),H(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}parseMessage(e,s){if(fr.log({messageType:e}),"smp"!==e)throw Error(`uncaught messageType ${e}`);t(this,Yn,"f")._notification(Array.from(new Uint8Array(s.buffer))),t(this,qn,"a",Gn).call(this,"smp",{dataView:s})}async uploadFirmware(e){fr.log("uploadFirmware",e);const s=this.waitForEvent("firmwareUploadComplete");await this.getImages();const i=await G(e),n=await t(this,Yn,"f").imageInfo(i);fr.log({imageInfo:n}),t(this,Yn,"f").cmdUpload(i,1),t(this,qn,"m",Jn).call(this,"uploading"),await s}get status(){return t(this,Hn,"f")}get images(){return t(this,Qn,"f")}async getImages(){const e=this.waitForEvent("firmwareImages");fr.log("getting firmware image state..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").cmdImageState()).buffer),await e}async testImage(e=1){if(t(this,qn,"m",Zn).call(this,e),t(this,qn,"m",Kn).call(this),!t(this,Qn,"f")[e])return void fr.log(`image ${e} not found`);if(1==t(this,Qn,"f")[e].pending)return void fr.log(`image ${e} is already pending`);if(t(this,Qn,"f")[e].empty)return void fr.log(`image ${e} is empty`);const s=this.waitForEvent("smp");fr.log("testing firmware image..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").cmdImageTest(t(this,Qn,"f")[e].hash)).buffer),await s}async eraseImage(){t(this,qn,"m",Kn).call(this);const e=this.waitForEvent("smp");fr.log("erasing image..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").cmdImageErase()).buffer),t(this,qn,"m",Jn).call(this,"erasing"),await e,await this.getImages()}async confirmImage(e=0){if(t(this,qn,"m",Zn).call(this,e),t(this,qn,"m",Kn).call(this),!0===t(this,Qn,"f")[e].confirmed)return void fr.log(`image ${e} is already confirmed`);const s=this.waitForEvent("smp");fr.log("confirming image..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").cmdImageConfirm(t(this,Qn,"f")[e].hash)).buffer),await s}async echo(e){fr.assertTypeWithError(e,"string");const s=this.waitForEvent("smp");fr.log("sending echo..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").smpEcho(e)).buffer),await s}async reset(){const e=this.waitForEvent("smp");fr.log("resetting..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").cmdReset()).buffer),await e}get mtu(){return t(this,Xn,"f")}set mtu(e){s(this,Xn,e,"f"),t(this,Yn,"f")._mtu=e}}var vr,wr,yr,br,Sr,Er,Mr,Cr,Dr,kr,Tr,Wr,_r,Ir,Lr,Fr,Ur,Rr;Hn=new WeakMap,Qn=new WeakMap,Xn=new WeakMap,Yn=new WeakMap,qn=new WeakSet,Gn=function(){return this.eventDispatcher.dispatchEvent},Jn=function(e){fr.assertEnumWithError(e,mr),t(this,Hn,"f")!=e?(s(this,Hn,e,"f"),fr.log({firmwareStatus:t(this,Hn,"f")}),t(this,qn,"a",Gn).call(this,"firmwareStatus",{firmwareStatus:t(this,Hn,"f")})):fr.log(`redundant firmwareStatus assignment "${e}"`)},Kn=function(){fr.assertWithError(t(this,Qn,"f"),"didn't get imageState")},Zn=function(e){fr.assertTypeWithError(e,"number"),fr.assertWithError(0==e||1==e,"imageIndex must be 0 or 1")},er=function(){t(this,Yn,"f").onMessage(t(this,qn,"m",tr).bind(this)),t(this,Yn,"f").onFileDownloadNext(t(this,qn,"m",sr)),t(this,Yn,"f").onFileDownloadProgress(t(this,qn,"m",ir).bind(this)),t(this,Yn,"f").onFileDownloadFinished(t(this,qn,"m",nr).bind(this)),t(this,Yn,"f").onFileUploadNext(t(this,qn,"m",rr).bind(this)),t(this,Yn,"f").onFileUploadProgress(t(this,qn,"m",ar).bind(this)),t(this,Yn,"f").onFileUploadFinished(t(this,qn,"m",or).bind(this)),t(this,Yn,"f").onImageUploadNext(t(this,qn,"m",cr).bind(this)),t(this,Yn,"f").onImageUploadProgress(t(this,qn,"m",hr).bind(this)),t(this,Yn,"f").onImageUploadFinished(t(this,qn,"m",lr).bind(this))},tr=function({op:e,group:s,id:i,data:n,length:r}){switch(fr.log("onMcuMessage",...arguments),s){case Un:switch(i){case An:fr.log(`echo "${n.r}"`);break;case On:fr.table(n.tasks);break;case $n:fr.log(n)}break;case Rn:if(i===Nn)t(this,qn,"m",gr).call(this,n);break;default:throw Error(`uncaught mcuMessage group ${s}`)}},sr=function(){fr.log("onMcuFileDownloadNext",...arguments)},ir=function(){fr.log("onMcuFileDownloadProgress",...arguments)},nr=function(){fr.log("onMcuFileDownloadFinished",...arguments)},rr=function(){fr.log("onMcuFileUploadNext")},ar=function(){fr.log("onMcuFileUploadProgress")},or=function(){fr.log("onMcuFileUploadFinished")},cr=function({packet:e}){fr.log("onMcuImageUploadNext"),this.sendMessage(Uint8Array.from(e).buffer)},hr=function({percentage:e}){const s=e/100;fr.log("onMcuImageUploadProgress",...arguments),t(this,qn,"a",Gn).call(this,"firmwareUploadProgress",{progress:s})},lr=async function(){fr.log("onMcuImageUploadFinished",...arguments),await this.getImages(),t(this,qn,"a",Gn).call(this,"firmwareUploadProgress",{progress:100}),t(this,qn,"a",Gn).call(this,"firmwareUploadComplete",{})},gr=function({images:e}){if(!e)return void fr.log("no images found");s(this,Qn,e,"f"),fr.log("images",t(this,Qn,"f"));let i="idle";2==t(this,Qn,"f").length&&(t(this,Qn,"f")[1].bootable?t(this,Qn,"f")[0].confirmed?t(this,Qn,"f")[1].pending?(fr.log("reset to upload to the new firmware image"),i="pending"):(fr.log("Slot 1 has a valid image. run testImage() to test it or upload a different image."),i="uploaded"):(fr.log('Slot 0 has a valid image. Click "Confirm Image" to confirm it or wait and the device will swap images back.'),i="testing"):fr.warn('Slot 1 has a invalid image. Click "Erase Image" to erase it or upload a different image')),1==t(this,Qn,"f").length&&(t(this,Qn,"f").push({slot:1,empty:!0,version:"Empty",pending:!1,confirmed:!1,bootable:!1,active:!1,permanent:!1}),fr.log("Select a firmware upload image to upload to slot 1.")),t(this,qn,"m",Jn).call(this,i),t(this,qn,"a",Gn).call(this,"firmwareImages",{firmwareImages:t(this,Qn,"f")})};const xr=T("DeviceManager",{log:!0}),Ar=["deviceConnected","deviceDisconnected","deviceIsConnected","availableDevices","connectedDevices"];class Or{constructor(){if(vr.add(this),wr.set(this,{getType:t(this,vr,"m",yr).bind(this),isConnected:t(this,vr,"m",Fr).bind(this)}),br.set(this,[]),Sr.set(this,!1),Er.set(this,{devices:[]}),Mr.set(this,void 0),Dr.set(this,"BS.Device"),_r.set(this,[]),Ir.set(this,new _(this,Ar)),Or.shared&&this!=Or.shared)throw Error("DeviceManager is a singleton - use DeviceManager.shared");this.CanUseLocalStorage&&(this.UseLocalStorage=!0)}onDevice(e){Hi(e,t(this,wr,"f"))}OnDeviceConnectionStatusUpdated(e,s){if("notConnected"==s&&!e.canReconnect&&t(this,_r,"f").includes(e)){const s=t(this,_r,"f").indexOf(e);this.AvailableDevices.splice(s,1),t(this,vr,"m",Ur).call(this)}}get ConnectedDevices(){return t(this,br,"f")}get UseLocalStorage(){return t(this,Sr,"f")}set UseLocalStorage(e){t(this,vr,"m",Cr).call(this),xr.assertTypeWithError(e,"boolean"),s(this,Sr,e,"f"),t(this,Sr,"f")&&!t(this,Mr,"f")&&t(this,vr,"m",Tr).call(this)}get CanUseLocalStorage(){return n&&window.localStorage}get AvailableDevices(){return t(this,_r,"f")}get CanGetDevices(){return n&&navigator.bluetooth?.getDevices}async GetDevices(){if(!n)return void xr.warn("GetDevices is only available in the browser");if(!navigator.bluetooth)return void xr.warn("bluetooth is not available in this browser");if(c)return void xr.warn("bluefy lists too many devices...");if(!navigator.bluetooth.getDevices)return void xr.warn("bluetooth.getDevices() is not available in this browser");if(!this.CanGetDevices)return void xr.log("CanGetDevices is false");t(this,Mr,"f")||t(this,vr,"m",Tr).call(this);const e=t(this,Mr,"f");if(!e.devices||0==e.devices.length)return void xr.log("no devices found in configuration");const s=await navigator.bluetooth.getDevices();return xr.log({bluetoothDevices:s}),s.forEach((s=>{if(!s.gatt)return;let i=e.devices.find((e=>s.id==e.bluetoothId));if(!i)return;let n=this.ConnectedDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==s.id));const r=this.AvailableDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==s.id));if(r)return void(n&&n?.bluetoothId==r.bluetoothId&&n!=r&&(this.AvailableDevices[t(this,_r,"f").indexOf(r)]=n));if(n)return void this.AvailableDevices.push(n);const a=new Wa,o=new Cn;o.device=s,s.name&&a._informationManager.updateName(s.name),a._informationManager.updateType(i.type),a.connectionManager=o,this.AvailableDevices.push(a)})),t(this,vr,"m",Ur).call(this),this.AvailableDevices}get AddEventListener(){return t(this,Ir,"f").addEventListener}get RemoveEventListener(){return t(this,Ir,"f").removeEventListener}get RemoveEventListeners(){return t(this,Ir,"f").removeEventListeners}get RemoveAllEventListeners(){return t(this,Ir,"f").removeAllEventListeners}}wr=new WeakMap,br=new WeakMap,Sr=new WeakMap,Er=new WeakMap,Mr=new WeakMap,Dr=new WeakMap,_r=new WeakMap,Ir=new WeakMap,vr=new WeakSet,yr=function(e){t(this,Sr,"f")&&t(this,vr,"m",Wr).call(this,e.target)},Cr=function(){xr.assertWithError(n,"localStorage is only available in the browser"),xr.assertWithError(window.localStorage,"localStorage not found")},kr=function(){t(this,vr,"m",Cr).call(this),localStorage.setItem(t(this,Dr,"f"),JSON.stringify(t(this,Mr,"f")))},Tr=async function(){t(this,vr,"m",Cr).call(this);let e=localStorage.getItem(t(this,Dr,"f"));if("string"!=typeof e)return xr.log("no info found in localStorage"),s(this,Mr,Object.assign({},t(this,Er,"f")),"f"),void t(this,vr,"m",kr).call(this);try{const t=JSON.parse(e);xr.log({configuration:t}),s(this,Mr,t,"f"),this.CanGetDevices&&await this.GetDevices()}catch(e){xr.error(e)}},Wr=function(e){if("webBluetooth"!=e.connectionType)return void xr.log("localStorage is only for webBluetooth devices");t(this,vr,"m",Cr).call(this);const s=t(this,Mr,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1!=s&&(t(this,Mr,"f").devices[s].type=e.type,t(this,vr,"m",kr).call(this))},Lr=function(){return t(this,Ir,"f").dispatchEvent},Fr=function(e){const{target:s}=e;if(s.isConnected)if(t(this,br,"f").includes(s))xr.log("device already included");else{if(xr.log("adding device",s),t(this,br,"f").push(s),this.UseLocalStorage&&"webBluetooth"==s.connectionType){const e={type:s.type,bluetoothId:s.bluetoothId},i=t(this,Mr,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1==i?t(this,Mr,"f").devices.push(e):t(this,Mr,"f").devices[i]=e,t(this,vr,"m",kr).call(this)}t(this,vr,"a",Lr).call(this,"deviceConnected",{device:s}),t(this,vr,"a",Lr).call(this,"deviceIsConnected",{device:s}),t(this,vr,"m",Rr).call(this)}else t(this,br,"f").includes(s)?(xr.log("removing device",s),t(this,br,"f").splice(t(this,br,"f").indexOf(s),1),t(this,vr,"a",Lr).call(this,"deviceDisconnected",{device:s}),t(this,vr,"a",Lr).call(this,"deviceIsConnected",{device:s}),t(this,vr,"m",Rr).call(this)):xr.log("device already not included");if(this.CanGetDevices&&this.GetDevices(),s.isConnected&&!this.AvailableDevices.includes(s)){const e=this.AvailableDevices.find((e=>e.bluetoothId==s.bluetoothId));xr.log({existingAvailableDevice:e}),e?this.AvailableDevices[this.AvailableDevices.indexOf(e)]=s:this.AvailableDevices.push(s),t(this,vr,"m",Ur).call(this)}},Ur=function(){xr.log({AvailableDevices:this.AvailableDevices}),t(this,vr,"a",Lr).call(this,"availableDevices",{availableDevices:this.AvailableDevices})},Rr=function(){xr.log({ConnectedDevices:this.ConnectedDevices}),t(this,vr,"a",Lr).call(this,"connectedDevices",{connectedDevices:this.ConnectedDevices})},Or.shared=new Or;var $r,Br,Nr,Pr,Vr,zr,jr,qr,Gr,Hr,Jr,Qr,Kr,Zr,Xr,Yr,ea,ta,sa,ia,na,ra,aa,oa,ca,ha,la,ga,fa,ua,da,ma,pa,va,wa=Or.shared;const ya=T("Device",{log:!0}),ba=["connectionMessage",...Ni,...zi,...Vi,...Xs,...Ws,...Ot,...bt,...Oe,...vs,...dr],Sa=["isCharging","getBatteryCurrent","getId","getMtu","getName","getType","getCurrentTime","getSensorConfiguration","getSensorScalars","getPressurePositions","maxFileLength","getFileLength","getFileChecksum","getFileType","fileTransferStatus","getTfliteName","getTfliteTask","getTfliteSampleRate","getTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","getTfliteThreshold","getTfliteInferencingEnabled"];class Ea{get bluetoothId(){return t(this,zr,"f")?.bluetoothId}constructor(){$r.add(this),Pr.set(this,new _(this,ba)),zr.set(this,void 0),this.sendTxMessages=t(this,$r,"m",jr).bind(this),qr.set(this,!1),Zr.set(this,Br.ReconnectOnDisconnection),Xr.set(this,void 0),this.latestConnectionMessage=new Map,ra.set(this,new _s),aa.set(this,0),this._informationManager=new Ys,ca.set(this,new $t),la.set(this,Br.ClearSensorConfigurationOnLeave),ga.set(this,new St),fa.set(this,new Ei),ua.set(this,new $e),da.set(this,new bs),ma.set(this,new pr),this.sendSmpMessage=t(this,$r,"m",pa).bind(this),va.set(this,!1),t(this,ra,"f").eventDispatcher=t(this,Pr,"f"),this._informationManager.sendMessage=this.sendTxMessages,this._informationManager.eventDispatcher=t(this,Pr,"f"),t(this,ca,"f").sendMessage=this.sendTxMessages,t(this,ca,"f").eventDispatcher=t(this,Pr,"f"),t(this,ga,"f").eventDispatcher=t(this,Pr,"f"),t(this,fa,"f").sendMessage=this.sendTxMessages,t(this,da,"f").sendMessage=this.sendTxMessages,t(this,da,"f").eventDispatcher=t(this,Pr,"f"),t(this,ua,"f").sendMessage=this.sendTxMessages,t(this,ua,"f").eventDispatcher=t(this,Pr,"f"),t(this,ma,"f").sendMessage=this.sendSmpMessage,t(this,ma,"f").eventDispatcher=t(this,Pr,"f"),this.addEventListener("getMtu",(()=>{t(this,ma,"f").mtu=this.mtu,t(this,ua,"f").mtu=this.mtu,this.connectionManager.mtu=this.mtu})),wa.onDevice(this),n&&window.addEventListener("beforeunload",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()})),r&&process.on("exit",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()}))}get addEventListener(){return t(this,Pr,"f").addEventListener}get removeEventListener(){return t(this,Pr,"f").removeEventListener}get waitForEvent(){return t(this,Pr,"f").waitForEvent}get removeEventListeners(){return t(this,Pr,"f").removeEventListeners}get removeAllEventListeners(){return t(this,Pr,"f").removeAllEventListeners}get connectionManager(){return t(this,zr,"f")}set connectionManager(e){this.connectionManager!=e?(this.connectionManager&&(this.connectionManager.onStatusUpdated=void 0,this.connectionManager.onMessageReceived=void 0,this.connectionManager.onMessagesReceived=void 0),e&&(e.onStatusUpdated=t(this,$r,"m",Yr).bind(this),e.onMessageReceived=t(this,$r,"m",ia).bind(this),e.onMessagesReceived=t(this,$r,"m",na).bind(this)),s(this,zr,e,"f"),ya.log("assigned new connectionManager",t(this,zr,"f"))):ya.log("same connectionManager is already assigned")}async connect(){return this.connectionManager||(this.connectionManager=t(Br,Br,"m",Nr).call(Br)),t(this,$r,"m",sa).call(this),this.connectionManager.connect()}get isConnected(){return t(this,qr,"f")}get canReconnect(){return this.connectionManager?.canReconnect}async reconnect(){return t(this,$r,"m",Qr).call(this),t(this,$r,"m",sa).call(this),this.connectionManager?.reconnect()}static async Connect(){const e=new Br;return await e.connect(),e}static get ReconnectOnDisconnection(){return t(this,Br,"f",Kr)}static set ReconnectOnDisconnection(e){ya.assertTypeWithError(e,"boolean"),s(this,Br,e,"f",Kr)}get reconnectOnDisconnection(){return t(this,Zr,"f")}set reconnectOnDisconnection(e){ya.assertTypeWithError(e,"boolean"),s(this,Zr,e,"f")}get connectionType(){return this.connectionManager?.type}async disconnect(){return t(this,$r,"m",Gr).call(this),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.addEventListener("isConnected",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this.connectionManager.disconnect()}toggleConnection(){this.isConnected?this.disconnect():this.canReconnect?this.reconnect():this.connect()}get connectionStatus(){switch(t(this,zr,"f")?.status){case"connected":return this.isConnected?"connected":"connecting";case"notConnected":case"connecting":case"disconnecting":return t(this,zr,"f").status;default:return"notConnected"}}get isConnectionBusy(){return"connecting"==this.connectionStatus||"disconnecting"==this.connectionStatus}get deviceInformation(){return t(this,ra,"f").information}get batteryLevel(){return t(this,aa,"f")}get id(){return this._informationManager.id}get isCharging(){return this._informationManager.isCharging}get batteryCurrent(){return this._informationManager.batteryCurrent}get getBatteryCurrent(){return this._informationManager.getBatteryCurrent}get name(){return this._informationManager.name}get setName(){return this._informationManager.setName}get type(){return this._informationManager.type}get setType(){return this._informationManager.setType}get isInsole(){return this._informationManager.isInsole}get insoleSide(){return this._informationManager.insoleSide}get mtu(){return this._informationManager.mtu}get sensorTypes(){return Object.keys(this.sensorConfiguration)}get continuousSensorTypes(){return wt.filter((e=>this.sensorTypes.includes(e)))}get sensorConfiguration(){return t(this,ca,"f").configuration}async setSensorConfiguration(e,s){await t(this,ca,"f").setConfiguration(e,s)}async clearSensorConfiguration(){return t(this,ca,"f").clearSensorConfiguration()}static get ClearSensorConfigurationOnLeave(){return t(this,Br,"f",ha)}static set ClearSensorConfigurationOnLeave(e){ya.assertTypeWithError(e,"boolean"),s(this,Br,e,"f",ha)}get clearSensorConfigurationOnLeave(){return t(this,la,"f")}set clearSensorConfigurationOnLeave(e){ya.assertTypeWithError(e,"boolean"),s(this,la,e,"f")}get numberOfPressureSensors(){return t(this,ga,"f").pressureSensorDataManager.numberOfSensors}resetPressureRange(){t(this,ga,"f").pressureSensorDataManager.resetRange()}async triggerVibration(e,s){t(this,fa,"f").triggerVibration(e,s)}get maxFileLength(){return t(this,ua,"f").maxLength}async sendFile(e,s){const i=this.waitForEvent("fileTransferComplete");t(this,ua,"f").send(e,s),await i}async receiveFile(e){const s=this.waitForEvent("fileTransferComplete");t(this,ua,"f").receive(e),await s}get fileTransferStatus(){return t(this,ua,"f").status}cancelFileTransfer(){t(this,ua,"f").cancel()}get tfliteName(){return t(this,da,"f").name}get setTfliteName(){return t(this,da,"f").setName}get tfliteTask(){return t(this,da,"f").task}get setTfliteTask(){return t(this,da,"f").setTask}get tfliteSampleRate(){return t(this,da,"f").sampleRate}get setTfliteSampleRate(){return t(this,da,"f").setSampleRate}get tfliteSensorTypes(){return t(this,da,"f").sensorTypes}get allowedTfliteSensorTypes(){return this.sensorTypes.filter((e=>ys.includes(e)))}get setTfliteSensorTypes(){return t(this,da,"f").setSensorTypes}get tfliteIsReady(){return t(this,da,"f").isReady}get tfliteInferencingEnabled(){return t(this,da,"f").inferencingEnabled}get setTfliteInferencingEnabled(){return t(this,da,"f").setInferencingEnabled}async enableTfliteInferencing(){return this.setTfliteInferencingEnabled(!0)}async disableTfliteInferencing(){return this.setTfliteInferencingEnabled(!1)}get toggleTfliteInferencing(){return t(this,da,"f").toggleInferencingEnabled}get tfliteCaptureDelay(){return t(this,da,"f").captureDelay}get setTfliteCaptureDelay(){return t(this,da,"f").setCaptureDelay}get tfliteThreshold(){return t(this,da,"f").threshold}get setTfliteThreshold(){return t(this,da,"f").setThreshold}get uploadFirmware(){return t(this,ma,"f").uploadFirmware}async reset(){return await t(this,ma,"f").reset(),t(this,zr,"f").disconnect()}get firmwareStatus(){return t(this,ma,"f").status}get getFirmwareImages(){return t(this,ma,"f").getImages}get firmwareImages(){return t(this,ma,"f").images}get eraseFirmwareImage(){return t(this,ma,"f").eraseImage}get confirmFirmwareImage(){return t(this,ma,"f").confirmImage}get testFirmwareImage(){return t(this,ma,"f").testImage}get isServerSide(){return t(this,va,"f")}set isServerSide(e){t(this,va,"f")!=e?(ya.log({newIsServerSide:e}),s(this,va,e,"f"),t(this,ua,"f").isServerSide=this.isServerSide):ya.log("redundant isServerSide assignment")}}Br=Ea,Pr=new WeakMap,zr=new WeakMap,qr=new WeakMap,Zr=new WeakMap,Xr=new WeakMap,ra=new WeakMap,aa=new WeakMap,ca=new WeakMap,la=new WeakMap,ga=new WeakMap,fa=new WeakMap,ua=new WeakMap,da=new WeakMap,ma=new WeakMap,va=new WeakMap,$r=new WeakSet,Nr=function(){return new Cn},Vr=function(){return t(this,Pr,"f").dispatchEvent},jr=async function(e,s){await(t(this,zr,"f")?.sendTxMessages(e,s))},Gr=function(){ya.assertWithError(this.isConnected,"notConnected")},Hr=function(){return Sa.every((e=>this.latestConnectionMessage.has(e)))},Jr=function(){const e=Sa.map((e=>({type:e})));t(this,$r,"m",jr).call(this,e)},Qr=function(){ya.assertWithError(this.canReconnect,"cannot reconnect to device")},Yr=function(e){ya.log({connectionStatus:e}),"notConnected"==e?this.canReconnect&&this.reconnectOnDisconnection&&(ya.log("starting reconnect interval..."),s(this,Xr,setInterval((()=>{ya.log("attempting reconnect..."),this.reconnect()}),1e3),"f")):null!=t(this,Xr,"f")&&(ya.log("clearing reconnect interval"),clearInterval(t(this,Xr,"f")),s(this,Xr,void 0,"f")),t(this,$r,"m",ta).call(this),"connected"!=e||t(this,qr,"f")||t(this,$r,"m",Jr).call(this),wa.OnDeviceConnectionStatusUpdated(this,e)},ea=function(e=!1){t(this,$r,"a",Vr).call(this,"connectionStatus",{connectionStatus:this.connectionStatus}),t(this,$r,"a",Vr).call(this,this.connectionStatus,{}),e&&t(this,$r,"a",Vr).call(this,"isConnected",{isConnected:this.isConnected})},ta=function(){switch(s(this,qr,Boolean(this.connectionManager?.isConnected)&&t(this,$r,"a",Hr)&&this._informationManager.isCurrentTimeSet,"f"),this.connectionStatus){case"connected":t(this,qr,"f")&&t(this,$r,"m",ea).call(this,!0);break;case"notConnected":t(this,$r,"m",ea).call(this,!0);break;default:t(this,$r,"m",ea).call(this,!1)}},sa=function(){this.latestConnectionMessage.clear(),this._informationManager.clear(),t(this,ra,"f").clear()},ia=function(e,s){if(ya.log({messageType:e,dataView:s}),"batteryLevel"===e){const e=s.getUint8(0);ya.log("received battery level",{batteryLevel:e}),t(this,$r,"m",oa).call(this,e)}else if(Ue.includes(e))t(this,ua,"f").parseMessage(e,s);else if(ps.includes(e))t(this,da,"f").parseMessage(e,s);else if(yt.includes(e))t(this,ga,"f").parseMessage(e,s);else if(ur.includes(e))t(this,ma,"f").parseMessage(e,s);else if(Ts.includes(e))t(this,ra,"f").parseMessage(e,s);else if(Zs.includes(e))this._informationManager.parseMessage(e,s);else{if(!At.includes(e))throw Error(`uncaught messageType ${e}`);t(this,ca,"f").parseMessage(e,s)}this.latestConnectionMessage.set(e,s),t(this,$r,"a",Vr).call(this,"connectionMessage",{messageType:e,dataView:s})},na=function(){!this.isConnected&&t(this,$r,"a",Hr)&&t(this,$r,"m",ta).call(this),"notConnected"!=this.connectionStatus&&t(this,$r,"m",jr).call(this)},oa=function(e){ya.assertTypeWithError(e,"number"),t(this,aa,"f")!=e?(s(this,aa,e,"f"),ya.log({updatedBatteryLevel:t(this,aa,"f")}),t(this,$r,"a",Vr).call(this,"batteryLevel",{batteryLevel:t(this,aa,"f")})):ya.log(`duplicate batteryLevel assignment ${e}`)},pa=function(e){return t(this,zr,"f").sendSmpMessage(e)},Kr={value:!1},ha={value:!0};var Ma,Ca,Da,ka,Ta,Wa=Ea;const _a=T("DevicePairPressureSensorDataManager",{log:!0});class Ia{constructor(){Ma.add(this),Ca.set(this,{}),Da.set(this,new Ze)}resetPressureRange(){t(this,Da,"f").reset()}onDevicePressureData(e){const{pressure:s}=e.message,i=e.target.insoleSide;if(_a.log({pressure:s,insoleSide:i}),t(this,Ca,"f")[i]=s,t(this,Ma,"a",ka))return t(this,Ma,"m",Ta).call(this);_a.log("doesn't have all pressure data yet...")}}var La;Ca=new WeakMap,Da=new WeakMap,Ma=new WeakSet,ka=function(){return Ks.every((e=>e in t(this,Ca,"f")))},Ta=function(){const e={rawSum:0,normalizedSum:0};return Ks.forEach((s=>{e.rawSum+=t(this,Ca,"f")[s].scaledSum,e.normalizedSum+=t(this,Ca,"f")[s].normalizedSum})),e.normalizedSum>.001&&(e.center={x:0,y:0},Ks.forEach((s=>{const i=t(this,Ca,"f")[s],n=i.normalizedSum/e.normalizedSum;n>0&&(null!=i.normalizedCenter?.y&&(e.center.y+=i.normalizedCenter.y*n),"right"==s&&(e.center.x=n))})),e.normalizedCenter=t(this,Da,"f").updateAndGetNormalization(e.center)),_a.log({devicePairPressure:e}),e};const Fa=T("DevicePairSensorDataManager",{log:!0}),Ua=["pressure","sensorData"];class Ra{constructor(){La.set(this,{}),this.pressureSensorDataManager=new Ia}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}resetPressureRange(){this.pressureSensorDataManager.resetPressureRange()}onDeviceSensorData(e){const{timestamp:s,sensorType:i}=e.message;let n;if(Fa.log({sensorType:i,timestamp:s,event:e}),t(this,La,"f")[i]||(t(this,La,"f")[i]={}),t(this,La,"f")[i][e.target.insoleSide]=s,"pressure"===i)n=this.pressureSensorDataManager.onDevicePressureData(e);else Fa.log(`uncaught sensorType "${i}"`);if(n){const e=Object.assign({},t(this,La,"f")[i]);this.dispatchEvent(i,{sensorType:i,timestamps:e,[i]:n}),this.dispatchEvent("sensorData",{sensorType:i,timestamps:e,[i]:n})}else Fa.log("no value received")}}var xa,Aa,Oa,$a,Ba,Na,Pa,Va,za,ja,qa,Ga,Ha,Ja,Qa,Ka;La=new WeakMap;const Za=T("DevicePair",{log:!0});function Xa(e){return`device${t=e,t[0].toUpperCase()+t.slice(1)}`;var t}const Ya=["isConnected",...Ua,...ba.map((e=>Xa(e)))];class eo{constructor(){xa.add(this),Oa.set(this,new _(this,Ya)),Ba.set(this,void 0),Na.set(this,void 0),ja.set(this,{isConnected:t(this,xa,"m",Ga).bind(this),sensorData:t(this,xa,"m",Qa).bind(this),getType:t(this,xa,"m",Ha).bind(this)}),Ja.set(this,new Ra),t(this,Ja,"f").eventDispatcher=t(this,Oa,"f")}get sides(){return Ks}get addEventListener(){return t(this,Oa,"f").addEventListener}get removeEventListener(){return t(this,Oa,"f").removeEventListener}get waitForEvent(){return t(this,Oa,"f").waitForEvent}get removeEventListeners(){return t(this,Oa,"f").removeEventListeners}get removeAllEventListeners(){return t(this,Oa,"f").removeAllEventListeners}get left(){return t(this,Ba,"f")}get right(){return t(this,Na,"f")}get isConnected(){return Ks.every((e=>this[e]?.isConnected))}get isPartiallyConnected(){return Ks.some((e=>this[e]?.isConnected))}get isHalfConnected(){return this.isPartiallyConnected&&!this.isConnected}assignInsole(e){if(!e.isInsole)return void Za.warn("device is not an insole");const i=e.insoleSide,n=this[i];if(e!=n){switch(n&&t(this,xa,"m",Va).call(this,n),t(this,xa,"m",Pa).call(this,e),i){case"left":s(this,Ba,e,"f");break;case"right":s(this,Na,e,"f")}return Za.log(`assigned ${i} insole`,e),this.resetPressureRange(),t(this,xa,"a",$a).call(this,"isConnected",{isConnected:this.isConnected}),t(this,xa,"a",$a).call(this,"deviceIsConnected",{device:e,isConnected:e.isConnected,side:i}),n}Za.log("device already assigned")}async setSensorConfiguration(e){for(let t=0;t<Ks.length;t++){const s=Ks[t];this[s]?.isConnected&&await this[s].setSensorConfiguration(e)}}resetPressureRange(){t(this,Ja,"f").resetPressureRange()}async triggerVibration(e,t){const s=Ks.map((s=>this[s]?.triggerVibration(e,t))).filter(Boolean);return Promise.allSettled(s)}static get shared(){return t(this,Aa,"f",Ka)}}Aa=eo,Oa=new WeakMap,Ba=new WeakMap,Na=new WeakMap,ja=new WeakMap,Ja=new WeakMap,xa=new WeakSet,$a=function(){return t(this,Oa,"f").dispatchEvent},Pa=function(e){Hi(e,t(this,ja,"f")),ba.forEach((s=>{e.addEventListener(s,t(this,xa,"m",qa).bind(this))}))},Va=function(e){Ji(e,t(this,ja,"f")),ba.forEach((s=>{e.removeEventListener(s,t(this,xa,"m",qa).bind(this))}))},za=function(e){const s=Ks.some((s=>this[s]==e&&(Za.log(`removing ${s} insole`,e),Ji(e,t(this,ja,"f")),delete this[s],!0)));return s&&t(this,xa,"a",$a).call(this,"isConnected",{isConnected:this.isConnected}),s},qa=function(e){const{type:s,target:i,message:n}=e;t(this,xa,"a",$a).call(this,Xa(s),{...n,device:i,side:i.insoleSide})},Ga=function(e){t(this,xa,"a",$a).call(this,"isConnected",{isConnected:this.isConnected})},Ha=function(e){const{target:s}=e;if(this[s.insoleSide]==s)return;t(this,xa,"m",za).call(this,s)&&this.assignInsole(s)},Qa=function(e){this.isConnected&&t(this,Ja,"f").onDeviceSensorData(e)},Ka={value:new Aa},wa.AddEventListener("deviceConnected",(e=>{const{device:s}=e.message;s.isInsole&&t(Aa,Aa,"f",Ka).assignInsole(s)}));const to=T("ServerUtils",{log:!1}),so=["isScanningAvailable","isScanning","startScan","stopScan","discoveredDevice","discoveredDevices","expiredDiscoveredDevice","connectToDevice","disconnectFromDevice","connectedDevices","deviceMessage"];function io(e,...t){to.log("createMessage",...t);const s=t.map((t=>{"string"==typeof t&&(t={type:t}),null!=t.data?Array.isArray(t.data)||(t.data=[t.data]):t.data=[];const s=z(...t.data),i=s.byteLength;to.assertEnumWithError(t.type,e);const n=e.indexOf(t.type),r=new DataView(new ArrayBuffer(2));return r.setUint16(0,i,!0),z(n,r,s)}));return to.log("messageBuffers",...s),z(...s)}function no(...e){return to.log("createServerMessage",...e),io(so,...e)}function ro(...e){return to.log("createClientDeviceMessage",...e),io(ji,...e)}var ao,oo,co,ho,lo;no("isScanningAvailable"),no("isScanning"),no("startScan"),no("stopScan"),no("discoveredDevices");const go=T("ClientConnectionManager",{log:!0}),fo=[...Ts,"batteryLevel"];class uo extends qi{constructor(){super(...arguments),ao.add(this),oo.set(this,void 0),co.set(this,!1)}static get isSupported(){return n}static get type(){return"client"}get bluetoothId(){return t(this,oo,"f")}set bluetoothId(e){go.assertTypeWithError(e,"string"),t(this,oo,"f")!=e?s(this,oo,e,"f"):go.log("redundant bluetoothId assignment")}get isConnected(){return t(this,co,"f")}set isConnected(e){go.assertTypeWithError(e,"boolean"),t(this,co,"f")!=e?(s(this,co,e,"f"),this.status=t(this,co,"f")?"connected":"notConnected",this.isConnected&&t(this,ao,"m",ho).call(this)):go.log("redundant newIsConnected assignment",e)}async connect(){await super.connect(),this.sendClientConnectMessage()}async disconnect(){await super.disconnect(),this.sendClientDisconnectMessage()}get canReconnect(){return!0}async reconnect(){await super.reconnect(),go.log("attempting to reconnect..."),this.connect()}async sendSmpMessage(e){super.sendSmpMessage(e),this.sendClientMessage({type:"smp",data:e})}async sendTxData(e){super.sendTxData(e),0!=e.byteLength&&this.sendClientMessage({type:"tx",data:e})}onClientMessage(e){go.log({dataView:e}),dt(e,ba,t(this,ao,"m",lo).bind(this),null,!0),this.onMessagesReceived()}}var mo,po,vo,wo,yo,bo,So,Eo,Mo,Co,Do,ko,To,Wo,_o,Io,Lo,Fo,Uo;oo=new WeakMap,co=new WeakMap,ao=new WeakSet,ho=function(){this.sendClientMessage(...fo)},lo=function(e,t){let s=0;switch(go.log({messageType:e},t),e){case"isConnected":const i=Boolean(t.getUint8(s++));go.log({isConnected:i}),this.isConnected=i;break;case"rx":this.parseRxMessage(t);break;default:this.onMessageReceived(e,t)}};const Ro=T("BaseClient",{log:!0}),xo=["notConnected","connecting","connected","disconnecting","connectionStatus","isConnected","isScanningAvailable","isScanning","discoveredDevice","expiredDiscoveredDevice"];class Ao{constructor(){mo.add(this),vo.set(this,{}),wo.set(this,new _(this,xo)),this._reconnectOnDisconnection=this.baseConstructor.ReconnectOnDisconnection,yo.set(this,"notConnected"),So.set(this,!1),Do.set(this,!1),Lo.set(this,{})}get baseConstructor(){return this.constructor}get devices(){return t(this,vo,"f")}get addEventListener(){return t(this,wo,"f").addEventListener}get dispatchEvent(){return t(this,wo,"f").dispatchEvent}get removeEventListener(){return t(this,wo,"f").removeEventListener}get waitForEvent(){return t(this,wo,"f").waitForEvent}assertConnection(){Ro.assertWithError(this.isConnected,"notConnected")}assertDisconnection(){Ro.assertWithError(this.isDisconnected,"not disconnected")}static get ReconnectOnDisconnection(){return this._reconnectOnDisconnection}static set ReconnectOnDisconnection(e){Ro.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get reconnectOnDisconnection(){return this._reconnectOnDisconnection}set reconnectOnDisconnection(e){Ro.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get _connectionStatus(){return t(this,yo,"f")}set _connectionStatus(e){switch(Ro.assertTypeWithError(e,"string"),Ro.log({newConnectionStatus:e}),s(this,yo,e,"f"),this.dispatchEvent("connectionStatus",{connectionStatus:this.connectionStatus}),this.dispatchEvent(this.connectionStatus,{}),e){case"connected":case"notConnected":this.dispatchEvent("isConnected",{isConnected:this.isConnected}),this.isConnected?this.sendServerMessage("isScanningAvailable","discoveredDevices","connectedDevices"):t(this,mo,"m",po).call(this)}}get connectionStatus(){return this._connectionStatus}parseMessage(e){Ro.log("parseMessage",{dataView:e}),dt(e,so,t(this,mo,"m",bo).bind(this),null,!0)}get isScanningAvailable(){return t(this,mo,"a",Eo)}requestIsScanningAvailable(){this.sendServerMessage("isScanningAvailable")}get isScanning(){return t(this,mo,"a",ko)}startScan(){t(this,mo,"m",Io).call(this),this.sendServerMessage("startScan")}stopScan(){t(this,mo,"m",_o).call(this),this.sendServerMessage("stopScan")}toggleScan(){t(this,mo,"m",Co).call(this),this.isScanning?this.stopScan():this.startScan()}get discoveredDevices(){return t(this,Lo,"f")}onDiscoveredDevice(e){Ro.log({discoveredDevice:e}),t(this,Lo,"f")[e.bluetoothId]=e,this.dispatchEvent("discoveredDevice",{discoveredDevice:e})}requestDiscoveredDevices(){this.sendServerMessage({type:"discoveredDevices"})}connectToDevice(e){return this.requestConnectionToDevice(e)}requestConnectionToDevice(e){this.assertConnection(),Ro.assertTypeWithError(e,"string");const s=t(this,mo,"m",Uo).call(this,e);return s.connect(),s}sendConnectToDeviceMessage(e){this.sendServerMessage({type:"connectToDevice",data:e})}createDevice(e){const t=new Wa,s=new uo;return s.bluetoothId=e,s.sendClientMessage=this.sendDeviceMessage.bind(this,e),s.sendClientConnectMessage=this.sendConnectToDeviceMessage.bind(this,e),s.sendClientDisconnectMessage=this.sendDisconnectFromDeviceMessage.bind(this,e),t.connectionManager=s,t}onConnectedBluetoothDeviceIds(e){Ro.log({bluetoothIds:e}),e.forEach((e=>{t(this,mo,"m",Uo).call(this,e).connectionManager.isConnected=!0}))}disconnectFromDevice(e){this.requestDisconnectionFromDevice(e)}requestDisconnectionFromDevice(e){this.assertConnection(),Ro.assertTypeWithError(e,"string");const t=this.devices[e];return Ro.assertWithError(t,`no device found with id ${e}`),t.disconnect(),t}sendDisconnectFromDeviceMessage(e){this.sendServerMessage({type:"disconnectFromDevice",data:e})}sendDeviceMessage(e,...t){this.sendServerMessage({type:"deviceMessage",data:[e,ro(...t)]})}}vo=new WeakMap,wo=new WeakMap,yo=new WeakMap,So=new WeakMap,Do=new WeakMap,Lo=new WeakMap,mo=new WeakSet,po=function(){s(this,mo,!1,"a",Mo),s(this,mo,!1,"a",To);for(const e in t(this,vo,"f")){t(this,vo,"f")[e].connectionManager.isConnected=!1}},bo=function(e,i){let n=0;switch(Ro.log({messageType:e},i),e){case"isScanningAvailable":{const e=Boolean(i.getUint8(n++));Ro.log({isScanningAvailable:e}),s(this,mo,e,"a",Mo)}break;case"isScanning":{const e=Boolean(i.getUint8(n++));Ro.log({isScanning:e}),s(this,mo,e,"a",To)}break;case"discoveredDevice":{const{string:e}=ut(i,n);Ro.log({discoveredDeviceString:e});const t=JSON.parse(e);Ro.log({discoveredDevice:t}),this.onDiscoveredDevice(t)}break;case"expiredDiscoveredDevice":{const{string:e}=ut(i,n);t(this,mo,"m",Fo).call(this,e)}break;case"connectedDevices":{if(0==i.byteLength)break;const{string:e}=ut(i,n);Ro.log({connectedBluetoothDeviceIdStrings:e});const t=JSON.parse(e);Ro.log({connectedBluetoothDeviceIds:t}),this.onConnectedBluetoothDeviceIds(t)}break;case"deviceMessage":{const{string:e,byteOffset:s}=ut(i,n);n=s;const r=t(this,vo,"f")[e];Ro.assertWithError(r,`no device found for id ${e}`);const a=r.connectionManager,o=q(i,n);a.onClientMessage(o)}break;default:Ro.error(`uncaught messageType "${e}"`)}},Eo=function(){return t(this,So,"f")},Mo=function(e){Ro.assertTypeWithError(e,"boolean"),s(this,So,e,"f"),this.dispatchEvent("isScanningAvailable",{isScanningAvailable:this.isScanningAvailable}),this.isScanningAvailable&&t(this,mo,"m",Wo).call(this)},Co=function(){this.assertConnection(),Ro.assertWithError(this.isScanningAvailable,"scanning is not available")},ko=function(){return t(this,Do,"f")},To=function(e){Ro.assertTypeWithError(e,"boolean"),s(this,Do,e,"f"),this.dispatchEvent("isScanning",{isScanning:this.isScanning})},Wo=function(){this.sendServerMessage("isScanning")},_o=function(){Ro.assertWithError(this.isScanning,"is not scanning")},Io=function(){Ro.assertWithError(!this.isScanning,"is already scanning")},Fo=function(e){Ro.log({expiredBluetoothDeviceId:e});const s=t(this,Lo,"f")[e];s?(Ro.log({expiredDiscoveredDevice:s}),delete t(this,Lo,"f")[e],this.dispatchEvent("expiredDiscoveredDevice",{discoveredDevice:s})):Ro.warn(`no discoveredDevice found with id "${e}"`)},Uo=function(e){let s=t(this,vo,"f")[e];return s||(s=this.createDevice(e),t(this,vo,"f")[e]=s),s},Ao._reconnectOnDisconnection=!0;const Oo=T("WebSocketUtils",{log:!1}),$o=["ping","pong","serverMessage"];function Bo(...e){return Oo.log("createWebSocketMessage",...e),io($o,...e)}var No,Po,Vo,zo,jo,qo,Go,Ho,Jo,Qo,Ko,Zo,Xo;Bo("ping"),Bo("pong");const Yo=T("WebSocketClient",{log:!0});Po=new WeakMap,zo=new WeakMap,Ko=new WeakMap,No=new WeakSet,Vo=function(...e){this.sendMessage(Bo(...e))},jo=function(e){Yo.log("webSocket.open",e),t(this,Ko,"f").start(),this._connectionStatus="connected"},qo=async function(e){Yo.log("webSocket.message",e),t(this,Ko,"f").restart();const s=await e.data.arrayBuffer(),i=new DataView(s);t(this,No,"m",Jo).call(this,i)},Go=function(e){Yo.log("webSocket.close",e),this._connectionStatus="notConnected",Object.entries(this.devices).forEach((([e,t])=>{t.connectionManager.isConnected=!1})),t(this,Ko,"f").stop(),this.reconnectOnDisconnection&&setTimeout((()=>{this.reconnect()}),3e3)},Ho=function(e){Yo.error("webSocket.error",e.message)},Jo=function(e){dt(e,$o,t(this,No,"m",Qo).bind(this),null,!0)},Qo=function(e,s){switch(e){case"ping":t(this,No,"m",Xo).call(this);break;case"pong":break;case"serverMessage":this.parseMessage(s);break;default:Yo.error(`uncaught messageType "${e}"`)}},Zo=function(){t(this,No,"m",Vo).call(this,"ping")},Xo=function(){t(this,No,"m",Vo).call(this,"pong")},e.ContinuousSensorTypes=wt,e.DefaultNumberOfPressureSensors=8,e.Device=Wa,e.DeviceManager=wa,e.DevicePair=eo,e.DeviceTypes=Qs,e.Environment=y,e.FileTransferDirections=["sending","receiving"],e.FileTypes=Re,e.InsoleSides=Ks,e.MaxNameLength=30,e.MaxNumberOfVibrationWaveformEffectSegments=8,e.MaxNumberOfVibrationWaveformSegments=20,e.MaxSensorRate=65535,e.MaxVibrationWaveformEffectSegmentDelay=Si,e.MaxVibrationWaveformEffectSegmentLoopCount=3,e.MaxVibrationWaveformEffectSequenceLoopCount=6,e.MaxVibrationWaveformSegmentDuration=bi,e.MinNameLength=2,e.RangeHelper=Ge,e.SensorRateStep=5,e.SensorTypes=vt,e.TfliteSensorTypes=ys,e.TfliteTasks=ws,e.VibrationLocations=wi,e.VibrationTypes=yi,e.VibrationWaveformEffects=ei,e.WebSocketClient=class extends Ao{constructor(){super(...arguments),No.add(this),Po.set(this,void 0),zo.set(this,{open:t(this,No,"m",jo).bind(this),message:t(this,No,"m",qo).bind(this),close:t(this,No,"m",Go).bind(this),error:t(this,No,"m",Ho).bind(this)}),Ko.set(this,new R(t(this,No,"m",Zo).bind(this),3e7))}get webSocket(){return t(this,Po,"f")}set webSocket(e){t(this,Po,"f")!=e?(Yo.log("assigning webSocket",e),t(this,Po,"f")&&Ji(t(this,Po,"f"),t(this,zo,"f")),Hi(e,t(this,zo,"f")),s(this,Po,e,"f"),Yo.log("assigned webSocket")):Yo.log("redundant webSocket assignment")}get readyState(){return this.webSocket?.readyState}get isConnected(){return this.readyState==WebSocket.OPEN}get isDisconnected(){return this.readyState==WebSocket.CLOSED}connect(e=`wss://${location.host}`){this.webSocket&&this.assertDisconnection(),this._connectionStatus="connecting",this.webSocket=new WebSocket(e)}disconnect(){this.assertConnection(),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.webSocket.addEventListener("close",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this._connectionStatus="disconnecting",this.webSocket.close()}reconnect(){this.assertDisconnection(),this.connect(this.webSocket.url)}toggleConnection(e){this.isConnected?this.disconnect():e&&this.webSocket?.url==e?this.reconnect():this.connect(e)}sendMessage(e){this.assertConnection(),t(this,Po,"f").send(e)}sendServerMessage(...e){this.sendMessage(Bo({type:"serverMessage",data:no(...e)}))}},e.setAllConsoleLevelFlags=function(e){k.setAllLevelFlags(e)},e.setConsoleLevelFlagsForType=function(e,t){k.setLevelFlagsForType(e,t)}}));
5
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BS={})}(this,(function(e){"use strict";function t(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)}function s(e,t,s,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,s):n?n.value=s:t.set(e,s),s}"function"==typeof SuppressedError&&SuppressedError;const i=!1,n="undefined"!=typeof window&&void 0!==window?.document,r="undefined"!=typeof process&&null!=process?.versions?.node,a=n&&navigator.userAgent||"";let o=!1;n?o=Boolean(navigator.bluetooth):r&&(o=!0);const c=n&&/Bluefy/i.test(a),h=n&&/WebBLE/i.test(a),l=n&&/Android/i.test(a),g=n&&/Safari/i.test(a)&&!/Chrome/i.test(a),f=n&&/iPad|iPhone|iPod/i.test(a),u=n&&/Macintosh/i.test(a),d=!n&&!r&&"undefined"!=typeof global&&"undefined"!=typeof Studio;var m,p,v,w,y=Object.freeze({__proto__:null,isAndroid:l,get isBluetoothSupported(){return o},isIOS:f,isInBluefy:c,isInBrowser:n,isInDev:i,isInLensStudio:d,isInNode:r,isInProduction:!0,isInWebBLE:h,isMac:u,isSafari:g});if(d){const e=function(...e){Studio.log(e.map((e=>new String(e))).join(","))};(w={}).log=e,w.warn=e.bind(w,"WARNING"),w.error=e.bind(w,"ERROR")}else w=console;if(!w.assert){const e=(e,...t)=>{e||w.warn(...t)};w.assert=e}if(!w.table){const e=(...e)=>{w.log(...e)};w.table=e}function b(){}const S=w.log.bind(w),E=w.warn.bind(w),M=w.error.bind(w),C=w.table.bind(w),D=w.assert.bind(w);class k{constructor(e){if(v.set(this,{log:i,warn:i,assert:!0,error:!0,table:!0}),t(m,m,"f",p)[e])throw new Error(`"${e}" console already exists`);t(m,m,"f",p)[e]=this}setLevelFlags(e){Object.assign(t(this,v,"f"),e)}static setLevelFlagsForType(e,s){if(!t(this,m,"f",p)[e])throw new Error(`no console found with type "${e}"`);t(this,m,"f",p)[e].setLevelFlags(s)}static setAllLevelFlags(e){for(const s in t(this,m,"f",p))t(this,m,"f",p)[s].setLevelFlags(e)}static create(e,s){return t(this,m,"f",p)[e]||new m(e)}get log(){return t(this,v,"f").log?S:b}get warn(){return t(this,v,"f").warn?E:b}get error(){return t(this,v,"f").error?M:b}get assert(){return t(this,v,"f").assert?D:b}get table(){return t(this,v,"f").table?C:b}assertWithError(e,t){if(!Boolean(e))throw new Error(t)}assertTypeWithError(e,t){this.assertWithError(typeof e==t,`value ${e} of type "${typeof e}" not of type "${t}"`)}assertEnumWithError(e,t){this.assertWithError(t.includes(e),`invalid enum "${e}"`)}}function T(e,t){return k.create(e,t)}m=k,v=new WeakMap,p={value:{}};const W=T("EventDispatcher",{log:!1});class _{constructor(e,t){this.target=e,this.validEventTypes=t,this.listeners={},this.addEventListener=this.addEventListener.bind(this),this.removeEventListener=this.removeEventListener.bind(this),this.removeEventListeners=this.removeEventListeners.bind(this),this.removeAllEventListeners=this.removeAllEventListeners.bind(this),this.dispatchEvent=this.dispatchEvent.bind(this),this.waitForEvent=this.waitForEvent.bind(this)}isValidEventType(e){return this.validEventTypes.includes(e)}updateEventListeners(e){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter((t=>(t.shouldRemove&&W.log(`removing "${e}" eventListener`,t),!t.shouldRemove))))}addEventListener(e,t,s={once:!1}){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]||(this.listeners[e]=[],W.log(`creating "${e}" listeners array`,this.listeners[e]));this.listeners[e].find((e=>e.listener==t&&e.once==s.once))?W.log("already added listener"):(W.log(`adding "${e}" listener`,t,s),this.listeners[e].push({listener:t,once:s.once}),W.log(`currently have ${this.listeners[e].length} "${e}" listeners`))}removeEventListener(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(W.log(`removing "${e}" listener...`,t),this.listeners[e].forEach((s=>{s.listener===t&&(W.log(`flagging "${e}" listener`,t),s.shouldRemove=!0)})),this.updateEventListeners(e))}removeEventListeners(e){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(W.log(`removing "${e}" listeners...`),this.listeners[e]=[])}removeAllEventListeners(){W.log("removing listeners..."),this.listeners={}}dispatchEvent(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(this.listeners[e].forEach((s=>{s.shouldRemove||(W.log(`dispatching "${e}" listener`,s),s.listener({type:e,target:this.target,message:t}),s.once&&(W.log(`flagging "${e}" listener`,s),s.shouldRemove=!0))})),this.updateEventListeners(e))}waitForEvent(e){return new Promise((t=>{this.addEventListener(e,(e=>{t(e)}),{once:!0})}))}}var I,L,F;const U=T("Timer",{log:!1});class R{get callback(){return t(this,I,"f")}set callback(e){U.assertTypeWithError(e,"function"),U.log({newCallback:e}),s(this,I,e,"f"),this.isRunning&&this.restart()}get interval(){return t(this,L,"f")}set interval(e){U.assertTypeWithError(e,"number"),U.assertWithError(e>0,"interval must be above 0"),U.log({newInterval:e}),s(this,L,e,"f"),this.isRunning&&this.restart()}constructor(e,t){I.set(this,void 0),L.set(this,void 0),F.set(this,void 0),this.interval=t,this.callback=e}get isRunning(){return null!=t(this,F,"f")}start(e=!1){this.isRunning?U.log("interval already running"):(U.log("starting interval"),s(this,F,setInterval(t(this,I,"f"),t(this,L,"f")),"f"),e&&t(this,I,"f").call(this))}stop(){this.isRunning?(U.log("stopping interval"),clearInterval(t(this,F,"f")),s(this,F,void 0,"f")):U.log("interval already not running")}restart(e=!1){this.stop(),this.start(e)}}function x(e){for(let t=0;t<8;++t)e=(1&e?0:3988292384)^e>>>1;return 4278190080^e}I=new WeakMap,L=new WeakMap,F=new WeakMap,T("checksum",{log:!0});const A=new Uint32Array(256);for(let e=0;e<256;++e)A[e]=x(e);function O(e){let t=new Uint8Array(e),s=0;for(let e=0;e<t.byteLength;++e){const i=255&s,n=t[e];s=(A[i^n]^s>>>8)>>>0}return s}var $,B;$="undefined"==typeof TextEncoder?class{encode(e){const t=Array.from(e).map((e=>e.charCodeAt(0)));return Uint8Array.from(t)}}:TextEncoder,B="undefined"==typeof TextDecoder?class{decode(e){return Array.from(new Uint8Array(e)).map((e=>String.fromCharCode(e))).join("")}}:TextDecoder;const N=new $,P=new B,V=T("ArrayBufferUtils",{log:!1});function z(...e){const t=(e=(e=(e=e.filter((e=>null!=e||null!=e))).map((e=>{if("number"==typeof e){const t=e;return Uint8Array.from([Math.floor(t)])}if("boolean"==typeof e){const t=e;return Uint8Array.from([t?1:0])}if("string"==typeof e){return j(e)}if(e instanceof Array){return z(...e)}if(e instanceof ArrayBuffer)return e;if("buffer"in e&&e.buffer instanceof ArrayBuffer){return e.buffer}if(e instanceof DataView){return e.buffer}if("object"==typeof e){return function(e){return j(JSON.stringify(e))}(e)}return e}))).filter((e=>e&&"byteLength"in e))).reduce(((e,t)=>e+t.byteLength),0),s=new Uint8Array(t);let i=0;return e.forEach((e=>{s.set(new Uint8Array(e),i),i+=e.byteLength})),s.buffer}function j(e){const t=N.encode(e);return z(t.byteLength,t)}function q(e,t,s){let i;return null!=s&&(i=e.byteOffset+t+s),V.log({dataView:e,begin:t,end:i,length:s}),new DataView(e.buffer.slice(e.byteOffset+t,i))}async function G(e){let t;if(e instanceof Array)t=Uint8Array.from(e);else if(e instanceof DataView)t=e.buffer;else if("string"==typeof e||e instanceof URL){const s=await fetch(e);t=await s.arrayBuffer()}else if(e instanceof File)t=await e.arrayBuffer();else{if(!(e instanceof ArrayBuffer))throw{error:"invalid file type",file:e};t=e}return t}function H(e,{include:t,exclude:s}={}){const i=e=>{const i=t=>"string"==typeof t?e===t:t.test(e);return t?t.some(i):!s||!s.some(i)};for(const[t,s]of(e=>{const t=new Set;do{for(const s of Reflect.ownKeys(e))t.add([e,s])}while((e=Reflect.getPrototypeOf(e))&&e!==Object.prototype);return t})(e.constructor.prototype)){if("constructor"===s||!i(s))continue;const n=Reflect.getOwnPropertyDescriptor(t,s);n&&"function"==typeof n.value&&(e[s]=e[s].bind(e))}return e}var J,Q,K,Z,X,Y,ee,te,se,ie,ne,re,ae,oe,ce,he,le,ge,fe,ue,de,me,pe,ve,we,ye,be,Se,Ee,Me,Ce,De,ke,Te,We,_e,Ie,Le;const Fe=T("FileTransferManager",{log:!0}),Ue=["maxFileLength","getFileType","setFileType","getFileLength","setFileLength","getFileChecksum","setFileChecksum","setFileTransferCommand","fileTransferStatus","getFileBlock","setFileBlock","fileBytesTransferred"],Re=["tflite"],xe=["idle","sending","receiving"],Ae=["startSend","startReceive","cancel"],Oe=[...Ue,"fileTransferProgress","fileTransferComplete","fileReceived"];class $e{constructor(){J.add(this),se.set(this,Q.MaxLength),ae.set(this,void 0),le.set(this,0),de.set(this,0),ye.set(this,"idle"),Ce.set(this,[]),ke.set(this,void 0),Te.set(this,0),Le.set(this,!1),H(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}static get MaxLength(){return t(this,Q,"f",te)}get maxLength(){return t(this,se,"f")}get type(){return t(this,ae,"f")}get length(){return t(this,le,"f")}get checksum(){return t(this,de,"f")}get status(){return t(this,ye,"f")}parseMessage(e,s){switch(Fe.log({messageType:e}),e){case"maxFileLength":t(this,J,"m",ie).call(this,s);break;case"getFileType":case"setFileType":t(this,J,"m",oe).call(this,s);break;case"getFileLength":case"setFileLength":t(this,J,"m",ge).call(this,s);break;case"getFileChecksum":case"setFileChecksum":t(this,J,"m",me).call(this,s);break;case"fileTransferStatus":t(this,J,"m",be).call(this,s);break;case"getFileBlock":t(this,J,"m",De).call(this,s);break;case"fileBytesTransferred":t(this,J,"m",Ie).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}async send(e,s){t(this,J,"m",Ee).call(this),t(this,J,"m",Z).call(this,e);const i=await G(s),n=[];n.push(t(this,J,"m",he).call(this,e,!1));const r=i.byteLength;n.push(t(this,J,"m",ue).call(this,r,!1));const a=O(i);n.push(t(this,J,"m",ve).call(this,a,!1)),n.push(t(this,J,"m",we).call(this,"startSend",!1)),this.sendMessage(),await Promise.all(n),await t(this,J,"m",We).call(this,i)}async receive(e){t(this,J,"m",Ee).call(this),t(this,J,"m",Z).call(this,e),await t(this,J,"m",he).call(this,e),await t(this,J,"m",we).call(this,"startReceive")}async cancel(){t(this,J,"m",Me).call(this),await t(this,J,"m",we).call(this,"cancel")}get isServerSide(){return t(this,Le,"f")}set isServerSide(e){t(this,Le,"f")!=e?(Fe.log({newIsServerSide:e}),s(this,Le,e,"f")):Fe.log("redundant isServerSide assignment")}}Q=$e,se=new WeakMap,ae=new WeakMap,le=new WeakMap,de=new WeakMap,ye=new WeakMap,Ce=new WeakMap,ke=new WeakMap,Te=new WeakMap,Le=new WeakMap,J=new WeakSet,K=function(){return this.eventDispatcher.dispatchEvent},Z=function(e){Fe.assertEnumWithError(e,Re)},X=function(e){Fe.assertWithError(e in Re,`invalid typeEnum ${e}`)},Y=function(e){Fe.assertWithError(e in xe,`invalid statusEnum ${e}`)},ee=function(e){Fe.assertEnumWithError(e,Ae)},ie=function(e){Fe.log("parseFileMaxLength",e);const s=e.getUint32(0,!0);Fe.log(`maxLength: ${s/1024}kB`),t(this,J,"m",ne).call(this,s)},ne=function(e){Fe.log({maxLength:e}),s(this,se,e,"f"),t(this,J,"a",K).call(this,"maxFileLength",{maxFileLength:e})},re=function(e){Fe.assertWithError(e<=this.maxLength,`file length ${e}kB too large - must be ${this.maxLength}kB or less`)},oe=function(e){Fe.log("parseFileType",e);const s=e.getUint8(0);t(this,J,"m",X).call(this,s);const i=Re[s];t(this,J,"m",ce).call(this,i)},ce=function(e){Fe.log({fileTransferType:e}),s(this,ae,e,"f"),t(this,J,"a",K).call(this,"getFileType",{fileType:e})},he=async function(e,s){if(t(this,J,"m",Z).call(this,e),this.type==e)return void Fe.log(`redundant type assignment ${e}`);const i=this.waitForEvent("getFileType"),n=Re.indexOf(e);this.sendMessage([{type:"setFileType",data:Uint8Array.from([n]).buffer}],s),await i},ge=function(e){Fe.log("parseFileLength",e);const s=e.getUint32(0,!0);t(this,J,"m",fe).call(this,s)},fe=function(e){Fe.log(`length: ${e/1024}kB`),s(this,le,e,"f"),t(this,J,"a",K).call(this,"getFileLength",{fileLength:e})},ue=async function(e,s){if(Fe.assertTypeWithError(e,"number"),t(this,J,"m",re).call(this,e),this.length==e)return void Fe.log(`redundant length assignment ${e}`);const i=this.waitForEvent("getFileLength"),n=new DataView(new ArrayBuffer(4));n.setUint32(0,e,!0),this.sendMessage([{type:"setFileLength",data:n.buffer}],s),await i},me=function(e){Fe.log("checksum",e);const s=e.getUint32(0,!0);t(this,J,"m",pe).call(this,s)},pe=function(e){Fe.log({checksum:e}),s(this,de,e,"f"),t(this,J,"a",K).call(this,"getFileChecksum",{fileChecksum:e})},ve=async function(e,t){if(Fe.assertTypeWithError(e,"number"),this.checksum==e)return void Fe.log(`redundant checksum assignment ${e}`);const s=this.waitForEvent("getFileChecksum"),i=new DataView(new ArrayBuffer(4));i.setUint32(0,e,!0),this.sendMessage([{type:"setFileChecksum",data:i.buffer}],t),await s},we=async function(e,s){t(this,J,"m",ee).call(this,e);const i=this.waitForEvent("fileTransferStatus"),n=Ae.indexOf(e);this.sendMessage([{type:"setFileTransferCommand",data:Uint8Array.from([n]).buffer}],s),await i},be=function(e){Fe.log("parseFileStatus",e);const s=e.getUint8(0);t(this,J,"m",Y).call(this,s);const i=xe[s];t(this,J,"m",Se).call(this,i)},Se=function(e){Fe.log({status:e}),s(this,ye,e,"f"),t(this,J,"a",K).call(this,"fileTransferStatus",{fileTransferStatus:e}),t(this,Ce,"f").length=0},Ee=function(){Fe.assertWithError("idle"==t(this,ye,"f"),"status is not idle")},Me=function(){Fe.assertWithError("idle"!=t(this,ye,"f"),"status is idle")},De=async function(e){Fe.log("parseFileBlock",e),t(this,Ce,"f").push(e.buffer);const s=t(this,Ce,"f").reduce(((e,t)=>e+t.byteLength),0),i=s/t(this,le,"f");if(Fe.log(`received ${s} of ${t(this,le,"f")} bytes (${100*i}%)`),t(this,J,"a",K).call(this,"fileTransferProgress",{progress:i}),s!=t(this,le,"f")){const e=new DataView(new ArrayBuffer(4));if(e.setUint32(0,s,!0),this.isServerSide)return;return void await this.sendMessage([{type:"fileBytesTransferred",data:e.buffer}])}Fe.log("file transfer complete");let n,r=(new Date).toLocaleString();if("tflite"===this.type)r+=".tflite";n="undefined"!=typeof File?new File(t(this,Ce,"f"),r):new Blob(t(this,Ce,"f"));const a=O(await n.arrayBuffer());Fe.log({checksum:a}),a==t(this,de,"f")?(Fe.log("received file",n),t(this,J,"a",K).call(this,"getFileBlock",{fileTransferBlock:e}),t(this,J,"a",K).call(this,"fileTransferComplete",{direction:"receiving"}),t(this,J,"a",K).call(this,"fileReceived",{file:n})):Fe.error(`wrong checksum - expected ${t(this,de,"f")}, got ${a}`)},We=async function(e){return s(this,ke,e,"f"),s(this,Te,0,"f"),t(this,J,"m",_e).call(this)},_e=async function(){if("sending"!=this.status)return;if(!t(this,ke,"f"))return void(this.isServerSide||Fe.error("no buffer defined"));const e=t(this,ke,"f");let i=t(this,Te,"f");const n=e.slice(i,i+(this.mtu-3-3));Fe.log("slicedBuffer",n);const r=1-(e.byteLength-i)/e.byteLength;Fe.log(`sending bytes ${i}-${i+n.byteLength} of ${e.byteLength} bytes (${100*r}%)`),t(this,J,"a",K).call(this,"fileTransferProgress",{progress:r}),0==n.byteLength?(Fe.log("finished sending buffer"),t(this,J,"a",K).call(this,"fileTransferComplete",{direction:"sending"})):(await this.sendMessage([{type:"setFileBlock",data:n}]),s(this,Te,i+n.byteLength,"f"))},Ie=async function(e){Fe.log("parseBytesTransferred",e);const s=e.getUint32(0,!0);if(Fe.log({bytesTransferred:s}),"sending"==this.status)return this.isServerSide||t(this,Te,"f")==s?void t(this,J,"m",_e).call(this):(Fe.error(`bytesTransferred are not equal - got ${s}, expected ${t(this,Te,"f")}`),void this.cancel());Fe.error("not currently sending file")},te={value:0};const Be=T("MathUtils",{log:!0});const Ne=65536;function Pe(e,t){const s=Date.now();var i;let n=(i=s)-i%Ne+e.getUint16(t,!0);return Math.abs(s-n)>6e4&&(Be.log("correcting timestamp delta"),n+=Ne*Math.sign(s-n)),n}var Ve,ze,je;const qe={min:1/0,max:-1/0,span:0};class Ge{constructor(){Ve.add(this),ze.set(this,Object.assign({},qe))}get min(){return t(this,ze,"f").min}get max(){return t(this,ze,"f").max}set min(e){t(this,ze,"f").min=e,t(this,ze,"f").max=Math.max(e,t(this,ze,"f").max),t(this,Ve,"m",je).call(this)}set max(e){t(this,ze,"f").max=e,t(this,ze,"f").min=Math.min(e,t(this,ze,"f").min),t(this,Ve,"m",je).call(this)}reset(){Object.assign(t(this,ze,"f"),qe)}update(e){t(this,ze,"f").min=Math.min(e,t(this,ze,"f").min),t(this,ze,"f").max=Math.max(e,t(this,ze,"f").max),t(this,Ve,"m",je).call(this)}getNormalization(e,s){let i=function(e,t,s,i){return null==i&&(i=s-t),(e-t)/i}(e,t(this,ze,"f").min,t(this,ze,"f").max,t(this,ze,"f").span);return s&&(i*=t(this,ze,"f").span),i||0}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}var He,Je,Qe,Ke;ze=new WeakMap,Ve=new WeakSet,je=function(){t(this,ze,"f").span=t(this,ze,"f").max-t(this,ze,"f").min};class Ze{constructor(){He.set(this,{x:new Ge,y:new Ge})}reset(){t(this,He,"f").x.reset(),t(this,He,"f").y.reset()}update(e){t(this,He,"f").x.update(e.x),t(this,He,"f").y.update(e.y)}getNormalization(e){return{x:t(this,He,"f").x.getNormalization(e.x,!1),y:t(this,He,"f").y.getNormalization(e.y,!1)}}updateAndGetNormalization(e){return this.update(e),this.getNormalization(e)}}He=new WeakMap;const Xe=T("PressureDataManager",{log:!0}),Ye=["pressure"],et=Ye;class tt{constructor(){Je.set(this,[]),Qe.set(this,void 0),Ke.set(this,new Ze)}get positions(){return t(this,Je,"f")}get numberOfSensors(){return this.positions.length}parsePositions(e){const t=[];for(let s=0,i=0;i<e.byteLength;s++,i+=2)t.push({x:e.getUint8(i)/256,y:e.getUint8(i+1)/256});var i,n;Xe.log({positions:t}),s(this,Je,t,"f"),s(this,Qe,(i=this.numberOfSensors,n=()=>new Ge,new Array(i).fill(1).map(((e,t)=>{if("function"==typeof n)return n(t);{const e=n;return Object.assign({},e)}}))),"f"),this.resetRange()}resetRange(){t(this,Qe,"f").forEach((e=>e.reset())),t(this,Ke,"f").reset()}parseData(e,s){const i={sensors:[],scaledSum:0,normalizedSum:0};for(let n=0,r=0;r<e.byteLength;n++,r+=2){const a=e.getUint16(r,!0),o=a*s,c=t(this,Qe,"f")[n].updateAndGetNormalization(o,!0),h=this.positions[n];i.sensors[n]={rawValue:a,scaledValue:o,normalizedValue:c,position:h,weightedValue:0},i.scaledSum+=o,i.normalizedSum+=c/this.numberOfSensors}return i.scaledSum>0&&i.normalizedSum>.001&&(i.center={x:0,y:0},i.sensors.forEach((e=>{e.weightedValue=e.scaledValue/i.scaledSum,i.center.x+=e.position.x*e.weightedValue,i.center.y+=e.position.y*e.weightedValue})),i.normalizedCenter=t(this,Ke,"f").updateAndGetNormalization(i.center)),Xe.log({pressure:i}),i}}Je=new WeakMap,Qe=new WeakMap,Ke=new WeakMap;const st=T("MotionSensorDataManager",{log:!0}),it=["still","walking","running","bicycle","vehicle","tilting"],nt=["portraitUpright","landscapeLeft","portraitUpsideDown","landscapeRight","unknown"];class rt{parseVector3(e,t){let[s,i,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));const r={x:s,y:i,z:n};return st.log({vector:r}),r}parseQuaternion(e,t){let[s,i,n,r]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0),e.getInt16(6,!0)].map((e=>e*t));const a={x:s,y:i,z:n,w:r};return st.log({quaternion:a}),a}parseEuler(e,t){let[s,i,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));i*=-1,s*=-1,s+=360;const r={heading:s,pitch:i,roll:n};return st.log({euler:r}),r}parseStepCounter(e){st.log("parseStepCounter",e);const t=e.getUint32(0,!0);return st.log({stepCount:t}),t}parseActivity(e){st.log("parseActivity",e);const t={},s=e.getUint8(0);return st.log("activityBitfield",s.toString(2)),it.forEach(((e,i)=>{t[e]=Boolean(s&1<<i)})),st.log("activity",t),t}parseDeviceOrientation(e){st.log("parseDeviceOrientation",e);const t=e.getUint8(0),s=nt[t];return st.assertWithError(s,"undefined deviceOrientation"),st.log({deviceOrientation:s}),s}}var at,ot;const ct=["barometer"],ht=ct,lt=T("BarometerSensorDataManager",{log:!0});class gt{constructor(){at.add(this)}parseData(e,s){const i=e.getUint32(0,!0)*s,n=t(this,at,"m",ot).call(this,i);return lt.log({pressure:i,altitude:n}),{pressure:i}}}at=new WeakSet,ot=function(e){const t=.0065;return 288.15/t*(1-Math.pow(e/101325,.19026643566373183))};const ft=T("ParseUtils",{log:!0});function ut(e,t=0){const s=e.getUint8(t++);return{string:P.decode(e.buffer.slice(e.byteOffset+t,e.byteOffset+t+s)),byteOffset:t+=s}}function dt(e,t,s,i,n=!1){let r=0;for(;r<e.byteLength;){const a=e.getUint8(r++);ft.assertWithError(a in t,`invalid messageTypeEnum ${a}`);const o=t[a];let c;n?(c=e.getUint16(r,!0),r+=2):c=e.getUint8(r++),ft.log({messageTypeEnum:a,messageType:o,messageLength:c,dataView:e,byteOffset:r});const h=q(e,r,c);ft.log({_dataView:h}),s(o,h,i),r+=c}}var mt;const pt=T("SensorDataManager",{log:!0}),vt=[...Ye,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation","activity","stepCounter","stepDetector","deviceOrientation",...ct],wt=[...et,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation",...ht],yt=["getPressurePositions","getSensorScalars","sensorData"],bt=[...yt,...vt];class St{constructor(){this.pressureSensorDataManager=new tt,this.motionSensorDataManager=new rt,this.barometerSensorDataManager=new gt,mt.set(this,new Map)}static AssertValidSensorType(e){pt.assertEnumWithError(e,vt)}static AssertValidSensorTypeEnum(e){pt.assertTypeWithError(e,"number"),pt.assertWithError(e in vt,`invalid sensorTypeEnum ${e}`)}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}parseMessage(e,t){switch(pt.log({messageType:e}),e){case"getSensorScalars":this.parseScalars(t);break;case"getPressurePositions":this.pressureSensorDataManager.parsePositions(t);break;case"sensorData":this.parseData(t);break;default:throw Error(`uncaught messageType ${e}`)}}parseScalars(e){for(let s=0;s<e.byteLength;s+=5){const i=e.getUint8(s),n=vt[i];if(!n){pt.warn(`unknown sensorType index ${i}`);continue}const r=e.getFloat32(s+1,!0);pt.log({sensorType:n,sensorScalar:r}),t(this,mt,"f").set(n,r)}}parseData(e){pt.log("sensorData",Array.from(new Uint8Array(e.buffer)));let t=0;const s=Pe(e,t);t+=2;dt(new DataView(e.buffer,t),vt,this.parseDataCallback.bind(this),{timestamp:s})}parseDataCallback(e,s,{timestamp:i}){const n=t(this,mt,"f").get(e)||1;let r=null;switch(e){case"pressure":r=this.pressureSensorDataManager.parseData(s,n);break;case"acceleration":case"gravity":case"linearAcceleration":case"gyroscope":case"magnetometer":r=this.motionSensorDataManager.parseVector3(s,n);break;case"gameRotation":case"rotation":r=this.motionSensorDataManager.parseQuaternion(s,n);break;case"orientation":r=this.motionSensorDataManager.parseEuler(s,n);break;case"stepCounter":r=this.motionSensorDataManager.parseStepCounter(s);break;case"stepDetector":r={};break;case"activity":r=this.motionSensorDataManager.parseActivity(s);break;case"deviceOrientation":r=this.motionSensorDataManager.parseDeviceOrientation(s);break;case"barometer":r=this.barometerSensorDataManager.parseData(s,n);break;default:pt.error(`uncaught sensorType "${e}"`)}pt.assertWithError(null!=r,`no sensorData defined for sensorType "${e}"`),pt.log({sensorType:e,sensorData:r}),this.dispatchEvent(e,{sensorType:e,[e]:r,timestamp:i}),this.dispatchEvent("sensorData",{sensorType:e,[e]:r,timestamp:i})}}var Et,Mt,Ct,Dt,kt,Tt,Wt,_t,It,Lt,Ft,Ut,Rt;mt=new WeakMap;const xt=T("SensorConfigurationManager",{log:!0}),At=["getSensorConfiguration","setSensorConfiguration"],Ot=At;class $t{constructor(){Et.add(this),Dt.set(this,void 0),Tt.set(this,void 0),H(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get configuration(){return t(this,Tt,"f")}async setConfiguration(e,s){if(s&&(e=Object.assign({...this.zeroSensorConfiguration},e)),xt.log({newSensorConfiguration:e}),t(this,Et,"m",_t).call(this,e))return void xt.log("redundant sensor configuration");const i=t(this,Et,"m",Ut).call(this,e);xt.log({setSensorConfigurationData:i});const n=this.waitForEvent("getSensorConfiguration");this.sendMessage([{type:"setSensorConfiguration",data:i.buffer}]),await n}static get ZeroSensorConfiguration(){return t(this,Mt,"f",Rt)}get zeroSensorConfiguration(){const e={};return vt.forEach((t=>{e[t]=0})),e}async clearSensorConfiguration(){return this.setConfiguration(this.zeroSensorConfiguration)}parseMessage(e,s){switch(xt.log({messageType:e}),e){case"getSensorConfiguration":case"setSensorConfiguration":const i=t(this,Et,"m",It).call(this,s);t(this,Et,"m",Wt).call(this,i);break;default:throw Error(`uncaught messageType ${e}`)}}}var Bt,Nt,Pt,Vt,zt,jt,qt,Gt,Ht,Jt,Qt,Kt,Zt,Xt,Yt,es,ts,ss,is,ns,rs,as,os,cs,hs,ls,gs,fs,us,ds;Mt=$t,Dt=new WeakMap,Tt=new WeakMap,Et=new WeakSet,Ct=function(){return this.eventDispatcher.dispatchEvent},kt=function(e){xt.assertWithError(t(this,Dt,"f"),"must get initial sensorConfiguration");const s=t(this,Dt,"f")?.includes(e);return xt.assert(s,`unavailable sensor type "${e}"`),s},Wt=function(e){s(this,Tt,e,"f"),xt.log({updatedConfiguration:t(this,Tt,"f")}),t(this,Et,"a",Ct).call(this,"getSensorConfiguration",{sensorConfiguration:this.configuration})},_t=function(e){return Object.keys(e).every((t=>this.configuration[t]==e[t]))},It=function(e){const t={};for(let s=0;s<e.byteLength;s+=3){const i=e.getUint8(s),n=vt[i];if(!n){xt.warn(`unknown sensorType index ${i}`);continue}const r=e.getUint16(s+1,!0);xt.log({sensorType:n,sensorRate:r}),t[n]=r}return xt.log({parsedSensorConfiguration:t}),s(this,Dt,Object.keys(t),"f"),t},Lt=function(e){xt.assertTypeWithError(e,"number"),xt.assertWithError(e>=0,`sensorRate must be 0 or greater (got ${e})`),xt.assertWithError(e<65535,`sensorRate must be 0 or greater (got ${e})`),xt.assertWithError(e%5==0,"sensorRate must be multiple of 5")},Ft=function(e){t(Mt,Mt,"m",Lt).call(Mt,e)},Ut=function(e){let s=Object.keys(e);s=s.filter((e=>t(this,Et,"m",kt).call(this,e)));const i=new DataView(new ArrayBuffer(3*s.length));return s.forEach(((s,n)=>{St.AssertValidSensorType(s);const r=vt.indexOf(s);i.setUint8(3*n,r);const a=e[s];t(this,Et,"m",Ft).call(this,a),i.setUint16(3*n+1,a,!0)})),xt.log({sensorConfigurationData:i}),i},Rt={value:{}},vt.forEach((e=>{t(Mt,Mt,"f",Rt)[e]=0}));const ms=T("TfliteManager",{log:!0}),ps=["getTfliteName","setTfliteName","getTfliteTask","setTfliteTask","getTfliteSampleRate","setTfliteSampleRate","getTfliteSensorTypes","setTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","setTfliteCaptureDelay","getTfliteThreshold","setTfliteThreshold","getTfliteInferencingEnabled","setTfliteInferencingEnabled","tfliteInference"],vs=ps,ws=["classification","regression"],ys=["pressure","linearAcceleration","gyroscope","magnetometer"];class bs{constructor(){Bt.add(this),zt.set(this,void 0),Gt.set(this,void 0),Qt.set(this,void 0),Xt.set(this,[]),ts.set(this,void 0),rs.set(this,void 0),cs.set(this,void 0),gs.set(this,void 0),H(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get name(){return t(this,zt,"f")}async setName(e,t){if(ms.assertTypeWithError(e,"string"),this.name==e)return void ms.log(`redundant name assignment ${e}`);const s=this.waitForEvent("getTfliteName"),i=N.encode(e);this.sendMessage([{type:"setTfliteName",data:i.buffer}],t),await s}get task(){return t(this,Gt,"f")}async setTask(e,s){if(t(this,Bt,"m",Nt).call(this,e),this.task==e)return void ms.log(`redundant task assignment ${e}`);const i=this.waitForEvent("getTfliteTask"),n=ws.indexOf(e);this.sendMessage([{type:"setTfliteTask",data:Uint8Array.from([n]).buffer}],s),await i}get sampleRate(){return t(this,Qt,"f")}async setSampleRate(e,s){if(ms.assertTypeWithError(e,"number"),e-=e%5,ms.assertWithError(e>=5,`sampleRate must be multiple of 5 greater than 0 (got ${e})`),t(this,Qt,"f")==e)return void ms.log(`redundant sampleRate assignment ${e}`);const i=this.waitForEvent("getTfliteSampleRate"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteSampleRate",data:n.buffer}],s),await i}static AssertValidSensorType(e){St.AssertValidSensorType(e),ms.assertWithError(ys.includes(e),`invalid tflite sensorType "${e}"`)}get sensorTypes(){return t(this,Xt,"f").slice()}async setSensorTypes(e,t){e.forEach((e=>{bs.AssertValidSensorType(e)}));const s=this.waitForEvent("getTfliteSensorTypes");var i;const n=(e=(i=e).filter(((e,t)=>i.indexOf(e)==t))).map((e=>vt.indexOf(e))).sort();ms.log(e,n),this.sendMessage([{type:"setTfliteSensorTypes",data:Uint8Array.from(n).buffer}],t),await s}get isReady(){return t(this,ts,"f")}get captureDelay(){return t(this,rs,"f")}async setCaptureDelay(e,s){if(ms.assertTypeWithError(e,"number"),t(this,rs,"f")==e)return void ms.log(`redundant captureDelay assignment ${e}`);const i=this.waitForEvent("getTfliteCaptureDelay"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteCaptureDelay",data:n.buffer}],s),await i}get threshold(){return t(this,cs,"f")}async setThreshold(e,s){if(ms.assertTypeWithError(e,"number"),ms.assertWithError(e>=0,`threshold must be positive (got ${e})`),t(this,cs,"f")==e)return void ms.log(`redundant threshold assignment ${e}`);const i=this.waitForEvent("getTfliteThreshold"),n=new DataView(new ArrayBuffer(4));n.setFloat32(0,e,!0),this.sendMessage([{type:"setTfliteThreshold",data:n.buffer}],s),await i}get inferencingEnabled(){return t(this,gs,"f")}async setInferencingEnabled(e,s=!0){if(ms.assertTypeWithError(e,"boolean"),!e&&!this.isReady)return;if(t(this,Bt,"m",ns).call(this),t(this,gs,"f")==e)return void ms.log(`redundant inferencingEnabled assignment ${e}`);const i=this.waitForEvent("getTfliteInferencingEnabled");this.sendMessage([{type:"setTfliteInferencingEnabled",data:Uint8Array.from([Number(e)]).buffer}],s),await i}async toggleInferencingEnabled(){return this.setInferencingEnabled(!this.inferencingEnabled)}async enableInferencing(){this.inferencingEnabled||this.setInferencingEnabled(!0)}async disableInferencing(){this.inferencingEnabled&&this.setInferencingEnabled(!1)}parseMessage(e,s){switch(ms.log({messageType:e}),e){case"getTfliteName":case"setTfliteName":t(this,Bt,"m",jt).call(this,s);break;case"getTfliteTask":case"setTfliteTask":t(this,Bt,"m",Ht).call(this,s);break;case"getTfliteSampleRate":case"setTfliteSampleRate":t(this,Bt,"m",Kt).call(this,s);break;case"getTfliteSensorTypes":case"setTfliteSensorTypes":t(this,Bt,"m",Yt).call(this,s);break;case"tfliteIsReady":t(this,Bt,"m",ss).call(this,s);break;case"getTfliteCaptureDelay":case"setTfliteCaptureDelay":t(this,Bt,"m",as).call(this,s);break;case"getTfliteThreshold":case"setTfliteThreshold":t(this,Bt,"m",hs).call(this,s);break;case"getTfliteInferencingEnabled":case"setTfliteInferencingEnabled":t(this,Bt,"m",fs).call(this,s);break;case"tfliteInference":t(this,Bt,"m",ds).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}}var Ss,Es,Ms,Cs,Ds;zt=new WeakMap,Gt=new WeakMap,Qt=new WeakMap,Xt=new WeakMap,ts=new WeakMap,rs=new WeakMap,cs=new WeakMap,gs=new WeakMap,Bt=new WeakSet,Nt=function(e){ms.assertEnumWithError(e,ws)},Pt=function(e){ms.assertWithError(e in ws,`invalid taskEnum ${e}`)},Vt=function(){return this.eventDispatcher.dispatchEvent},jt=function(e){ms.log("parseName",e);const s=P.decode(e.buffer);t(this,Bt,"m",qt).call(this,s)},qt=function(e){ms.log({name:e}),s(this,zt,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteName",{tfliteName:e})},Ht=function(e){ms.log("parseTask",e);const s=e.getUint8(0);t(this,Bt,"m",Pt).call(this,s);const i=ws[s];t(this,Bt,"m",Jt).call(this,i)},Jt=function(e){ms.log({task:e}),s(this,Gt,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteTask",{tfliteTask:e})},Kt=function(e){ms.log("parseSampleRate",e);const s=e.getUint16(0,!0);t(this,Bt,"m",Zt).call(this,s)},Zt=function(e){ms.log({sampleRate:e}),s(this,Qt,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteSampleRate",{tfliteSampleRate:e})},Yt=function(e){ms.log("parseSensorTypes",e);const s=[];for(let t=0;t<e.byteLength;t++){const i=e.getUint8(t),n=vt[i];n?s.push(n):ms.error(`invalid sensorTypeEnum ${i}`)}t(this,Bt,"m",es).call(this,s)},es=function(e){ms.log({sensorTypes:e}),s(this,Xt,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteSensorTypes",{tfliteSensorTypes:e})},ss=function(e){ms.log("parseIsReady",e);const s=Boolean(e.getUint8(0));t(this,Bt,"m",is).call(this,s)},is=function(e){ms.log({isReady:e}),s(this,ts,e,"f"),t(this,Bt,"a",Vt).call(this,"tfliteIsReady",{tfliteIsReady:e})},ns=function(){ms.assertWithError(this.isReady,"tflite is not ready")},as=function(e){ms.log("parseCaptureDelay",e);const s=e.getUint16(0,!0);t(this,Bt,"m",os).call(this,s)},os=function(e){ms.log({captureDelay:e}),s(this,rs,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteCaptureDelay",{tfliteCaptureDelay:e})},hs=function(e){ms.log("parseThreshold",e);const s=e.getFloat32(0,!0);t(this,Bt,"m",ls).call(this,s)},ls=function(e){ms.log({threshold:e}),s(this,cs,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteThreshold",{tfliteThreshold:e})},fs=function(e){ms.log("parseInferencingEnabled",e);const s=Boolean(e.getUint8(0));t(this,Bt,"m",us).call(this,s)},us=function(e){ms.log({inferencingEnabled:e}),s(this,gs,e,"f"),t(this,Bt,"a",Vt).call(this,"getTfliteInferencingEnabled",{tfliteInferencingEnabled:e})},ds=function(e){ms.log("parseInference",e);const s=Pe(e,0);ms.log({timestamp:s});const i=[];for(let t=0,s=2;s<e.byteLength;t++,s+=4){const t=e.getFloat32(s,!0);i.push(t)}ms.log("values",i);const n={timestamp:s,values:i};if("classification"==this.task){let e=0,t=0;i.forEach(((s,i)=>{s>e&&(e=s,t=i)})),ms.log({maxIndex:t,maxValue:e}),n.maxIndex=t,n.maxValue=e}t(this,Bt,"a",Vt).call(this,"tfliteInference",{tfliteInference:n})};const ks=T("DeviceInformationManager",{log:!0}),Ts=["manufacturerName","modelNumber","softwareRevision","hardwareRevision","firmwareRevision","pnpId","serialNumber"],Ws=[...Ts,"deviceInformation"];class _s{constructor(){Ss.add(this),Ms.set(this,{})}get information(){return t(this,Ms,"f")}clear(){s(this,Ms,{},"f")}parseMessage(e,s){switch(ks.log({messageType:e}),e){case"manufacturerName":const i=P.decode(s.buffer);ks.log({manufacturerName:i}),t(this,Ss,"m",Ds).call(this,{manufacturerName:i});break;case"modelNumber":const n=P.decode(s.buffer);ks.log({modelNumber:n}),t(this,Ss,"m",Ds).call(this,{modelNumber:n});break;case"softwareRevision":const r=P.decode(s.buffer);ks.log({softwareRevision:r}),t(this,Ss,"m",Ds).call(this,{softwareRevision:r});break;case"hardwareRevision":const a=P.decode(s.buffer);ks.log({hardwareRevision:a}),t(this,Ss,"m",Ds).call(this,{hardwareRevision:a});break;case"firmwareRevision":const o=P.decode(s.buffer);ks.log({firmwareRevision:o}),t(this,Ss,"m",Ds).call(this,{firmwareRevision:o});break;case"pnpId":const c={source:1===s.getUint8(0)?"Bluetooth":"USB",productId:s.getUint16(3,!0),productVersion:s.getUint16(5,!0),vendorId:0};"Bluetooth"==c.source&&(c.vendorId=s.getUint16(1,!0)),ks.log({pnpId:c}),t(this,Ss,"m",Ds).call(this,{pnpId:c});break;case"serialNumber":const h=P.decode(s.buffer);ks.log({serialNumber:h});break;default:throw Error(`uncaught messageType ${e}`)}}}var Is,Ls,Fs,Us,Rs,xs,As,Os,$s,Bs,Ns,Ps,Vs,zs,js,qs,Gs,Hs;Ms=new WeakMap,Ss=new WeakSet,Es=function(){return this.eventDispatcher.dispatchEvent},Cs=function(){return Ts.every((e=>e in t(this,Ms,"f")))},Ds=function(e){ks.log({partialDeviceInformation:e});Object.keys(e).forEach((s=>{t(this,Ss,"a",Es).call(this,s,{[s]:e[s]})})),Object.assign(t(this,Ms,"f"),e),ks.log({deviceInformation:t(this,Ms,"f")}),t(this,Ss,"a",Cs)&&(ks.log("completed deviceInformation"),t(this,Ss,"a",Es).call(this,"deviceInformation",{deviceInformation:this.information}))};const Js=T("InformationManager",{log:!0}),Qs=["leftInsole","rightInsole"],Ks=["left","right"],Zs=["isCharging","getBatteryCurrent","getMtu","getId","getName","setName","getType","setType","getCurrentTime","setCurrentTime"],Xs=Zs;class Ys{constructor(){Is.add(this),Fs.set(this,!1),Rs.set(this,void 0),As.set(this,void 0),$s.set(this,""),Bs.set(this,void 0),zs.set(this,0),qs.set(this,!1),H(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}get isCharging(){return t(this,Fs,"f")}get batteryCurrent(){return t(this,Rs,"f")}async getBatteryCurrent(){Js.log("getting battery current...");const e=this.waitForEvent("getBatteryCurrent");this.sendMessage([{type:"getBatteryCurrent"}]),await e}get id(){return t(this,As,"f")}get name(){return t(this,$s,"f")}updateName(e){Js.assertTypeWithError(e,"string"),s(this,$s,e,"f"),Js.log({updatedName:t(this,$s,"f")}),t(this,Is,"a",Ls).call(this,"getName",{name:t(this,$s,"f")})}async setName(e){Js.assertTypeWithError(e,"string"),Js.assertWithError(e.length>=2,`name must be greater than 2 characters long ("${e}" is ${e.length} characters long)`),Js.assertWithError(e.length<30,`name must be less than 30 characters long ("${e}" is ${e.length} characters long)`);const t=N.encode(e);Js.log({setNameData:t});const s=this.waitForEvent("getName");this.sendMessage([{type:"setName",data:t.buffer}]),await s}get type(){return t(this,Bs,"f")}get typeEnum(){return Qs.indexOf(this.type)}updateType(e){t(this,Is,"m",Ns).call(this,e),e!=this.type?(s(this,Bs,e,"f"),Js.log({updatedType:t(this,Bs,"f")}),t(this,Is,"a",Ls).call(this,"getType",{type:t(this,Bs,"f")})):Js.log("redundant type assignment")}async setType(e){t(this,Is,"m",Ns).call(this,e);const s=Qs.indexOf(e);t(this,Is,"m",Vs).call(this,s)}get isInsole(){switch(this.type){case"leftInsole":case"rightInsole":return!0;default:return!1}}get insoleSide(){switch(this.type){case"leftInsole":return"left";case"rightInsole":return"right"}}get mtu(){return t(this,zs,"f")}get isCurrentTimeSet(){return t(this,qs,"f")}parseMessage(e,s){switch(Js.log({messageType:e}),e){case"isCharging":const i=Boolean(s.getUint8(0));Js.log({isCharging:i}),t(this,Is,"m",Us).call(this,i);break;case"getBatteryCurrent":const n=s.getFloat32(0,!0);Js.log({batteryCurrent:n}),t(this,Is,"m",xs).call(this,n);break;case"getId":const r=P.decode(s.buffer);Js.log({id:r}),t(this,Is,"m",Os).call(this,r);break;case"getName":case"setName":const a=P.decode(s.buffer);Js.log({name:a}),this.updateName(a);break;case"getType":case"setType":const o=s.getUint8(0),c=Qs[o];Js.log({typeEnum:o,type:c}),this.updateType(c);break;case"getMtu":const h=s.getUint16(0,!0);Js.log({mtu:h}),t(this,Is,"m",js).call(this,h);break;case"getCurrentTime":case"setCurrentTime":const l=Number(s.getBigUint64(0,!0));t(this,Is,"m",Gs).call(this,l);break;default:throw Error(`uncaught messageType ${e}`)}}clear(){s(this,qs,!1,"f")}}Fs=new WeakMap,Rs=new WeakMap,As=new WeakMap,$s=new WeakMap,Bs=new WeakMap,zs=new WeakMap,qs=new WeakMap,Is=new WeakSet,Ls=function(){return this.eventDispatcher.dispatchEvent},Us=function(e){Js.assertTypeWithError(e,"boolean"),s(this,Fs,e,"f"),Js.log({isCharging:t(this,Fs,"f")}),t(this,Is,"a",Ls).call(this,"isCharging",{isCharging:t(this,Fs,"f")})},xs=function(e){Js.assertTypeWithError(e,"number"),s(this,Rs,e,"f"),Js.log({batteryCurrent:t(this,Rs,"f")}),t(this,Is,"a",Ls).call(this,"getBatteryCurrent",{batteryCurrent:t(this,Rs,"f")})},Os=function(e){Js.assertTypeWithError(e,"string"),s(this,As,e,"f"),Js.log({id:t(this,As,"f")}),t(this,Is,"a",Ls).call(this,"getId",{id:t(this,As,"f")})},Ns=function(e){Js.assertEnumWithError(e,Qs)},Ps=function(e){Js.assertTypeWithError(e,"number"),Js.assertWithError(e in Qs,`invalid typeEnum ${e}`)},Vs=async function(e){t(this,Is,"m",Ps).call(this,e);const s=Uint8Array.from([e]);Js.log({setTypeData:s});const i=this.waitForEvent("getType");this.sendMessage([{type:"setType",data:s.buffer}]),await i},js=function(e){Js.assertTypeWithError(e,"number"),t(this,zs,"f")!=e?(s(this,zs,e,"f"),t(this,Is,"a",Ls).call(this,"getMtu",{mtu:t(this,zs,"f")})):Js.log("redundant mtu assignment",e)},Gs=function(e){Js.log({currentTime:e}),s(this,qs,0!=e||Math.abs(Date.now()-e)<Ne,"f"),t(this,qs,"f")||t(this,Is,"m",Hs).call(this,!1)},Hs=async function(e){Js.log("setting current time...");const t=new DataView(new ArrayBuffer(8));t.setBigUint64(0,BigInt(Date.now()),!0);const s=this.waitForEvent("getCurrentTime");this.sendMessage([{type:"setCurrentTime",data:t.buffer}],e),await s};const ei=["none","strongClick100","strongClick60","strongClick30","sharpClick100","sharpClick60","sharpClick30","softBump100","softBump60","softBump30","doubleClick100","doubleClick60","tripleClick100","softFuzz60","strongBuzz100","alert750ms","alert1000ms","strongClick1_100","strongClick2_80","strongClick3_60","strongClick4_30","mediumClick100","mediumClick80","mediumClick60","sharpTick100","sharpTick80","sharpTick60","shortDoubleClickStrong100","shortDoubleClickStrong80","shortDoubleClickStrong60","shortDoubleClickStrong30","shortDoubleClickMedium100","shortDoubleClickMedium80","shortDoubleClickMedium60","shortDoubleSharpTick100","shortDoubleSharpTick80","shortDoubleSharpTick60","longDoubleSharpClickStrong100","longDoubleSharpClickStrong80","longDoubleSharpClickStrong60","longDoubleSharpClickStrong30","longDoubleSharpClickMedium100","longDoubleSharpClickMedium80","longDoubleSharpClickMedium60","longDoubleSharpTick100","longDoubleSharpTick80","longDoubleSharpTick60","buzz100","buzz80","buzz60","buzz40","buzz20","pulsingStrong100","pulsingStrong60","pulsingMedium100","pulsingMedium60","pulsingSharp100","pulsingSharp60","transitionClick100","transitionClick80","transitionClick60","transitionClick40","transitionClick20","transitionClick10","transitionHum100","transitionHum80","transitionHum60","transitionHum40","transitionHum20","transitionHum10","transitionRampDownLongSmooth2_100","transitionRampDownLongSmooth1_100","transitionRampDownMediumSmooth1_100","transitionRampDownMediumSmooth2_100","transitionRampDownShortSmooth1_100","transitionRampDownShortSmooth2_100","transitionRampDownLongSharp1_100","transitionRampDownLongSharp2_100","transitionRampDownMediumSharp1_100","transitionRampDownMediumSharp2_100","transitionRampDownShortSharp1_100","transitionRampDownShortSharp2_100","transitionRampUpLongSmooth1_100","transitionRampUpLongSmooth2_100","transitionRampUpMediumSmooth1_100","transitionRampUpMediumSmooth2_100","transitionRampUpShortSmooth1_100","transitionRampUpShortSmooth2_100","transitionRampUpLongSharp1_100","transitionRampUpLongSharp2_100","transitionRampUpMediumSharp1_100","transitionRampUpMediumSharp2_100","transitionRampUpShortSharp1_100","transitionRampUpShortSharp2_100","transitionRampDownLongSmooth1_50","transitionRampDownLongSmooth2_50","transitionRampDownMediumSmooth1_50","transitionRampDownMediumSmooth2_50","transitionRampDownShortSmooth1_50","transitionRampDownShortSmooth2_50","transitionRampDownLongSharp1_50","transitionRampDownLongSharp2_50","transitionRampDownMediumSharp1_50","transitionRampDownMediumSharp2_50","transitionRampDownShortSharp1_50","transitionRampDownShortSharp2_50","transitionRampUpLongSmooth1_50","transitionRampUpLongSmooth2_50","transitionRampUpMediumSmooth1_50","transitionRampUpMediumSmooth2_50","transitionRampUpShortSmooth1_50","transitionRampUpShortSmooth2_50","transitionRampUpLongSharp1_50","transitionRampUpLongSharp2_50","transitionRampUpMediumSharp1_50","transitionRampUpMediumSharp2_50","transitionRampUpShortSharp1_50","transitionRampUpShortSharp2_50","longBuzz100","smoothHum50","smoothHum40","smoothHum30","smoothHum20","smoothHum10"];var ti,si,ii,ni,ri,ai,oi,ci,hi,li,gi,fi,ui,di,mi,pi;const vi=T("VibrationManager"),wi=["front","rear"],yi=["waveformEffect","waveform"],bi=2550,Si=1270;class Ei{constructor(){ti.add(this),H(this)}async triggerVibration(e,s=!0){let i;e.forEach((e=>{const{type:s}=e;let n,{locations:r}=e;switch(r=r||wi.slice(),s){case"waveformEffect":{const{segments:s,loopCount:i}=e;n=t(this,ti,"m",ui).call(this,r,s,i)}break;case"waveform":{const{segments:s}=e;n=t(this,ti,"m",di).call(this,r,s)}break;default:throw Error(`invalid vibration type "${s}"`)}vi.log({type:s,arrayBuffer:n}),i=z(i,n)})),await this.sendMessage([{type:"triggerVibration",data:i}],s)}}var Mi,Ci,Di,ki,Ti,Wi,_i,Ii,Li,Fi,Ui,Ri,xi,Ai,Oi;ti=new WeakSet,si=function(e){vi.assertTypeWithError(e,"string"),vi.assertWithError(wi.includes(e),`invalid location "${e}"`)},ii=function(e){t(this,ti,"m",ri).call(this,e),e.forEach((e=>{t(this,ti,"m",si).call(this,e)}))},ni=function(e){t(this,ti,"m",ii).call(this,e);let s=0;return e.forEach((e=>{const t=wi.indexOf(e);s|=1<<t})),vi.log({locationsBitmask:s}),vi.assertWithError(s>0,"locationsBitmask must not be zero"),s},ri=function(e){vi.assertWithError(Array.isArray(e),"passed non-array"),vi.assertWithError(e.length>0,"passed empty array")},ai=function(e){vi.assertWithError(ei.includes(e),`invalid waveformEffect "${e}"`)},oi=function(e){if(null!=e.effect){const s=e.effect;t(this,ti,"m",ai).call(this,s)}else{if(null==e.delay)throw Error("no effect or delay found in waveformEffectSegment");{const{delay:t}=e;vi.assertWithError(t>=0,`delay must be 0ms or greater (got ${t})`),vi.assertWithError(t<=Si,`delay must be 1270ms or less (got ${t})`)}}if(null!=e.loopCount){const{loopCount:s}=e;t(this,ti,"m",ci).call(this,s)}},ci=function(e){vi.assertTypeWithError(e,"number"),vi.assertWithError(e>=0,`waveformEffectSegmentLoopCount must be 0 or greater (got ${e})`),vi.assertWithError(e<=3,`waveformEffectSegmentLoopCount must be 3 or fewer (got ${e})`)},hi=function(e){t(this,ti,"m",ri).call(this,e),vi.assertWithError(e.length<=8,`must have 8 waveformEffectSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,ti,"m",oi).call(this,e)}))},li=function(e){vi.assertTypeWithError(e,"number"),vi.assertWithError(e>=0,`waveformEffectSequenceLoopCount must be 0 or greater (got ${e})`),vi.assertWithError(e<=6,`waveformEffectSequenceLoopCount must be 6 or fewer (got ${e})`)},gi=function(e){vi.assertTypeWithError(e.amplitude,"number"),vi.assertWithError(e.amplitude>=0,`amplitude must be 0 or greater (got ${e.amplitude})`),vi.assertWithError(e.amplitude<=1,`amplitude must be 1 or less (got ${e.amplitude})`),vi.assertTypeWithError(e.duration,"number"),vi.assertWithError(e.duration>0,`duration must be greater than 0ms (got ${e.duration}ms)`),vi.assertWithError(e.duration<=bi,`duration must be 2550ms or less (got ${e.duration}ms)`)},fi=function(e){t(this,ti,"m",ri).call(this,e),vi.assertWithError(e.length<=20,`must have 20 waveformSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,ti,"m",gi).call(this,e)}))},ui=function(e,s,i=0){t(this,ti,"m",hi).call(this,s),t(this,ti,"m",li).call(this,i);let n=[],r=0;const a=s.some((e=>{const{loopCount:t}=e;return null!=t&&t>0}))||0!=i;for(let e=0;e<s.length||a&&e<8;e++){const t=s[e]||{effect:"none"};if(null!=t.effect){const e=t.effect;n[r++]=ei.indexOf(e)}else{if(null==t.delay)throw Error("invalid waveformEffectSegment");{const{delay:e}=t;n[r++]=128|Math.floor(e/10)}}}const o=0!=i;for(let e=0;e<s.length||o&&e<8;e++){const t=s[e]?.loopCount||0;0!=e&&4!=e||(n[r]=0);const i=e%4*2;n[r]|=t<<i,3!=e&&7!=e||r++}0!=i&&(n[r++]=i);const c=new DataView(Uint8Array.from(n).buffer);return vi.log({dataArray:n,dataView:c}),t(this,ti,"m",pi).call(this,e,"waveformEffect",c)},di=function(e,s){t(this,ti,"m",fi).call(this,s);const i=new DataView(new ArrayBuffer(2*s.length));return s.forEach(((e,t)=>{i.setUint8(2*t,Math.floor(127*e.amplitude)),i.setUint8(2*t+1,Math.floor(e.duration/10))})),vi.log({dataView:i}),t(this,ti,"m",pi).call(this,e,"waveform",i)},mi=function(e){vi.assertTypeWithError(e,"string"),vi.assertWithError(yi.includes(e),`invalid vibrationType "${e}"`)},pi=function(e,s,i){vi.assertWithError(i?.byteLength>0,"no data received");const n=t(this,ti,"m",ni).call(this,e);t(this,ti,"m",mi).call(this,s);const r=yi.indexOf(s);vi.log({locationsBitmask:n,vibrationTypeIndex:r,dataView:i});const a=z(n,r,i.byteLength,i);return vi.log({data:a}),a};const $i=T("BaseConnectionManager",{log:!0}),Bi=["notConnected","connecting","connected","disconnecting"],Ni=[...Bi,"connectionStatus","isConnected"],Pi=[...Zs,...At,...yt,"triggerVibration",...ps,...Ue],Vi=["batteryLevel"],zi=["rx","tx"],ji=[...Vi,...Ts,...zi,...Pi,"smp"];class qi{get baseConstructor(){return this.constructor}static get isSupported(){return!1}get isSupported(){return this.baseConstructor.isSupported}get type(){return this.baseConstructor.type}constructor(){Mi.add(this),Ti.set(this,"notConnected"),Ui.set(this,[]),Ri.set(this,!1),Ai.set(this,new R(t(this,Mi,"m",Oi).bind(this),5e3)),t(this,Mi,"m",ki).call(this)}get status(){return t(this,Ti,"f")}set status(e){$i.assertEnumWithError(e,Bi),t(this,Ti,"f")!=e?($i.log(`new connection status "${e}"`),s(this,Ti,e,"f"),this.onStatusUpdated(this.status),this.isConnected?t(this,Ai,"f").start():t(this,Ai,"f").stop(),"notConnected"==t(this,Ti,"f")&&(this.mtu=void 0)):$i.log(`tried to assign same connection status "${e}"`)}get isConnected(){return"connected"==this.status}async connect(){t(this,Mi,"m",Wi).call(this),t(this,Mi,"m",_i).call(this),this.status="connecting"}get canReconnect(){return!1}async reconnect(){t(this,Mi,"m",Wi).call(this),t(this,Mi,"m",_i).call(this),$i.assert(this.canReconnect,"unable to reconnect")}async disconnect(){t(this,Mi,"m",Ii).call(this),t(this,Mi,"m",Li).call(this),this.status="disconnecting",$i.log("disconnecting from device...")}async sendSmpMessage(e){t(this,Mi,"m",Fi).call(this),$i.log("sending smp message",e)}async sendTxMessages(e,i=!0){if(t(this,Mi,"m",Fi).call(this),e&&t(this,Ui,"f").push(...e),!i)return;if(t(this,Ri,"f"))return;s(this,Ri,!0,"f"),$i.log("sendTxMessages",t(this,Ui,"f").slice());const n=t(this,Ui,"f").map((e=>{t(Ci,Ci,"m",Di).call(Ci,e.type);const s=Pi.indexOf(e.type),i=new DataView(new ArrayBuffer(2));return i.setUint16(0,e.data?.byteLength||0,!0),z(s,i,e.data)}));if(this.mtu)for(;n.length>0;){let e=0,t=0;n.some((s=>{if(e+s.byteLength>this.mtu-3)return!0;t++,e+=s.byteLength}));const s=n.splice(0,t);$i.log({arrayBufferCount:t,arrayBuffersToSend:s});const i=z(...s);$i.log("sending arrayBuffer",i),await this.sendTxData(i)}else{const e=z(...n);$i.log("sending arrayBuffer",e),await this.sendTxData(e)}t(this,Ui,"f").length=0,s(this,Ri,!1,"f")}async sendTxData(e){$i.log("sendTxData",e)}parseRxMessage(e){dt(e,Pi,t(this,Mi,"m",xi).bind(this),null,!0),this.onMessagesReceived()}}Ci=qi,Ti=new WeakMap,Ui=new WeakMap,Ri=new WeakMap,Ai=new WeakMap,Mi=new WeakSet,Di=function(e){$i.assertEnumWithError(e,Pi)},ki=function(){$i.assertWithError(this.isSupported,`${this.constructor.name} is not supported`)},Wi=function(){$i.assertWithError(!this.isConnected,"device is already connected")},_i=function(){$i.assertWithError("connecting"!=this.status,"device is already connecting")},Ii=function(){$i.assertWithError(this.isConnected,"device is not connected")},Li=function(){$i.assertWithError("disconnecting"!=this.status,"device is already disconnecting")},Fi=function(){t(this,Mi,"m",Ii).call(this),t(this,Mi,"m",Li).call(this)},xi=function(e,t){$i.log({messageType:e,dataView:t}),this.onMessageReceived(e,t)},Oi=function(){this.isConnected||($i.log("timer detected disconnection"),this.status="notConnected")};const Gi=T("EventUtils",{log:!1});function Hi(e,t){let s=e.addEventListener||e.addListener||e.on||e.AddEventListener;Gi.assertWithError(s,"no add listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}function Ji(e,t){let s=e.removeEventListener||e.removeListener||e.RemoveEventListener;Gi.assertWithError(s,"no remove listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}const Qi=T("bluetoothUUIDs",{log:!1});if(n)var Ki=window.BluetoothUUID;function Zi(e){return Qi.assertTypeWithError(e,"string"),Qi.assertWithError(4==e.length,"value must be 4 characters long"),`ea6da725-${e}-4f9b-893d-c3913e33b39f`}function Xi(e){return Ki?.getCharacteristic?.(e)}function Yi(e){return Ki?.getService?.(e)}const en=Object.freeze({services:{deviceInformation:{uuid:Yi("device_information"),characteristics:{manufacturerName:{uuid:Xi("manufacturer_name_string")},modelNumber:{uuid:Xi("model_number_string")},hardwareRevision:{uuid:Xi("hardware_revision_string")},firmwareRevision:{uuid:Xi("firmware_revision_string")},softwareRevision:{uuid:Xi("software_revision_string")},pnpId:{uuid:Xi("pnp_id")},serialNumber:{uuid:Xi("serial_number_string")}}},battery:{uuid:Yi("battery_service"),characteristics:{batteryLevel:{uuid:Xi("battery_level")}}},main:{uuid:Zi("0000"),characteristics:{rx:{uuid:Zi("1000")},tx:{uuid:Zi("1001")}}},smp:{uuid:"8d53dc1d-1db7-4cd3-868b-8a527460aa84",characteristics:{smp:{uuid:"da2e7828-fbce-4e01-ae9e-261174997c48"}}}}}),tn=[en.services.main.uuid],sn=[en.services.deviceInformation.uuid,en.services.battery.uuid,en.services.smp.uuid];function nn(e){e=e.toString().toLowerCase();return Object.keys(en.services).find((t=>{let s=en.services[t].uuid.toString();return 4==e.length&&(s=s.slice(4,8)),e.includes("-")||(s=s.replaceAll("-","")),e==s}))}const rn=[],an=[];function on(e){var t;return e=e.toString().toLowerCase(),Object.values(en.services).some((s=>{const i=Object.keys(s.characteristics);return t=i.find((t=>{let i=s.characteristics[t].uuid.toString();return 4==e.length&&(i=i.slice(4,8)),e.includes("-")||(i=i.replaceAll("-","")),e==i}))})),t}function cn(e){const t={broadcast:!1,read:!0,writeWithoutResponse:!1,write:!1,notify:!1,indicate:!1,authenticatedSignedWrites:!1,reliableWrite:!1,writableAuxiliaries:!1};switch(e){case"rx":case"tx":case"smp":t.read=!1}switch(e){case"batteryLevel":case"rx":case"smp":t.notify=!0}if("smp"===e)t.writeWithoutResponse=!0;if("tx"===e)t.write=!0;return t}Object.values(en.services).forEach((e=>{if(!e.characteristics)return;const t=Object.keys(e.characteristics);t.forEach((s=>{const i=e.characteristics[s];tn.includes(e.uuid)&&(rn.push(i.uuid),t.push(s)),an.push(i.uuid)}))}),[]);const hn=T("BluetoothConnectionManager",{log:!0});class ln extends qi{constructor(){super(...arguments),this.isInRange=!0}onCharacteristicValueChanged(e,t){"rx"==e?this.parseRxMessage(t):this.onMessageReceived?.(e,t)}async writeCharacteristic(e,t){hn.log("writeCharacteristic",...arguments)}async sendSmpMessage(e){super.sendSmpMessage(e),await this.writeCharacteristic("smp",e)}async sendTxData(e){super.sendTxData(e),0!=e.byteLength&&await this.writeCharacteristic("tx",e)}}var gn,fn,un,dn,mn,pn,vn,wn,yn,bn,Sn;const En=T("WebBluetoothConnectionManager",{log:!0});var Mn;n&&(Mn=window.navigator.bluetooth);class Cn extends ln{constructor(){super(...arguments),gn.add(this),fn.set(this,{characteristicvaluechanged:t(this,gn,"m",yn).bind(this)}),un.set(this,{gattserverdisconnected:t(this,gn,"m",Sn).bind(this)}),dn.set(this,void 0),mn.set(this,new Map),pn.set(this,new Map)}get bluetoothId(){return this.device.id}static get isSupported(){return Boolean(Mn)}static get type(){return"webBluetooth"}get device(){return t(this,dn,"f")}set device(e){t(this,dn,"f")!=e?(t(this,dn,"f")&&Ji(t(this,dn,"f"),t(this,un,"f")),e&&Hi(e,t(this,un,"f")),s(this,dn,e,"f")):En.log("tried to assign the same BluetoothDevice")}get server(){return t(this,dn,"f")?.gatt}get isConnected(){return this.server?.connected||!1}async connect(){await super.connect();try{const e=await Mn.requestDevice({filters:[{services:tn}],optionalServices:n?sn:[]});En.log("got BluetoothDevice"),this.device=e,En.log("connecting to device...");const s=await this.server.connect();En.log(`connected to device? ${s.connected}`),await t(this,gn,"m",vn).call(this),En.log("fully connected"),this.status="connected"}catch(e){En.error(e),this.status="notConnected",this.server?.disconnect(),t(this,gn,"m",wn).call(this)}}async disconnect(){await t(this,gn,"m",wn).call(this),await super.disconnect(),this.server?.disconnect(),this.status="notConnected"}async writeCharacteristic(e,s){super.writeCharacteristic(e,s);const i=t(this,pn,"f").get(e);En.assertWithError(i,`${e} characteristic not found`),En.log("writing characteristic",i,s);const n=i.properties||cn(e);n.writeWithoutResponse?(En.log("writing without response"),await i.writeValueWithoutResponse(s)):(En.log("writing with response"),await i.writeValueWithResponse(s)),En.log("wrote characteristic"),n.read&&!n.notify&&(En.log("reading value after write..."),await i.readValue(),(c||h)&&t(this,gn,"m",bn).call(this,i))}get canReconnect(){return Boolean(this.server&&!this.server.connected&&this.isInRange)}async reconnect(){await super.reconnect(),En.log("attempting to reconnect..."),this.status="connecting";try{await this.server.connect()}catch(e){En.error(e),this.isInRange=!1}this.isConnected?(En.log("successfully reconnected!"),await t(this,gn,"m",vn).call(this),this.status="connected"):(En.log("unable to reconnect"),this.status="notConnected")}}fn=new WeakMap,un=new WeakMap,dn=new WeakMap,mn=new WeakMap,pn=new WeakMap,gn=new WeakSet,vn=async function(){t(this,gn,"m",wn).call(this),En.log("getting services...");const e=await this.server.getPrimaryServices();En.log("got services",e.length),En.log("getting characteristics...");for(const s in e){const i=e[s];En.log({service:i});const n=nn(i.uuid);En.assertWithError(n,`no name found for service uuid "${i.uuid}"`),En.log(`got "${n}" service`),i.name=n,t(this,mn,"f").set(n,i),En.log(`getting characteristics for "${n}" service`);const r=await i.getCharacteristics();En.log(`got characteristics for "${n}" service`);for(const e in r){const s=r[e];En.log({characteristic:s});const i=on(s.uuid);En.assertWithError(Boolean(i),`no name found for characteristic uuid "${s.uuid}" in "${n}" service`),En.log(`got "${i}" characteristic in "${n}" service`),s.name=i,t(this,pn,"f").set(i,s),Hi(s,t(this,fn,"f"));const a=s.properties||cn(i);a.notify&&(En.log(`starting notifications for "${i}" characteristic`),await s.startNotifications()),a.read&&(En.log(`reading "${i}" characteristic...`),await s.readValue(),(c||h)&&t(this,gn,"m",bn).call(this,s))}}},wn=async function(){this.device&&Ji(this.device,t(this,un,"f"));const e=Array.from(t(this,pn,"f").keys()).map((e=>{const s=t(this,pn,"f").get(e);Ji(s,t(this,fn,"f"));if((s.properties||cn(e)).notify)return En.log(`stopping notifications for "${e}" characteristic`),s.stopNotifications()}));return Promise.allSettled(e)},yn=function(e){En.log("oncharacteristicvaluechanged");const s=e.target;t(this,gn,"m",bn).call(this,s)},bn=function(e){En.log("onCharacteristicValue");const t=e.name;En.assertWithError(Boolean(t),`no name found for characteristic with uuid "${e.uuid}"`),En.log(`oncharacteristicvaluechanged for "${t}" characteristic`);const s=e.value;En.assertWithError(s,`no data found for "${t}" characteristic`),En.log(`data for "${t}" characteristic`,Array.from(new Uint8Array(s.buffer)));try{this.onCharacteristicValueChanged(t,s)}catch(e){En.error(e)}},Sn=function(){En.log("gattserverdisconnected"),this.status="notConnected"};const Dn=4294967296,kn=9007199254740992;const Tn={encode:function(e){let t,s=new ArrayBuffer(256),i=new DataView(s),n=0;function r(e){let r=s.byteLength;const a=n+e;for(;r<a;)r<<=1;if(r!==s.byteLength){const e=i;s=new ArrayBuffer(r),i=new DataView(s);const t=n+3>>2;for(let s=0;s<t;++s)i.setUint32(s<<2,e.getUint32(s<<2))}return t=e,i}function a(){n+=t}function o(e){a(r(1).setUint8(n,e))}function c(e){const t=r(e.length);for(let s=0;s<e.length;++s)t.setUint8(n+s,e[s]);a()}function h(e,t){t<24?o(e<<5|t):t<256?(o(e<<5|24),o(t)):t<65536?(o(e<<5|25),function(e){a(r(2).setUint16(n,e))}(t)):t<4294967296?(o(e<<5|26),function(e){a(r(4).setUint32(n,e))}(t)):(o(e<<5|27),function(e){const t=e%Dn,s=(e-t)/Dn,i=r(8);i.setUint32(n,s),i.setUint32(n+4,t),a()}(t))}if(function e(t){let s;const i=[];let l;if(!1===t)return o(244);if(!0===t)return o(245);if(null===t)return o(246);if(void 0===t)return o(247);switch(typeof t){case"number":if(Math.floor(t)===t){if(t>=0&&t<=kn)return h(0,t);if(-kn<=t&&t<0)return h(1,-(t+1))}return o(251),function(e){a(r(8).setFloat64(n,e))}(t);case"string":for(s=0;s<t.length;++s){let e=t.charCodeAt(s);e<128?i.push(e):e<2048?(i.push(192|e>>6),i.push(128|63&e)):e<55296?(i.push(224|e>>12),i.push(128|e>>6&63),i.push(128|63&e)):(e=(1023&e)<<10,e|=1023&t.charCodeAt(++s),e+=65536,i.push(240|e>>18),i.push(128|e>>12&63),i.push(128|e>>6&63),i.push(128|63&e))}return h(3,i.length),c(i);default:if(Array.isArray(t))for(l=t.length,h(4,l),s=0;s<l;++s)e(t[s]);else if(t instanceof Uint8Array)h(2,t.length),c(t);else{const i=Object.keys(t);for(l=i.length,h(5,l),s=0;s<l;++s){const n=i[s];e(n),e(t[n])}}}}(e),"slice"in s)return s.slice(0,n);const l=new ArrayBuffer(n),g=new DataView(l);for(let e=0;e<n;++e)g.setUint8(e,i.getUint8(e));return l},decode:function(e,t,s){const i=new DataView(e);let n=0;function r(e,t){return n+=e,t}function a(t){return r(t,new Uint8Array(e,n,t))}function o(){return r(1,i.getUint8(n))}function c(){return r(2,i.getUint16(n))}function h(){return r(4,i.getUint32(n))}function l(){return 255===i.getUint8(n)&&(n+=1,!0)}function g(e){if(e<24)return e;if(24===e)return o();if(25===e)return c();if(26===e)return h();if(27===e)return h()*Dn+h();if(31===e)return-1;throw new Error("Invalid length encoding")}function f(e){const t=o();if(255===t)return-1;const s=g(31&t);if(s<0||t>>5!==e)throw new Error("Invalid indefinite length element");return s}function u(e,t){for(let s=0;s<t;++s){let s=o();128&s&&(s<224?(s=(31&s)<<6|63&o(),t-=1):s<240?(s=(15&s)<<12|(63&o())<<6|63&o(),t-=2):(s=(15&s)<<18|(63&o())<<12|(63&o())<<6|63&o(),t-=3)),s<65536?e.push(s):(s-=65536,e.push(55296|s>>10),e.push(56320|1023&s))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof s&&(s=function(){});const d=function e(){const h=o(),d=h>>5,m=31&h;let p,v;if(7===d)switch(m){case 25:return function(){const e=new ArrayBuffer(4),t=new DataView(e),s=c(),i=32768&s;let n=31744&s;const r=1023&s;if(31744===n)n=261120;else if(0!==n)n+=114688;else if(0!==r)return(i?-1:1)*r*5.960464477539063e-8;return t.setUint32(0,i<<16|n<<13|r<<13),t.getFloat32(0)}();case 26:return r(4,i.getFloat32(n));case 27:return r(8,i.getFloat64(n))}if(v=g(m),v<0&&(d<2||d>6))throw new Error("Invalid length");const w=[];let y;const b={};switch(d){case 0:return v;case 1:return-1-v;case 2:if(v<0){const e=[];let t=0;for(;(v=f(d))>=0;)t+=v,e.push(a(v));const s=new Uint8Array(t);let i=0;for(p=0;p<e.length;++p)s.set(e[p],i),i+=e[p].length;return s}return a(v);case 3:if(v<0)for(;(v=f(d))>=0;)u(w,v);else u(w,v);return String.fromCharCode.apply(null,w);case 4:if(v<0)for(y=[];!l();)y.push(e());else for(y=new Array(v),p=0;p<v;++p)y[p]=e();return y;case 5:for(p=0;p<v||v<0&&!l();++p){b[e()]=e()}return b;case 6:return t(e(),v);case 7:switch(v){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:return s(v)}}}();if(n!==e.byteLength)throw new Error("Remaining bytes");return d}},Wn=T("mcumgr",{log:!0}),_n=0,In=1,Ln=2,Fn=3,Un=0,Rn=1,xn=8,An=0,On=2,$n=3,Bn=5,Nn=0,Pn=1,Vn=5,zn=0;class jn{constructor(){this._mtu=256,this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}onMessage(e){return this._messageCallback=e,this}onImageUploadNext(e){return this._imageUploadNextCallback=e,this}onImageUploadProgress(e){return this._imageUploadProgressCallback=e,this}onImageUploadFinished(e){return this._imageUploadFinishedCallback=e,this}onFileUploadNext(e){return this._fileUploadNextCallback=e,this}onFileUploadProgress(e){return this._fileUploadProgressCallback=e,this}onFileUploadFinished(e){return this._fileUploadFinishedCallback=e,this}onFileDownloadNext(e){return this._fileDownloadNextCallback=e,this}onFileDownloadProgress(e){return this._fileDownloadProgressCallback=e,this}onFileDownloadFinished(e){return this._fileDownloadFinishedCallback=e,this}_getMessage(e,t,s,i){let n=[];void 0!==i&&(n=[...new Uint8Array(Tn.encode(i))]);const r=255&n.length,a=[e,0,n.length>>8,r,t>>8,255&t,this._seq,s,...n];return this._seq=(this._seq+1)%256,a}_notification(e){Wn.log("mcumgr - message received");const t=new Uint8Array(e);this._buffer=new Uint8Array([...this._buffer,...t]);const s=256*this._buffer[2]+this._buffer[3];this._buffer.length<s+8||(this._processMessage(this._buffer.slice(0,s+8)),this._buffer=this._buffer.slice(s+8))}_processMessage(e){const[t,,s,i,n,r,,a]=e,o=Tn.decode(e.slice(8).buffer),c=256*s+i,h=256*n+r;return Wn.log("mcumgr - Process Message - Group: "+h+", Id: "+a+", Off: "+o.off),h===Rn&&a===Pn&&o.off?(this._uploadOffset=o.off,void this._uploadNext()):t===Fn&&h===xn&&a===zn&&o.off?(this._uploadFileOffset=o.off,void this._uploadFileNext()):t===In&&h===xn&&a===zn?(this._downloadFileOffset+=o.data.length,null!=o.len&&(this._downloadFileLength=o.len),Wn.log("downloaded "+this._downloadFileOffset+" bytes of "+this._downloadFileLength),this._downloadFileLength>0&&this._fileDownloadProgressCallback({percentage:Math.floor(this._downloadFileOffset/this._downloadFileLength*100)}),this._messageCallback&&this._messageCallback({op:t,group:h,id:a,data:o,length:c}),void this._downloadFileNext()):void(this._messageCallback&&this._messageCallback({op:t,group:h,id:a,data:o,length:c}))}cmdReset(){return this._getMessage(Ln,Un,Bn)}smpEcho(e){return this._getMessage(Ln,Un,An,{d:e})}cmdImageState(){return this._getMessage(_n,Rn,Nn)}cmdImageErase(){return this._getMessage(Ln,Rn,Vn,{})}cmdImageTest(e){return this._getMessage(Ln,Rn,Nn,{hash:e,confirm:!1})}cmdImageConfirm(e){return this._getMessage(Ln,Rn,Nn,{hash:e,confirm:!0})}_hash(e){return crypto.subtle.digest("SHA-256",e)}async _uploadNext(){if(!this._uploadImage)return;if(this._uploadOffset>=this._uploadImage.byteLength)return this._uploadIsInProgress=!1,void this._imageUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadOffset};0===this._uploadOffset&&(e.len=this._uploadImage.byteLength,e.sha=new Uint8Array(await this._hash(this._uploadImage))),this._imageUploadProgressCallback({percentage:Math.floor(this._uploadOffset/this._uploadImage.byteLength*100)});const t=this._mtu-Tn.encode(e).byteLength-8-3-5;e.data=new Uint8Array(this._uploadImage.slice(this._uploadOffset,this._uploadOffset+t)),this._uploadOffset+=t;const s=this._getMessage(Ln,Rn,Pn,e);Wn.log("mcumgr - _uploadNext: Message Length: "+s.length),this._imageUploadNextCallback({packet:s})}async reset(){this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}async cmdUpload(e,t=0){this._uploadIsInProgress?Wn.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadOffset=0,this._uploadImage=e,this._uploadSlot=t,this._uploadNext())}async cmdUploadFile(e,t){this._uploadIsInProgress?Wn.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadFileOffset=0,this._uploadFile=e,this._uploadFilename=t,this._uploadFileNext())}async _uploadFileNext(){if(Wn.log("uploadFileNext - offset: "+this._uploadFileOffset+", length: "+this._uploadFile.byteLength),this._uploadFileOffset>=this._uploadFile.byteLength)return this._uploadIsInProgress=!1,void this._fileUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadFileOffset};0===this._uploadFileOffset&&(e.len=this._uploadFile.byteLength),e.name=this._uploadFilename,this._fileUploadProgressCallback({percentage:Math.floor(this._uploadFileOffset/this._uploadFile.byteLength*100)});const t=this._mtu-Tn.encode(e).byteLength-8;e.data=new Uint8Array(this._uploadFile.slice(this._uploadFileOffset,this._uploadFileOffset+t)),this._uploadFileOffset+=t;const s=this._getMessage(Ln,xn,zn,e);Wn.log("mcumgr - _uploadNext: Message Length: "+s.length),this._fileUploadNextCallback({packet:s})}async cmdDownloadFile(e,t){this._downloadIsInProgress?Wn.error("Download is already in progress."):(this._downloadIsInProgress=!0,this._downloadFileOffset=0,this._downloadFileLength=0,this._downloadRemoteFilename=e,this._downloadLocalFilename=t,this._downloadFileNext())}async _downloadFileNext(){if(this._downloadFileLength>0&&this._downloadFileOffset>=this._downloadFileLength)return this._downloadIsInProgress=!1,void this._fileDownloadFinishedCallback();const e={off:this._downloadFileOffset};0===this._downloadFileOffset&&(e.name=this._downloadRemoteFilename);const t=this._getMessage(_n,xn,zn,e);Wn.log("mcumgr - _downloadNext: Message Length: "+t.length),this._fileDownloadNextCallback({packet:t})}async imageInfo(e){const t={},s=new Uint8Array(e);if(s.length<32)throw new Error("Invalid image (too short file)");if(61!==s[0]||184!==s[1]||243!==s[2]||150!==s[3])throw new Error("Invalid image (wrong magic bytes)");if(0!==s[4]||0!==s[5]||0!==s[6]||0!==s[7])throw new Error("Invalid image (wrong load address)");const i=s[8]+256*s[9];if(0!==s[10]||0!==s[11])throw new Error("Invalid image (wrong protected TLV area size)");const n=s[12]+256*s[13]+65536*s[14]+s[15]*2**24;if(t.imageSize=n,s.length<n+i)throw new Error("Invalid image (wrong image size)");if(0!==s[16]||0!==s[17]||0!==s[18]||0!==s[19])throw new Error("Invalid image (wrong flags)");const r=`${s[20]}.${s[21]}.${s[22]+256*s[23]}`;return t.version=r,t.hash=[...new Uint8Array(await this._hash(e.slice(0,n+32)))].map((e=>e.toString(16).padStart(2,"0"))).join(""),t}}var qn,Gn,Hn,Jn,Qn,Kn,Zn,Xn,Yn,er,tr,sr,ir,nr,rr,ar,or,cr,hr,lr,gr;const fr=T("FirmwareManager",{log:!0}),ur=["smp"],dr=[...ur,"firmwareImages","firmwareUploadProgress","firmwareStatus","firmwareUploadComplete"],mr=["idle","uploading","uploaded","pending","testing","erasing"];class pr{constructor(){qn.add(this),Hn.set(this,"idle"),Qn.set(this,void 0),Xn.set(this,void 0),Yn.set(this,new jn),t(this,qn,"m",er).call(this),H(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}parseMessage(e,s){if(fr.log({messageType:e}),"smp"!==e)throw Error(`uncaught messageType ${e}`);t(this,Yn,"f")._notification(Array.from(new Uint8Array(s.buffer))),t(this,qn,"a",Gn).call(this,"smp",{dataView:s})}async uploadFirmware(e){fr.log("uploadFirmware",e);const s=this.waitForEvent("firmwareUploadComplete");await this.getImages();const i=await G(e),n=await t(this,Yn,"f").imageInfo(i);fr.log({imageInfo:n}),t(this,Yn,"f").cmdUpload(i,1),t(this,qn,"m",Jn).call(this,"uploading"),await s}get status(){return t(this,Hn,"f")}get images(){return t(this,Qn,"f")}async getImages(){const e=this.waitForEvent("firmwareImages");fr.log("getting firmware image state..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").cmdImageState()).buffer),await e}async testImage(e=1){if(t(this,qn,"m",Zn).call(this,e),t(this,qn,"m",Kn).call(this),!t(this,Qn,"f")[e])return void fr.log(`image ${e} not found`);if(1==t(this,Qn,"f")[e].pending)return void fr.log(`image ${e} is already pending`);if(t(this,Qn,"f")[e].empty)return void fr.log(`image ${e} is empty`);const s=this.waitForEvent("smp");fr.log("testing firmware image..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").cmdImageTest(t(this,Qn,"f")[e].hash)).buffer),await s}async eraseImage(){t(this,qn,"m",Kn).call(this);const e=this.waitForEvent("smp");fr.log("erasing image..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").cmdImageErase()).buffer),t(this,qn,"m",Jn).call(this,"erasing"),await e,await this.getImages()}async confirmImage(e=0){if(t(this,qn,"m",Zn).call(this,e),t(this,qn,"m",Kn).call(this),!0===t(this,Qn,"f")[e].confirmed)return void fr.log(`image ${e} is already confirmed`);const s=this.waitForEvent("smp");fr.log("confirming image..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").cmdImageConfirm(t(this,Qn,"f")[e].hash)).buffer),await s}async echo(e){fr.assertTypeWithError(e,"string");const s=this.waitForEvent("smp");fr.log("sending echo..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").smpEcho(e)).buffer),await s}async reset(){const e=this.waitForEvent("smp");fr.log("resetting..."),this.sendMessage(Uint8Array.from(t(this,Yn,"f").cmdReset()).buffer),await e}get mtu(){return t(this,Xn,"f")}set mtu(e){s(this,Xn,e,"f"),t(this,Yn,"f")._mtu=e}}var vr,wr,yr,br,Sr,Er,Mr,Cr,Dr,kr,Tr,Wr,_r,Ir,Lr,Fr,Ur,Rr;Hn=new WeakMap,Qn=new WeakMap,Xn=new WeakMap,Yn=new WeakMap,qn=new WeakSet,Gn=function(){return this.eventDispatcher.dispatchEvent},Jn=function(e){fr.assertEnumWithError(e,mr),t(this,Hn,"f")!=e?(s(this,Hn,e,"f"),fr.log({firmwareStatus:t(this,Hn,"f")}),t(this,qn,"a",Gn).call(this,"firmwareStatus",{firmwareStatus:t(this,Hn,"f")})):fr.log(`redundant firmwareStatus assignment "${e}"`)},Kn=function(){fr.assertWithError(t(this,Qn,"f"),"didn't get imageState")},Zn=function(e){fr.assertTypeWithError(e,"number"),fr.assertWithError(0==e||1==e,"imageIndex must be 0 or 1")},er=function(){t(this,Yn,"f").onMessage(t(this,qn,"m",tr).bind(this)),t(this,Yn,"f").onFileDownloadNext(t(this,qn,"m",sr)),t(this,Yn,"f").onFileDownloadProgress(t(this,qn,"m",ir).bind(this)),t(this,Yn,"f").onFileDownloadFinished(t(this,qn,"m",nr).bind(this)),t(this,Yn,"f").onFileUploadNext(t(this,qn,"m",rr).bind(this)),t(this,Yn,"f").onFileUploadProgress(t(this,qn,"m",ar).bind(this)),t(this,Yn,"f").onFileUploadFinished(t(this,qn,"m",or).bind(this)),t(this,Yn,"f").onImageUploadNext(t(this,qn,"m",cr).bind(this)),t(this,Yn,"f").onImageUploadProgress(t(this,qn,"m",hr).bind(this)),t(this,Yn,"f").onImageUploadFinished(t(this,qn,"m",lr).bind(this))},tr=function({op:e,group:s,id:i,data:n,length:r}){switch(fr.log("onMcuMessage",...arguments),s){case Un:switch(i){case An:fr.log(`echo "${n.r}"`);break;case On:fr.table(n.tasks);break;case $n:fr.log(n)}break;case Rn:if(i===Nn)t(this,qn,"m",gr).call(this,n);break;default:throw Error(`uncaught mcuMessage group ${s}`)}},sr=function(){fr.log("onMcuFileDownloadNext",...arguments)},ir=function(){fr.log("onMcuFileDownloadProgress",...arguments)},nr=function(){fr.log("onMcuFileDownloadFinished",...arguments)},rr=function(){fr.log("onMcuFileUploadNext")},ar=function(){fr.log("onMcuFileUploadProgress")},or=function(){fr.log("onMcuFileUploadFinished")},cr=function({packet:e}){fr.log("onMcuImageUploadNext"),this.sendMessage(Uint8Array.from(e).buffer)},hr=function({percentage:e}){const s=e/100;fr.log("onMcuImageUploadProgress",...arguments),t(this,qn,"a",Gn).call(this,"firmwareUploadProgress",{progress:s})},lr=async function(){fr.log("onMcuImageUploadFinished",...arguments),await this.getImages(),t(this,qn,"a",Gn).call(this,"firmwareUploadProgress",{progress:100}),t(this,qn,"a",Gn).call(this,"firmwareUploadComplete",{})},gr=function({images:e}){if(!e)return void fr.log("no images found");s(this,Qn,e,"f"),fr.log("images",t(this,Qn,"f"));let i="idle";2==t(this,Qn,"f").length&&(t(this,Qn,"f")[1].bootable?t(this,Qn,"f")[0].confirmed?t(this,Qn,"f")[1].pending?(fr.log("reset to upload to the new firmware image"),i="pending"):(fr.log("Slot 1 has a valid image. run testImage() to test it or upload a different image."),i="uploaded"):(fr.log('Slot 0 has a valid image. Click "Confirm Image" to confirm it or wait and the device will swap images back.'),i="testing"):fr.warn('Slot 1 has a invalid image. Click "Erase Image" to erase it or upload a different image')),1==t(this,Qn,"f").length&&(t(this,Qn,"f").push({slot:1,empty:!0,version:"Empty",pending:!1,confirmed:!1,bootable:!1,active:!1,permanent:!1}),fr.log("Select a firmware upload image to upload to slot 1.")),t(this,qn,"m",Jn).call(this,i),t(this,qn,"a",Gn).call(this,"firmwareImages",{firmwareImages:t(this,Qn,"f")})};const xr=T("DeviceManager",{log:!0}),Ar=["deviceConnected","deviceDisconnected","deviceIsConnected","availableDevices","connectedDevices"];class Or{constructor(){if(vr.add(this),wr.set(this,{getType:t(this,vr,"m",yr).bind(this),isConnected:t(this,vr,"m",Fr).bind(this)}),br.set(this,[]),Sr.set(this,!1),Er.set(this,{devices:[]}),Mr.set(this,void 0),Dr.set(this,"BS.Device"),_r.set(this,[]),Ir.set(this,new _(this,Ar)),Or.shared&&this!=Or.shared)throw Error("DeviceManager is a singleton - use DeviceManager.shared");this.CanUseLocalStorage&&(this.UseLocalStorage=!0)}onDevice(e){Hi(e,t(this,wr,"f"))}OnDeviceConnectionStatusUpdated(e,s){if("notConnected"==s&&!e.canReconnect&&t(this,_r,"f").includes(e)){const s=t(this,_r,"f").indexOf(e);this.AvailableDevices.splice(s,1),t(this,vr,"m",Ur).call(this)}}get ConnectedDevices(){return t(this,br,"f")}get UseLocalStorage(){return t(this,Sr,"f")}set UseLocalStorage(e){t(this,vr,"m",Cr).call(this),xr.assertTypeWithError(e,"boolean"),s(this,Sr,e,"f"),t(this,Sr,"f")&&!t(this,Mr,"f")&&t(this,vr,"m",Tr).call(this)}get CanUseLocalStorage(){return n&&window.localStorage}get AvailableDevices(){return t(this,_r,"f")}get CanGetDevices(){return n&&navigator.bluetooth?.getDevices}async GetDevices(){if(!n)return void xr.warn("GetDevices is only available in the browser");if(!navigator.bluetooth)return void xr.warn("bluetooth is not available in this browser");if(c)return void xr.warn("bluefy lists too many devices...");if(!navigator.bluetooth.getDevices)return void xr.warn("bluetooth.getDevices() is not available in this browser");if(!this.CanGetDevices)return void xr.log("CanGetDevices is false");t(this,Mr,"f")||t(this,vr,"m",Tr).call(this);const e=t(this,Mr,"f");if(!e.devices||0==e.devices.length)return void xr.log("no devices found in configuration");const s=await navigator.bluetooth.getDevices();return xr.log({bluetoothDevices:s}),s.forEach((s=>{if(!s.gatt)return;let i=e.devices.find((e=>s.id==e.bluetoothId));if(!i)return;let n=this.ConnectedDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==s.id));const r=this.AvailableDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==s.id));if(r)return void(n&&n?.bluetoothId==r.bluetoothId&&n!=r&&(this.AvailableDevices[t(this,_r,"f").indexOf(r)]=n));if(n)return void this.AvailableDevices.push(n);const a=new Ea,o=new Cn;o.device=s,s.name&&a._informationManager.updateName(s.name),a._informationManager.updateType(i.type),a.connectionManager=o,this.AvailableDevices.push(a)})),t(this,vr,"m",Ur).call(this),this.AvailableDevices}get AddEventListener(){return t(this,Ir,"f").addEventListener}get RemoveEventListener(){return t(this,Ir,"f").removeEventListener}get RemoveEventListeners(){return t(this,Ir,"f").removeEventListeners}get RemoveAllEventListeners(){return t(this,Ir,"f").removeAllEventListeners}}wr=new WeakMap,br=new WeakMap,Sr=new WeakMap,Er=new WeakMap,Mr=new WeakMap,Dr=new WeakMap,_r=new WeakMap,Ir=new WeakMap,vr=new WeakSet,yr=function(e){t(this,Sr,"f")&&t(this,vr,"m",Wr).call(this,e.target)},Cr=function(){xr.assertWithError(n,"localStorage is only available in the browser"),xr.assertWithError(window.localStorage,"localStorage not found")},kr=function(){t(this,vr,"m",Cr).call(this),localStorage.setItem(t(this,Dr,"f"),JSON.stringify(t(this,Mr,"f")))},Tr=async function(){t(this,vr,"m",Cr).call(this);let e=localStorage.getItem(t(this,Dr,"f"));if("string"!=typeof e)return xr.log("no info found in localStorage"),s(this,Mr,Object.assign({},t(this,Er,"f")),"f"),void t(this,vr,"m",kr).call(this);try{const t=JSON.parse(e);xr.log({configuration:t}),s(this,Mr,t,"f"),this.CanGetDevices&&await this.GetDevices()}catch(e){xr.error(e)}},Wr=function(e){if("webBluetooth"!=e.connectionType)return void xr.log("localStorage is only for webBluetooth devices");t(this,vr,"m",Cr).call(this);const s=t(this,Mr,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1!=s&&(t(this,Mr,"f").devices[s].type=e.type,t(this,vr,"m",kr).call(this))},Lr=function(){return t(this,Ir,"f").dispatchEvent},Fr=function(e){const{target:s}=e;if(s.isConnected)if(t(this,br,"f").includes(s))xr.log("device already included");else{if(xr.log("adding device",s),t(this,br,"f").push(s),this.UseLocalStorage&&"webBluetooth"==s.connectionType){const e={type:s.type,bluetoothId:s.bluetoothId},i=t(this,Mr,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1==i?t(this,Mr,"f").devices.push(e):t(this,Mr,"f").devices[i]=e,t(this,vr,"m",kr).call(this)}t(this,vr,"a",Lr).call(this,"deviceConnected",{device:s}),t(this,vr,"a",Lr).call(this,"deviceIsConnected",{device:s}),t(this,vr,"m",Rr).call(this)}else t(this,br,"f").includes(s)?(xr.log("removing device",s),t(this,br,"f").splice(t(this,br,"f").indexOf(s),1),t(this,vr,"a",Lr).call(this,"deviceDisconnected",{device:s}),t(this,vr,"a",Lr).call(this,"deviceIsConnected",{device:s}),t(this,vr,"m",Rr).call(this)):xr.log("device already not included");if(this.CanGetDevices&&this.GetDevices(),s.isConnected&&!this.AvailableDevices.includes(s)){const e=this.AvailableDevices.find((e=>e.bluetoothId==s.bluetoothId));xr.log({existingAvailableDevice:e}),e?this.AvailableDevices[this.AvailableDevices.indexOf(e)]=s:this.AvailableDevices.push(s),t(this,vr,"m",Ur).call(this)}},Ur=function(){xr.log({AvailableDevices:this.AvailableDevices}),t(this,vr,"a",Lr).call(this,"availableDevices",{availableDevices:this.AvailableDevices})},Rr=function(){xr.log({ConnectedDevices:this.ConnectedDevices}),t(this,vr,"a",Lr).call(this,"connectedDevices",{connectedDevices:this.ConnectedDevices})},Or.shared=new Or;var $r,Br,Nr,Pr,Vr,zr,jr,qr,Gr,Hr,Jr,Qr,Kr,Zr,Xr,Yr,ea,ta,sa,ia,na,ra,aa,oa,ca,ha,la,ga,fa,ua,da,ma,pa,va,wa=Or.shared;const ya=T("Device",{log:!0}),ba=["connectionMessage",...Ni,...zi,...Vi,...Xs,...Ws,...Ot,...bt,...Oe,...vs,...dr],Sa=["isCharging","getBatteryCurrent","getId","getMtu","getName","getType","getCurrentTime","getSensorConfiguration","getSensorScalars","getPressurePositions","maxFileLength","getFileLength","getFileChecksum","getFileType","fileTransferStatus","getTfliteName","getTfliteTask","getTfliteSampleRate","getTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","getTfliteThreshold","getTfliteInferencingEnabled"];class Ea{get bluetoothId(){return t(this,zr,"f")?.bluetoothId}constructor(){$r.add(this),Pr.set(this,new _(this,ba)),zr.set(this,void 0),this.sendTxMessages=t(this,$r,"m",jr).bind(this),qr.set(this,!1),Zr.set(this,Br.ReconnectOnDisconnection),Xr.set(this,void 0),this.latestConnectionMessage=new Map,ra.set(this,new _s),aa.set(this,0),this._informationManager=new Ys,ca.set(this,new $t),la.set(this,Br.ClearSensorConfigurationOnLeave),ga.set(this,new St),fa.set(this,new Ei),ua.set(this,new $e),da.set(this,new bs),ma.set(this,new pr),this.sendSmpMessage=t(this,$r,"m",pa).bind(this),va.set(this,!1),t(this,ra,"f").eventDispatcher=t(this,Pr,"f"),this._informationManager.sendMessage=this.sendTxMessages,this._informationManager.eventDispatcher=t(this,Pr,"f"),t(this,ca,"f").sendMessage=this.sendTxMessages,t(this,ca,"f").eventDispatcher=t(this,Pr,"f"),t(this,ga,"f").eventDispatcher=t(this,Pr,"f"),t(this,fa,"f").sendMessage=this.sendTxMessages,t(this,da,"f").sendMessage=this.sendTxMessages,t(this,da,"f").eventDispatcher=t(this,Pr,"f"),t(this,ua,"f").sendMessage=this.sendTxMessages,t(this,ua,"f").eventDispatcher=t(this,Pr,"f"),t(this,ma,"f").sendMessage=this.sendSmpMessage,t(this,ma,"f").eventDispatcher=t(this,Pr,"f"),this.addEventListener("getMtu",(()=>{t(this,ma,"f").mtu=this.mtu,t(this,ua,"f").mtu=this.mtu,this.connectionManager.mtu=this.mtu})),wa.onDevice(this),n&&window.addEventListener("beforeunload",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()})),r&&process.on("exit",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()}))}get addEventListener(){return t(this,Pr,"f").addEventListener}get removeEventListener(){return t(this,Pr,"f").removeEventListener}get waitForEvent(){return t(this,Pr,"f").waitForEvent}get removeEventListeners(){return t(this,Pr,"f").removeEventListeners}get removeAllEventListeners(){return t(this,Pr,"f").removeAllEventListeners}get connectionManager(){return t(this,zr,"f")}set connectionManager(e){this.connectionManager!=e?(this.connectionManager&&(this.connectionManager.onStatusUpdated=void 0,this.connectionManager.onMessageReceived=void 0,this.connectionManager.onMessagesReceived=void 0),e&&(e.onStatusUpdated=t(this,$r,"m",Yr).bind(this),e.onMessageReceived=t(this,$r,"m",ia).bind(this),e.onMessagesReceived=t(this,$r,"m",na).bind(this)),s(this,zr,e,"f"),ya.log("assigned new connectionManager",t(this,zr,"f"))):ya.log("same connectionManager is already assigned")}async connect(){return this.connectionManager||(this.connectionManager=t(Br,Br,"m",Nr).call(Br)),t(this,$r,"m",sa).call(this),this.connectionManager.connect()}get isConnected(){return t(this,qr,"f")}get canReconnect(){return this.connectionManager?.canReconnect}async reconnect(){return t(this,$r,"m",Qr).call(this),t(this,$r,"m",sa).call(this),this.connectionManager?.reconnect()}static async Connect(){const e=new Br;return await e.connect(),e}static get ReconnectOnDisconnection(){return t(this,Br,"f",Kr)}static set ReconnectOnDisconnection(e){ya.assertTypeWithError(e,"boolean"),s(this,Br,e,"f",Kr)}get reconnectOnDisconnection(){return t(this,Zr,"f")}set reconnectOnDisconnection(e){ya.assertTypeWithError(e,"boolean"),s(this,Zr,e,"f")}get connectionType(){return this.connectionManager?.type}async disconnect(){return t(this,$r,"m",Gr).call(this),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.addEventListener("isConnected",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this.connectionManager.disconnect()}toggleConnection(){this.isConnected?this.disconnect():this.canReconnect?this.reconnect():this.connect()}get connectionStatus(){switch(t(this,zr,"f")?.status){case"connected":return this.isConnected?"connected":"connecting";case"notConnected":case"connecting":case"disconnecting":return t(this,zr,"f").status;default:return"notConnected"}}get isConnectionBusy(){return"connecting"==this.connectionStatus||"disconnecting"==this.connectionStatus}get deviceInformation(){return t(this,ra,"f").information}get batteryLevel(){return t(this,aa,"f")}get id(){return this._informationManager.id}get isCharging(){return this._informationManager.isCharging}get batteryCurrent(){return this._informationManager.batteryCurrent}get getBatteryCurrent(){return this._informationManager.getBatteryCurrent}get name(){return this._informationManager.name}get setName(){return this._informationManager.setName}get type(){return this._informationManager.type}get setType(){return this._informationManager.setType}get isInsole(){return this._informationManager.isInsole}get insoleSide(){return this._informationManager.insoleSide}get mtu(){return this._informationManager.mtu}get sensorTypes(){return Object.keys(this.sensorConfiguration)}get continuousSensorTypes(){return wt.filter((e=>this.sensorTypes.includes(e)))}get sensorConfiguration(){return t(this,ca,"f").configuration}async setSensorConfiguration(e,s){await t(this,ca,"f").setConfiguration(e,s)}async clearSensorConfiguration(){return t(this,ca,"f").clearSensorConfiguration()}static get ClearSensorConfigurationOnLeave(){return t(this,Br,"f",ha)}static set ClearSensorConfigurationOnLeave(e){ya.assertTypeWithError(e,"boolean"),s(this,Br,e,"f",ha)}get clearSensorConfigurationOnLeave(){return t(this,la,"f")}set clearSensorConfigurationOnLeave(e){ya.assertTypeWithError(e,"boolean"),s(this,la,e,"f")}get numberOfPressureSensors(){return t(this,ga,"f").pressureSensorDataManager.numberOfSensors}resetPressureRange(){t(this,ga,"f").pressureSensorDataManager.resetRange()}async triggerVibration(e,s){t(this,fa,"f").triggerVibration(e,s)}get maxFileLength(){return t(this,ua,"f").maxLength}async sendFile(e,s){const i=this.waitForEvent("fileTransferComplete");t(this,ua,"f").send(e,s),await i}async receiveFile(e){const s=this.waitForEvent("fileTransferComplete");t(this,ua,"f").receive(e),await s}get fileTransferStatus(){return t(this,ua,"f").status}cancelFileTransfer(){t(this,ua,"f").cancel()}get tfliteName(){return t(this,da,"f").name}get setTfliteName(){return t(this,da,"f").setName}get tfliteTask(){return t(this,da,"f").task}get setTfliteTask(){return t(this,da,"f").setTask}get tfliteSampleRate(){return t(this,da,"f").sampleRate}get setTfliteSampleRate(){return t(this,da,"f").setSampleRate}get tfliteSensorTypes(){return t(this,da,"f").sensorTypes}get allowedTfliteSensorTypes(){return this.sensorTypes.filter((e=>ys.includes(e)))}get setTfliteSensorTypes(){return t(this,da,"f").setSensorTypes}get tfliteIsReady(){return t(this,da,"f").isReady}get tfliteInferencingEnabled(){return t(this,da,"f").inferencingEnabled}get setTfliteInferencingEnabled(){return t(this,da,"f").setInferencingEnabled}async enableTfliteInferencing(){return this.setTfliteInferencingEnabled(!0)}async disableTfliteInferencing(){return this.setTfliteInferencingEnabled(!1)}get toggleTfliteInferencing(){return t(this,da,"f").toggleInferencingEnabled}get tfliteCaptureDelay(){return t(this,da,"f").captureDelay}get setTfliteCaptureDelay(){return t(this,da,"f").setCaptureDelay}get tfliteThreshold(){return t(this,da,"f").threshold}get setTfliteThreshold(){return t(this,da,"f").setThreshold}get uploadFirmware(){return t(this,ma,"f").uploadFirmware}async reset(){return await t(this,ma,"f").reset(),t(this,zr,"f").disconnect()}get firmwareStatus(){return t(this,ma,"f").status}get getFirmwareImages(){return t(this,ma,"f").getImages}get firmwareImages(){return t(this,ma,"f").images}get eraseFirmwareImage(){return t(this,ma,"f").eraseImage}get confirmFirmwareImage(){return t(this,ma,"f").confirmImage}get testFirmwareImage(){return t(this,ma,"f").testImage}get isServerSide(){return t(this,va,"f")}set isServerSide(e){t(this,va,"f")!=e?(ya.log({newIsServerSide:e}),s(this,va,e,"f"),t(this,ua,"f").isServerSide=this.isServerSide):ya.log("redundant isServerSide assignment")}}var Ma,Ca,Da,ka,Ta;Br=Ea,Pr=new WeakMap,zr=new WeakMap,qr=new WeakMap,Zr=new WeakMap,Xr=new WeakMap,ra=new WeakMap,aa=new WeakMap,ca=new WeakMap,la=new WeakMap,ga=new WeakMap,fa=new WeakMap,ua=new WeakMap,da=new WeakMap,ma=new WeakMap,va=new WeakMap,$r=new WeakSet,Nr=function(){return new Cn},Vr=function(){return t(this,Pr,"f").dispatchEvent},jr=async function(e,s){await(t(this,zr,"f")?.sendTxMessages(e,s))},Gr=function(){ya.assertWithError(this.isConnected,"notConnected")},Hr=function(){return Sa.every((e=>this.latestConnectionMessage.has(e)))},Jr=function(){const e=Sa.map((e=>({type:e})));t(this,$r,"m",jr).call(this,e)},Qr=function(){ya.assertWithError(this.canReconnect,"cannot reconnect to device")},Yr=function(e){ya.log({connectionStatus:e}),"notConnected"==e?this.canReconnect&&this.reconnectOnDisconnection&&(ya.log("starting reconnect interval..."),s(this,Xr,setInterval((()=>{ya.log("attempting reconnect..."),this.reconnect()}),1e3),"f")):null!=t(this,Xr,"f")&&(ya.log("clearing reconnect interval"),clearInterval(t(this,Xr,"f")),s(this,Xr,void 0,"f")),t(this,$r,"m",ta).call(this),"connected"!=e||t(this,qr,"f")||t(this,$r,"m",Jr).call(this),wa.OnDeviceConnectionStatusUpdated(this,e)},ea=function(e=!1){t(this,$r,"a",Vr).call(this,"connectionStatus",{connectionStatus:this.connectionStatus}),t(this,$r,"a",Vr).call(this,this.connectionStatus,{}),e&&t(this,$r,"a",Vr).call(this,"isConnected",{isConnected:this.isConnected})},ta=function(){switch(s(this,qr,Boolean(this.connectionManager?.isConnected)&&t(this,$r,"a",Hr)&&this._informationManager.isCurrentTimeSet,"f"),this.connectionStatus){case"connected":t(this,qr,"f")&&t(this,$r,"m",ea).call(this,!0);break;case"notConnected":t(this,$r,"m",ea).call(this,!0);break;default:t(this,$r,"m",ea).call(this,!1)}},sa=function(){this.latestConnectionMessage.clear(),this._informationManager.clear(),t(this,ra,"f").clear()},ia=function(e,s){if(ya.log({messageType:e,dataView:s}),"batteryLevel"===e){const e=s.getUint8(0);ya.log("received battery level",{batteryLevel:e}),t(this,$r,"m",oa).call(this,e)}else if(Ue.includes(e))t(this,ua,"f").parseMessage(e,s);else if(ps.includes(e))t(this,da,"f").parseMessage(e,s);else if(yt.includes(e))t(this,ga,"f").parseMessage(e,s);else if(ur.includes(e))t(this,ma,"f").parseMessage(e,s);else if(Ts.includes(e))t(this,ra,"f").parseMessage(e,s);else if(Zs.includes(e))this._informationManager.parseMessage(e,s);else{if(!At.includes(e))throw Error(`uncaught messageType ${e}`);t(this,ca,"f").parseMessage(e,s)}this.latestConnectionMessage.set(e,s),t(this,$r,"a",Vr).call(this,"connectionMessage",{messageType:e,dataView:s})},na=function(){!this.isConnected&&t(this,$r,"a",Hr)&&t(this,$r,"m",ta).call(this),"notConnected"!=this.connectionStatus&&t(this,$r,"m",jr).call(this)},oa=function(e){ya.assertTypeWithError(e,"number"),t(this,aa,"f")!=e?(s(this,aa,e,"f"),ya.log({updatedBatteryLevel:t(this,aa,"f")}),t(this,$r,"a",Vr).call(this,"batteryLevel",{batteryLevel:t(this,aa,"f")})):ya.log(`duplicate batteryLevel assignment ${e}`)},pa=function(e){return t(this,zr,"f").sendSmpMessage(e)},Kr={value:!1},ha={value:!0};const Wa=T("DevicePairPressureSensorDataManager",{log:!0});class _a{constructor(){Ma.add(this),Ca.set(this,{}),Da.set(this,new Ze)}resetPressureRange(){t(this,Da,"f").reset()}onDevicePressureData(e){const{pressure:s}=e.message,i=e.target.insoleSide;if(Wa.log({pressure:s,insoleSide:i}),t(this,Ca,"f")[i]=s,t(this,Ma,"a",ka))return t(this,Ma,"m",Ta).call(this);Wa.log("doesn't have all pressure data yet...")}}var Ia;Ca=new WeakMap,Da=new WeakMap,Ma=new WeakSet,ka=function(){return Ks.every((e=>e in t(this,Ca,"f")))},Ta=function(){const e={rawSum:0,normalizedSum:0};return Ks.forEach((s=>{e.rawSum+=t(this,Ca,"f")[s].scaledSum,e.normalizedSum+=t(this,Ca,"f")[s].normalizedSum})),e.normalizedSum>.001&&(e.center={x:0,y:0},Ks.forEach((s=>{const i=t(this,Ca,"f")[s],n=i.normalizedSum/e.normalizedSum;n>0&&(null!=i.normalizedCenter?.y&&(e.center.y+=i.normalizedCenter.y*n),"right"==s&&(e.center.x=n))})),e.normalizedCenter=t(this,Da,"f").updateAndGetNormalization(e.center)),Wa.log({devicePairPressure:e}),e};const La=T("DevicePairSensorDataManager",{log:!0}),Fa=["pressure","sensorData"];class Ua{constructor(){Ia.set(this,{}),this.pressureSensorDataManager=new _a}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}resetPressureRange(){this.pressureSensorDataManager.resetPressureRange()}onDeviceSensorData(e){const{timestamp:s,sensorType:i}=e.message;let n;if(La.log({sensorType:i,timestamp:s,event:e}),t(this,Ia,"f")[i]||(t(this,Ia,"f")[i]={}),t(this,Ia,"f")[i][e.target.insoleSide]=s,"pressure"===i)n=this.pressureSensorDataManager.onDevicePressureData(e);else La.log(`uncaught sensorType "${i}"`);if(n){const e=Object.assign({},t(this,Ia,"f")[i]);this.dispatchEvent(i,{sensorType:i,timestamps:e,[i]:n}),this.dispatchEvent("sensorData",{sensorType:i,timestamps:e,[i]:n})}else La.log("no value received")}}var Ra,xa,Aa,Oa,$a,Ba,Na,Pa,Va,za,ja,qa,Ga,Ha,Ja,Qa;Ia=new WeakMap;const Ka=T("DevicePair",{log:!0});function Za(e){return`device${t=e,t[0].toUpperCase()+t.slice(1)}`;var t}const Xa=["isConnected",...Fa,...ba.map((e=>Za(e)))];class Ya{constructor(){Ra.add(this),Aa.set(this,new _(this,Xa)),$a.set(this,void 0),Ba.set(this,void 0),za.set(this,{isConnected:t(this,Ra,"m",qa).bind(this),sensorData:t(this,Ra,"m",Ja).bind(this),getType:t(this,Ra,"m",Ga).bind(this)}),Ha.set(this,new Ua),t(this,Ha,"f").eventDispatcher=t(this,Aa,"f")}get sides(){return Ks}get addEventListener(){return t(this,Aa,"f").addEventListener}get removeEventListener(){return t(this,Aa,"f").removeEventListener}get waitForEvent(){return t(this,Aa,"f").waitForEvent}get removeEventListeners(){return t(this,Aa,"f").removeEventListeners}get removeAllEventListeners(){return t(this,Aa,"f").removeAllEventListeners}get left(){return t(this,$a,"f")}get right(){return t(this,Ba,"f")}get isConnected(){return Ks.every((e=>this[e]?.isConnected))}get isPartiallyConnected(){return Ks.some((e=>this[e]?.isConnected))}get isHalfConnected(){return this.isPartiallyConnected&&!this.isConnected}assignInsole(e){if(!e.isInsole)return void Ka.warn("device is not an insole");const i=e.insoleSide,n=this[i];if(e!=n){switch(n&&t(this,Ra,"m",Pa).call(this,n),t(this,Ra,"m",Na).call(this,e),i){case"left":s(this,$a,e,"f");break;case"right":s(this,Ba,e,"f")}return Ka.log(`assigned ${i} insole`,e),this.resetPressureRange(),t(this,Ra,"a",Oa).call(this,"isConnected",{isConnected:this.isConnected}),t(this,Ra,"a",Oa).call(this,"deviceIsConnected",{device:e,isConnected:e.isConnected,side:i}),n}Ka.log("device already assigned")}async setSensorConfiguration(e){for(let t=0;t<Ks.length;t++){const s=Ks[t];this[s]?.isConnected&&await this[s].setSensorConfiguration(e)}}resetPressureRange(){t(this,Ha,"f").resetPressureRange()}async triggerVibration(e,t){const s=Ks.map((s=>this[s]?.triggerVibration(e,t))).filter(Boolean);return Promise.allSettled(s)}static get shared(){return t(this,xa,"f",Qa)}}xa=Ya,Aa=new WeakMap,$a=new WeakMap,Ba=new WeakMap,za=new WeakMap,Ha=new WeakMap,Ra=new WeakSet,Oa=function(){return t(this,Aa,"f").dispatchEvent},Na=function(e){Hi(e,t(this,za,"f")),ba.forEach((s=>{e.addEventListener(s,t(this,Ra,"m",ja).bind(this))}))},Pa=function(e){Ji(e,t(this,za,"f")),ba.forEach((s=>{e.removeEventListener(s,t(this,Ra,"m",ja).bind(this))}))},Va=function(e){const s=Ks.some((s=>this[s]==e&&(Ka.log(`removing ${s} insole`,e),Ji(e,t(this,za,"f")),delete this[s],!0)));return s&&t(this,Ra,"a",Oa).call(this,"isConnected",{isConnected:this.isConnected}),s},ja=function(e){const{type:s,target:i,message:n}=e;t(this,Ra,"a",Oa).call(this,Za(s),{...n,device:i,side:i.insoleSide})},qa=function(e){t(this,Ra,"a",Oa).call(this,"isConnected",{isConnected:this.isConnected})},Ga=function(e){const{target:s}=e;if(this[s.insoleSide]==s)return;t(this,Ra,"m",Va).call(this,s)&&this.assignInsole(s)},Ja=function(e){this.isConnected&&t(this,Ha,"f").onDeviceSensorData(e)},Qa={value:new xa},wa.AddEventListener("deviceConnected",(e=>{const{device:s}=e.message;s.isInsole&&t(xa,xa,"f",Qa).assignInsole(s)}));const eo=T("ServerUtils",{log:!1}),to=["isScanningAvailable","isScanning","startScan","stopScan","discoveredDevice","discoveredDevices","expiredDiscoveredDevice","connectToDevice","disconnectFromDevice","connectedDevices","deviceMessage"];function so(e,...t){eo.log("createMessage",...t);const s=t.map((t=>{"string"==typeof t&&(t={type:t}),null!=t.data?Array.isArray(t.data)||(t.data=[t.data]):t.data=[];const s=z(...t.data),i=s.byteLength;eo.assertEnumWithError(t.type,e);const n=e.indexOf(t.type),r=new DataView(new ArrayBuffer(2));return r.setUint16(0,i,!0),z(n,r,s)}));return eo.log("messageBuffers",...s),z(...s)}function io(...e){return eo.log("createServerMessage",...e),so(to,...e)}function no(...e){return eo.log("createClientDeviceMessage",...e),so(ji,...e)}var ro,ao,oo,co,ho;io("isScanningAvailable"),io("isScanning"),io("startScan"),io("stopScan"),io("discoveredDevices");const lo=T("ClientConnectionManager",{log:!0}),go=[...Ts,"batteryLevel"];class fo extends qi{constructor(){super(...arguments),ro.add(this),ao.set(this,void 0),oo.set(this,!1)}static get isSupported(){return n}static get type(){return"client"}get bluetoothId(){return t(this,ao,"f")}set bluetoothId(e){lo.assertTypeWithError(e,"string"),t(this,ao,"f")!=e?s(this,ao,e,"f"):lo.log("redundant bluetoothId assignment")}get isConnected(){return t(this,oo,"f")}set isConnected(e){lo.assertTypeWithError(e,"boolean"),t(this,oo,"f")!=e?(s(this,oo,e,"f"),this.status=t(this,oo,"f")?"connected":"notConnected",this.isConnected&&t(this,ro,"m",co).call(this)):lo.log("redundant newIsConnected assignment",e)}async connect(){await super.connect(),this.sendClientConnectMessage()}async disconnect(){await super.disconnect(),this.sendClientDisconnectMessage()}get canReconnect(){return!0}async reconnect(){await super.reconnect(),lo.log("attempting to reconnect..."),this.connect()}async sendSmpMessage(e){super.sendSmpMessage(e),this.sendClientMessage({type:"smp",data:e})}async sendTxData(e){super.sendTxData(e),0!=e.byteLength&&this.sendClientMessage({type:"tx",data:e})}onClientMessage(e){lo.log({dataView:e}),dt(e,ba,t(this,ro,"m",ho).bind(this),null,!0),this.onMessagesReceived()}}var uo,mo,po,vo,wo,yo,bo,So,Eo,Mo,Co,Do,ko,To,Wo,_o,Io,Lo,Fo;ao=new WeakMap,oo=new WeakMap,ro=new WeakSet,co=function(){this.sendClientMessage(...go)},ho=function(e,t){let s=0;switch(lo.log({messageType:e},t),e){case"isConnected":const i=Boolean(t.getUint8(s++));lo.log({isConnected:i}),this.isConnected=i;break;case"rx":this.parseRxMessage(t);break;default:this.onMessageReceived(e,t)}};const Uo=T("BaseClient",{log:!0}),Ro=["notConnected","connecting","connected","disconnecting","connectionStatus","isConnected","isScanningAvailable","isScanning","discoveredDevice","expiredDiscoveredDevice"];class xo{constructor(){uo.add(this),po.set(this,{}),vo.set(this,new _(this,Ro)),this._reconnectOnDisconnection=this.baseConstructor.ReconnectOnDisconnection,wo.set(this,"notConnected"),bo.set(this,!1),Co.set(this,!1),Io.set(this,{})}get baseConstructor(){return this.constructor}get devices(){return t(this,po,"f")}get addEventListener(){return t(this,vo,"f").addEventListener}get dispatchEvent(){return t(this,vo,"f").dispatchEvent}get removeEventListener(){return t(this,vo,"f").removeEventListener}get waitForEvent(){return t(this,vo,"f").waitForEvent}assertConnection(){Uo.assertWithError(this.isConnected,"notConnected")}assertDisconnection(){Uo.assertWithError(this.isDisconnected,"not disconnected")}static get ReconnectOnDisconnection(){return this._reconnectOnDisconnection}static set ReconnectOnDisconnection(e){Uo.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get reconnectOnDisconnection(){return this._reconnectOnDisconnection}set reconnectOnDisconnection(e){Uo.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get _connectionStatus(){return t(this,wo,"f")}set _connectionStatus(e){switch(Uo.assertTypeWithError(e,"string"),Uo.log({newConnectionStatus:e}),s(this,wo,e,"f"),this.dispatchEvent("connectionStatus",{connectionStatus:this.connectionStatus}),this.dispatchEvent(this.connectionStatus,{}),e){case"connected":case"notConnected":this.dispatchEvent("isConnected",{isConnected:this.isConnected}),this.isConnected?this.sendServerMessage("isScanningAvailable","discoveredDevices","connectedDevices"):t(this,uo,"m",mo).call(this)}}get connectionStatus(){return this._connectionStatus}parseMessage(e){Uo.log("parseMessage",{dataView:e}),dt(e,to,t(this,uo,"m",yo).bind(this),null,!0)}get isScanningAvailable(){return t(this,uo,"a",So)}requestIsScanningAvailable(){this.sendServerMessage("isScanningAvailable")}get isScanning(){return t(this,uo,"a",Do)}startScan(){t(this,uo,"m",_o).call(this),this.sendServerMessage("startScan")}stopScan(){t(this,uo,"m",Wo).call(this),this.sendServerMessage("stopScan")}toggleScan(){t(this,uo,"m",Mo).call(this),this.isScanning?this.stopScan():this.startScan()}get discoveredDevices(){return t(this,Io,"f")}onDiscoveredDevice(e){Uo.log({discoveredDevice:e}),t(this,Io,"f")[e.bluetoothId]=e,this.dispatchEvent("discoveredDevice",{discoveredDevice:e})}requestDiscoveredDevices(){this.sendServerMessage({type:"discoveredDevices"})}connectToDevice(e){return this.requestConnectionToDevice(e)}requestConnectionToDevice(e){this.assertConnection(),Uo.assertTypeWithError(e,"string");const s=t(this,uo,"m",Fo).call(this,e);return s.connect(),s}sendConnectToDeviceMessage(e){this.sendServerMessage({type:"connectToDevice",data:e})}createDevice(e){const t=new Ea,s=new fo;return s.bluetoothId=e,s.sendClientMessage=this.sendDeviceMessage.bind(this,e),s.sendClientConnectMessage=this.sendConnectToDeviceMessage.bind(this,e),s.sendClientDisconnectMessage=this.sendDisconnectFromDeviceMessage.bind(this,e),t.connectionManager=s,t}onConnectedBluetoothDeviceIds(e){Uo.log({bluetoothIds:e}),e.forEach((e=>{t(this,uo,"m",Fo).call(this,e).connectionManager.isConnected=!0}))}disconnectFromDevice(e){this.requestDisconnectionFromDevice(e)}requestDisconnectionFromDevice(e){this.assertConnection(),Uo.assertTypeWithError(e,"string");const t=this.devices[e];return Uo.assertWithError(t,`no device found with id ${e}`),t.disconnect(),t}sendDisconnectFromDeviceMessage(e){this.sendServerMessage({type:"disconnectFromDevice",data:e})}sendDeviceMessage(e,...t){this.sendServerMessage({type:"deviceMessage",data:[e,no(...t)]})}}po=new WeakMap,vo=new WeakMap,wo=new WeakMap,bo=new WeakMap,Co=new WeakMap,Io=new WeakMap,uo=new WeakSet,mo=function(){s(this,uo,!1,"a",Eo),s(this,uo,!1,"a",ko);for(const e in t(this,po,"f")){t(this,po,"f")[e].connectionManager.isConnected=!1}},yo=function(e,i){let n=0;switch(Uo.log({messageType:e},i),e){case"isScanningAvailable":{const e=Boolean(i.getUint8(n++));Uo.log({isScanningAvailable:e}),s(this,uo,e,"a",Eo)}break;case"isScanning":{const e=Boolean(i.getUint8(n++));Uo.log({isScanning:e}),s(this,uo,e,"a",ko)}break;case"discoveredDevice":{const{string:e}=ut(i,n);Uo.log({discoveredDeviceString:e});const t=JSON.parse(e);Uo.log({discoveredDevice:t}),this.onDiscoveredDevice(t)}break;case"expiredDiscoveredDevice":{const{string:e}=ut(i,n);t(this,uo,"m",Lo).call(this,e)}break;case"connectedDevices":{if(0==i.byteLength)break;const{string:e}=ut(i,n);Uo.log({connectedBluetoothDeviceIdStrings:e});const t=JSON.parse(e);Uo.log({connectedBluetoothDeviceIds:t}),this.onConnectedBluetoothDeviceIds(t)}break;case"deviceMessage":{const{string:e,byteOffset:s}=ut(i,n);n=s;const r=t(this,po,"f")[e];Uo.assertWithError(r,`no device found for id ${e}`);const a=r.connectionManager,o=q(i,n);a.onClientMessage(o)}break;default:Uo.error(`uncaught messageType "${e}"`)}},So=function(){return t(this,bo,"f")},Eo=function(e){Uo.assertTypeWithError(e,"boolean"),s(this,bo,e,"f"),this.dispatchEvent("isScanningAvailable",{isScanningAvailable:this.isScanningAvailable}),this.isScanningAvailable&&t(this,uo,"m",To).call(this)},Mo=function(){this.assertConnection(),Uo.assertWithError(this.isScanningAvailable,"scanning is not available")},Do=function(){return t(this,Co,"f")},ko=function(e){Uo.assertTypeWithError(e,"boolean"),s(this,Co,e,"f"),this.dispatchEvent("isScanning",{isScanning:this.isScanning})},To=function(){this.sendServerMessage("isScanning")},Wo=function(){Uo.assertWithError(this.isScanning,"is not scanning")},_o=function(){Uo.assertWithError(!this.isScanning,"is already scanning")},Lo=function(e){Uo.log({expiredBluetoothDeviceId:e});const s=t(this,Io,"f")[e];s?(Uo.log({expiredDiscoveredDevice:s}),delete t(this,Io,"f")[e],this.dispatchEvent("expiredDiscoveredDevice",{discoveredDevice:s})):Uo.warn(`no discoveredDevice found with id "${e}"`)},Fo=function(e){let s=t(this,po,"f")[e];return s||(s=this.createDevice(e),t(this,po,"f")[e]=s),s},xo._reconnectOnDisconnection=!0;const Ao=T("WebSocketUtils",{log:!1}),Oo=["ping","pong","serverMessage"];function $o(...e){return Ao.log("createWebSocketMessage",...e),so(Oo,...e)}var Bo,No,Po,Vo,zo,jo,qo,Go,Ho,Jo,Qo,Ko,Zo;$o("ping"),$o("pong");const Xo=T("WebSocketClient",{log:!0});No=new WeakMap,Vo=new WeakMap,Qo=new WeakMap,Bo=new WeakSet,Po=function(...e){this.sendMessage($o(...e))},zo=function(e){Xo.log("webSocket.open",e),t(this,Qo,"f").start(),this._connectionStatus="connected"},jo=async function(e){Xo.log("webSocket.message",e),t(this,Qo,"f").restart();const s=await e.data.arrayBuffer(),i=new DataView(s);t(this,Bo,"m",Ho).call(this,i)},qo=function(e){Xo.log("webSocket.close",e),this._connectionStatus="notConnected",Object.entries(this.devices).forEach((([e,t])=>{t.connectionManager.isConnected=!1})),t(this,Qo,"f").stop(),this.reconnectOnDisconnection&&setTimeout((()=>{this.reconnect()}),3e3)},Go=function(e){Xo.error("webSocket.error",e.message)},Ho=function(e){dt(e,Oo,t(this,Bo,"m",Jo).bind(this),null,!0)},Jo=function(e,s){switch(e){case"ping":t(this,Bo,"m",Zo).call(this);break;case"pong":break;case"serverMessage":this.parseMessage(s);break;default:Xo.error(`uncaught messageType "${e}"`)}},Ko=function(){t(this,Bo,"m",Po).call(this,"ping")},Zo=function(){t(this,Bo,"m",Po).call(this,"pong")},e.ContinuousSensorTypes=wt,e.DefaultNumberOfPressureSensors=8,e.Device=Ea,e.DeviceManager=wa,e.DevicePair=Ya,e.DeviceTypes=Qs,e.Environment=y,e.FileTransferDirections=["sending","receiving"],e.FileTypes=Re,e.InsoleSides=Ks,e.MaxNameLength=30,e.MaxNumberOfVibrationWaveformEffectSegments=8,e.MaxNumberOfVibrationWaveformSegments=20,e.MaxSensorRate=65535,e.MaxVibrationWaveformEffectSegmentDelay=Si,e.MaxVibrationWaveformEffectSegmentLoopCount=3,e.MaxVibrationWaveformEffectSequenceLoopCount=6,e.MaxVibrationWaveformSegmentDuration=bi,e.MinNameLength=2,e.RangeHelper=Ge,e.SensorRateStep=5,e.SensorTypes=vt,e.TfliteSensorTypes=ys,e.TfliteTasks=ws,e.VibrationLocations=wi,e.VibrationTypes=yi,e.VibrationWaveformEffects=ei,e.WebSocketClient=class extends xo{constructor(){super(...arguments),Bo.add(this),No.set(this,void 0),Vo.set(this,{open:t(this,Bo,"m",zo).bind(this),message:t(this,Bo,"m",jo).bind(this),close:t(this,Bo,"m",qo).bind(this),error:t(this,Bo,"m",Go).bind(this)}),Qo.set(this,new R(t(this,Bo,"m",Ko).bind(this),3e7))}get webSocket(){return t(this,No,"f")}set webSocket(e){t(this,No,"f")!=e?(Xo.log("assigning webSocket",e),t(this,No,"f")&&Ji(t(this,No,"f"),t(this,Vo,"f")),Hi(e,t(this,Vo,"f")),s(this,No,e,"f"),Xo.log("assigned webSocket")):Xo.log("redundant webSocket assignment")}get readyState(){return this.webSocket?.readyState}get isConnected(){return this.readyState==WebSocket.OPEN}get isDisconnected(){return this.readyState==WebSocket.CLOSED}connect(e=`wss://${location.host}`){this.webSocket&&this.assertDisconnection(),this._connectionStatus="connecting",this.webSocket=new WebSocket(e)}disconnect(){this.assertConnection(),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.webSocket.addEventListener("close",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this._connectionStatus="disconnecting",this.webSocket.close()}reconnect(){this.assertDisconnection(),this.connect(this.webSocket.url)}toggleConnection(e){this.isConnected?this.disconnect():e&&this.webSocket?.url==e?this.reconnect():this.connect(e)}sendMessage(e){this.assertConnection(),t(this,No,"f").send(e)}sendServerMessage(...e){this.sendMessage($o({type:"serverMessage",data:io(...e)}))}},e.setAllConsoleLevelFlags=function(e){k.setAllLevelFlags(e)},e.setConsoleLevelFlagsForType=function(e,t){k.setLevelFlagsForType(e,t)}}));
6
6
  //# sourceMappingURL=brilliantsole.min.js.map