@neurosity/sdk 6.2.2 → 6.2.4

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.
@@ -144,16 +144,20 @@ class Neurosity {
144
144
  streamingState() {
145
145
  const isWifiOnline = (state) => [status_1.STATUS.ONLINE, status_1.STATUS.UPDATING].includes(state);
146
146
  return this.streamingMode$.pipe((0, operators_1.switchMap)((streamingMode) => {
147
- if (this.isMissingBluetoothTransport) {
148
- return this.cloudClient.status().pipe((0, operators_1.map)(({ state }) => ({
149
- connected: isWifiOnline(state),
150
- streamingMode,
151
- activeMode: streaming_1.STREAMING_TYPE.WIFI
152
- })));
153
- }
154
- return this.onDeviceChange().pipe((0, operators_1.switchMap)((selectDevice) => !selectDevice
155
- ? rxjs_2.EMPTY
156
- : (0, rxjs_1.combineLatest)({
147
+ return this.onDeviceChange().pipe((0, operators_1.switchMap)((selectDevice) => {
148
+ if (!selectDevice) {
149
+ return rxjs_2.EMPTY;
150
+ }
151
+ const isUnableToUseBluetooth = this.isMissingBluetoothTransport ||
152
+ !(0, bluetooth_1.osHasBluetoothSupport)(selectDevice);
153
+ if (isUnableToUseBluetooth) {
154
+ return this.cloudClient.status().pipe((0, operators_1.map)(({ state }) => ({
155
+ connected: isWifiOnline(state),
156
+ streamingMode,
157
+ activeMode: streaming_1.STREAMING_TYPE.WIFI
158
+ })));
159
+ }
160
+ return (0, rxjs_1.combineLatest)({
157
161
  wifiStatus: this.cloudClient.status(),
158
162
  bluetoothConnection: !!(this === null || this === void 0 ? void 0 : this.bluetoothClient)
159
163
  ? this.bluetoothClient.connection()
@@ -170,13 +174,11 @@ class Neurosity {
170
174
  };
171
175
  case streaming_1.STREAMING_MODE.WIFI_WITH_BLUETOOTH_FALLBACK:
172
176
  return {
173
- connected: isWifiOnline(wifiStatus.state) ||
174
- !isBluetoothConnected
177
+ connected: isWifiOnline(wifiStatus.state) || !isBluetoothConnected
175
178
  ? isWifiOnline(wifiStatus.state)
176
179
  : isBluetoothConnected,
177
180
  streamingMode,
178
- activeMode: isWifiOnline(wifiStatus.state) ||
179
- !isBluetoothConnected
181
+ activeMode: isWifiOnline(wifiStatus.state) || !isBluetoothConnected
180
182
  ? streaming_1.STREAMING_TYPE.WIFI
181
183
  : streaming_1.STREAMING_TYPE.BLUETOOTH
182
184
  };
@@ -191,7 +193,8 @@ class Neurosity {
191
193
  : streaming_1.STREAMING_TYPE.WIFI
192
194
  };
193
195
  }
194
- }), (0, operators_1.distinctUntilChanged)((a, b) => (0, fast_deep_equal_1.default)(a, b)))));
196
+ }), (0, operators_1.distinctUntilChanged)((a, b) => (0, fast_deep_equal_1.default)(a, b)));
197
+ }));
195
198
  }));
196
199
  }
197
200
  /**
@@ -55,6 +55,7 @@ export declare class ReactNativeTransport implements BluetoothTransport {
55
55
  scan(options?: {
56
56
  seconds?: number;
57
57
  once?: boolean;
58
+ skipConnectionUpdate?: boolean;
58
59
  }): Observable<Peripheral[]>;
59
60
  connect(peripheral: Peripheral): Promise<void>;
60
61
  disconnect(): Promise<void>;
@@ -134,10 +134,14 @@ class ReactNativeTransport {
134
134
  (0, operators_3.share)());
135
135
  }
136
136
  scan(options) {
137
- var _a, _b;
137
+ var _a, _b, _c;
138
138
  const RESCAN_INTERVAL = 10000; // 10 seconds
139
139
  const seconds = (_a = options === null || options === void 0 ? void 0 : options.seconds) !== null && _a !== void 0 ? _a : RESCAN_INTERVAL / 1000;
140
140
  const once = (_b = options === null || options === void 0 ? void 0 : options.once) !== null && _b !== void 0 ? _b : false;
141
+ // If we are already connected to a peripheral and start scanning,
142
+ // be default, it will set the connection status to SCANNING and not
143
+ // update it back if no device is connected to
144
+ const skipConnectionUpdate = (_c = options === null || options === void 0 ? void 0 : options.skipConnectionUpdate) !== null && _c !== void 0 ? _c : false;
141
145
  const serviceUUIDs = [ipk_1.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING];
142
146
  const allowDuplicates = true;
143
147
  const scanOptions = {};
@@ -161,7 +165,9 @@ class ReactNativeTransport {
161
165
  ? scanOnce$
162
166
  : (0, rxjs_1.timer)(0, RESCAN_INTERVAL).pipe((0, operators_1.switchMap)(() => scanOnce$));
163
167
  const peripherals$ = scan$.pipe((0, operators_1.tap)(() => {
164
- this.connection$.next(types_1.BLUETOOTH_CONNECTION.SCANNING);
168
+ if (!skipConnectionUpdate) {
169
+ this.connection$.next(types_1.BLUETOOTH_CONNECTION.SCANNING);
170
+ }
165
171
  }), (0, operators_1.takeUntil)(this.onDisconnected$), (0, operators_1.switchMap)(() => this.bleEvents.discoverPeripheral$),
166
172
  // Filter out devices that are not Neurosity devices
167
173
  (0, operators_1.filter)((peripheral) => {
@@ -69,7 +69,7 @@ process.env.HMR_PORT=0;process.env.HMR_HOSTNAME="localhost";parcelRequire=functi
69
69
  },{}],"ouKb":[function(require,module,exports) {
70
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;
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;const h=null!==(e=null==t?void 0:t.seconds)&&void 0!==e?e:10,v=null!==(d=null==t?void 0:t.once)&&void 0!==d&&d,p=[i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING],g={},E=new s.Observable(t=>{var i;try{this.BleManager.scan(p,h,!0,g).then(()=>{this.addLog(`BleManger scanning ${v?"once":"indefintely"}`),t.next()})}catch(e){this.addLog(`BleManger scanning ${v?"once":"indefintely"} failed. ${null!==(i=null==e?void 0:e.message)&&void 0!==i?i:e}`),t.error(e)}return()=>{this.BleManager.stopScan()}});return(v?E:(0,r.timer)(0,1e4).pipe((0,a.switchMap)(()=>E))).pipe((0,a.tap)(()=>{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){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;
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) {
@@ -79,7 +79,7 @@ process.env.HMR_PORT=0;process.env.HMR_HOSTNAME="localhost";parcelRequire=functi
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,n){function r(e){try{l(o.next(e))}catch(t){n(t)}}function c(e){try{l(o.throw(e))}catch(t){n(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(r,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 n=require("rxjs"),r=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"),M=require("./utils/is-node"),b=require("./utils/metrics"),T=require("./api/bluetooth"),_=require("./api/bluetooth/types"),E={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 r.ReplaySubject(1);const{streamingMode:t,bluetoothTransport:i}=e;this.options=Object.freeze(Object.assign(Object.assign({},E),e)),this.cloudClient=new u.CloudClient(this.options),i&&(this.bluetoothClient=new T.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.isMissingBluetoothTransport?this.cloudClient.status().pipe((0,c.map)(({state:i})=>({connected:e(i),streamingMode:t,activeMode:d.STREAMING_TYPE.WIFI}))):this.onDeviceChange().pipe((0,c.switchMap)(i=>i?(0,n.combineLatest)({wifiStatus:this.cloudClient.status(),bluetoothConnection:(null==this?void 0:this.bluetoothClient)?this.bluetoothClient.connection():(0,n.of)(_.BLUETOOTH_CONNECTION.DISCONNECTED)}).pipe((0,c.map)(({wifiStatus:i,bluetoothConnection:o})=>{const s=o===_.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))):r.EMPTY))))}_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,r.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,n.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,n.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],n=7;if(s.length>n)return Promise.reject(C.exceededMaxItems(n));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,n.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,b.getCloudMetric)(this._getCloudMetricDependencies(),{metric:e,labels:(0,h.getLabels)(e),atomic:!0}),bluetooth:()=>this.bluetoothClient.accelerometer()}):(0,n.throwError)(()=>C.metricNotSupportedByModel(e,i))}))}brainwaves(e){const[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"brainwaves");return t?(0,n.throwError)(()=>i):this._withStreamingModeObservable({wifi:()=>(0,b.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,n.throwError)(()=>t):this._withStreamingModeObservable({wifi:()=>(0,b.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,n.throwError)(()=>i):this._withStreamingModeObservable({wifi:()=>(0,b.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,n.throwError)(()=>t):this.cloudClient.observeNamespace("settings")}focus(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"focus");return e?(0,n.throwError)(()=>t):this._withStreamingModeObservable({wifi:()=>(0,b.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,n.throwError)(()=>i):(0,b.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,n.throwError)(()=>i):(0,b.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"predictions",labels:e?[e]:[],atomic:!1})}status(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"status");return e?(0,n.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 M.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 M.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 r=Object.getOwnPropertyDescriptor(t,i);r&&("get"in r?t.__esModule:!r.writable&&!r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,o,r)}: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 r in i)"default"!==r&&Object.prototype.hasOwnProperty.call(i,r)&&e(o,i,r);return t(o,i),o},o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))(function(r,s){function n(e){try{l(o.next(e))}catch(t){s(t)}}function c(e){try{l(o.throw(e))}catch(t){s(t)}}function l(e){var t;e.done?r(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())})},r=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 s=require("rxjs"),n=require("rxjs"),c=require("rxjs/operators"),l=r(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"),M=require("./utils/is-node"),b=require("./utils/metrics"),T=require("./api/bluetooth"),_=require("./api/bluetooth/types"),E={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),e)),this.cloudClient=new u.CloudClient(this.options),i&&(this.bluetoothClient=new T.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),r=i&&!t;this.isMissingBluetoothTransport=r,!e||o||r?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,T.osHasBluetoothSupport)(i)?this.cloudClient.status().pipe((0,c.map)(({state:i})=>({connected:e(i),streamingMode:t,activeMode:d.STREAMING_TYPE.WIFI}))):(0,s.combineLatest)({wifiStatus:this.cloudClient.status(),bluetoothConnection:(null==this?void 0:this.bluetoothClient)?this.bluetoothClient.connection():(0,s.of)(_.BLUETOOTH_CONNECTION.DISCONNECTED)}).pipe((0,c.map)(({wifiStatus:i,bluetoothConnection:o})=>{const r=o===_.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)||!r?e(i.state):r,streamingMode:t,activeMode:e(i.state)||!r?d.STREAMING_TYPE.WIFI:d.STREAMING_TYPE.BLUETOOTH};case d.STREAMING_MODE.BLUETOOTH_WITH_WIFI_FALLBACK:return{connected:!!r||e(i.state),streamingMode:t,activeMode:r?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,s.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,s.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 r=e[t],s=7;if(r.length>s)return Promise.reject(C.exceededMaxItems(s));o[t]=r}const r={command:"haptics",action:"queue",responseRequired:!0,responseTimeout:1e3,message:{effects:o}};return yield this._withStreamingModePromise({wifi:()=>this.cloudClient.dispatchAction(r),bluetooth:()=>this.bluetoothClient.dispatchAction(r)})})}getHapticEffects(){return v}accelerometer(){const e="accelerometer",[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,e);return t?(0,s.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,b.getCloudMetric)(this._getCloudMetricDependencies(),{metric:e,labels:(0,h.getLabels)(e),atomic:!0}),bluetooth:()=>this.bluetoothClient.accelerometer()}):(0,s.throwError)(()=>C.metricNotSupportedByModel(e,i))}))}brainwaves(e){const[t,i]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"brainwaves");return t?(0,s.throwError)(()=>i):this._withStreamingModeObservable({wifi:()=>(0,b.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,s.throwError)(()=>t):this._withStreamingModeObservable({wifi:()=>(0,b.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,s.throwError)(()=>i):this._withStreamingModeObservable({wifi:()=>(0,b.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,s.throwError)(()=>t):this.cloudClient.observeNamespace("settings")}focus(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"focus");return e?(0,s.throwError)(()=>t):this._withStreamingModeObservable({wifi:()=>(0,b.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,s.throwError)(()=>i):(0,b.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,s.throwError)(()=>i):(0,b.getCloudMetric)(this._getCloudMetricDependencies(),{metric:"predictions",labels:e?[e]:[],atomic:!1})}status(){const[e,t]=(0,g.validateOAuthScopeForFunctionName)(this.cloudClient.userClaims,"status");return e?(0,s.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 M.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 M.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;
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)