@neurosity/sdk 6.3.0 → 6.4.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/browser/neurosity.iife.js +61 -18
  2. package/dist/browser/neurosity.js +6 -6
  3. package/dist/browser/neurosity.js.map +1 -1
  4. package/dist/cjs/Neurosity.js +5 -3
  5. package/dist/cjs/api/bluetooth/BluetoothClient.d.ts +3 -1
  6. package/dist/cjs/api/bluetooth/BluetoothClient.js +9 -5
  7. package/dist/cjs/api/bluetooth/BluetoothTransport.d.ts +2 -2
  8. package/dist/cjs/api/bluetooth/react-native/ReactNativeTransport.d.ts +3 -3
  9. package/dist/cjs/api/bluetooth/react-native/ReactNativeTransport.js +6 -4
  10. package/dist/cjs/api/bluetooth/utils/osHasBluetoothSupport.d.ts +2 -2
  11. package/dist/cjs/api/bluetooth/utils/osHasBluetoothSupport.js +4 -2
  12. package/dist/cjs/api/bluetooth/web/WebBluetoothTransport.d.ts +3 -3
  13. package/dist/cjs/api/bluetooth/web/WebBluetoothTransport.js +8 -4
  14. package/dist/cjs/api/index.d.ts +3 -1
  15. package/dist/cjs/api/index.js +4 -0
  16. package/dist/electron/index.js +6 -6
  17. package/dist/electron/index.js.map +1 -1
  18. package/dist/esm/Neurosity.js +5 -3
  19. package/dist/esm/api/bluetooth/BluetoothClient.d.ts +3 -1
  20. package/dist/esm/api/bluetooth/BluetoothClient.js +10 -6
  21. package/dist/esm/api/bluetooth/BluetoothTransport.d.ts +2 -2
  22. package/dist/esm/api/bluetooth/react-native/ReactNativeTransport.d.ts +3 -3
  23. package/dist/esm/api/bluetooth/react-native/ReactNativeTransport.js +7 -5
  24. package/dist/esm/api/bluetooth/utils/osHasBluetoothSupport.d.ts +2 -2
  25. package/dist/esm/api/bluetooth/utils/osHasBluetoothSupport.js +4 -2
  26. package/dist/esm/api/bluetooth/web/WebBluetoothTransport.d.ts +3 -3
  27. package/dist/esm/api/bluetooth/web/WebBluetoothTransport.js +9 -5
  28. package/dist/esm/api/index.d.ts +3 -1
  29. package/dist/esm/api/index.js +4 -0
  30. package/dist/esm/neurosity.mjs +61 -18
  31. package/dist/examples/neurosity.iife.js +61 -18
  32. package/dist/examples/neurosity.js +6 -6
  33. package/dist/examples/neurosity.mjs +61 -18
  34. package/package.json +1 -1
@@ -25,7 +25,7 @@ process.env.HMR_PORT=0;process.env.HMR_HOSTNAME="localhost";parcelRequire=functi
25
25
  },{"../types/status":"Ttuy"}],"qny3":[function(require,module,exports) {
26
26
  "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.filterInternalKeys=void 0;const e=require("rxjs"),r=require("rxjs/operators");function t(){return(0,e.pipe)((0,r.map)(e=>{if(!e)return e;return Object.entries(e).reduce((e,[r,t])=>(r.startsWith("__")||(e[r]=t),e),{})}))}exports.filterInternalKeys=t;
27
27
  },{}],"LXvB":[function(require,module,exports) {
28
- "use strict";var e=this&&this.__awaiter||function(e,i,t,s){return new(t||(t=Promise))(function(r,n){function c(e){try{a(s.next(e))}catch(i){n(i)}}function o(e){try{a(s.throw(e))}catch(i){n(i)}}function a(e){var i;e.done?r(e.value):(i=e.value,i instanceof t?i:new t(function(e){e(i)})).then(c,o)}a((s=s.apply(e,i||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.CloudClient=exports.SERVER_TIMESTAMP=exports.createUser=exports.credentialWithLink=void 0;const i=require("rxjs"),t=require("rxjs"),s=require("rxjs/operators"),r=require("./firebase"),n=require("../timesync"),c=require("../subscriptions/SubscriptionManager"),o=require("../utils/heartbeat"),a=require("../utils/filterInternalKeys");var u=require("./firebase");Object.defineProperty(exports,"credentialWithLink",{enumerable:!0,get:function(){return u.credentialWithLink}}),Object.defineProperty(exports,"createUser",{enumerable:!0,get:function(){return u.createUser}}),Object.defineProperty(exports,"SERVER_TIMESTAMP",{enumerable:!0,get:function(){return u.SERVER_TIMESTAMP}});class h{constructor(e){this._selectedDevice=new i.ReplaySubject(1),this.options=e,this.subscriptionManager=new c.SubscriptionManager,this.firebaseApp=new r.FirebaseApp(e),this.firebaseUser=new r.FirebaseUser(this.firebaseApp),this._selectedDevice.next(void 0),this.status$=(0,o.heartbeatAwareStatus)(this.observeNamespace("status").pipe((0,s.share)())).pipe((0,a.filterInternalKeys)(),(0,s.shareReplay)(1)),this.firebaseUser.onAuthStateChanged().subscribe(e=>{this.user=e}),this.firebaseUser.onUserClaimsChange().subscribe(e=>{this.userClaims=e}),this.onDeviceChange().subscribe(e=>{this.firebaseDevice&&this.firebaseDevice.disconnect(),e&&(this.firebaseDevice=new r.FirebaseDevice({deviceId:e.deviceId,firebaseApp:this.firebaseApp,dependencies:{subscriptionManager:this.subscriptionManager}}),this.options.timesync&&(this.timesync=new n.Timesync({status$:this.status(),getTimesync:this.firebaseDevice.getTimesync.bind(this.firebaseDevice)})))})}onDeviceChange(){return this._selectedDevice.asObservable().pipe((0,s.filter)(e=>void 0!==e))}setAutoSelectedDevice(){return e(this,void 0,void 0,function*(){return this.options.deviceId?yield this.selectDevice(e=>e.find(e=>e.deviceId===this.options.deviceId)):!this.options.deviceId&&this.options.autoSelectDevice?yield this.selectDevice(e=>e[0]):null})}get actions(){return{dispatch:e=>this.firebaseDevice.dispatchAction(e)}}dispatchAction(i){return e(this,void 0,void 0,function*(){return yield this.firebaseDevice.dispatchAction(i)})}disconnect(){return e(this,void 0,void 0,function*(){return this.firebaseApp.disconnect()})}getInfo(){return e(this,void 0,void 0,function*(){return yield this.firebaseDevice.getInfo()})}login(i){return e(this,void 0,void 0,function*(){if(this.user)return Promise.reject("Already logged in.");const e=yield this.firebaseUser.login(i),t=yield this.setAutoSelectedDevice();return Object.assign(Object.assign({},e),{selectedDevice:t})})}logout(){return e(this,void 0,void 0,function*(){return this.firebaseDevice&&this.firebaseDevice.disconnect(),yield this.firebaseUser.logout()})}onAuthStateChanged(){return this.firebaseUser.onAuthStateChanged().pipe((0,s.switchMap)(i=>e(this,void 0,void 0,function*(){if(!i)return null;const e=this.didSelectDevice()?yield this.getSelectedDevice():yield this.setAutoSelectedDevice();return Object.assign(Object.assign({},i),{selectedDevice:e})})))}getDevices(){return this.firebaseUser.getDevices()}addDevice(e){return this.firebaseUser.addDevice(e)}removeDevice(i){return e(this,void 0,void 0,function*(){const[e,t]=yield this.firebaseUser.removeDevice(i).then(()=>[!1]).catch(e=>[!0,e]);if(e)return Promise.reject(t);const s=yield this.getSelectedDevice();(null==s?void 0:s.deviceId)===i&&this._selectedDevice.next(null)})}transferDevice(i){return e(this,void 0,void 0,function*(){const[e,t]=yield this.firebaseUser.transferDevice(i).then(()=>[!1]).catch(e=>[!0,e]);if(e)return Promise.reject(t);const s=yield this.getSelectedDevice();(null==s?void 0:s.deviceId)===i.deviceId&&this._selectedDevice.next(null)})}onUserDevicesChange(){return this.firebaseUser.onUserDevicesChange()}onUserClaimsChange(){return this.firebaseUser.onUserClaimsChange()}didSelectDevice(){return e(this,void 0,void 0,function*(){return!!(yield this.getSelectedDevice())})}selectDevice(i){return e(this,void 0,void 0,function*(){const e=yield this.getDevices();if(!e)return Promise.reject("Did not find any devices for this user. Make sure your device is claimed by your Neurosity account.");const t="function"==typeof i?i(e):(e=>e.find(e=>{if(!Array.isArray(i))return!1;const[t,s]=i;return JSON.stringify(null==e?void 0:e[t])===JSON.stringify(s)}))(e);return t?(yield this.firebaseUser.hasDevicePermission(t.deviceId))?(this._selectedDevice.next(t),t):Promise.reject("Rejected device access due to permissions."):Promise.reject("A device was not provided. Try returning a device from the devicesList provided in the callback.")})}getSelectedDevice(){return e(this,void 0,void 0,function*(){return yield(0,t.firstValueFrom)(this._selectedDevice)})}status(){return this.status$}observeNamespace(e){const r=()=>(0,t.fromEventPattern)(i=>this.firebaseDevice.onNamespace(e,i),i=>this.firebaseDevice.offNamespace(e,i));return this.onDeviceChange().pipe((0,s.switchMap)(e=>e?r():i.EMPTY))}onceNamespace(i){return e(this,void 0,void 0,function*(){return yield this.firebaseDevice.onceNamespace(i)})}get metrics(){return{next:(e,i)=>{this.firebaseDevice.nextMetric(e,i)},on:(e,i)=>this.firebaseDevice.onMetric(e,i),subscribe:e=>{const i=this.firebaseDevice.subscribeToMetric(e);return this.subscriptionManager.add(i),i},unsubscribe:(e,i)=>{this.subscriptionManager.remove(e),this.firebaseDevice.unsubscribeFromMetric(e),this.firebaseDevice.removeMetricListener(e,i)}}}createAccount(e){return this.firebaseUser.createAccount(e)}deleteAccount(){return this.firebaseUser.deleteAccount()}createBluetoothToken(){return this.firebaseDevice.createBluetoothToken()}createCustomToken(){return this.firebaseUser.createCustomToken()}removeOAuthAccess(){return this.firebaseUser.removeOAuthAccess()}onUserExperiments(){return this.firebaseUser.onUserExperiments()}deleteUserExperiment(e){return this.firebaseUser.deleteUserExperiment(e)}get skills(){return{get:i=>e(this,void 0,void 0,function*(){return this.firebaseDevice.getSkill(i)})}}get timestamp(){return this.options.timesync?this.timesync.timestamp:Date.now()}getTimesyncOffset(){return this.timesync.offset}changeSettings(e){return this.firebaseDevice.changeSettings(e)}goOffline(){this.firebaseApp.goOffline()}goOnline(){this.firebaseApp.goOnline()}__getApp(){return this.firebaseApp.app}}exports.CloudClient=h;
28
+ "use strict";var e=this&&this.__awaiter||function(e,i,t,s){return new(t||(t=Promise))(function(r,n){function c(e){try{a(s.next(e))}catch(i){n(i)}}function o(e){try{a(s.throw(e))}catch(i){n(i)}}function a(e){var i;e.done?r(e.value):(i=e.value,i instanceof t?i:new t(function(e){e(i)})).then(c,o)}a((s=s.apply(e,i||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.CloudClient=exports.SERVER_TIMESTAMP=exports.createUser=exports.credentialWithLink=void 0;const i=require("rxjs"),t=require("rxjs"),s=require("rxjs/operators"),r=require("./firebase"),n=require("../timesync"),c=require("../subscriptions/SubscriptionManager"),o=require("../utils/heartbeat"),a=require("../utils/filterInternalKeys");var u=require("./firebase");Object.defineProperty(exports,"credentialWithLink",{enumerable:!0,get:function(){return u.credentialWithLink}}),Object.defineProperty(exports,"createUser",{enumerable:!0,get:function(){return u.createUser}}),Object.defineProperty(exports,"SERVER_TIMESTAMP",{enumerable:!0,get:function(){return u.SERVER_TIMESTAMP}});class h{constructor(e){this._selectedDevice=new i.ReplaySubject(1),this.options=e,this.subscriptionManager=new c.SubscriptionManager,this.firebaseApp=new r.FirebaseApp(e),this.firebaseUser=new r.FirebaseUser(this.firebaseApp),this._selectedDevice.next(void 0),this.status$=(0,o.heartbeatAwareStatus)(this.observeNamespace("status").pipe((0,s.share)())).pipe((0,a.filterInternalKeys)(),(0,s.shareReplay)(1)),this.osVersion$=this.observeNamespace("info/osVersion").pipe((0,s.shareReplay)(1)),this.firebaseUser.onAuthStateChanged().subscribe(e=>{this.user=e}),this.firebaseUser.onUserClaimsChange().subscribe(e=>{this.userClaims=e}),this.onDeviceChange().subscribe(e=>{this.firebaseDevice&&this.firebaseDevice.disconnect(),e&&(this.firebaseDevice=new r.FirebaseDevice({deviceId:e.deviceId,firebaseApp:this.firebaseApp,dependencies:{subscriptionManager:this.subscriptionManager}}),this.options.timesync&&(this.timesync=new n.Timesync({status$:this.status(),getTimesync:this.firebaseDevice.getTimesync.bind(this.firebaseDevice)})))})}onDeviceChange(){return this._selectedDevice.asObservable().pipe((0,s.filter)(e=>void 0!==e))}osVersion(){return this.osVersion$}setAutoSelectedDevice(){return e(this,void 0,void 0,function*(){return this.options.deviceId?yield this.selectDevice(e=>e.find(e=>e.deviceId===this.options.deviceId)):!this.options.deviceId&&this.options.autoSelectDevice?yield this.selectDevice(e=>e[0]):null})}get actions(){return{dispatch:e=>this.firebaseDevice.dispatchAction(e)}}dispatchAction(i){return e(this,void 0,void 0,function*(){return yield this.firebaseDevice.dispatchAction(i)})}disconnect(){return e(this,void 0,void 0,function*(){return this.firebaseApp.disconnect()})}getInfo(){return e(this,void 0,void 0,function*(){return yield this.firebaseDevice.getInfo()})}login(i){return e(this,void 0,void 0,function*(){if(this.user)return Promise.reject("Already logged in.");const e=yield this.firebaseUser.login(i),t=yield this.setAutoSelectedDevice();return Object.assign(Object.assign({},e),{selectedDevice:t})})}logout(){return e(this,void 0,void 0,function*(){return this.firebaseDevice&&this.firebaseDevice.disconnect(),yield this.firebaseUser.logout()})}onAuthStateChanged(){return this.firebaseUser.onAuthStateChanged().pipe((0,s.switchMap)(i=>e(this,void 0,void 0,function*(){if(!i)return null;const e=this.didSelectDevice()?yield this.getSelectedDevice():yield this.setAutoSelectedDevice();return Object.assign(Object.assign({},i),{selectedDevice:e})})))}getDevices(){return this.firebaseUser.getDevices()}addDevice(e){return this.firebaseUser.addDevice(e)}removeDevice(i){return e(this,void 0,void 0,function*(){const[e,t]=yield this.firebaseUser.removeDevice(i).then(()=>[!1]).catch(e=>[!0,e]);if(e)return Promise.reject(t);const s=yield this.getSelectedDevice();(null==s?void 0:s.deviceId)===i&&this._selectedDevice.next(null)})}transferDevice(i){return e(this,void 0,void 0,function*(){const[e,t]=yield this.firebaseUser.transferDevice(i).then(()=>[!1]).catch(e=>[!0,e]);if(e)return Promise.reject(t);const s=yield this.getSelectedDevice();(null==s?void 0:s.deviceId)===i.deviceId&&this._selectedDevice.next(null)})}onUserDevicesChange(){return this.firebaseUser.onUserDevicesChange()}onUserClaimsChange(){return this.firebaseUser.onUserClaimsChange()}didSelectDevice(){return e(this,void 0,void 0,function*(){return!!(yield this.getSelectedDevice())})}selectDevice(i){return e(this,void 0,void 0,function*(){const e=yield this.getDevices();if(!e)return Promise.reject("Did not find any devices for this user. Make sure your device is claimed by your Neurosity account.");const t="function"==typeof i?i(e):(e=>e.find(e=>{if(!Array.isArray(i))return!1;const[t,s]=i;return JSON.stringify(null==e?void 0:e[t])===JSON.stringify(s)}))(e);return t?(yield this.firebaseUser.hasDevicePermission(t.deviceId))?(this._selectedDevice.next(t),t):Promise.reject("Rejected device access due to permissions."):Promise.reject("A device was not provided. Try returning a device from the devicesList provided in the callback.")})}getSelectedDevice(){return e(this,void 0,void 0,function*(){return yield(0,t.firstValueFrom)(this._selectedDevice)})}status(){return this.status$}observeNamespace(e){const r=()=>(0,t.fromEventPattern)(i=>this.firebaseDevice.onNamespace(e,i),i=>this.firebaseDevice.offNamespace(e,i));return this.onDeviceChange().pipe((0,s.switchMap)(e=>e?r():i.EMPTY))}onceNamespace(i){return e(this,void 0,void 0,function*(){return yield this.firebaseDevice.onceNamespace(i)})}get metrics(){return{next:(e,i)=>{this.firebaseDevice.nextMetric(e,i)},on:(e,i)=>this.firebaseDevice.onMetric(e,i),subscribe:e=>{const i=this.firebaseDevice.subscribeToMetric(e);return this.subscriptionManager.add(i),i},unsubscribe:(e,i)=>{this.subscriptionManager.remove(e),this.firebaseDevice.unsubscribeFromMetric(e),this.firebaseDevice.removeMetricListener(e,i)}}}createAccount(e){return this.firebaseUser.createAccount(e)}deleteAccount(){return this.firebaseUser.deleteAccount()}createBluetoothToken(){return this.firebaseDevice.createBluetoothToken()}createCustomToken(){return this.firebaseUser.createCustomToken()}removeOAuthAccess(){return this.firebaseUser.removeOAuthAccess()}onUserExperiments(){return this.firebaseUser.onUserExperiments()}deleteUserExperiment(e){return this.firebaseUser.deleteUserExperiment(e)}get skills(){return{get:i=>e(this,void 0,void 0,function*(){return this.firebaseDevice.getSkill(i)})}}get timestamp(){return this.options.timesync?this.timesync.timestamp:Date.now()}getTimesyncOffset(){return this.timesync.offset}changeSettings(e){return this.firebaseDevice.changeSettings(e)}goOffline(){this.firebaseApp.goOffline()}goOnline(){this.firebaseApp.goOnline()}__getApp(){return this.firebaseApp.app}}exports.CloudClient=h;
29
29
  },{"./firebase":"kM30","../timesync":"CXqr","../subscriptions/SubscriptionManager":"BX8M","../utils/heartbeat":"ImaE","../utils/filterInternalKeys":"qny3"}],"rekm":[function(require,module,exports) {
30
30
  "use strict";var t,o;Object.defineProperty(exports,"__esModule",{value:!0}),exports.STREAMING_MODE=exports.STREAMING_TYPE=void 0,function(t){t.WIFI="wifi",t.BLUETOOTH="bluetooth"}(t=exports.STREAMING_TYPE||(exports.STREAMING_TYPE={})),function(t){t.WIFI_ONLY="wifi-only",t.WIFI_WITH_BLUETOOTH_FALLBACK="wifi-with-bluetooth-fallback",t.BLUETOOTH_WITH_WIFI_FALLBACK="bluetooth-with-wifi-fallback"}(o=exports.STREAMING_MODE||(exports.STREAMING_MODE={}));
31
31
  },{}],"WDyG":[function(require,module,exports) {
@@ -65,21 +65,21 @@ process.env.HMR_PORT=0;process.env.HMR_HOSTNAME="localhost";parcelRequire=functi
65
65
  },{"../types":"iwtf"}],"dGLb":[function(require,module,exports) {
66
66
  "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CHARACTERISTIC_UUIDS_TO_NAMES=exports.DEFAULT_ACTION_RESPONSE_TIMEOUT=exports.REACT_NATIVE_MAX_BYTE_SIZE=exports.ANDROID_MAX_MTU=void 0;const e=require("@neurosity/ipk");exports.ANDROID_MAX_MTU=512,exports.REACT_NATIVE_MAX_BYTE_SIZE=512,exports.DEFAULT_ACTION_RESPONSE_TIMEOUT=6e4,exports.CHARACTERISTIC_UUIDS_TO_NAMES=Object.fromEntries(Object.entries(e.BLUETOOTH_CHARACTERISTICS).map(e=>e.reverse()));
67
67
  },{}],"rH2Y":[function(require,module,exports) {
68
- "use strict";var e=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.osHasBluetoothSupport=void 0;const t=e(require("semver/functions/gte"));function o(e){if(!e)return!1;return Number(e.modelVersion)>=3&&(!!!(null==e?void 0:e.emulator)&&(0,t.default)(e.osVersion,"16.0.0"))}exports.osHasBluetoothSupport=o;
68
+ "use strict";var e=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.osHasBluetoothSupport=void 0;const t=e(require("semver/functions/gte"));function o(e,o){if(!e)return!1;return Number(e.modelVersion)>=3&&(!!!(null==e?void 0:e.emulator)&&(0,t.default)(null!=o?o:e.osVersion,"16.0.0"))}exports.osHasBluetoothSupport=o;
69
69
  },{}],"ouKb":[function(require,module,exports) {
70
- "use strict";var t=this&&this.__awaiter||function(t,e,i,n){return new(i||(i=Promise))(function(s,o){function r(t){try{a(n.next(t))}catch(e){o(e)}}function c(t){try{a(n.throw(t))}catch(e){o(e)}}function a(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,c)}a((n=n.apply(t,e||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.WebBluetoothTransport=void 0;const e=require("@neurosity/ipk"),i=require("@neurosity/ipk"),n=require("@neurosity/ipk"),s=require("@neurosity/ipk"),o=require("rxjs"),r=require("rxjs"),c=require("rxjs/operators"),a=require("rxjs/operators"),d=require("rxjs/operators"),h=require("./isWebBluetoothSupported"),u=require("../utils/create6DigitPin"),v=require("../utils/stitch"),l=require("../utils/encoding"),p=require("../types"),g=require("../constants"),f=require("../constants"),E=require("../utils/osHasBluetoothSupport"),N={autoConnect:!0};class C{constructor(t={}){if(this.type=p.TRANSPORT_TYPE.WEB,this.characteristicsByName={},this.connection$=new o.BehaviorSubject(p.BLUETOOTH_CONNECTION.DISCONNECTED),this.pendingActions$=new o.BehaviorSubject([]),this.logs$=new o.ReplaySubject(10),this.onDisconnected$=this._onDisconnected().pipe((0,d.share)()),this.connectionStream$=this.connection$.asObservable().pipe((0,c.filter)(t=>!!t),(0,a.distinctUntilChanged)(),(0,a.shareReplay)(1)),this._isAutoConnectEnabled$=new o.ReplaySubject(1),this.options=Object.assign(Object.assign({},N),t),!(0,h.isWebBluetoothSupported)()){const t="Web Bluetooth is not supported";throw this.addLog(t),new Error(t)}this._isAutoConnectEnabled$.subscribe(t=>{this.addLog(`Auto connect: ${t?"enabled":"disabled"}`)}),this._isAutoConnectEnabled$.next(this.options.autoConnect),this.connection$.asObservable().subscribe(t=>{this.addLog(`connection status is ${t}`)}),this.onDisconnected$.subscribe(()=>{this.connection$.next(p.BLUETOOTH_CONNECTION.DISCONNECTED)})}_getPairedDevices(){return t(this,void 0,void 0,function*(){return yield navigator.bluetooth.getDevices()})}_autoConnect(e){return this._isAutoConnectEnabled$.pipe((0,c.switchMap)(t=>t?(0,o.merge)(e,this.onDisconnected$.pipe((0,c.switchMap)(()=>e))):r.NEVER),(0,c.switchMap)(t=>(0,E.osHasBluetoothSupport)(t)?(0,o.of)(t):r.EMPTY),(0,c.switchMap)(e=>t(this,void 0,void 0,function*(){var t;const{deviceNickname:i}=e;if(this.isConnected())return void this.addLog(`Auto connect: ${i} is already connected. Skipping auto connect.`);const[n,s]=yield this._getPairedDevices().then(t=>[null,t]).catch(t=>[t,null]);if(n)throw new Error(`failed to get devices: ${null!==(t=null==n?void 0:n.message)&&void 0!==t?t:n}`);this.addLog(`Auto connect: found ${s.length} devices ${s.map(({name:t})=>t).join(", ")}`);const o=s.findLast(t=>t.name===i);if(!o)throw new Error("couldn't find selected device in the list of paired devices.");return this.addLog(`Auto connect: ${i} was detected and previously paired`),o})),(0,c.tap)(()=>{this.connection$.next(p.BLUETOOTH_CONNECTION.SCANNING)}),(0,c.switchMap)(t=>m(t)),(0,c.switchMap)(e=>t(this,void 0,void 0,function*(){return this.addLog(`Advertisement received for ${e.device.name}`),yield this.getServerServiceAndCharacteristics(e.device)})))}enableAutoConnect(t){this._isAutoConnectEnabled$.next(t)}addLog(t){this.logs$.next(t)}isConnected(){return this.connection$.getValue()===p.BLUETOOTH_CONNECTION.CONNECTED}connection(){return this.connectionStream$}connect(e){return t(this,void 0,void 0,function*(){try{const i=yield this.requestDevice(e);yield this.getServerServiceAndCharacteristics(i)}catch(t){return Promise.reject(t)}})}requestDevice(i){return t(this,void 0,void 0,function*(){try{this.addLog("Requesting Bluetooth Device...");const o=n.BLUETOOTH_DEVICE_NAME_PREFIXES.map(t=>({namePrefix:t})),r=i?[{name:i}]:o;return yield window.navigator.bluetooth.requestDevice({filters:[...r,{manufacturerData:[{companyIdentifier:s.BLUETOOTH_COMPANY_IDENTIFIER_HEX}]}],optionalServices:[e.BLUETOOTH_PRIMARY_SERVICE_UUID_HEX]})}catch(t){return Promise.reject(t)}})}getServerServiceAndCharacteristics(i){return t(this,void 0,void 0,function*(){try{this.device=i,this.connection$.getValue()===p.BLUETOOTH_CONNECTION.CONNECTING||this.connection$.next(p.BLUETOOTH_CONNECTION.CONNECTING),this.server=yield i.gatt.connect(),this.addLog("Getting service..."),this.service=yield this.server.getPrimaryService(e.BLUETOOTH_PRIMARY_SERVICE_UUID_HEX),this.addLog(`Got service ${this.service.uuid}, getting characteristics...`);const n=yield this.service.getCharacteristics();this.addLog("Got characteristics"),this.characteristicsByName=Object.fromEntries(n.map(t=>[f.CHARACTERISTIC_UUIDS_TO_NAMES[t.uuid],t])),this.connection$.next(p.BLUETOOTH_CONNECTION.CONNECTED)}catch(t){return Promise.reject(t)}})}_onDisconnected(){return this.connection$.asObservable().pipe((0,c.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?O(this.device,"gattserverdisconnected"):r.NEVER))}disconnect(){var e,i;return t(this,void 0,void 0,function*(){(null===(i=null===(e=null==this?void 0:this.device)||void 0===e?void 0:e.gatt)||void 0===i?void 0:i.connected)&&this.device.gatt.disconnect()})}getCharacteristicByName(e){var i;return t(this,void 0,void 0,function*(){return null===(i=this.characteristicsByName)||void 0===i?void 0:i[e]})}subscribeToCharacteristic({characteristicName:e,manageNotifications:n=!0}){const s=(0,o.defer)(()=>this.getCharacteristicByName(e)).pipe((0,c.switchMap)(i=>t(this,void 0,void 0,function*(){var t;if(this.isConnected()&&n)try{yield i.startNotifications(),this.addLog(`Started notifications for ${e} characteristic`)}catch(s){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==s?void 0:s.message)&&void 0!==t?t:s}`)}return i})),(0,c.switchMap)(i=>O(i,"characteristicvaluechanged",()=>t(this,void 0,void 0,function*(){var t;if(this.isConnected()&&n)try{yield i.stopNotifications(),this.addLog(`Stopped notifications for ${e} characteristic`)}catch(s){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==s?void 0:s.message)&&void 0!==t?t:s}`)}}))),(0,c.map)(t=>{const i=t.target.value,n=(0,l.decode)(this.type,i);return this.addLog(`Received chunk with buffer size of ${i.byteLength} and decoded size ${n.length} for ${e} characteristic: \n${n}`),n}),(0,v.stitchChunks)({delimiter:i.BLUETOOTH_CHUNK_DELIMITER}),(0,c.map)(t=>{var i;try{return JSON.parse(t)}catch(n){return this.addLog(`Failed to parse JSON for ${e} characteristic. Falling back to unparsed string. ${null!==(i=null==n?void 0:n.message)&&void 0!==i?i:n}`),t}}));return this.connection$.pipe((0,c.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?s:r.NEVER))}readCharacteristic(e,i=!1){return t(this,void 0,void 0,function*(){try{this.addLog(`Reading characteristic: ${e}`);const n=yield this.getCharacteristicByName(e);if(!n)return this.addLog(`Did not fund ${e} characteristic`),Promise.reject(`Did not find characteristic by the name: ${e}`);const s=yield n.readValue(),o=(0,l.decode)(this.type,s),r=i?JSON.parse(o):o;return this.addLog(`Received read data from ${e} characteristic: \n${r}`),r}catch(t){return Promise.reject(`Error reading characteristic: ${t.message}`)}})}writeCharacteristic(e,i){return t(this,void 0,void 0,function*(){this.addLog(`Writing characteristic: ${e}`);const t=yield this.getCharacteristicByName(e);if(!t)return this.addLog(`Did not fund ${e} characteristic`),Promise.reject(`Did not find characteristic by the name: ${e}`);const n=(0,l.encode)(this.type,i);yield t.writeValueWithResponse(n)})}_addPendingAction(t){const e=this.pendingActions$.getValue();this.pendingActions$.next([...e,t])}_removePendingAction(t){const e=this.pendingActions$.getValue();this.pendingActions$.next(e.filter(e=>e!==t))}_autoToggleActionNotifications(e){return t(this,void 0,void 0,function*(){let i,n=!1;const s=this.connection$.asObservable().pipe((0,c.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?(0,o.defer)(()=>this.getCharacteristicByName("actions")).pipe((0,c.switchMap)(t=>(i=t,this.pendingActions$))):r.NEVER),(0,c.tap)(e=>t(this,void 0,void 0,function*(){var t,s;const o=!!e.length;if(o&&!n){n=!0;try{yield i.startNotifications(),this.addLog("Started notifications for [actions] characteristic")}catch(r){this.addLog(`Attemped to start notifications for [actions] characteristic: ${null!==(t=null==r?void 0:r.message)&&void 0!==t?t:r}`)}}if(!o&&n){n=!1;try{yield i.stopNotifications(),this.addLog("Stopped notifications for actions characteristic")}catch(r){this.addLog(`Attemped to stop notifications for [actions] characteristic: ${null!==(s=null==r?void 0:r.message)&&void 0!==s?s:r}`)}}})));e.pipe((0,c.switchMap)(t=>(0,E.osHasBluetoothSupport)(t)?s:r.EMPTY)).subscribe()})}dispatchAction({characteristicName:e,action:i}){return t(this,void 0,void 0,function*(){const{responseRequired:n=!1,responseTimeout:s=g.DEFAULT_ACTION_RESPONSE_TIMEOUT}=i;return new Promise((r,a)=>t(this,void 0,void 0,function*(){if(!(yield this.getCharacteristicByName(e).catch(()=>{a(`Did not find characteristic by the name: ${e}`)})))return;const t=(0,u.create6DigitPin)(),h=JSON.stringify(Object.assign({actionId:t},i));if(this.addLog(`Dispatched action with id ${t}`),n&&s){this._addPendingAction(t);const i=(0,o.timer)(s).subscribe(()=>{this._removePendingAction(t),a(`Action with id ${t} timed out after ${s}ms`)});this.subscribeToCharacteristic({characteristicName:e,manageNotifications:!1}).pipe((0,c.filter)(e=>(null==e?void 0:e.actionId)===t),(0,d.take)(1)).subscribe(e=>{i.unsubscribe(),this._removePendingAction(t),r(e)}),this.writeCharacteristic(e,h).catch(e=>{this._removePendingAction(t),a(e.message)})}else this.writeCharacteristic(e,h).then(()=>{r(null)}).catch(t=>{a(t.message)})}))})}}function O(e,i,n){return(0,r.fromEventPattern)(t=>{e.addEventListener(i,t)},s=>t(this,void 0,void 0,function*(){n&&(yield n()),e.removeEventListener(i,s)}))}function m(t){return new r.Observable(e=>{const i=new AbortController,{signal:n}=i,s=t.addEventListener("advertisementreceived",t=>{i.abort(),e.next(t),e.complete()},{once:!0});try{t.watchAdvertisements({signal:n})}catch(o){e.error(o)}return()=>{i.abort(),t.removeEventListener("advertisementreceived",s)}})}exports.WebBluetoothTransport=C;
70
+ "use strict";var t=this&&this.__awaiter||function(t,e,i,n){return new(i||(i=Promise))(function(s,o){function r(t){try{a(n.next(t))}catch(e){o(e)}}function c(t){try{a(n.throw(t))}catch(e){o(e)}}function a(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,c)}a((n=n.apply(t,e||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.WebBluetoothTransport=void 0;const e=require("@neurosity/ipk"),i=require("@neurosity/ipk"),n=require("@neurosity/ipk"),s=require("@neurosity/ipk"),o=require("rxjs"),r=require("rxjs"),c=require("rxjs/operators"),a=require("rxjs/operators"),d=require("rxjs/operators"),h=require("./isWebBluetoothSupported"),u=require("../utils/create6DigitPin"),v=require("../utils/stitch"),l=require("../utils/encoding"),p=require("../types"),g=require("../constants"),f=require("../constants"),E=require("../utils/osHasBluetoothSupport"),N={autoConnect:!0};class C{constructor(t={}){if(this.type=p.TRANSPORT_TYPE.WEB,this.characteristicsByName={},this.connection$=new o.BehaviorSubject(p.BLUETOOTH_CONNECTION.DISCONNECTED),this.pendingActions$=new o.BehaviorSubject([]),this.logs$=new o.ReplaySubject(10),this.onDisconnected$=this._onDisconnected().pipe((0,d.share)()),this.connectionStream$=this.connection$.asObservable().pipe((0,c.filter)(t=>!!t),(0,a.distinctUntilChanged)(),(0,a.shareReplay)(1)),this._isAutoConnectEnabled$=new o.ReplaySubject(1),this.options=Object.assign(Object.assign({},N),t),!(0,h.isWebBluetoothSupported)()){const t="Web Bluetooth is not supported";throw this.addLog(t),new Error(t)}this._isAutoConnectEnabled$.subscribe(t=>{this.addLog(`Auto connect: ${t?"enabled":"disabled"}`)}),this._isAutoConnectEnabled$.next(this.options.autoConnect),this.connection$.asObservable().subscribe(t=>{this.addLog(`connection status is ${t}`)}),this.onDisconnected$.subscribe(()=>{this.connection$.next(p.BLUETOOTH_CONNECTION.DISCONNECTED)})}_getPairedDevices(){return t(this,void 0,void 0,function*(){return yield navigator.bluetooth.getDevices()})}_autoConnect(e,i){return this._isAutoConnectEnabled$.pipe((0,c.switchMap)(t=>t?(0,o.merge)(e,this.onDisconnected$.pipe((0,c.switchMap)(()=>e))):r.NEVER),(0,c.combineLatestWith)(i),(0,c.switchMap)(([t,e])=>(0,E.osHasBluetoothSupport)(t,e)?(0,o.of)(t):r.EMPTY),(0,c.switchMap)(e=>t(this,void 0,void 0,function*(){var t;const{deviceNickname:i}=e;if(this.isConnected())return void this.addLog(`Auto connect: ${i} is already connected. Skipping auto connect.`);const[n,s]=yield this._getPairedDevices().then(t=>[null,t]).catch(t=>[t,null]);if(n)throw new Error(`failed to get devices: ${null!==(t=null==n?void 0:n.message)&&void 0!==t?t:n}`);this.addLog(`Auto connect: found ${s.length} devices ${s.map(({name:t})=>t).join(", ")}`);const o=s.findLast(t=>t.name===i);if(!o)throw new Error("couldn't find selected device in the list of paired devices.");return this.addLog(`Auto connect: ${i} was detected and previously paired`),o})),(0,c.tap)(()=>{this.connection$.next(p.BLUETOOTH_CONNECTION.SCANNING)}),(0,c.switchMap)(t=>m(t)),(0,c.switchMap)(e=>t(this,void 0,void 0,function*(){return this.addLog(`Advertisement received for ${e.device.name}`),yield this.getServerServiceAndCharacteristics(e.device)})))}enableAutoConnect(t){this._isAutoConnectEnabled$.next(t)}addLog(t){this.logs$.next(t)}isConnected(){return this.connection$.getValue()===p.BLUETOOTH_CONNECTION.CONNECTED}connection(){return this.connectionStream$}connect(e){return t(this,void 0,void 0,function*(){try{const i=yield this.requestDevice(e);yield this.getServerServiceAndCharacteristics(i)}catch(t){return Promise.reject(t)}})}requestDevice(i){return t(this,void 0,void 0,function*(){try{this.addLog("Requesting Bluetooth Device...");const o=n.BLUETOOTH_DEVICE_NAME_PREFIXES.map(t=>({namePrefix:t})),r=i?[{name:i}]:o;return yield window.navigator.bluetooth.requestDevice({filters:[...r,{manufacturerData:[{companyIdentifier:s.BLUETOOTH_COMPANY_IDENTIFIER_HEX}]}],optionalServices:[e.BLUETOOTH_PRIMARY_SERVICE_UUID_HEX]})}catch(t){return Promise.reject(t)}})}getServerServiceAndCharacteristics(i){return t(this,void 0,void 0,function*(){try{this.device=i,this.connection$.getValue()===p.BLUETOOTH_CONNECTION.CONNECTING||this.connection$.next(p.BLUETOOTH_CONNECTION.CONNECTING),this.server=yield i.gatt.connect(),this.addLog("Getting service..."),this.service=yield this.server.getPrimaryService(e.BLUETOOTH_PRIMARY_SERVICE_UUID_HEX),this.addLog(`Got service ${this.service.uuid}, getting characteristics...`);const n=yield this.service.getCharacteristics();this.addLog("Got characteristics"),this.characteristicsByName=Object.fromEntries(n.map(t=>[f.CHARACTERISTIC_UUIDS_TO_NAMES[t.uuid],t])),this.connection$.next(p.BLUETOOTH_CONNECTION.CONNECTED)}catch(t){return Promise.reject(t)}})}_onDisconnected(){return this.connection$.asObservable().pipe((0,c.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?O(this.device,"gattserverdisconnected"):r.NEVER))}disconnect(){var e,i;return t(this,void 0,void 0,function*(){(null===(i=null===(e=null==this?void 0:this.device)||void 0===e?void 0:e.gatt)||void 0===i?void 0:i.connected)&&this.device.gatt.disconnect()})}getCharacteristicByName(e){var i;return t(this,void 0,void 0,function*(){return null===(i=this.characteristicsByName)||void 0===i?void 0:i[e]})}subscribeToCharacteristic({characteristicName:e,manageNotifications:n=!0}){const s=(0,o.defer)(()=>this.getCharacteristicByName(e)).pipe((0,c.switchMap)(i=>t(this,void 0,void 0,function*(){var t;if(this.isConnected()&&n)try{yield i.startNotifications(),this.addLog(`Started notifications for ${e} characteristic`)}catch(s){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==s?void 0:s.message)&&void 0!==t?t:s}`)}return i})),(0,c.switchMap)(i=>O(i,"characteristicvaluechanged",()=>t(this,void 0,void 0,function*(){var t;if(this.isConnected()&&n)try{yield i.stopNotifications(),this.addLog(`Stopped notifications for ${e} characteristic`)}catch(s){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==s?void 0:s.message)&&void 0!==t?t:s}`)}}))),(0,c.map)(t=>{const i=t.target.value,n=(0,l.decode)(this.type,i);return this.addLog(`Received chunk with buffer size of ${i.byteLength} and decoded size ${n.length} for ${e} characteristic: \n${n}`),n}),(0,v.stitchChunks)({delimiter:i.BLUETOOTH_CHUNK_DELIMITER}),(0,c.map)(t=>{var i;try{return JSON.parse(t)}catch(n){return this.addLog(`Failed to parse JSON for ${e} characteristic. Falling back to unparsed string. ${null!==(i=null==n?void 0:n.message)&&void 0!==i?i:n}`),t}}));return this.connection$.pipe((0,c.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?s:r.NEVER))}readCharacteristic(e,i=!1){return t(this,void 0,void 0,function*(){try{this.addLog(`Reading characteristic: ${e}`);const n=yield this.getCharacteristicByName(e);if(!n)return this.addLog(`Did not fund ${e} characteristic`),Promise.reject(`Did not find characteristic by the name: ${e}`);const s=yield n.readValue(),o=(0,l.decode)(this.type,s),r=i?JSON.parse(o):o;return this.addLog(`Received read data from ${e} characteristic: \n${r}`),r}catch(t){return Promise.reject(`Error reading characteristic: ${t.message}`)}})}writeCharacteristic(e,i){return t(this,void 0,void 0,function*(){this.addLog(`Writing characteristic: ${e}`);const t=yield this.getCharacteristicByName(e);if(!t)return this.addLog(`Did not fund ${e} characteristic`),Promise.reject(`Did not find characteristic by the name: ${e}`);const n=(0,l.encode)(this.type,i);yield t.writeValueWithResponse(n)})}_addPendingAction(t){const e=this.pendingActions$.getValue();this.pendingActions$.next([...e,t])}_removePendingAction(t){const e=this.pendingActions$.getValue();this.pendingActions$.next(e.filter(e=>e!==t))}_autoToggleActionNotifications(e,i){return t(this,void 0,void 0,function*(){let n,s=!1;const a=this.connection$.asObservable().pipe((0,c.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?(0,o.defer)(()=>this.getCharacteristicByName("actions")).pipe((0,c.switchMap)(t=>(n=t,this.pendingActions$))):r.NEVER),(0,c.tap)(e=>t(this,void 0,void 0,function*(){var t,i;const o=!!e.length;if(o&&!s){s=!0;try{yield n.startNotifications(),this.addLog("Started notifications for [actions] characteristic")}catch(r){this.addLog(`Attemped to start notifications for [actions] characteristic: ${null!==(t=null==r?void 0:r.message)&&void 0!==t?t:r}`)}}if(!o&&s){s=!1;try{yield n.stopNotifications(),this.addLog("Stopped notifications for actions characteristic")}catch(r){this.addLog(`Attemped to stop notifications for [actions] characteristic: ${null!==(i=null==r?void 0:r.message)&&void 0!==i?i:r}`)}}})));e.pipe((0,c.combineLatestWith)(i),(0,c.switchMap)(([t,e])=>(0,E.osHasBluetoothSupport)(t,e)?a:r.EMPTY)).subscribe()})}dispatchAction({characteristicName:e,action:i}){return t(this,void 0,void 0,function*(){const{responseRequired:n=!1,responseTimeout:s=g.DEFAULT_ACTION_RESPONSE_TIMEOUT}=i;return new Promise((r,a)=>t(this,void 0,void 0,function*(){if(!(yield this.getCharacteristicByName(e).catch(()=>{a(`Did not find characteristic by the name: ${e}`)})))return;const t=(0,u.create6DigitPin)(),h=JSON.stringify(Object.assign({actionId:t},i));if(this.addLog(`Dispatched action with id ${t}`),n&&s){this._addPendingAction(t);const i=(0,o.timer)(s).subscribe(()=>{this._removePendingAction(t),a(`Action with id ${t} timed out after ${s}ms`)});this.subscribeToCharacteristic({characteristicName:e,manageNotifications:!1}).pipe((0,c.filter)(e=>(null==e?void 0:e.actionId)===t),(0,d.take)(1)).subscribe(e=>{i.unsubscribe(),this._removePendingAction(t),r(e)}),this.writeCharacteristic(e,h).catch(e=>{this._removePendingAction(t),a(e.message)})}else this.writeCharacteristic(e,h).then(()=>{r(null)}).catch(t=>{a(t.message)})}))})}}function O(e,i,n){return(0,r.fromEventPattern)(t=>{e.addEventListener(i,t)},s=>t(this,void 0,void 0,function*(){n&&(yield n()),e.removeEventListener(i,s)}))}function m(t){return new r.Observable(e=>{const i=new AbortController,{signal:n}=i,s=t.addEventListener("advertisementreceived",t=>{i.abort(),e.next(t),e.complete()},{once:!0});try{t.watchAdvertisements({signal:n})}catch(o){e.error(o)}return()=>{i.abort(),t.removeEventListener("advertisementreceived",s)}})}exports.WebBluetoothTransport=C;
71
71
  },{"./isWebBluetoothSupported":"ljun","../utils/create6DigitPin":"UDAB","../utils/stitch":"V73a","../utils/encoding":"jTvL","../types":"iwtf","../constants":"dGLb","../utils/osHasBluetoothSupport":"rH2Y"}],"FtS5":[function(require,module,exports) {
72
- "use strict";var t=this&&this.__awaiter||function(t,i,e,n){return new(e||(e=Promise))(function(r,s){function a(t){try{c(n.next(t))}catch(i){s(i)}}function o(t){try{c(n.throw(t))}catch(i){s(i)}}function c(t){var i;t.done?r(t.value):(i=t.value,i instanceof e?i:new e(function(t){t(i)})).then(a,o)}c((n=n.apply(t,i||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ReactNativeTransport=void 0;const i=require("@neurosity/ipk"),e=require("@neurosity/ipk"),n=require("@neurosity/ipk"),r=require("rxjs"),s=require("rxjs"),a=require("rxjs/operators"),o=require("rxjs/operators"),c=require("rxjs/operators"),d=require("../utils/create6DigitPin"),h=require("../utils/stitch"),l=require("../utils/encoding"),u=require("../types"),v=require("../constants"),p=require("../constants"),g=require("../constants"),E=require("../constants"),f=require("../utils/osHasBluetoothSupport"),N={autoConnect:!0};class m{constructor(t){if(this.type=u.TRANSPORT_TYPE.REACT_NATIVE,this.characteristicsByName={},this.connection$=new r.BehaviorSubject(u.BLUETOOTH_CONNECTION.DISCONNECTED),this.pendingActions$=new r.BehaviorSubject([]),this.logs$=new r.ReplaySubject(10),this.connectionStream$=this.connection$.asObservable().pipe((0,a.filter)(t=>!!t),(0,o.distinctUntilChanged)(),(0,o.shareReplay)(1)),this._isAutoConnectEnabled$=new r.ReplaySubject(1),!t){const t="React Native transport: missing options.";throw this.addLog(t),new Error(t)}this.options=Object.assign(Object.assign({},N),t);const{BleManager:i,bleManagerEmitter:e,platform:n,autoConnect:s}=this.options;if(!i){const t="React Native option: BleManager not provided.";throw this.addLog(t),new Error(t)}if(!e){const t="React Native option: bleManagerEmitter not provided.";throw this.addLog(t),new Error(t)}if(!n){const t="React Native option: platform not provided.";throw this.addLog(t),new Error(t)}this.BleManager=i,this.bleManagerEmitter=e,this.platform=n,this._isAutoConnectEnabled$.next(s),this._isAutoConnectEnabled$.subscribe(t=>{this.addLog(`Auto connect: ${t?"enabled":"disabled"}`)}),this.bleEvents={stopScan$:this._fromEvent("BleManagerStopScan"),discoverPeripheral$:this._fromEvent("BleManagerDiscoverPeripheral"),connectPeripheral$:this._fromEvent("BleManagerConnectPeripheral"),disconnectPeripheral$:this._fromEvent("BleManagerDisconnectPeripheral"),didUpdateValueForCharacteristic$:this._fromEvent("BleManagerDidUpdateValueForCharacteristic"),didUpdateState$:this._fromEvent("BleManagerDidUpdateState")},this.onDisconnected$=this.bleEvents.disconnectPeripheral$.pipe((0,c.share)()),this.BleManager.start({showAlert:!1}).then(()=>{this.addLog("BleManger started")}).catch(t=>{var i;this.addLog(`BleManger failed to start. ${null!==(i=null==t?void 0:t.message)&&void 0!==i?i:t}`)}),this.connection$.asObservable().subscribe(t=>{this.addLog(`connection status is ${t}`)}),this.onDisconnected$.subscribe(()=>{this.connection$.next(u.BLUETOOTH_CONNECTION.DISCONNECTED)})}addLog(t){this.logs$.next(t)}isConnected(){return this.connection$.getValue()===u.BLUETOOTH_CONNECTION.CONNECTED}_autoConnect(i){const e=this.onDisconnected$.pipe((0,a.switchMap)(()=>i));return this._isAutoConnectEnabled$.pipe((0,a.switchMap)(t=>t?(0,r.merge)(i,e):s.NEVER),(0,a.switchMap)(t=>(0,f.osHasBluetoothSupport)(t)?this.scan().pipe((0,a.switchMap)(i=>{const e=i.find(i=>i.name===(null==t?void 0:t.deviceNickname));return e?(0,r.of)(e):s.NEVER}),(0,c.distinct)(t=>t.id),(0,c.take)(1)):s.NEVER),(0,a.switchMap)(i=>t(this,void 0,void 0,function*(){return yield this.connect(i)})))}enableAutoConnect(t){this._isAutoConnectEnabled$.next(t)}connection(){return this.connectionStream$}_fromEvent(t){return(0,s.fromEventPattern)(i=>{this.bleManagerEmitter.addListener(t,i)},()=>{this.bleManagerEmitter.removeAllListeners(t)}).pipe((0,c.share)())}scan(t){var e,d,h;const v=null!==(e=null==t?void 0:t.seconds)&&void 0!==e?e:10,p=null!==(d=null==t?void 0:t.once)&&void 0!==d&&d,g=null!==(h=null==t?void 0:t.skipConnectionUpdate)&&void 0!==h&&h,E=[i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING],f={},N=new s.Observable(t=>{var i;try{this.BleManager.scan(E,v,!0,f).then(()=>{this.addLog(`BleManger scanning ${p?"once":"indefintely"}`),t.next()})}catch(e){this.addLog(`BleManger scanning ${p?"once":"indefintely"} failed. ${null!==(i=null==e?void 0:e.message)&&void 0!==i?i:e}`),t.error(e)}return()=>{this.BleManager.stopScan()}});return(p?N:(0,r.timer)(0,1e4).pipe((0,a.switchMap)(()=>N))).pipe((0,a.tap)(()=>{g||this.connection$.next(u.BLUETOOTH_CONNECTION.SCANNING)}),(0,a.takeUntil)(this.onDisconnected$),(0,a.switchMap)(()=>this.bleEvents.discoverPeripheral$),(0,a.filter)(t=>{var i,e,r;const s=null!==(r=null!==(e=null===(i=null==t?void 0:t.advertising)||void 0===i?void 0:i.localName)&&void 0!==e?e:t.name)&&void 0!==r?r:"";return!!s&&-1!==n.BLUETOOTH_DEVICE_NAME_PREFIXES.findIndex(t=>s.startsWith(t))}),(0,c.scan)((t,i)=>{var e,n,r,s,a,o,c,d;const h=null!==(r=null!==(n=null===(e=null==i?void 0:i.advertising)||void 0===e?void 0:e.localName)&&void 0!==n?n:i.name)&&void 0!==r?r:"",u=null===(d=null===(c=(0,l.decode)(this.type,null!==(o=null===(a=null===(s=null==i?void 0:i.advertising)||void 0===s?void 0:s.manufacturerData)||void 0===a?void 0:a.bytes)&&void 0!==o?o:[]))||void 0===c?void 0:c.slice)||void 0===d?void 0:d.call(c,2);return Object.assign(Object.assign({},t),{[i.id]:Object.assign(Object.assign({},i),{name:h,manufactureDataString:u})})},{}),(0,o.distinctUntilChanged)((t,i)=>JSON.stringify(t)===JSON.stringify(i)),(0,a.map)(t=>Object.values(t)),(0,c.share)())}connect(e){return t(this,void 0,void 0,function*(){return new Promise((n,r)=>t(this,void 0,void 0,function*(){try{if(!e)return void this.addLog("Peripheral not found");this.connection$.next(u.BLUETOOTH_CONNECTION.CONNECTING),yield this.BleManager.connect(e.id),this.addLog("Getting service...");const s=yield this.BleManager.retrieveServices(e.id,[i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING]);if(!s)return this.addLog("Could not retreive services"),void r(new Error("Could not retreive services"));this.addLog(`Got service ${i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING}, getting characteristics...`),this.device=e,this.characteristicsByName=Object.fromEntries(s.characteristics.map(t=>[p.CHARACTERISTIC_UUIDS_TO_NAMES[t.characteristic.toLowerCase()],{characteristicUUID:t.characteristic,serviceUUID:t.service,peripheralId:e.id}])),this.addLog("Got characteristics."),"android"===this.platform&&(yield this.BleManager.requestMTU(e.id,g.ANDROID_MAX_MTU).then(t=>{this.addLog(`Successfully updated Android MTU to ${t} bytes. Requested MTU: ${g.ANDROID_MAX_MTU} bytes.`)}).catch(t=>{this.addLog(`Failed to set Android MTU of ${g.ANDROID_MAX_MTU} bytes. Error: ${t}`)})),this.addLog(`Successfully connected to peripheral ${e.id}`),this.connection$.next(u.BLUETOOTH_CONNECTION.CONNECTED),n()}catch(t){r(t)}}))})}disconnect(){var i;return t(this,void 0,void 0,function*(){try{this.isConnected()&&(null===(i=null==this?void 0:this.device)||void 0===i?void 0:i.id)&&(yield this.BleManager.disconnect(this.device.id))}catch(t){return Promise.reject(t)}})}getCharacteristicByName(t){var i;if(!(t in this.characteristicsByName))throw new Error(`Characteristic by name ${t} is not found`);return null===(i=this.characteristicsByName)||void 0===i?void 0:i[t]}subscribeToCharacteristic({characteristicName:i,manageNotifications:n=!0}){const c=({peripheralId:s,serviceUUID:c,characteristicUUID:d})=>(0,r.defer)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.startNotification(s,c,d),this.addLog(`Started notifications for ${i} characteristic`)}catch(e){this.addLog(`Attemped to stop notifications for ${i} characteristic: ${null!==(t=null==e?void 0:e.message)&&void 0!==t?t:e}`)}})).pipe((0,a.switchMap)(()=>this.bleEvents.didUpdateValueForCharacteristic$),(0,o.finalize)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.stopNotification(s,c,d),this.addLog(`Stopped notifications for ${i} characteristic`)}catch(e){this.addLog(`Attemped to stop notifications for ${i} characteristic: ${null!==(t=null==e?void 0:e.message)&&void 0!==t?t:e}`)}})),(0,a.filter)(({characteristic:t})=>t===d),(0,a.map)(({value:t})=>(0,l.decode)(this.type,t)),(0,h.stitchChunks)({delimiter:e.BLUETOOTH_CHUNK_DELIMITER}),(0,a.map)(t=>{var e;try{return JSON.parse(t)}catch(n){return this.addLog(`Failed to parse JSON for ${i} characteristic. Falling back to unparsed string. ${null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n}`),t}}));return this.connection$.pipe((0,a.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?c(this.getCharacteristicByName(i)):s.NEVER))}readCharacteristic(i,e=!1){var n;return t(this,void 0,void 0,function*(){this.addLog(`Reading characteristic: ${i}`);const{peripheralId:t,serviceUUID:r,characteristicUUID:s}=this.getCharacteristicByName(i);if(!s)return Promise.reject(new Error(`Did not find characteristic matching ${i}`));try{const o=yield this.BleManager.read(t,r,s),c=(0,l.decode)(this.type,o),d=e?JSON.parse(c):c;return this.addLog(`Received read data from ${i} characteristic: \n${d}`),d}catch(a){return Promise.reject(new Error(`readCharacteristic ${i} error. ${null!==(n=null==a?void 0:a.message)&&void 0!==n?n:a}`))}})}writeCharacteristic(i,e){return t(this,void 0,void 0,function*(){this.addLog(`Writing characteristic: ${i}`);const{peripheralId:t,serviceUUID:n,characteristicUUID:r}=this.getCharacteristicByName(i);if(!r)return Promise.reject(new Error(`Did not find characteristic matching ${i}`));const s=(0,l.encode)(this.type,e);yield this.BleManager.write(t,n,r,s,E.REACT_NATIVE_MAX_BYTE_SIZE)})}_addPendingAction(t){const i=this.pendingActions$.getValue();this.pendingActions$.next([...i,t])}_removePendingAction(t){const i=this.pendingActions$.getValue();this.pendingActions$.next(i.filter(i=>i!==t))}_autoToggleActionNotifications(i){return t(this,void 0,void 0,function*(){let e=!1;const n=this.connection$.asObservable().pipe((0,a.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?this.pendingActions$:s.NEVER),(0,a.tap)(i=>t(this,void 0,void 0,function*(){var t,n;const{peripheralId:r,serviceUUID:s,characteristicUUID:a}=this.getCharacteristicByName("actions"),o=!!i.length;if(o&&!e){e=!0;try{yield this.BleManager.startNotification(r,s,a),this.addLog("Started notifications for [actions] characteristic")}catch(c){this.addLog(`Attemped to start notifications for [actions] characteristic: ${null!==(t=null==c?void 0:c.message)&&void 0!==t?t:c}`)}}if(!o&&e){e=!1;try{yield this.BleManager.stopNotification(r,s,a),this.addLog("Stopped notifications for actions characteristic")}catch(c){this.addLog(`Attemped to stop notifications for [actions] characteristic: ${null!==(n=null==c?void 0:c.message)&&void 0!==n?n:c}`)}}})));i.pipe((0,a.switchMap)(t=>(0,f.osHasBluetoothSupport)(t)?n:s.EMPTY)).subscribe()})}dispatchAction({characteristicName:i,action:e}){return t(this,void 0,void 0,function*(){const{responseRequired:n=!1,responseTimeout:s=v.DEFAULT_ACTION_RESPONSE_TIMEOUT}=e;return new Promise((o,h)=>t(this,void 0,void 0,function*(){const t=(0,d.create6DigitPin)(),l=JSON.stringify(Object.assign({actionId:t},e));if(this.addLog(`Dispatched action with id ${t}`),n&&s){this._addPendingAction(t);const e=(0,r.timer)(s).subscribe(()=>{this._removePendingAction(t),h(new Error(`Action with id ${t} timed out after ${s}ms`))});this.subscribeToCharacteristic({characteristicName:i,manageNotifications:!1}).pipe((0,a.filter)(i=>(null==i?void 0:i.actionId)===t),(0,c.take)(1)).subscribe(i=>{e.unsubscribe(),this._removePendingAction(t),o(i)}),this.writeCharacteristic(i,l).catch(i=>{this._removePendingAction(t),h(i)})}else this.writeCharacteristic(i,l).then(()=>{o(null)}).catch(t=>{h(t)})}))})}}exports.ReactNativeTransport=m;
72
+ "use strict";var t=this&&this.__awaiter||function(t,i,e,n){return new(e||(e=Promise))(function(r,s){function a(t){try{c(n.next(t))}catch(i){s(i)}}function o(t){try{c(n.throw(t))}catch(i){s(i)}}function c(t){var i;t.done?r(t.value):(i=t.value,i instanceof e?i:new e(function(t){t(i)})).then(a,o)}c((n=n.apply(t,i||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ReactNativeTransport=void 0;const i=require("@neurosity/ipk"),e=require("@neurosity/ipk"),n=require("@neurosity/ipk"),r=require("rxjs"),s=require("rxjs"),a=require("rxjs/operators"),o=require("rxjs/operators"),c=require("rxjs/operators"),d=require("../utils/create6DigitPin"),h=require("../utils/stitch"),l=require("../utils/encoding"),u=require("../types"),v=require("../constants"),p=require("../constants"),g=require("../constants"),E=require("../constants"),f=require("../utils/osHasBluetoothSupport"),N={autoConnect:!0};class m{constructor(t){if(this.type=u.TRANSPORT_TYPE.REACT_NATIVE,this.characteristicsByName={},this.connection$=new r.BehaviorSubject(u.BLUETOOTH_CONNECTION.DISCONNECTED),this.pendingActions$=new r.BehaviorSubject([]),this.logs$=new r.ReplaySubject(10),this.connectionStream$=this.connection$.asObservable().pipe((0,a.filter)(t=>!!t),(0,o.distinctUntilChanged)(),(0,o.shareReplay)(1)),this._isAutoConnectEnabled$=new r.ReplaySubject(1),!t){const t="React Native transport: missing options.";throw this.addLog(t),new Error(t)}this.options=Object.assign(Object.assign({},N),t);const{BleManager:i,bleManagerEmitter:e,platform:n,autoConnect:s}=this.options;if(!i){const t="React Native option: BleManager not provided.";throw this.addLog(t),new Error(t)}if(!e){const t="React Native option: bleManagerEmitter not provided.";throw this.addLog(t),new Error(t)}if(!n){const t="React Native option: platform not provided.";throw this.addLog(t),new Error(t)}this.BleManager=i,this.bleManagerEmitter=e,this.platform=n,this._isAutoConnectEnabled$.next(s),this._isAutoConnectEnabled$.subscribe(t=>{this.addLog(`Auto connect: ${t?"enabled":"disabled"}`)}),this.bleEvents={stopScan$:this._fromEvent("BleManagerStopScan"),discoverPeripheral$:this._fromEvent("BleManagerDiscoverPeripheral"),connectPeripheral$:this._fromEvent("BleManagerConnectPeripheral"),disconnectPeripheral$:this._fromEvent("BleManagerDisconnectPeripheral"),didUpdateValueForCharacteristic$:this._fromEvent("BleManagerDidUpdateValueForCharacteristic"),didUpdateState$:this._fromEvent("BleManagerDidUpdateState")},this.onDisconnected$=this.bleEvents.disconnectPeripheral$.pipe((0,c.share)()),this.BleManager.start({showAlert:!1}).then(()=>{this.addLog("BleManger started")}).catch(t=>{var i;this.addLog(`BleManger failed to start. ${null!==(i=null==t?void 0:t.message)&&void 0!==i?i:t}`)}),this.connection$.asObservable().subscribe(t=>{this.addLog(`connection status is ${t}`)}),this.onDisconnected$.subscribe(()=>{this.connection$.next(u.BLUETOOTH_CONNECTION.DISCONNECTED)})}addLog(t){this.logs$.next(t)}isConnected(){return this.connection$.getValue()===u.BLUETOOTH_CONNECTION.CONNECTED}_autoConnect(i,e){const n=this.onDisconnected$.pipe((0,a.switchMap)(()=>i));return this._isAutoConnectEnabled$.pipe((0,a.switchMap)(t=>t?(0,r.merge)(i,n):s.NEVER),(0,c.combineLatestWith)(e),(0,a.switchMap)(([t,i])=>(0,f.osHasBluetoothSupport)(t,i)?this.scan().pipe((0,a.switchMap)(i=>{const e=i.find(i=>i.name===(null==t?void 0:t.deviceNickname));return e?(0,r.of)(e):s.NEVER}),(0,c.distinct)(t=>t.id),(0,c.take)(1)):s.NEVER),(0,a.switchMap)(i=>t(this,void 0,void 0,function*(){return yield this.connect(i)})))}enableAutoConnect(t){this._isAutoConnectEnabled$.next(t)}connection(){return this.connectionStream$}_fromEvent(t){return(0,s.fromEventPattern)(i=>{this.bleManagerEmitter.addListener(t,i)},()=>{this.bleManagerEmitter.removeAllListeners(t)}).pipe((0,c.share)())}scan(t){var e,d,h;const v=null!==(e=null==t?void 0:t.seconds)&&void 0!==e?e:10,p=null!==(d=null==t?void 0:t.once)&&void 0!==d&&d,g=null!==(h=null==t?void 0:t.skipConnectionUpdate)&&void 0!==h&&h,E=[i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING],f={},N=new s.Observable(t=>{var i;try{this.BleManager.scan(E,v,!0,f).then(()=>{this.addLog(`BleManger scanning ${p?"once":"indefintely"}`),t.next()})}catch(e){this.addLog(`BleManger scanning ${p?"once":"indefintely"} failed. ${null!==(i=null==e?void 0:e.message)&&void 0!==i?i:e}`),t.error(e)}return()=>{this.BleManager.stopScan()}});return(p?N:(0,r.timer)(0,1e4).pipe((0,a.switchMap)(()=>N))).pipe((0,a.tap)(()=>{g||this.connection$.next(u.BLUETOOTH_CONNECTION.SCANNING)}),(0,a.takeUntil)(this.onDisconnected$),(0,a.switchMap)(()=>this.bleEvents.discoverPeripheral$),(0,a.filter)(t=>{var i,e,r;const s=null!==(r=null!==(e=null===(i=null==t?void 0:t.advertising)||void 0===i?void 0:i.localName)&&void 0!==e?e:t.name)&&void 0!==r?r:"";return!!s&&-1!==n.BLUETOOTH_DEVICE_NAME_PREFIXES.findIndex(t=>s.startsWith(t))}),(0,c.scan)((t,i)=>{var e,n,r,s,a,o,c,d;const h=null!==(r=null!==(n=null===(e=null==i?void 0:i.advertising)||void 0===e?void 0:e.localName)&&void 0!==n?n:i.name)&&void 0!==r?r:"",u=null===(d=null===(c=(0,l.decode)(this.type,null!==(o=null===(a=null===(s=null==i?void 0:i.advertising)||void 0===s?void 0:s.manufacturerData)||void 0===a?void 0:a.bytes)&&void 0!==o?o:[]))||void 0===c?void 0:c.slice)||void 0===d?void 0:d.call(c,2);return Object.assign(Object.assign({},t),{[i.id]:Object.assign(Object.assign({},i),{name:h,manufactureDataString:u})})},{}),(0,o.distinctUntilChanged)((t,i)=>JSON.stringify(t)===JSON.stringify(i)),(0,a.map)(t=>Object.values(t)),(0,c.share)())}connect(e){return t(this,void 0,void 0,function*(){return new Promise((n,r)=>t(this,void 0,void 0,function*(){try{if(!e)return void this.addLog("Peripheral not found");this.connection$.next(u.BLUETOOTH_CONNECTION.CONNECTING),yield this.BleManager.connect(e.id),this.addLog("Getting service...");const s=yield this.BleManager.retrieveServices(e.id,[i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING]);if(!s)return this.addLog("Could not retreive services"),void r(new Error("Could not retreive services"));this.addLog(`Got service ${i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING}, getting characteristics...`),this.device=e,this.characteristicsByName=Object.fromEntries(s.characteristics.map(t=>[p.CHARACTERISTIC_UUIDS_TO_NAMES[t.characteristic.toLowerCase()],{characteristicUUID:t.characteristic,serviceUUID:t.service,peripheralId:e.id}])),this.addLog("Got characteristics."),"android"===this.platform&&(yield this.BleManager.requestMTU(e.id,g.ANDROID_MAX_MTU).then(t=>{this.addLog(`Successfully updated Android MTU to ${t} bytes. Requested MTU: ${g.ANDROID_MAX_MTU} bytes.`)}).catch(t=>{this.addLog(`Failed to set Android MTU of ${g.ANDROID_MAX_MTU} bytes. Error: ${t}`)})),this.addLog(`Successfully connected to peripheral ${e.id}`),this.connection$.next(u.BLUETOOTH_CONNECTION.CONNECTED),n()}catch(t){r(t)}}))})}disconnect(){var i;return t(this,void 0,void 0,function*(){try{this.isConnected()&&(null===(i=null==this?void 0:this.device)||void 0===i?void 0:i.id)&&(yield this.BleManager.disconnect(this.device.id))}catch(t){return Promise.reject(t)}})}getCharacteristicByName(t){var i;if(!(t in this.characteristicsByName))throw new Error(`Characteristic by name ${t} is not found`);return null===(i=this.characteristicsByName)||void 0===i?void 0:i[t]}subscribeToCharacteristic({characteristicName:i,manageNotifications:n=!0}){const c=({peripheralId:s,serviceUUID:c,characteristicUUID:d})=>(0,r.defer)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.startNotification(s,c,d),this.addLog(`Started notifications for ${i} characteristic`)}catch(e){this.addLog(`Attemped to stop notifications for ${i} characteristic: ${null!==(t=null==e?void 0:e.message)&&void 0!==t?t:e}`)}})).pipe((0,a.switchMap)(()=>this.bleEvents.didUpdateValueForCharacteristic$),(0,o.finalize)(()=>t(this,void 0,void 0,function*(){var t;if(n)try{yield this.BleManager.stopNotification(s,c,d),this.addLog(`Stopped notifications for ${i} characteristic`)}catch(e){this.addLog(`Attemped to stop notifications for ${i} characteristic: ${null!==(t=null==e?void 0:e.message)&&void 0!==t?t:e}`)}})),(0,a.filter)(({characteristic:t})=>t===d),(0,a.map)(({value:t})=>(0,l.decode)(this.type,t)),(0,h.stitchChunks)({delimiter:e.BLUETOOTH_CHUNK_DELIMITER}),(0,a.map)(t=>{var e;try{return JSON.parse(t)}catch(n){return this.addLog(`Failed to parse JSON for ${i} characteristic. Falling back to unparsed string. ${null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n}`),t}}));return this.connection$.pipe((0,a.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?c(this.getCharacteristicByName(i)):s.NEVER))}readCharacteristic(i,e=!1){var n;return t(this,void 0,void 0,function*(){this.addLog(`Reading characteristic: ${i}`);const{peripheralId:t,serviceUUID:r,characteristicUUID:s}=this.getCharacteristicByName(i);if(!s)return Promise.reject(new Error(`Did not find characteristic matching ${i}`));try{const o=yield this.BleManager.read(t,r,s),c=(0,l.decode)(this.type,o),d=e?JSON.parse(c):c;return this.addLog(`Received read data from ${i} characteristic: \n${d}`),d}catch(a){return Promise.reject(new Error(`readCharacteristic ${i} error. ${null!==(n=null==a?void 0:a.message)&&void 0!==n?n:a}`))}})}writeCharacteristic(i,e){return t(this,void 0,void 0,function*(){this.addLog(`Writing characteristic: ${i}`);const{peripheralId:t,serviceUUID:n,characteristicUUID:r}=this.getCharacteristicByName(i);if(!r)return Promise.reject(new Error(`Did not find characteristic matching ${i}`));const s=(0,l.encode)(this.type,e);yield this.BleManager.write(t,n,r,s,E.REACT_NATIVE_MAX_BYTE_SIZE)})}_addPendingAction(t){const i=this.pendingActions$.getValue();this.pendingActions$.next([...i,t])}_removePendingAction(t){const i=this.pendingActions$.getValue();this.pendingActions$.next(i.filter(i=>i!==t))}_autoToggleActionNotifications(i,e){return t(this,void 0,void 0,function*(){let n=!1;const r=this.connection$.asObservable().pipe((0,a.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?this.pendingActions$:s.NEVER),(0,a.tap)(i=>t(this,void 0,void 0,function*(){var t,e;const{peripheralId:r,serviceUUID:s,characteristicUUID:a}=this.getCharacteristicByName("actions"),o=!!i.length;if(o&&!n){n=!0;try{yield this.BleManager.startNotification(r,s,a),this.addLog("Started notifications for [actions] characteristic")}catch(c){this.addLog(`Attemped to start notifications for [actions] characteristic: ${null!==(t=null==c?void 0:c.message)&&void 0!==t?t:c}`)}}if(!o&&n){n=!1;try{yield this.BleManager.stopNotification(r,s,a),this.addLog("Stopped notifications for actions characteristic")}catch(c){this.addLog(`Attemped to stop notifications for [actions] characteristic: ${null!==(e=null==c?void 0:c.message)&&void 0!==e?e:c}`)}}})));i.pipe((0,c.combineLatestWith)(e),(0,a.switchMap)(([t,i])=>(0,f.osHasBluetoothSupport)(t,i)?r:s.EMPTY)).subscribe()})}dispatchAction({characteristicName:i,action:e}){return t(this,void 0,void 0,function*(){const{responseRequired:n=!1,responseTimeout:s=v.DEFAULT_ACTION_RESPONSE_TIMEOUT}=e;return new Promise((o,h)=>t(this,void 0,void 0,function*(){const t=(0,d.create6DigitPin)(),l=JSON.stringify(Object.assign({actionId:t},e));if(this.addLog(`Dispatched action with id ${t}`),n&&s){this._addPendingAction(t);const e=(0,r.timer)(s).subscribe(()=>{this._removePendingAction(t),h(new Error(`Action with id ${t} timed out after ${s}ms`))});this.subscribeToCharacteristic({characteristicName:i,manageNotifications:!1}).pipe((0,a.filter)(i=>(null==i?void 0:i.actionId)===t),(0,c.take)(1)).subscribe(i=>{e.unsubscribe(),this._removePendingAction(t),o(i)}),this.writeCharacteristic(i,l).catch(i=>{this._removePendingAction(t),h(i)})}else this.writeCharacteristic(i,l).then(()=>{o(null)}).catch(t=>{h(t)})}))})}}exports.ReactNativeTransport=m;
73
73
  },{"../utils/create6DigitPin":"UDAB","../utils/stitch":"V73a","../utils/encoding":"jTvL","../types":"iwtf","../constants":"dGLb","../utils/osHasBluetoothSupport":"rH2Y"}],"Oj1i":[function(require,module,exports) {
74
74
  "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.epoch=exports.bufferToEpoch=exports.addInfo=void 0;const e=require("rxjs"),t=require("rxjs/operators"),a="data",o=256,n=e=>e instanceof Object&&e===Object(e),s=e=>"function"==typeof e,i=e=>t=>{var a;return Object.assign(Object.assign({},e),{info:Object.assign(Object.assign({},null!==(a=null==e?void 0:e.info)&&void 0!==a?a:{}),t||{})})},r=a=>(0,e.pipe)((0,t.map)(e=>{if(!n(e)||!n(a)&&!s(a))return e;const t=s(a)?a(e):a;return i(e)(t)}));exports.addInfo=r;const p=(e,t="data")=>e[0][t].map((a,o)=>e.map(e=>e[t][o])),c=({samplingRate:a=256,dataProp:o="data"}={})=>(0,e.pipe)((0,t.map)(e=>({[o]:p(e,o),info:Object.assign(Object.assign({},e[0]&&e[0].info?e[0].info:{}),{startTime:e[0].timestamp,samplingRate:e[0].info&&e[0].info.samplingRate?e[0].info.samplingRate:a})})));exports.bufferToEpoch=c;const f=({duration:a,interval:o,samplingRate:n,dataProp:s="data"})=>(0,e.pipe)((0,t.bufferCount)(o),(0,t.scan)((e,t)=>e.concat(t).slice(e.length<a?0:-a)),(0,t.filter)(e=>e.length===a),(0,exports.bufferToEpoch)({samplingRate:n,dataProp:s}));exports.epoch=f;
75
75
  },{}],"WTrV":[function(require,module,exports) {
76
76
  "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.csvBufferToSamples=exports.csvBufferToEpoch=void 0;const e=require("rxjs"),r=require("rxjs/operators"),a=require("../../../utils/pipes"),s=16,t=256;function o(r){var o;return(null==r?void 0:r.samplingRate)||console.warn(`Didn't receive a sampling rate, defaulting to ${t}`),(0,e.pipe)(n(),(0,a.epoch)({duration:s,interval:s,samplingRate:null!==(o=null==r?void 0:r.samplingRate)&&void 0!==o?o:t}),(0,a.addInfo)({channelNames:r.channelNames,samplingRate:r.samplingRate}))}function n(){return(0,e.pipe)((0,r.mergeMap)(r=>(0,e.from)(r)),(0,r.map)(([e,r,...a])=>({timestamp:e,data:a})))}exports.csvBufferToEpoch=o,exports.csvBufferToSamples=n;
77
77
  },{"../../../utils/pipes":"Oj1i"}],"fihV":[function(require,module,exports) {
78
- "use strict";var t=this&&this.__awaiter||function(t,e,i,s){return new(i||(i=Promise))(function(r,n){function o(t){try{c(s.next(t))}catch(e){n(e)}}function a(t){try{c(s.throw(t))}catch(e){n(e)}}function c(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}c((s=s.apply(t,e||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.BluetoothClient=void 0;const e=require("rxjs"),i=require("rxjs"),s=require("rxjs/operators"),r=require("rxjs/operators"),n=require("./web/WebBluetoothTransport"),o=require("./react-native/ReactNativeTransport"),a=require("./utils/csvBufferToEpoch"),c=require("./types"),h=require("./utils/osHasBluetoothSupport");class u{constructor(t){this.selectedDevice$=new i.ReplaySubject(1),this.isAuthenticated$=new i.ReplaySubject(1);const{transport:e,selectedDevice$:s,createBluetoothToken:r}=null!=t?t:{};if(!e)throw new Error("No bluetooth transport provided.");this.transport=e,s&&s.subscribe(this.selectedDevice$),this.transport._autoConnect(this.selectedDevice$).subscribe({error:t=>{var e;this.transport.addLog(`Auto connect: error -> ${null!==(e=null==t?void 0:t.message)&&void 0!==e?e:t}`)}}),"function"==typeof r?(this.transport.addLog("Auto authentication enabled"),this._autoAuthenticate(r).subscribe()):this.transport.addLog("Auto authentication not enabled"),this.transport._autoToggleActionNotifications(this.selectedDevice$),this._focus$=this._subscribeWhileAuthenticated("focus"),this._calm$=this._subscribeWhileAuthenticated("calm"),this._accelerometer$=this._subscribeWhileAuthenticated("accelerometer"),this._brainwavesRaw$=this._subscribeWhileAuthenticated("raw"),this._brainwavesRawUnfiltered$=this._subscribeWhileAuthenticated("rawUnfiltered"),this._brainwavesPSD$=this._subscribeWhileAuthenticated("psd"),this._brainwavesPowerByBand$=this._subscribeWhileAuthenticated("powerByBand"),this._signalQuality$=this._subscribeWhileAuthenticated("signalQuality"),this._status$=this._subscribeWhileAuthenticated("status"),this._settings$=this._subscribeWhileAuthenticated("settings"),this._wifiNearbyNetworks$=this._subscribeWhileAuthenticated("wifiNearbyNetworks"),this._wifiConnections$=this._subscribeWhileAuthenticated("wifiConnections")}_autoAuthenticate(r){const n=(0,e.timer)(0,36e5).pipe((0,s.tap)(()=>{this.transport.addLog("Auto authentication in progress...")}));return this.selectedDevice$.pipe((0,s.switchMap)(e=>(0,h.osHasBluetoothSupport)(e)?this.connection().pipe((0,s.switchMap)(t=>t===c.BLUETOOTH_CONNECTION.CONNECTED?n:i.EMPTY),(0,s.switchMap)(()=>t(this,void 0,void 0,function*(){return yield this.isAuthenticated()})),(0,s.tap)(([e])=>t(this,void 0,void 0,function*(){if(e)this.transport.addLog("Already authenticated");else{const t=yield r();yield this.authenticate(t)}}))):i.EMPTY))}enableAutoConnect(t){this.transport.enableAutoConnect(t)}_hasBluetoothSupport(){return t(this,void 0,void 0,function*(){const t=yield(0,e.firstValueFrom)(this.selectedDevice$);return(0,h.osHasBluetoothSupport)(t)})}authenticate(e){return t(this,void 0,void 0,function*(){if(!(yield this._hasBluetoothSupport())){const t="authenticate method: The OS version does not support Bluetooth.";return this.transport.addLog(t),Promise.reject(t)}yield this.transport.writeCharacteristic("auth",e);const t=yield this.isAuthenticated(),[i]=t;return this.transport.addLog(`Authentication ${i?"succeeded":"failed"}`),this.isAuthenticated$.next(i),t})}isAuthenticated(){return t(this,void 0,void 0,function*(){const[t,e]=yield this.transport.readCharacteristic("auth",!0);return this.isAuthenticated$.next(t),[t,e]})}scan(t){if(this.transport instanceof o.ReactNativeTransport)return this.transport.scan(t);if(this.transport instanceof n.WebBluetoothTransport)throw new Error("scan method is compatibly with the React Native transport only");throw new Error("unknown transport")}connect(t){return this.transport instanceof o.ReactNativeTransport?this.transport.connect(t):this.transport instanceof n.WebBluetoothTransport?t?this.transport.connect(t):this.transport.connect():void 0}disconnect(){return this.transport.disconnect()}connection(){return this.transport.connection()}logs(){return this.transport.logs$.asObservable()}getDeviceId(){return t(this,void 0,void 0,function*(){return this.transport.readCharacteristic("deviceId")})}_withAuthentication(i){return t(this,void 0,void 0,function*(){if(!(yield this._hasBluetoothSupport())){const t="The OS version does not support Bluetooth.";return this.transport.addLog(t),Promise.reject(t)}if(!(yield(0,e.firstValueFrom)(this.isAuthenticated$))){const t="Authentication required.";return this.transport.addLog(t),Promise.reject(t)}return yield i()})}_subscribeWhileAuthenticated(t){return this.selectedDevice$.pipe((0,s.switchMap)(e=>(0,h.osHasBluetoothSupport)(e)?this.isAuthenticated$.pipe((0,r.distinctUntilChanged)(),(0,s.switchMap)(e=>e?this.transport.subscribeToCharacteristic({characteristicName:t}):i.EMPTY)):i.EMPTY),(0,s.share)())}focus(){return this._focus$}calm(){return this._calm$}accelerometer(){return this._accelerometer$}brainwaves(t){switch(t){default:case"raw":return(0,e.defer)(()=>this.getInfo()).pipe((0,s.switchMap)(t=>this._brainwavesRaw$.pipe((0,a.csvBufferToEpoch)(t))));case"rawUnfiltered":return(0,e.defer)(()=>this.getInfo()).pipe((0,s.switchMap)(t=>this._brainwavesRawUnfiltered$.pipe((0,a.csvBufferToEpoch)(t))));case"psd":return this._brainwavesPSD$;case"powerByBand":return this._brainwavesPowerByBand$}}signalQuality(){return this._signalQuality$}addMarker(e){return t(this,void 0,void 0,function*(){yield this.dispatchAction({action:"marker",command:"add",message:{timestamp:Date.now(),label:e}})})}getInfo(){return t(this,void 0,void 0,function*(){return yield this._withAuthentication(()=>(0,e.firstValueFrom)(this.transport.subscribeToCharacteristic({characteristicName:"deviceInfo"})))})}status(){return this._status$}dispatchAction(e){return t(this,void 0,void 0,function*(){return yield this._withAuthentication(()=>this.transport.dispatchAction({characteristicName:"actions",action:e}))})}settings(){return this._settings$}haptics(t){return this.dispatchAction({action:"haptics",command:"queue",responseRequired:!0,responseTimeout:4e3,message:{effects:t}})}get wifi(){return{nearbyNetworks:()=>this._wifiNearbyNetworks$,connections:()=>this._wifiConnections$,connect:(t,e)=>t?this.dispatchAction({action:"wifi",command:"connect",responseRequired:!0,responseTimeout:12e4,message:{ssid:t,password:null!=e?e:null}}):Promise.reject("Missing ssid"),forgetConnection:t=>t?this.dispatchAction({action:"wifi",command:"forget-connection",responseRequired:!0,responseTimeout:15e3,message:{ssid:t}}):Promise.reject("Missing ssid"),reset:()=>this.dispatchAction({action:"wifi",command:"reset",responseRequired:!0,responseTimeout:3e4,message:{respondOnSuccess:!0}}),speedTest:()=>this.dispatchAction({action:"wifi",command:"speed-test",responseRequired:!0,responseTimeout:6e4})}}}exports.BluetoothClient=u;
78
+ "use strict";var t=this&&this.__awaiter||function(t,e,i,s){return new(i||(i=Promise))(function(r,n){function o(t){try{c(s.next(t))}catch(e){n(e)}}function a(t){try{c(s.throw(t))}catch(e){n(e)}}function c(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}c((s=s.apply(t,e||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.BluetoothClient=void 0;const e=require("rxjs"),i=require("rxjs"),s=require("rxjs/operators"),r=require("rxjs/operators"),n=require("./web/WebBluetoothTransport"),o=require("./react-native/ReactNativeTransport"),a=require("./utils/csvBufferToEpoch"),c=require("./types"),h=require("./utils/osHasBluetoothSupport");class u{constructor(t){this.selectedDevice$=new i.ReplaySubject(1),this.osVersion$=new i.ReplaySubject(1),this.isAuthenticated$=new i.ReplaySubject(1);const{transport:e,selectedDevice$:s,createBluetoothToken:r}=null!=t?t:{};if(!e)throw new Error("No bluetooth transport provided.");this.transport=e,s&&s.subscribe(this.selectedDevice$),this.transport._autoConnect(this.selectedDevice$,this.osVersion$).subscribe({error:t=>{var e;this.transport.addLog(`Auto connect: error -> ${null!==(e=null==t?void 0:t.message)&&void 0!==e?e:t}`)}}),"function"==typeof r?(this.transport.addLog("Auto authentication enabled"),this._autoAuthenticate(r).subscribe()):this.transport.addLog("Auto authentication not enabled"),this.transport._autoToggleActionNotifications(this.selectedDevice$,this.osVersion$),this._focus$=this._subscribeWhileAuthenticated("focus"),this._calm$=this._subscribeWhileAuthenticated("calm"),this._accelerometer$=this._subscribeWhileAuthenticated("accelerometer"),this._brainwavesRaw$=this._subscribeWhileAuthenticated("raw"),this._brainwavesRawUnfiltered$=this._subscribeWhileAuthenticated("rawUnfiltered"),this._brainwavesPSD$=this._subscribeWhileAuthenticated("psd"),this._brainwavesPowerByBand$=this._subscribeWhileAuthenticated("powerByBand"),this._signalQuality$=this._subscribeWhileAuthenticated("signalQuality"),this._status$=this._subscribeWhileAuthenticated("status"),this._settings$=this._subscribeWhileAuthenticated("settings"),this._wifiNearbyNetworks$=this._subscribeWhileAuthenticated("wifiNearbyNetworks"),this._wifiConnections$=this._subscribeWhileAuthenticated("wifiConnections")}_autoAuthenticate(r){const n=(0,e.timer)(0,36e5).pipe((0,s.tap)(()=>{this.transport.addLog("Auto authentication in progress...")}));return this.selectedDevice$.pipe((0,s.combineLatestWith)(this.osVersion$),(0,s.switchMap)(([e,o])=>(0,h.osHasBluetoothSupport)(e,o)?this.connection().pipe((0,s.switchMap)(t=>t===c.BLUETOOTH_CONNECTION.CONNECTED?n:i.EMPTY),(0,s.switchMap)(()=>t(this,void 0,void 0,function*(){return yield this.isAuthenticated()})),(0,s.tap)(([e])=>t(this,void 0,void 0,function*(){if(e)this.transport.addLog("Already authenticated");else{const t=yield r();yield this.authenticate(t)}}))):i.EMPTY))}enableAutoConnect(t){this.transport.enableAutoConnect(t)}_hasBluetoothSupport(){return t(this,void 0,void 0,function*(){const t=yield(0,e.firstValueFrom)(this.selectedDevice$),i=yield(0,e.firstValueFrom)(this.osVersion$);return(0,h.osHasBluetoothSupport)(t,i)})}authenticate(e){return t(this,void 0,void 0,function*(){if(!(yield this._hasBluetoothSupport())){const t="authenticate method: The OS version does not support Bluetooth.";return this.transport.addLog(t),Promise.reject(t)}yield this.transport.writeCharacteristic("auth",e);const t=yield this.isAuthenticated(),[i]=t;return this.transport.addLog(`Authentication ${i?"succeeded":"failed"}`),this.isAuthenticated$.next(i),t})}isAuthenticated(){return t(this,void 0,void 0,function*(){const[t,e]=yield this.transport.readCharacteristic("auth",!0);return this.isAuthenticated$.next(t),[t,e]})}scan(t){if(this.transport instanceof o.ReactNativeTransport)return this.transport.scan(t);if(this.transport instanceof n.WebBluetoothTransport)throw new Error("scan method is compatibly with the React Native transport only");throw new Error("unknown transport")}connect(t){return this.transport instanceof o.ReactNativeTransport?this.transport.connect(t):this.transport instanceof n.WebBluetoothTransport?t?this.transport.connect(t):this.transport.connect():void 0}disconnect(){return this.transport.disconnect()}connection(){return this.transport.connection()}logs(){return this.transport.logs$.asObservable()}getDeviceId(){return t(this,void 0,void 0,function*(){return this.transport.readCharacteristic("deviceId")})}_withAuthentication(i){return t(this,void 0,void 0,function*(){if(!(yield this._hasBluetoothSupport())){const t="The OS version does not support Bluetooth.";return this.transport.addLog(t),Promise.reject(t)}if(!(yield(0,e.firstValueFrom)(this.isAuthenticated$))){const t="Authentication required.";return this.transport.addLog(t),Promise.reject(t)}return yield i()})}_subscribeWhileAuthenticated(t){return this.selectedDevice$.pipe((0,s.combineLatestWith)(this.osVersion$),(0,s.switchMap)(([e,n])=>(0,h.osHasBluetoothSupport)(e,n)?this.isAuthenticated$.pipe((0,r.distinctUntilChanged)(),(0,s.switchMap)(e=>e?this.transport.subscribeToCharacteristic({characteristicName:t}):i.EMPTY)):i.EMPTY),(0,s.share)())}focus(){return this._focus$}calm(){return this._calm$}accelerometer(){return this._accelerometer$}brainwaves(t){switch(t){default:case"raw":return(0,e.defer)(()=>this.getInfo()).pipe((0,s.switchMap)(t=>this._brainwavesRaw$.pipe((0,a.csvBufferToEpoch)(t))));case"rawUnfiltered":return(0,e.defer)(()=>this.getInfo()).pipe((0,s.switchMap)(t=>this._brainwavesRawUnfiltered$.pipe((0,a.csvBufferToEpoch)(t))));case"psd":return this._brainwavesPSD$;case"powerByBand":return this._brainwavesPowerByBand$}}signalQuality(){return this._signalQuality$}addMarker(e){return t(this,void 0,void 0,function*(){yield this.dispatchAction({action:"marker",command:"add",message:{timestamp:Date.now(),label:e}})})}getInfo(){return t(this,void 0,void 0,function*(){return yield this._withAuthentication(()=>(0,e.firstValueFrom)(this.transport.subscribeToCharacteristic({characteristicName:"deviceInfo"})))})}status(){return this._status$}dispatchAction(e){return t(this,void 0,void 0,function*(){return yield this._withAuthentication(()=>this.transport.dispatchAction({characteristicName:"actions",action:e}))})}settings(){return this._settings$}haptics(t){return this.dispatchAction({action:"haptics",command:"queue",responseRequired:!0,responseTimeout:4e3,message:{effects:t}})}get wifi(){return{nearbyNetworks:()=>this._wifiNearbyNetworks$,connections:()=>this._wifiConnections$,connect:(t,e)=>t?this.dispatchAction({action:"wifi",command:"connect",responseRequired:!0,responseTimeout:12e4,message:{ssid:t,password:null!=e?e:null}}):Promise.reject("Missing ssid"),forgetConnection:t=>t?this.dispatchAction({action:"wifi",command:"forget-connection",responseRequired:!0,responseTimeout:15e3,message:{ssid:t}}):Promise.reject("Missing ssid"),reset:()=>this.dispatchAction({action:"wifi",command:"reset",responseRequired:!0,responseTimeout:3e4,message:{respondOnSuccess:!0}}),speedTest:()=>this.dispatchAction({action:"wifi",command:"speed-test",responseRequired:!0,responseTimeout:6e4})}}}exports.BluetoothClient=u;
79
79
  },{"./web/WebBluetoothTransport":"ouKb","./react-native/ReactNativeTransport":"FtS5","./utils/csvBufferToEpoch":"WTrV","./types":"iwtf","./utils/osHasBluetoothSupport":"rH2Y"}],"TICO":[function(require,module,exports) {
80
80
  "use strict";var e=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&("get"in i?t.__esModule:!i.writable&&!i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,i)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),t=this&&this.__exportStar||function(t,r){for(var o in t)"default"===o||Object.prototype.hasOwnProperty.call(r,o)||e(r,t,o)};Object.defineProperty(exports,"__esModule",{value:!0}),t(require("./BluetoothClient"),exports),t(require("./web/WebBluetoothTransport"),exports),t(require("./react-native/ReactNativeTransport"),exports),t(require("./utils/osHasBluetoothSupport"),exports),t(require("./types/index"),exports);
81
81
  },{"./BluetoothClient":"fihV","./web/WebBluetoothTransport":"ouKb","./react-native/ReactNativeTransport":"FtS5","./utils/osHasBluetoothSupport":"rH2Y","./types/index":"iwtf"}],"BZP9":[function(require,module,exports) {
82
- "use strict";var e=this&&this.__createBinding||(Object.create?function(e,t,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&("get"in s?t.__esModule:!s.writable&&!s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,o,s)}:function(e,t,i,o){void 0===o&&(o=i),e[o]=t[i]}),t=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(i){if(i&&i.__esModule)return i;var o={};if(null!=i)for(var s in i)"default"!==s&&Object.prototype.hasOwnProperty.call(i,s)&&e(o,i,s);return t(o,i),o},o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))(function(s,r){function n(e){try{l(o.next(e))}catch(t){r(t)}}function c(e){try{l(o.throw(e))}catch(t){r(t)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(n,c)}l((o=o.apply(e,t||[])).next())})},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Notion=exports.Neurosity=void 0;const r=require("rxjs"),n=require("rxjs"),c=require("rxjs/operators"),l=s(require("fast-deep-equal")),u=require("./api/index"),a=require("./api/index"),d=require("./types/streaming"),h=require("./utils/subscription"),m=require("./types/status"),C=i(require("./utils/errors")),p=i(require("./utils/platform")),v=i(require("./utils/hapticEffects")),g=require("./utils/oauth"),f=require("./utils/oauth"),O=require("./api/https/createOAuthURL"),S=require("./api/https/getOAuthToken"),b=require("./utils/is-node"),M=require("./utils/metrics"),E=require("./api/bluetooth"),T=require("./api/bluetooth/types"),_={timesync:!1,autoSelectDevice:!0,streamingMode:d.STREAMING_MODE.WIFI_ONLY,emulator:!1,emulatorHost:"localhost",emulatorAuthPort:9099,emulatorDatabasePort:9e3,emulatorFunctionsPort:5001,emulatorFirestorePort:8080,emulatorOptions:{}};class A{constructor(e={}){this.streamingMode$=new n.ReplaySubject(1);const{streamingMode:t,bluetoothTransport:i}=e;this.options=Object.freeze(Object.assign(Object.assign({},_),e)),this.cloudClient=new u.CloudClient(this.options),i&&(this.bluetoothClient=new E.BluetoothClient({selectedDevice$:this.onDeviceChange(),createBluetoothToken:this.createBluetoothToken.bind(this),transport:i})),this._initStreamingMode(t,!!i)}_initStreamingMode(e,t){const i=[d.STREAMING_MODE.BLUETOOTH_WITH_WIFI_FALLBACK,d.STREAMING_MODE.WIFI_WITH_BLUETOOTH_FALLBACK].includes(e),o=!Object.values(d.STREAMING_MODE).includes(e),s=i&&!t;this.isMissingBluetoothTransport=s,!e||o||s?this.streamingMode$.next(d.STREAMING_MODE.WIFI_ONLY):this.streamingMode$.next(e)}streamingState(){const e=e=>[m.STATUS.ONLINE,m.STATUS.UPDATING].includes(e);return this.streamingMode$.pipe((0,c.switchMap)(t=>this.onDeviceChange().pipe((0,c.switchMap)(i=>{if(!i)return n.EMPTY;return this.isMissingBluetoothTransport||!(0,E.osHasBluetoothSupport)(i)?this.cloudClient.status().pipe((0,c.map)(({state:i})=>({connected:e(i),streamingMode:t,activeMode:d.STREAMING_TYPE.WIFI}))):(0,r.combineLatest)({wifiStatus:this.cloudClient.status(),bluetoothConnection:(null==this?void 0:this.bluetoothClient)?this.bluetoothClient.connection():(0,r.of)(T.BLUETOOTH_CONNECTION.DISCONNECTED)}).pipe((0,c.map)(({wifiStatus:i,bluetoothConnection:o})=>{const s=o===T.BLUETOOTH_CONNECTION.CONNECTED;switch(t){default:case d.STREAMING_MODE.WIFI_ONLY:return{connected:e(i.state),streamingMode:t,activeMode:d.STREAMING_TYPE.WIFI};case d.STREAMING_MODE.WIFI_WITH_BLUETOOTH_FALLBACK:return{connected:e(i.state)||!s?e(i.state):s,streamingMode:t,activeMode:e(i.state)||!s?d.STREAMING_TYPE.WIFI:d.STREAMING_TYPE.BLUETOOTH};case d.STREAMING_MODE.BLUETOOTH_WITH_WIFI_FALLBACK:return{connected:!!s||e(i.state),streamingMode:t,activeMode:s?d.STREAMING_TYPE.BLUETOOTH:d.STREAMING_TYPE.WIFI}}}),(0,c.distinctUntilChanged)((e,t)=>(0,l.default)(e,t)))}))))}_withStreamingModeObservable(e){const{wifi:t,bluetooth:i}=e;return this.streamingState().pipe((0,c.switchMap)(({activeMode:e})=>{switch(e){case d.STREAMING_TYPE.WIFI:return t();case d.STREAMING_TYPE.BLUETOOTH:return i();default:return t()}}))}_withStreamingModePromise(e){return o(this,void 0,void 0,function*(){const{wifi:t,bluetooth:i}=e,{activeMode:o}=yield(0,n.firstValueFrom)(this.streamingState());switch(o){case d.STREAMING_TYPE.WIFI:return yield t();case d.STREAMING_TYPE.BLUETOOTH:return yield i();default:return yield t()}})}get bluetooth(){return null==this?void 0:this.bluetoothClient}_getCloudMetricDependencies(){return{options:this.options,cloudClient:this.cloudClient,onDeviceChange:this.onDeviceChange.bind(this),status:this.status.bind(this)}}login(e){return o(this,void 0,void 0,function*(){return yield this.cloudClient.login(e)})}logout(){return o(this,void 0,void 0,function*(){return yield this.cloudClient.logout()})}__getApp(){return this.cloudClient.__getApp()}onAuthStateChanged(){return this.cloudClient.onAuthStateChanged()}addDevice(e){const[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"addDevice");return t?Promise.reject(i):this.cloudClient.addDevice(e)}removeDevice(e){const[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"removeDevice");return t?Promise.reject(i):this.cloudClient.removeDevice(e)}transferDevice(e){const[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"transferDevice");return t?Promise.reject(i):this.cloudClient.transferDevice(e)}onUserDevicesChange(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"onUserDevicesChange");return e?(0,r.throwError)(()=>t):this.cloudClient.onUserDevicesChange()}onUserClaimsChange(){return this.cloudClient.onUserClaimsChange()}getDevices(){return o(this,void 0,void 0,function*(){return yield this.cloudClient.getDevices()})}selectDevice(e){return o(this,void 0,void 0,function*(){const[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"selectDevice");return t?Promise.reject(i):yield this.cloudClient.selectDevice(e)})}getSelectedDevice(){return o(this,void 0,void 0,function*(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"getSelectedDevice");return e?Promise.reject(t):yield this.cloudClient.getSelectedDevice()})}getInfo(){return o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))return Promise.reject(C.mustSelectDevice);const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"getInfo");return e?Promise.reject(t):yield this._withStreamingModePromise({wifi:()=>this.cloudClient.getInfo(),bluetooth:()=>this.bluetoothClient.getInfo()})})}onDeviceChange(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"onDeviceChange");return e?(0,r.throwError)(()=>t):this.cloudClient.onDeviceChange()}disconnect(){return o(this,void 0,void 0,function*(){return yield this._withStreamingModePromise({wifi:()=>this.cloudClient.disconnect(),bluetooth:()=>this.bluetoothClient.disconnect()})})}dispatchAction(e){return o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))return Promise.reject(C.mustSelectDevice);const[t,i]=(0,f.validateOAuthScopeForAction)(this.cloudClient.userClaims,e);return t?Promise.reject(i):yield this._withStreamingModePromise({wifi:()=>this.cloudClient.dispatchAction(e),bluetooth:()=>this.bluetoothClient.dispatchAction(e)})})}addMarker(e){return o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))throw C.mustSelectDevice;if(!e)throw new Error(`${C.prefix}A label is required for addMarker`);return yield this._withStreamingModePromise({wifi:()=>this.cloudClient.dispatchAction({command:"marker",action:"add",message:{label:e,timestamp:this.cloudClient.timestamp}}),bluetooth:()=>this.bluetoothClient.addMarker(e)})})}haptics(e){var t;return o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))return Promise.reject(C.mustSelectDevice);const i=null===(t=yield this.getSelectedDevice())||void 0===t?void 0:t.modelVersion;if(!p.supportsHaptics(i))return Promise.reject(C.metricNotSupportedByModel("haptics",i));const o=p.getPlatformHapticMotors(i);for(const t in e){if(!Object.keys(o).includes(t))return Promise.reject(C.locationNotFound(t,i));const s=e[t],r=7;if(s.length>r)return Promise.reject(C.exceededMaxItems(r));o[t]=s}const s={command:"haptics",action:"queue",responseRequired:!0,responseTimeout:1e3,message:{effects:o}};return yield this._withStreamingModePromise({wifi:()=>this.cloudClient.dispatchAction(s),bluetooth:()=>this.bluetoothClient.dispatchAction(s)})})}getHapticEffects(){return v}accelerometer(){const e="accelerometer",[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,e);return t?(0,r.throwError)(()=>i):this.onDeviceChange().pipe((0,c.switchMap)(t=>{const i=(null==t?void 0:t.modelVersion)||p.MODEL_VERSION_1;return p.supportsAccel(i)?this._withStreamingModeObservable({wifi:()=>(0,M.getCloudMetric)(this._getCloudMetricDependencies(),{metric:e,labels:(0,h.getLabels)(e),atomic:!0}),bluetooth:()=>this.bluetoothClient.accelerometer()}):(0,r.throwError)(()=>C.metricNotSupportedByModel(e,i))}))}brainwaves(e){const[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"brainwaves");return t?(0,r.throwError)(()=>i):this._withStreamingModeObservable({wifi:()=>(0,M.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"brainwaves",labels:e?[e]:[],atomic:!1}),bluetooth:()=>this.bluetoothClient.brainwaves(e)})}calm(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"calm");return e?(0,r.throwError)(()=>t):this._withStreamingModeObservable({wifi:()=>(0,M.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"awareness",labels:["calm"],atomic:!1}),bluetooth:()=>this.bluetoothClient.calm()})}signalQuality(){const e="signalQuality",[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,e);return t?(0,r.throwError)(()=>i):this._withStreamingModeObservable({wifi:()=>(0,M.getCloudMetric)(this._getCloudMetricDependencies(),{metric:e,labels:(0,h.getLabels)(e),atomic:!0}),bluetooth:()=>this.bluetoothClient.signalQuality()})}settings(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"settings");return e?(0,r.throwError)(()=>t):this.cloudClient.observeNamespace("settings")}osVersion(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"osVersion");return e?(0,r.throwError)(()=>t):this.cloudClient.observeNamespace("info/osVersion")}focus(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"focus");return e?(0,r.throwError)(()=>t):this._withStreamingModeObservable({wifi:()=>(0,M.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"awareness",labels:["focus"],atomic:!1}),bluetooth:()=>this.bluetoothClient.focus()})}kinesis(e){const[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"kinesis");return t?(0,r.throwError)(()=>i):(0,M.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"kinesis",labels:e?[e]:[],atomic:!1})}predictions(e){const[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"predictions");return t?(0,r.throwError)(()=>i):(0,M.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"predictions",labels:e?[e]:[],atomic:!1})}status(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"status");return e?(0,r.throwError)(()=>t):this._withStreamingModeObservable({wifi:()=>this.cloudClient.status(),bluetooth:()=>this.bluetoothClient.status()})}changeSettings(e){return o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))return Promise.reject(C.mustSelectDevice);const[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"changeSettings");return t?Promise.reject(i):yield this.cloudClient.changeSettings(e)})}get training(){return{record:e=>o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))throw C.mustSelectDevice;const t=this.cloudClient.user&&"uid"in this.cloudClient.user?this.cloudClient.user.uid:null,i=Object.assign(Object.assign({fit:!1,baseline:!1,timestamp:this.cloudClient.timestamp},e),{userId:t});yield this.cloudClient.actions.dispatch({command:"training",action:"record",message:i})}),stop:e=>o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))throw C.mustSelectDevice;yield this.cloudClient.actions.dispatch({command:"training",action:"stop",message:Object.assign({},e)})}),stopAll:()=>o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))throw C.mustSelectDevice;yield this.cloudClient.actions.dispatch({command:"training",action:"stopAll",message:{}})})}}goOffline(){this.cloudClient.goOffline()}goOnline(){this.cloudClient.goOnline()}createAccount(e){return this.cloudClient.createAccount(e)}deleteAccount(){return this.cloudClient.deleteAccount()}createBluetoothToken(){return this.cloudClient.createBluetoothToken()}createCustomToken(){return this.cloudClient.createCustomToken()}getTimesyncOffset(){return this.options.timesync||console.warn("getTimesyncOffset() requires options.timesync to be true."),this.options.timesync?this.cloudClient.getTimesyncOffset():0}createOAuthURL(e){return b.isNode?(0,O.createOAuthURL)(e,this.options):Promise.reject(new Error(`${C.prefix}the createOAuthURL method must be used on the server side (node.js) for security reasons.`))}getOAuthToken(e){return b.isNode?(0,S.getOAuthToken)(e,this.options):Promise.reject(new Error(`${C.prefix}the getOAuthToken method must be used on the server side (node.js) for security reasons.`))}removeOAuthAccess(){return this.cloudClient.removeOAuthAccess()}onUserExperiments(){return this.cloudClient.onUserExperiments()}deleteUserExperiment(e){return this.cloudClient.deleteUserExperiment(e)}}exports.Neurosity=A,A.credentialWithLink=a.credentialWithLink,A.createUser=u.createUser,A.SERVER_TIMESTAMP=a.SERVER_TIMESTAMP;class w extends A{constructor(e={}){super(e),console.log("The Notion class is deprecated and will be removed in the next version of the SDK. Please use the Neurosity class instead. e.g. new Notion() => new Neurosity()")}}exports.Notion=w;
82
+ "use strict";var e=this&&this.__createBinding||(Object.create?function(e,t,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&("get"in s?t.__esModule:!s.writable&&!s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,o,s)}:function(e,t,i,o){void 0===o&&(o=i),e[o]=t[i]}),t=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(i){if(i&&i.__esModule)return i;var o={};if(null!=i)for(var s in i)"default"!==s&&Object.prototype.hasOwnProperty.call(i,s)&&e(o,i,s);return t(o,i),o},o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))(function(s,r){function n(e){try{l(o.next(e))}catch(t){r(t)}}function c(e){try{l(o.throw(e))}catch(t){r(t)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(n,c)}l((o=o.apply(e,t||[])).next())})},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Notion=exports.Neurosity=void 0;const r=require("rxjs"),n=require("rxjs"),c=require("rxjs/operators"),l=require("rxjs/operators"),u=s(require("fast-deep-equal")),a=require("./api/index"),d=require("./api/index"),h=require("./types/streaming"),m=require("./utils/subscription"),C=require("./types/status"),p=i(require("./utils/errors")),v=i(require("./utils/platform")),g=i(require("./utils/hapticEffects")),f=require("./utils/oauth"),O=require("./utils/oauth"),S=require("./api/https/createOAuthURL"),b=require("./api/https/getOAuthToken"),M=require("./utils/is-node"),E=require("./utils/metrics"),T=require("./api/bluetooth"),_=require("./api/bluetooth/types"),A={timesync:!1,autoSelectDevice:!0,streamingMode:h.STREAMING_MODE.WIFI_ONLY,emulator:!1,emulatorHost:"localhost",emulatorAuthPort:9099,emulatorDatabasePort:9e3,emulatorFunctionsPort:5001,emulatorFirestorePort:8080,emulatorOptions:{}};class w{constructor(e={}){this.streamingMode$=new n.ReplaySubject(1);const{streamingMode:t,bluetoothTransport:i}=e;this.options=Object.freeze(Object.assign(Object.assign({},A),e)),this.cloudClient=new a.CloudClient(this.options),i&&(this.bluetoothClient=new T.BluetoothClient({selectedDevice$:this.onDeviceChange(),osVersion$:this.osVersion(),createBluetoothToken:this.createBluetoothToken.bind(this),transport:i})),this._initStreamingMode(t,!!i)}_initStreamingMode(e,t){const i=[h.STREAMING_MODE.BLUETOOTH_WITH_WIFI_FALLBACK,h.STREAMING_MODE.WIFI_WITH_BLUETOOTH_FALLBACK].includes(e),o=!Object.values(h.STREAMING_MODE).includes(e),s=i&&!t;this.isMissingBluetoothTransport=s,!e||o||s?this.streamingMode$.next(h.STREAMING_MODE.WIFI_ONLY):this.streamingMode$.next(e)}streamingState(){const e=e=>[C.STATUS.ONLINE,C.STATUS.UPDATING].includes(e);return this.streamingMode$.pipe((0,c.switchMap)(t=>this.onDeviceChange().pipe((0,l.combineLatestWith)(this.osVersion()),(0,c.switchMap)(([i,o])=>{if(!i)return n.EMPTY;return this.isMissingBluetoothTransport||!(0,T.osHasBluetoothSupport)(i,o)?this.cloudClient.status().pipe((0,c.map)(({state:i})=>({connected:e(i),streamingMode:t,activeMode:h.STREAMING_TYPE.WIFI}))):(0,r.combineLatest)({wifiStatus:this.cloudClient.status(),bluetoothConnection:(null==this?void 0:this.bluetoothClient)?this.bluetoothClient.connection():(0,r.of)(_.BLUETOOTH_CONNECTION.DISCONNECTED)}).pipe((0,c.map)(({wifiStatus:i,bluetoothConnection:o})=>{const s=o===_.BLUETOOTH_CONNECTION.CONNECTED;switch(t){default:case h.STREAMING_MODE.WIFI_ONLY:return{connected:e(i.state),streamingMode:t,activeMode:h.STREAMING_TYPE.WIFI};case h.STREAMING_MODE.WIFI_WITH_BLUETOOTH_FALLBACK:return{connected:e(i.state)||!s?e(i.state):s,streamingMode:t,activeMode:e(i.state)||!s?h.STREAMING_TYPE.WIFI:h.STREAMING_TYPE.BLUETOOTH};case h.STREAMING_MODE.BLUETOOTH_WITH_WIFI_FALLBACK:return{connected:!!s||e(i.state),streamingMode:t,activeMode:s?h.STREAMING_TYPE.BLUETOOTH:h.STREAMING_TYPE.WIFI}}}),(0,c.distinctUntilChanged)((e,t)=>(0,u.default)(e,t)))}))))}_withStreamingModeObservable(e){const{wifi:t,bluetooth:i}=e;return this.streamingState().pipe((0,c.switchMap)(({activeMode:e})=>{switch(e){case h.STREAMING_TYPE.WIFI:return t();case h.STREAMING_TYPE.BLUETOOTH:return i();default:return t()}}))}_withStreamingModePromise(e){return o(this,void 0,void 0,function*(){const{wifi:t,bluetooth:i}=e,{activeMode:o}=yield(0,n.firstValueFrom)(this.streamingState());switch(o){case h.STREAMING_TYPE.WIFI:return yield t();case h.STREAMING_TYPE.BLUETOOTH:return yield i();default:return yield t()}})}get bluetooth(){return null==this?void 0:this.bluetoothClient}_getCloudMetricDependencies(){return{options:this.options,cloudClient:this.cloudClient,onDeviceChange:this.onDeviceChange.bind(this),status:this.status.bind(this)}}login(e){return o(this,void 0,void 0,function*(){return yield this.cloudClient.login(e)})}logout(){return o(this,void 0,void 0,function*(){return yield this.cloudClient.logout()})}__getApp(){return this.cloudClient.__getApp()}onAuthStateChanged(){return this.cloudClient.onAuthStateChanged()}addDevice(e){const[t,i]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"addDevice");return t?Promise.reject(i):this.cloudClient.addDevice(e)}removeDevice(e){const[t,i]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"removeDevice");return t?Promise.reject(i):this.cloudClient.removeDevice(e)}transferDevice(e){const[t,i]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"transferDevice");return t?Promise.reject(i):this.cloudClient.transferDevice(e)}onUserDevicesChange(){const[e,t]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"onUserDevicesChange");return e?(0,r.throwError)(()=>t):this.cloudClient.onUserDevicesChange()}onUserClaimsChange(){return this.cloudClient.onUserClaimsChange()}getDevices(){return o(this,void 0,void 0,function*(){return yield this.cloudClient.getDevices()})}selectDevice(e){return o(this,void 0,void 0,function*(){const[t,i]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"selectDevice");return t?Promise.reject(i):yield this.cloudClient.selectDevice(e)})}getSelectedDevice(){return o(this,void 0,void 0,function*(){const[e,t]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"getSelectedDevice");return e?Promise.reject(t):yield this.cloudClient.getSelectedDevice()})}getInfo(){return o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))return Promise.reject(p.mustSelectDevice);const[e,t]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"getInfo");return e?Promise.reject(t):yield this._withStreamingModePromise({wifi:()=>this.cloudClient.getInfo(),bluetooth:()=>this.bluetoothClient.getInfo()})})}onDeviceChange(){const[e,t]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"onDeviceChange");return e?(0,r.throwError)(()=>t):this.cloudClient.onDeviceChange()}disconnect(){return o(this,void 0,void 0,function*(){return yield this._withStreamingModePromise({wifi:()=>this.cloudClient.disconnect(),bluetooth:()=>this.bluetoothClient.disconnect()})})}dispatchAction(e){return o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))return Promise.reject(p.mustSelectDevice);const[t,i]=(0,O.validateOAuthScopeForAction)(this.cloudClient.userClaims,e);return t?Promise.reject(i):yield this._withStreamingModePromise({wifi:()=>this.cloudClient.dispatchAction(e),bluetooth:()=>this.bluetoothClient.dispatchAction(e)})})}addMarker(e){return o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))throw p.mustSelectDevice;if(!e)throw new Error(`${p.prefix}A label is required for addMarker`);return yield this._withStreamingModePromise({wifi:()=>this.cloudClient.dispatchAction({command:"marker",action:"add",message:{label:e,timestamp:this.cloudClient.timestamp}}),bluetooth:()=>this.bluetoothClient.addMarker(e)})})}haptics(e){var t;return o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))return Promise.reject(p.mustSelectDevice);const i=null===(t=yield this.getSelectedDevice())||void 0===t?void 0:t.modelVersion;if(!v.supportsHaptics(i))return Promise.reject(p.metricNotSupportedByModel("haptics",i));const o=v.getPlatformHapticMotors(i);for(const t in e){if(!Object.keys(o).includes(t))return Promise.reject(p.locationNotFound(t,i));const s=e[t],r=7;if(s.length>r)return Promise.reject(p.exceededMaxItems(r));o[t]=s}const s={command:"haptics",action:"queue",responseRequired:!0,responseTimeout:1e3,message:{effects:o}};return yield this._withStreamingModePromise({wifi:()=>this.cloudClient.dispatchAction(s),bluetooth:()=>this.bluetoothClient.dispatchAction(s)})})}getHapticEffects(){return g}accelerometer(){const e="accelerometer",[t,i]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,e);return t?(0,r.throwError)(()=>i):this.onDeviceChange().pipe((0,c.switchMap)(t=>{const i=(null==t?void 0:t.modelVersion)||v.MODEL_VERSION_1;return v.supportsAccel(i)?this._withStreamingModeObservable({wifi:()=>(0,E.getCloudMetric)(this._getCloudMetricDependencies(),{metric:e,labels:(0,m.getLabels)(e),atomic:!0}),bluetooth:()=>this.bluetoothClient.accelerometer()}):(0,r.throwError)(()=>p.metricNotSupportedByModel(e,i))}))}brainwaves(e){const[t,i]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"brainwaves");return t?(0,r.throwError)(()=>i):this._withStreamingModeObservable({wifi:()=>(0,E.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"brainwaves",labels:e?[e]:[],atomic:!1}),bluetooth:()=>this.bluetoothClient.brainwaves(e)})}calm(){const[e,t]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"calm");return e?(0,r.throwError)(()=>t):this._withStreamingModeObservable({wifi:()=>(0,E.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"awareness",labels:["calm"],atomic:!1}),bluetooth:()=>this.bluetoothClient.calm()})}signalQuality(){const e="signalQuality",[t,i]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,e);return t?(0,r.throwError)(()=>i):this._withStreamingModeObservable({wifi:()=>(0,E.getCloudMetric)(this._getCloudMetricDependencies(),{metric:e,labels:(0,m.getLabels)(e),atomic:!0}),bluetooth:()=>this.bluetoothClient.signalQuality()})}settings(){const[e,t]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"settings");return e?(0,r.throwError)(()=>t):this.cloudClient.observeNamespace("settings")}osVersion(){const[e,t]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"osVersion");return e?(0,r.throwError)(()=>t):this.cloudClient.osVersion()}focus(){const[e,t]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"focus");return e?(0,r.throwError)(()=>t):this._withStreamingModeObservable({wifi:()=>(0,E.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"awareness",labels:["focus"],atomic:!1}),bluetooth:()=>this.bluetoothClient.focus()})}kinesis(e){const[t,i]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"kinesis");return t?(0,r.throwError)(()=>i):(0,E.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"kinesis",labels:e?[e]:[],atomic:!1})}predictions(e){const[t,i]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"predictions");return t?(0,r.throwError)(()=>i):(0,E.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"predictions",labels:e?[e]:[],atomic:!1})}status(){const[e,t]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"status");return e?(0,r.throwError)(()=>t):this._withStreamingModeObservable({wifi:()=>this.cloudClient.status(),bluetooth:()=>this.bluetoothClient.status()})}changeSettings(e){return o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))return Promise.reject(p.mustSelectDevice);const[t,i]=(0,f.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"changeSettings");return t?Promise.reject(i):yield this.cloudClient.changeSettings(e)})}get training(){return{record:e=>o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))throw p.mustSelectDevice;const t=this.cloudClient.user&&"uid"in this.cloudClient.user?this.cloudClient.user.uid:null,i=Object.assign(Object.assign({fit:!1,baseline:!1,timestamp:this.cloudClient.timestamp},e),{userId:t});yield this.cloudClient.actions.dispatch({command:"training",action:"record",message:i})}),stop:e=>o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))throw p.mustSelectDevice;yield this.cloudClient.actions.dispatch({command:"training",action:"stop",message:Object.assign({},e)})}),stopAll:()=>o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))throw p.mustSelectDevice;yield this.cloudClient.actions.dispatch({command:"training",action:"stopAll",message:{}})})}}goOffline(){this.cloudClient.goOffline()}goOnline(){this.cloudClient.goOnline()}createAccount(e){return this.cloudClient.createAccount(e)}deleteAccount(){return this.cloudClient.deleteAccount()}createBluetoothToken(){return this.cloudClient.createBluetoothToken()}createCustomToken(){return this.cloudClient.createCustomToken()}getTimesyncOffset(){return this.options.timesync||console.warn("getTimesyncOffset() requires options.timesync to be true."),this.options.timesync?this.cloudClient.getTimesyncOffset():0}createOAuthURL(e){return M.isNode?(0,S.createOAuthURL)(e,this.options):Promise.reject(new Error(`${p.prefix}the createOAuthURL method must be used on the server side (node.js) for security reasons.`))}getOAuthToken(e){return M.isNode?(0,b.getOAuthToken)(e,this.options):Promise.reject(new Error(`${p.prefix}the getOAuthToken method must be used on the server side (node.js) for security reasons.`))}removeOAuthAccess(){return this.cloudClient.removeOAuthAccess()}onUserExperiments(){return this.cloudClient.onUserExperiments()}deleteUserExperiment(e){return this.cloudClient.deleteUserExperiment(e)}}exports.Neurosity=w,w.credentialWithLink=d.credentialWithLink,w.createUser=a.createUser,w.SERVER_TIMESTAMP=d.SERVER_TIMESTAMP;class D extends w{constructor(e={}){super(e),console.log("The Notion class is deprecated and will be removed in the next version of the SDK. Please use the Neurosity class instead. e.g. new Notion() => new Neurosity()")}}exports.Notion=D;
83
83
  },{"./api/index":"LXvB","./types/streaming":"rekm","./utils/subscription":"yLLB","./types/status":"Ttuy","./utils/errors":"WDyG","./utils/platform":"wAkn","./utils/hapticEffects":"lLai","./utils/oauth":"xIH5","./api/https/createOAuthURL":"MDrB","./api/https/getOAuthToken":"nfg4","./utils/is-node":"vsps","./utils/metrics":"DCuD","./api/bluetooth":"TICO","./api/bluetooth/types":"iwtf"}],"QCba":[function(require,module,exports) {
84
84
  "use strict";var e=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&("get"in o?t.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,o)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),t=this&&this.__exportStar||function(t,r){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(r,i)||e(r,t,i)};Object.defineProperty(exports,"__esModule",{value:!0}),t(require("./Neurosity"),exports),t(require("./api/bluetooth"),exports);
85
85
  },{"./Neurosity":"BZP9","./api/bluetooth":"TICO"}]},{},["QCba"], null)