brilliantsole 0.0.11 → 0.0.13

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