@neurosity/sdk 6.0.0 → 6.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/dist/browser/neurosity.iife.js +44 -113
- package/dist/browser/neurosity.js +8 -14
- package/dist/browser/neurosity.js.map +1 -1
- package/dist/cjs/{Notion.d.ts → Neurosity.d.ts} +0 -0
- package/dist/cjs/{Notion.js → Neurosity.js} +0 -47
- package/dist/cjs/api/bluetooth/BluetoothClient.d.ts +1 -0
- package/dist/cjs/api/bluetooth/BluetoothClient.js +3 -0
- package/dist/cjs/api/bluetooth/BluetoothTransport.d.ts +1 -0
- package/dist/cjs/api/bluetooth/react-native/ReactNativeTransport.d.ts +5 -0
- package/dist/cjs/api/bluetooth/react-native/ReactNativeTransport.js +23 -3
- package/dist/cjs/api/bluetooth/web/WebBluetoothTransport.d.ts +8 -1
- package/dist/cjs/api/bluetooth/web/WebBluetoothTransport.js +16 -2
- package/dist/cjs/index.d.ts +1 -2
- package/dist/cjs/index.js +1 -2
- package/dist/electron/index.js +8 -14
- package/dist/electron/index.js.map +1 -1
- package/dist/esm/{Notion.d.ts → Neurosity.d.ts} +0 -0
- package/dist/esm/{Notion.js → Neurosity.js} +1 -48
- package/dist/esm/api/bluetooth/BluetoothClient.d.ts +1 -0
- package/dist/esm/api/bluetooth/BluetoothClient.js +3 -0
- package/dist/esm/api/bluetooth/BluetoothTransport.d.ts +1 -0
- package/dist/esm/api/bluetooth/react-native/ReactNativeTransport.d.ts +5 -0
- package/dist/esm/api/bluetooth/react-native/ReactNativeTransport.js +23 -3
- package/dist/esm/api/bluetooth/web/WebBluetoothTransport.d.ts +8 -1
- package/dist/esm/api/bluetooth/web/WebBluetoothTransport.js +16 -2
- package/dist/esm/index.d.ts +1 -2
- package/dist/esm/index.js +1 -2
- package/dist/esm/neurosity.mjs +45 -112
- package/dist/examples/neurosity.iife.js +44 -113
- package/dist/examples/neurosity.js +8 -14
- package/dist/examples/neurosity.mjs +45 -112
- package/package.json +1 -1
- package/dist/cjs/skills/NotionOnDevice.d.ts +0 -7
- package/dist/cjs/skills/NotionOnDevice.js +0 -25
- package/dist/cjs/skills/createSkill.d.ts +0 -7
- package/dist/cjs/skills/createSkill.js +0 -40
- package/dist/cjs/skills/index.d.ts +0 -2
- package/dist/cjs/skills/index.js +0 -18
- package/dist/esm/skills/NotionOnDevice.d.ts +0 -7
- package/dist/esm/skills/NotionOnDevice.js +0 -21
- package/dist/esm/skills/createSkill.d.ts +0 -7
- package/dist/esm/skills/createSkill.js +0 -36
- package/dist/esm/skills/index.d.ts +0 -2
- package/dist/esm/skills/index.js +0 -2
|
File without changes
|
|
@@ -1171,53 +1171,6 @@ class Neurosity {
|
|
|
1171
1171
|
removeOAuthAccess() {
|
|
1172
1172
|
return this.cloudClient.removeOAuthAccess();
|
|
1173
1173
|
}
|
|
1174
|
-
/**
|
|
1175
|
-
* @internal
|
|
1176
|
-
* Proof of Concept for Skills - Not user facing yet
|
|
1177
|
-
*
|
|
1178
|
-
* Accesses a skill by Bundle ID. Additionally, allows to observe
|
|
1179
|
-
* and push skill metrics
|
|
1180
|
-
*
|
|
1181
|
-
* @param bundleId Bundle ID of skill
|
|
1182
|
-
* @returns Skill instance
|
|
1183
|
-
*/
|
|
1184
|
-
skill(bundleId) {
|
|
1185
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
1186
|
-
if (!(yield this.cloudClient.didSelectDevice())) {
|
|
1187
|
-
return Promise.reject(errors.mustSelectDevice);
|
|
1188
|
-
}
|
|
1189
|
-
const skillData = yield this.cloudClient.skills.get(bundleId);
|
|
1190
|
-
if (skillData === null) {
|
|
1191
|
-
return Promise.reject(new Error(`${errors.prefix}Access denied for: ${bundleId}. Make sure the skill is installed.`));
|
|
1192
|
-
}
|
|
1193
|
-
return {
|
|
1194
|
-
metric: (label) => {
|
|
1195
|
-
const metricName = `skill~${skillData.id}~${label}`;
|
|
1196
|
-
const subscription = new rxjs_1.Observable((observer) => {
|
|
1197
|
-
const subscription = this.cloudClient.metrics.subscribe({
|
|
1198
|
-
metric: metricName,
|
|
1199
|
-
labels: [label],
|
|
1200
|
-
atomic: true
|
|
1201
|
-
});
|
|
1202
|
-
const listener = this.cloudClient.metrics.on(subscription, (...data) => {
|
|
1203
|
-
observer.next(...data);
|
|
1204
|
-
});
|
|
1205
|
-
return () => {
|
|
1206
|
-
this.cloudClient.metrics.unsubscribe(subscription, listener);
|
|
1207
|
-
};
|
|
1208
|
-
}).pipe((0, operators_1.map)((metric) => metric[label]));
|
|
1209
|
-
Object.defineProperty(subscription, "next", {
|
|
1210
|
-
value: (metricValue) => {
|
|
1211
|
-
this.cloudClient.metrics.next(metricName, {
|
|
1212
|
-
[label]: metricValue
|
|
1213
|
-
});
|
|
1214
|
-
}
|
|
1215
|
-
});
|
|
1216
|
-
return subscription;
|
|
1217
|
-
}
|
|
1218
|
-
};
|
|
1219
|
-
});
|
|
1220
|
-
}
|
|
1221
1174
|
/**
|
|
1222
1175
|
* <StreamingModes wifi={true} />
|
|
1223
1176
|
*
|
|
@@ -37,6 +37,7 @@ export declare class BluetoothClient {
|
|
|
37
37
|
_wifiConnections$: Observable<any>;
|
|
38
38
|
constructor(options: Options);
|
|
39
39
|
_autoAuthenticate(createBluetoothToken: CreateBluetoothToken): Observable<IsAuthenticatedResponse>;
|
|
40
|
+
enableAutoConnect(autoConnect: boolean): void;
|
|
40
41
|
_hasBluetoothSupport(): Promise<boolean>;
|
|
41
42
|
authenticate(token: string): Promise<IsAuthenticatedResponse>;
|
|
42
43
|
isAuthenticated(): Promise<IsAuthenticatedResponse>;
|
|
@@ -86,6 +86,9 @@ class BluetoothClient {
|
|
|
86
86
|
}
|
|
87
87
|
})))));
|
|
88
88
|
}
|
|
89
|
+
enableAutoConnect(autoConnect) {
|
|
90
|
+
this.transport.enableAutoConnect(autoConnect);
|
|
91
|
+
}
|
|
89
92
|
_hasBluetoothSupport() {
|
|
90
93
|
return __awaiter(this, void 0, void 0, function* () {
|
|
91
94
|
const selectedDevice = yield (0, rxjs_1.firstValueFrom)(this.selectedDevice$);
|
|
@@ -20,6 +20,7 @@ declare type Options = {
|
|
|
20
20
|
BleManager: BleManager;
|
|
21
21
|
bleManagerEmitter: NativeEventEmitter;
|
|
22
22
|
platform: PlatformOSType;
|
|
23
|
+
autoConnect?: boolean;
|
|
23
24
|
};
|
|
24
25
|
declare type BleManagerEvents = {
|
|
25
26
|
stopScan$: Observable<void>;
|
|
@@ -27,9 +28,11 @@ declare type BleManagerEvents = {
|
|
|
27
28
|
connectPeripheral$: Observable<void>;
|
|
28
29
|
disconnectPeripheral$: Observable<void>;
|
|
29
30
|
didUpdateValueForCharacteristic$: Observable<any>;
|
|
31
|
+
didUpdateState$: Observable<any>;
|
|
30
32
|
};
|
|
31
33
|
export declare class ReactNativeTransport implements BluetoothTransport {
|
|
32
34
|
type: TRANSPORT_TYPE;
|
|
35
|
+
options: Options;
|
|
33
36
|
BleManager: BleManager;
|
|
34
37
|
bleManagerEmitter: NativeEventEmitter;
|
|
35
38
|
platform: PlatformOSType;
|
|
@@ -41,10 +44,12 @@ export declare class ReactNativeTransport implements BluetoothTransport {
|
|
|
41
44
|
logs$: ReplaySubject<string>;
|
|
42
45
|
onDisconnected$: Observable<void>;
|
|
43
46
|
connectionStream$: Observable<BLUETOOTH_CONNECTION>;
|
|
47
|
+
_isAutoConnectEnabled$: ReplaySubject<boolean>;
|
|
44
48
|
constructor(options: Options);
|
|
45
49
|
addLog(log: string): void;
|
|
46
50
|
isConnected(): boolean;
|
|
47
51
|
_autoConnect(selectedDevice$: Observable<DeviceInfo>): Observable<void>;
|
|
52
|
+
enableAutoConnect(autoConnect: boolean): void;
|
|
48
53
|
connection(): Observable<BLUETOOTH_CONNECTION>;
|
|
49
54
|
_fromEvent(eventName: string): Observable<any>;
|
|
50
55
|
scan(options?: {
|
|
@@ -27,6 +27,9 @@ const constants_2 = require("../constants");
|
|
|
27
27
|
const constants_3 = require("../constants");
|
|
28
28
|
const constants_4 = require("../constants");
|
|
29
29
|
const osHasBluetoothSupport_1 = require("../utils/osHasBluetoothSupport");
|
|
30
|
+
const defaultOptions = {
|
|
31
|
+
autoConnect: true
|
|
32
|
+
};
|
|
30
33
|
class ReactNativeTransport {
|
|
31
34
|
constructor(options) {
|
|
32
35
|
this.type = types_1.TRANSPORT_TYPE.REACT_NATIVE;
|
|
@@ -37,7 +40,14 @@ class ReactNativeTransport {
|
|
|
37
40
|
this.connectionStream$ = this.connection$
|
|
38
41
|
.asObservable()
|
|
39
42
|
.pipe((0, operators_1.filter)((connection) => !!connection), (0, operators_2.distinctUntilChanged)(), (0, operators_2.shareReplay)(1));
|
|
40
|
-
|
|
43
|
+
this._isAutoConnectEnabled$ = new rxjs_1.ReplaySubject(1);
|
|
44
|
+
if (!options) {
|
|
45
|
+
const errorMessage = "React Native transport: missing options.";
|
|
46
|
+
this.addLog(errorMessage);
|
|
47
|
+
throw new Error(errorMessage);
|
|
48
|
+
}
|
|
49
|
+
this.options = Object.assign(Object.assign({}, defaultOptions), options);
|
|
50
|
+
const { BleManager, bleManagerEmitter, platform, autoConnect } = this.options;
|
|
41
51
|
if (!BleManager) {
|
|
42
52
|
const errorMessage = "React Native option: BleManager not provided.";
|
|
43
53
|
this.addLog(errorMessage);
|
|
@@ -56,6 +66,10 @@ class ReactNativeTransport {
|
|
|
56
66
|
this.BleManager = BleManager;
|
|
57
67
|
this.bleManagerEmitter = bleManagerEmitter;
|
|
58
68
|
this.platform = platform;
|
|
69
|
+
this._isAutoConnectEnabled$.next(autoConnect);
|
|
70
|
+
this._isAutoConnectEnabled$.subscribe((autoConnect) => {
|
|
71
|
+
this.addLog(`Auto connect: ${autoConnect ? "enabled" : "disabled"}`);
|
|
72
|
+
});
|
|
59
73
|
// We create a single listener per event type to
|
|
60
74
|
// avoid missing events when multiple listeners are attached.
|
|
61
75
|
this.bleEvents = {
|
|
@@ -63,7 +77,8 @@ class ReactNativeTransport {
|
|
|
63
77
|
discoverPeripheral$: this._fromEvent("BleManagerDiscoverPeripheral"),
|
|
64
78
|
connectPeripheral$: this._fromEvent("BleManagerConnectPeripheral"),
|
|
65
79
|
disconnectPeripheral$: this._fromEvent("BleManagerDisconnectPeripheral"),
|
|
66
|
-
didUpdateValueForCharacteristic$: this._fromEvent("BleManagerDidUpdateValueForCharacteristic")
|
|
80
|
+
didUpdateValueForCharacteristic$: this._fromEvent("BleManagerDidUpdateValueForCharacteristic"),
|
|
81
|
+
didUpdateState$: this._fromEvent("BleManagerDidUpdateState")
|
|
67
82
|
};
|
|
68
83
|
this.onDisconnected$ = this.bleEvents.disconnectPeripheral$.pipe((0, operators_3.share)());
|
|
69
84
|
// Initializes the module. This can only be called once.
|
|
@@ -91,7 +106,9 @@ class ReactNativeTransport {
|
|
|
91
106
|
}
|
|
92
107
|
_autoConnect(selectedDevice$) {
|
|
93
108
|
const selectedDeviceAfterDisconnect$ = this.onDisconnected$.pipe((0, operators_1.switchMap)(() => selectedDevice$));
|
|
94
|
-
return
|
|
109
|
+
return this._isAutoConnectEnabled$.pipe((0, operators_1.switchMap)((isAutoConnectEnabled) => isAutoConnectEnabled
|
|
110
|
+
? (0, rxjs_1.merge)(selectedDevice$, selectedDeviceAfterDisconnect$)
|
|
111
|
+
: rxjs_2.NEVER), (0, operators_1.switchMap)((selectedDevice) => !(0, osHasBluetoothSupport_1.osHasBluetoothSupport)(selectedDevice)
|
|
95
112
|
? rxjs_2.NEVER
|
|
96
113
|
: this.scan().pipe((0, operators_1.switchMap)((peripherals) => {
|
|
97
114
|
const peripheralMatch = peripherals.find((peripheral) => peripheral.name === (selectedDevice === null || selectedDevice === void 0 ? void 0 : selectedDevice.deviceNickname));
|
|
@@ -100,6 +117,9 @@ class ReactNativeTransport {
|
|
|
100
117
|
return yield this.connect(peripheral);
|
|
101
118
|
})));
|
|
102
119
|
}
|
|
120
|
+
enableAutoConnect(autoConnect) {
|
|
121
|
+
this._isAutoConnectEnabled$.next(autoConnect);
|
|
122
|
+
}
|
|
103
123
|
connection() {
|
|
104
124
|
return this.connectionStream$;
|
|
105
125
|
}
|
|
@@ -5,8 +5,12 @@ import { BluetoothTransport } from "../BluetoothTransport";
|
|
|
5
5
|
import { ActionOptions, SubscribeOptions } from "../types";
|
|
6
6
|
import { TRANSPORT_TYPE, BLUETOOTH_CONNECTION } from "../types";
|
|
7
7
|
import { DeviceInfo } from "../../../types/deviceInfo";
|
|
8
|
+
declare type Options = {
|
|
9
|
+
autoConnect?: boolean;
|
|
10
|
+
};
|
|
8
11
|
export declare class WebBluetoothTransport implements BluetoothTransport {
|
|
9
12
|
type: TRANSPORT_TYPE;
|
|
13
|
+
options: Options;
|
|
10
14
|
device: BluetoothDevice;
|
|
11
15
|
server: BluetoothRemoteGATTServer;
|
|
12
16
|
service: BluetoothRemoteGATTService;
|
|
@@ -18,9 +22,11 @@ export declare class WebBluetoothTransport implements BluetoothTransport {
|
|
|
18
22
|
logs$: ReplaySubject<string>;
|
|
19
23
|
onDisconnected$: Observable<void>;
|
|
20
24
|
connectionStream$: Observable<BLUETOOTH_CONNECTION>;
|
|
21
|
-
|
|
25
|
+
_isAutoConnectEnabled$: ReplaySubject<boolean>;
|
|
26
|
+
constructor(options?: Options);
|
|
22
27
|
_getPairedDevices(): Promise<BluetoothDevice[]>;
|
|
23
28
|
_autoConnect(selectedDevice$: Observable<DeviceInfo>): Observable<void>;
|
|
29
|
+
enableAutoConnect(autoConnect: boolean): void;
|
|
24
30
|
addLog(log: string): void;
|
|
25
31
|
isConnected(): boolean;
|
|
26
32
|
connection(): Observable<BLUETOOTH_CONNECTION>;
|
|
@@ -45,3 +51,4 @@ export declare class WebBluetoothTransport implements BluetoothTransport {
|
|
|
45
51
|
_autoToggleActionNotifications(selectedDevice$: Observable<DeviceInfo>): Promise<void>;
|
|
46
52
|
dispatchAction({ characteristicName, action }: ActionOptions): Promise<any>;
|
|
47
53
|
}
|
|
54
|
+
export {};
|
|
@@ -27,8 +27,11 @@ const types_1 = require("../types");
|
|
|
27
27
|
const constants_1 = require("../constants");
|
|
28
28
|
const constants_2 = require("../constants");
|
|
29
29
|
const osHasBluetoothSupport_1 = require("../utils/osHasBluetoothSupport");
|
|
30
|
+
const defaultOptions = {
|
|
31
|
+
autoConnect: true
|
|
32
|
+
};
|
|
30
33
|
class WebBluetoothTransport {
|
|
31
|
-
constructor() {
|
|
34
|
+
constructor(options = {}) {
|
|
32
35
|
this.type = types_1.TRANSPORT_TYPE.WEB;
|
|
33
36
|
this.characteristicsByName = {};
|
|
34
37
|
this.connection$ = new rxjs_1.BehaviorSubject(types_1.BLUETOOTH_CONNECTION.DISCONNECTED);
|
|
@@ -38,11 +41,17 @@ class WebBluetoothTransport {
|
|
|
38
41
|
this.connectionStream$ = this.connection$
|
|
39
42
|
.asObservable()
|
|
40
43
|
.pipe((0, operators_1.filter)((connection) => !!connection), (0, operators_2.distinctUntilChanged)(), (0, operators_2.shareReplay)(1));
|
|
44
|
+
this._isAutoConnectEnabled$ = new rxjs_1.ReplaySubject(1);
|
|
45
|
+
this.options = Object.assign(Object.assign({}, defaultOptions), options);
|
|
41
46
|
if (!(0, isWebBluetoothSupported_1.isWebBluetoothSupported)()) {
|
|
42
47
|
const errorMessage = "Web Bluetooth is not supported";
|
|
43
48
|
this.addLog(errorMessage);
|
|
44
49
|
throw new Error(errorMessage);
|
|
45
50
|
}
|
|
51
|
+
this._isAutoConnectEnabled$.subscribe((autoConnect) => {
|
|
52
|
+
this.addLog(`Auto connect: ${autoConnect ? "enabled" : "disabled"}`);
|
|
53
|
+
});
|
|
54
|
+
this._isAutoConnectEnabled$.next(this.options.autoConnect);
|
|
46
55
|
this.connection$.asObservable().subscribe((connection) => {
|
|
47
56
|
this.addLog(`connection status is ${connection}`);
|
|
48
57
|
});
|
|
@@ -56,7 +65,9 @@ class WebBluetoothTransport {
|
|
|
56
65
|
});
|
|
57
66
|
}
|
|
58
67
|
_autoConnect(selectedDevice$) {
|
|
59
|
-
return
|
|
68
|
+
return this._isAutoConnectEnabled$.pipe((0, operators_1.switchMap)((isAutoConnectEnabled) => isAutoConnectEnabled
|
|
69
|
+
? (0, rxjs_1.merge)(selectedDevice$, this.onDisconnected$.pipe((0, operators_1.switchMap)(() => selectedDevice$)))
|
|
70
|
+
: rxjs_2.NEVER), (0, operators_1.switchMap)((selectedDevice) => (0, osHasBluetoothSupport_1.osHasBluetoothSupport)(selectedDevice) ? (0, rxjs_1.of)(selectedDevice) : rxjs_2.EMPTY), (0, operators_1.switchMap)((selectedDevice) => __awaiter(this, void 0, void 0, function* () {
|
|
60
71
|
var _a;
|
|
61
72
|
const { deviceNickname } = selectedDevice;
|
|
62
73
|
if (this.isConnected()) {
|
|
@@ -87,6 +98,9 @@ class WebBluetoothTransport {
|
|
|
87
98
|
return yield this.getServerServiceAndCharacteristics(advertisement.device);
|
|
88
99
|
})));
|
|
89
100
|
}
|
|
101
|
+
enableAutoConnect(autoConnect) {
|
|
102
|
+
this._isAutoConnectEnabled$.next(autoConnect);
|
|
103
|
+
}
|
|
90
104
|
addLog(log) {
|
|
91
105
|
this.logs$.next(log);
|
|
92
106
|
}
|
package/dist/cjs/index.d.ts
CHANGED
package/dist/cjs/index.js
CHANGED
|
@@ -14,6 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
__exportStar(require("./
|
|
17
|
+
__exportStar(require("./Neurosity"), exports);
|
|
18
18
|
__exportStar(require("./api/bluetooth"), exports);
|
|
19
|
-
__exportStar(require("./skills"), exports);
|
package/dist/electron/index.js
CHANGED
|
@@ -67,26 +67,20 @@ process.env.HMR_PORT=0;process.env.HMR_HOSTNAME="localhost";parcelRequire=functi
|
|
|
67
67
|
},{}],"rH2Y":[function(require,module,exports) {
|
|
68
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;
|
|
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(r,s){function c(t){try{a(n.next(t))}catch(e){s(e)}}function o(t){try{a(n.throw(t))}catch(e){s(e)}}function a(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(c,o)}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"),r=require("@neurosity/ipk"),s=require("rxjs"),c=require("rxjs"),o=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"),N=require("../utils/osHasBluetoothSupport");class E{constructor(){if(this.type=p.TRANSPORT_TYPE.WEB,this.characteristicsByName={},this.connection$=new s.BehaviorSubject(p.BLUETOOTH_CONNECTION.DISCONNECTED),this.pendingActions$=new s.BehaviorSubject([]),this.logs$=new s.ReplaySubject(10),this.onDisconnected$=this._onDisconnected().pipe((0,d.share)()),this.connectionStream$=this.connection$.asObservable().pipe((0,o.filter)(t=>!!t),(0,a.distinctUntilChanged)(),(0,a.shareReplay)(1)),!(0,h.isWebBluetoothSupported)()){const t="Web Bluetooth is not supported";throw this.addLog(t),new Error(t)}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(0,s.merge)(e,this.onDisconnected$.pipe((0,o.switchMap)(()=>e))).pipe((0,o.switchMap)(t=>(0,N.osHasBluetoothSupport)(t)?(0,s.of)(t):c.EMPTY),(0,o.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,r]=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 ${r.length} devices ${r.map(({name:t})=>t).join(", ")}`);const s=r.findLast(t=>t.name===i);if(!s)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`),s})),(0,o.tap)(()=>{this.connection$.next(p.BLUETOOTH_CONNECTION.SCANNING)}),(0,o.switchMap)(t=>m(t)),(0,o.switchMap)(e=>t(this,void 0,void 0,function*(){return this.addLog(`Advertisement received for ${e.device.name}`),yield this.getServerServiceAndCharacteristics(e.device)})))}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 s=n.BLUETOOTH_DEVICE_NAME_PREFIXES.map(t=>({namePrefix:t})),c=i?[{name:i}]:s;return yield window.navigator.bluetooth.requestDevice({filters:[...c,{manufacturerData:[{companyIdentifier:r.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,o.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?O(this.device,"gattserverdisconnected"):c.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 r=(0,s.defer)(()=>this.getCharacteristicByName(e)).pipe((0,o.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(r){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==r?void 0:r.message)&&void 0!==t?t:r}`)}return i})),(0,o.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(r){this.addLog(`Attemped to stop notifications for ${e} characteristic: ${null!==(t=null==r?void 0:r.message)&&void 0!==t?t:r}`)}}))),(0,o.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,o.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,o.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?r:c.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 r=yield n.readValue(),s=(0,l.decode)(this.type,r),c=i?JSON.parse(s):s;return this.addLog(`Received read data from ${e} characteristic: \n${c}`),c}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 r=this.connection$.asObservable().pipe((0,o.switchMap)(t=>t===p.BLUETOOTH_CONNECTION.CONNECTED?(0,s.defer)(()=>this.getCharacteristicByName("actions")).pipe((0,o.switchMap)(t=>(i=t,this.pendingActions$))):c.NEVER),(0,o.tap)(e=>t(this,void 0,void 0,function*(){var t,r;const s=!!e.length;if(s&&!n){n=!0;try{yield i.startNotifications(),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(!s&&n){n=!1;try{yield i.stopNotifications(),this.addLog("Stopped notifications for actions characteristic")}catch(c){this.addLog(`Attemped to stop notifications for [actions] characteristic: ${null!==(r=null==c?void 0:c.message)&&void 0!==r?r:c}`)}}})));e.pipe((0,o.switchMap)(t=>(0,N.osHasBluetoothSupport)(t)?r:c.EMPTY)).subscribe()})}dispatchAction({characteristicName:e,action:i}){return t(this,void 0,void 0,function*(){const{responseRequired:n=!1,responseTimeout:r=g.DEFAULT_ACTION_RESPONSE_TIMEOUT}=i;return new Promise((c,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&&r){this._addPendingAction(t);const i=(0,s.timer)(r).subscribe(()=>{this._removePendingAction(t),a(`Action with id ${t} timed out after ${r}ms`)});this.subscribeToCharacteristic({characteristicName:e,manageNotifications:!1}).pipe((0,o.filter)(e=>(null==e?void 0:e.actionId)===t),(0,d.take)(1)).subscribe(e=>{i.unsubscribe(),this._removePendingAction(t),c(e)}),this.writeCharacteristic(e,h).catch(e=>{this._removePendingAction(t),a(e.message)})}else this.writeCharacteristic(e,h).then(()=>{c(null)}).catch(t=>{a(t.message)})}))})}}function O(e,i,n){return(0,c.fromEventPattern)(t=>{e.addEventListener(i,t)},r=>t(this,void 0,void 0,function*(){n&&(yield n()),e.removeEventListener(i,r)}))}function m(t){return new c.Observable(e=>{const i=new AbortController,{signal:n}=i,r=t.addEventListener("advertisementreceived",t=>{i.abort(),e.next(t),e.complete()},{once:!0});try{t.watchAdvertisements({signal:n})}catch(s){e.error(s)}return()=>{i.abort(),t.removeEventListener("advertisementreceived",r)}})}exports.WebBluetoothTransport=E;
|
|
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,r){return new(e||(e=Promise))(function(n,a){function s(t){try{c(r.next(t))}catch(i){a(i)}}function o(t){try{c(r.throw(t))}catch(i){a(i)}}function c(t){var i;t.done?n(t.value):(i=t.value,i instanceof e?i:new e(function(t){t(i)})).then(s,o)}c((r=r.apply(t,i||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ReactNativeTransport=void 0;const i=require("@neurosity/ipk"),e=require("@neurosity/ipk"),r=require("@neurosity/ipk"),n=require("rxjs"),a=require("rxjs"),s=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"),f=require("../constants"),N=require("../utils/osHasBluetoothSupport");class E{constructor(t){this.type=u.TRANSPORT_TYPE.REACT_NATIVE,this.characteristicsByName={},this.connection$=new n.BehaviorSubject(u.BLUETOOTH_CONNECTION.DISCONNECTED),this.pendingActions$=new n.BehaviorSubject([]),this.logs$=new n.ReplaySubject(10),this.connectionStream$=this.connection$.asObservable().pipe((0,s.filter)(t=>!!t),(0,o.distinctUntilChanged)(),(0,o.shareReplay)(1));const{BleManager:i,bleManagerEmitter:e,platform:r}=t;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(!r){const t="React Native option: platform not provided.";throw this.addLog(t),new Error(t)}this.BleManager=i,this.bleManagerEmitter=e,this.platform=r,this.bleEvents={stopScan$:this._fromEvent("BleManagerStopScan"),discoverPeripheral$:this._fromEvent("BleManagerDiscoverPeripheral"),connectPeripheral$:this._fromEvent("BleManagerConnectPeripheral"),disconnectPeripheral$:this._fromEvent("BleManagerDisconnectPeripheral"),didUpdateValueForCharacteristic$:this._fromEvent("BleManagerDidUpdateValueForCharacteristic")},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,s.switchMap)(()=>i));return(0,n.merge)(i,e).pipe((0,s.switchMap)(t=>(0,N.osHasBluetoothSupport)(t)?this.scan().pipe((0,s.switchMap)(i=>{const e=i.find(i=>i.name===(null==t?void 0:t.deviceNickname));return e?(0,n.of)(e):a.NEVER}),(0,c.distinct)(t=>t.id),(0,c.take)(1)):a.NEVER),(0,s.switchMap)(i=>t(this,void 0,void 0,function*(){return yield this.connect(i)})))}connection(){return this.connectionStream$}_fromEvent(t){return(0,a.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={},f=new a.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?f:(0,n.timer)(0,1e4).pipe((0,s.switchMap)(()=>f))).pipe((0,s.tap)(()=>{this.connection$.next(u.BLUETOOTH_CONNECTION.SCANNING)}),(0,s.takeUntil)(this.onDisconnected$),(0,s.switchMap)(()=>this.bleEvents.discoverPeripheral$),(0,s.filter)(t=>{var i,e,n;const a=null!==(n=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!==n?n:"";return!!a&&-1!==r.BLUETOOTH_DEVICE_NAME_PREFIXES.findIndex(t=>a.startsWith(t))}),(0,c.scan)((t,i)=>{var e,r,n,a,s,o,c,d;const h=null!==(n=null!==(r=null===(e=null==i?void 0:i.advertising)||void 0===e?void 0:e.localName)&&void 0!==r?r:i.name)&&void 0!==n?n:"",u=null===(d=null===(c=(0,l.decode)(this.type,null!==(o=null===(s=null===(a=null==i?void 0:i.advertising)||void 0===a?void 0:a.manufacturerData)||void 0===s?void 0:s.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,s.map)(t=>Object.values(t)),(0,c.share)())}connect(e){return t(this,void 0,void 0,function*(){return new Promise((r,n)=>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 a=yield this.BleManager.retrieveServices(e.id,[i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING]);if(!a)return this.addLog("Could not retreive services"),void n("Could not retreive services");this.addLog(`Got service ${i.BLUETOOTH_PRIMARY_SERVICE_UUID_STRING}, getting characteristics...`),this.device=e,this.characteristicsByName=Object.fromEntries(a.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&&(this.addLog(`Setting Android MTU to ${g.ANDROID_MAX_MTU}`),yield this.BleManager.requestMTU(e.id,g.ANDROID_MAX_MTU)),this.addLog(`Successfully connected to peripheral ${e.id}`),this.connection$.next(u.BLUETOOTH_CONNECTION.CONNECTED),r()}catch(t){n(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:r=!0}){const c=({peripheralId:a,serviceUUID:c,characteristicUUID:d})=>(0,n.defer)(()=>t(this,void 0,void 0,function*(){var t;if(r)try{yield this.BleManager.startNotification(a,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,s.switchMap)(()=>this.bleEvents.didUpdateValueForCharacteristic$),(0,o.finalize)(()=>t(this,void 0,void 0,function*(){var t;if(r)try{yield this.BleManager.stopNotification(a,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,s.filter)(({characteristic:t})=>t===d),(0,s.map)(({value:t})=>(0,l.decode)(this.type,t)),(0,h.stitchChunks)({delimiter:e.BLUETOOTH_CHUNK_DELIMITER}),(0,s.map)(t=>{var e;try{return JSON.parse(t)}catch(r){return this.addLog(`Failed to parse JSON for ${i} characteristic. Falling back to unparsed string. ${null!==(e=null==r?void 0:r.message)&&void 0!==e?e:r}`),t}}));return this.connection$.pipe((0,s.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?c(this.getCharacteristicByName(i)):a.NEVER))}readCharacteristic(i,e=!1){var r;return t(this,void 0,void 0,function*(){this.addLog(`Reading characteristic: ${i}`);const{peripheralId:t,serviceUUID:n,characteristicUUID:a}=this.getCharacteristicByName(i);if(!a)return Promise.reject(`Did not find characteristic matching ${i}`);try{const o=yield this.BleManager.read(t,n,a),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(s){return Promise.reject(`readCharacteristic ${i} error. ${null!==(r=null==s?void 0:s.message)&&void 0!==r?r:s}`)}})}writeCharacteristic(i,e){return t(this,void 0,void 0,function*(){this.addLog(`Writing characteristic: ${i}`);const{peripheralId:t,serviceUUID:r,characteristicUUID:n}=this.getCharacteristicByName(i);if(!n)return Promise.reject(`Did not find characteristic matching ${i}`);const a=(0,l.encode)(this.type,e);yield this.BleManager.write(t,r,n,a,f.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 r=this.connection$.asObservable().pipe((0,s.switchMap)(t=>t===u.BLUETOOTH_CONNECTION.CONNECTED?this.pendingActions$:a.NEVER),(0,s.tap)(i=>t(this,void 0,void 0,function*(){var t,r;const{peripheralId:n,serviceUUID:a,characteristicUUID:s}=this.getCharacteristicByName("actions"),o=!!i.length;if(o&&!e){e=!0;try{yield this.BleManager.startNotification(n,a,s),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(n,a,s),this.addLog("Stopped notifications for actions characteristic")}catch(c){this.addLog(`Attemped to stop notifications for [actions] characteristic: ${null!==(r=null==c?void 0:c.message)&&void 0!==r?r:c}`)}}})));i.pipe((0,s.switchMap)(t=>(0,N.osHasBluetoothSupport)(t)?r:a.EMPTY)).subscribe()})}dispatchAction({characteristicName:i,action:e}){return t(this,void 0,void 0,function*(){const{responseRequired:r=!1,responseTimeout:a=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}`),r&&a){this._addPendingAction(t);const e=(0,n.timer)(a).subscribe(()=>{this._removePendingAction(t),h(`Action with id ${t} timed out after ${a}ms`)});this.subscribeToCharacteristic({characteristicName:i,manageNotifications:!1}).pipe((0,s.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.message)})}else this.writeCharacteristic(i,l).then(()=>{o(null)}).catch(t=>{h(t.message)})}))})}}exports.ReactNativeTransport=E;
|
|
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("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&&(this.addLog(`Setting Android MTU to ${g.ANDROID_MAX_MTU}`),yield this.BleManager.requestMTU(e.id,g.ANDROID_MAX_MTU)),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(`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(`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(`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(`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.message)})}else this.writeCharacteristic(i,l).then(()=>{o(null)}).catch(t=>{h(t.message)})}))})}}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))}_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.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;
|
|
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);
|
|
81
|
-
},{"./BluetoothClient":"fihV","./web/WebBluetoothTransport":"ouKb","./react-native/ReactNativeTransport":"FtS5","./utils/osHasBluetoothSupport":"rH2Y"}],"
|
|
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"),b=require("./api/https/createOAuthURL"),O=require("./api/https/getOAuthToken"),S=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.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,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))):n.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,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")}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 S.isNode?(0,b.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 S.isNode?(0,O.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()}skill(e){return o(this,void 0,void 0,function*(){if(!(yield this.cloudClient.didSelectDevice()))return Promise.reject(C.mustSelectDevice);const t=yield this.cloudClient.skills.get(e);return null===t?Promise.reject(new Error(`${C.prefix}Access denied for: ${e}. Make sure the skill is installed.`)):{metric:e=>{const i=`skill~${t.id}~${e}`,o=new r.Observable(t=>{const o=this.cloudClient.metrics.subscribe({metric:i,labels:[e],atomic:!0}),s=this.cloudClient.metrics.on(o,(...e)=>{t.next(...e)});return()=>{this.cloudClient.metrics.unsubscribe(o,s)}}).pipe((0,c.map)(t=>t[e]));return Object.defineProperty(o,"next",{value:t=>{this.cloudClient.metrics.next(i,{[e]:t})}}),o}}})}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
|
-
},{"./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"}],"
|
|
84
|
-
"use strict";var e=this&&this.
|
|
85
|
-
},{"
|
|
86
|
-
"use strict";var n=this&&this.__awaiter||function(n,t,e,i){return new(e||(e=Promise))(function(o,c){function r(n){try{s(i.next(n))}catch(t){c(t)}}function u(n){try{s(i.throw(n))}catch(t){c(t)}}function s(n){var t;n.done?o(n.value):(t=n.value,t instanceof e?t:new e(function(n){n(t)})).then(r,u)}s((i=i.apply(n,t||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.createSkill=void 0;const t=require("./NotionOnDevice");function e(e){return{subscribe:i=>n(this,void 0,void 0,function*(){const[o,c]=yield(0,t.createNotionOnDevice)(Object.assign({},i)),r=e(o,c);return{unsubscribe:()=>n(this,void 0,void 0,function*(){if(yield o.disconnect(),r&&"then"in r){const n=yield r;"function"==typeof n&&n()}return"function"==typeof r&&"then"in r()?yield r():"function"==typeof r?r():r})}})}}exports.createSkill=e;
|
|
87
|
-
},{"./NotionOnDevice":"DCNc"}],"d8ek":[function(require,module,exports) {
|
|
88
|
-
"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("./createSkill"),exports),t(require("./NotionOnDevice"),exports);
|
|
89
|
-
},{"./createSkill":"T9Vd","./NotionOnDevice":"DCNc"}],"QCba":[function(require,module,exports) {
|
|
90
|
-
"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("./Notion"),exports),t(require("./api/bluetooth"),exports),t(require("./skills"),exports);
|
|
91
|
-
},{"./Notion":"KQ4u","./api/bluetooth":"TICO","./skills":"d8ek"}]},{},["QCba"], null)
|
|
81
|
+
},{"./BluetoothClient":"fihV","./web/WebBluetoothTransport":"ouKb","./react-native/ReactNativeTransport":"FtS5","./utils/osHasBluetoothSupport":"rH2Y"}],"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;
|
|
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
|
+
"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
|
+
},{"./Neurosity":"BZP9","./api/bluetooth":"TICO"}]},{},["QCba"], null)
|
|
92
86
|
//# sourceMappingURL=/index.js.map
|