pryv 2.4.6 → 3.0.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.
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Global type declarations for JSDoc references in JavaScript files.
3
+ * These types are re-exported from the 'pryv' module for use in @param, @returns, etc.
4
+ */
5
+
6
+ import type * as PryvModule from 'pryv';
7
+
8
+ declare global {
9
+ // API types
10
+ type APIEndpoint = string;
11
+ type TokenAndEndpoint = PryvModule.TokenAndAPIEndpoint;
12
+
13
+ // Core classes (for JSDoc @param {Connection} etc.)
14
+ interface Connection extends PryvModule.Connection {
15
+ socket?: any;
16
+ _chunkedBatchCall?: any;
17
+ }
18
+ type Service = PryvModule.Service;
19
+ type ServiceInfo = PryvModule.ServiceInfo;
20
+ type ServiceAssets = PryvModule.ServiceAssets;
21
+
22
+ // Auth types
23
+ type AuthController = PryvModule.AuthController;
24
+ type AuthSettings = PryvModule.AuthSettings;
25
+ type AuthRequestResponse = PryvModule.AuthRequestResponse;
26
+ type CustomLoginButton = PryvModule.CustomLoginButton;
27
+ interface LoginButton extends PryvModule.LoginButton {
28
+ loginButtonText?: HTMLElement;
29
+ }
30
+
31
+ // Data types
32
+ type AccessInfo = PryvModule.AccessInfo & { error?: PryvModule.Error };
33
+ type HFSeriesAddResult = PryvModule.HFSeriesAddResult;
34
+ type APICall = PryvModule.APICall;
35
+ type Event = PryvModule.Event;
36
+ type Stream = PryvModule.Stream;
37
+
38
+ // Method call type for socket.io
39
+ type MethodCall = PryvModule.APICall;
40
+
41
+ // Monitor types
42
+ type Monitor = PryvModule.Monitor;
43
+ type MonitorScope = PryvModule.MonitorScope;
44
+
45
+ // SocketIO type
46
+ type SocketIO = PryvModule.SocketIO;
47
+
48
+ // Namespace for JSDoc like @type {pryv.Service}
49
+ namespace pryv {
50
+ export type Service = PryvModule.Service;
51
+ export type Connection = PryvModule.Connection;
52
+ export type Monitor = PryvModule.Monitor;
53
+ export type ServiceInfo = PryvModule.ServiceInfo;
54
+ export type ServiceAssets = PryvModule.ServiceAssets;
55
+ export type AuthController = PryvModule.AuthController;
56
+ export type Event = PryvModule.Event;
57
+ export type Stream = PryvModule.Stream;
58
+ export type ItemDeletion = PryvModule.ItemDeletion;
59
+ }
60
+
61
+ // Browser namespace for JSDoc
62
+ namespace Browser {
63
+ export type LoginButton = PryvModule.LoginButton;
64
+ }
65
+
66
+ /**
67
+ * Custom error class for Pryv library errors
68
+ */
69
+ class PryvError extends Error {
70
+ constructor(message: string, innerObject?: Error | object);
71
+ name: 'PryvError';
72
+ innerObject?: Error | object;
73
+ }
74
+ }
75
+
76
+ export {};
package/src/index.d.ts CHANGED
@@ -1,6 +1,19 @@
1
1
  declare module 'pryv' {
2
2
  type Timestamp = number;
3
3
  type Identifier = string;
4
+
5
+ /**
6
+ * Common metadata returned by all API responses
7
+ * @see https://api.pryv.com/reference/#in-method-results
8
+ */
9
+ export type ApiMeta = {
10
+ /** API version in format {major}.{minor}.{revision} */
11
+ apiVersion: string;
12
+ /** Current server time as Unix timestamp in seconds */
13
+ serverTime: Timestamp;
14
+ /** Serial that changes when core or register is updated */
15
+ serial: string;
16
+ };
4
17
  export type PermissionLevel = 'read' | 'contribute' | 'manage' | 'create-only';
5
18
  export type KeyValue = { [key: string]: string | number };
6
19
 
@@ -104,7 +117,16 @@ declare module 'pryv' {
104
117
  export type HFSeries = {
105
118
  format: 'flatJSON';
106
119
  fields: string[];
107
- points: Array<number | string>;
120
+ points: Array<Array<number | string>>;
121
+ };
122
+
123
+ /**
124
+ * Response from adding data points to an HF series event
125
+ * @see https://api.pryv.com/reference/#add-hf-series-data-points
126
+ */
127
+ export type HFSeriesAddResult = {
128
+ status: 'ok';
129
+ meta: ApiMeta;
108
130
  };
109
131
 
110
132
  type Run = {
@@ -142,6 +164,16 @@ declare module 'pryv' {
142
164
  subErrors?: Error[];
143
165
  };
144
166
 
167
+ /**
168
+ * Custom error class for Pryv library errors.
169
+ * Includes an innerObject property for wrapping underlying errors.
170
+ */
171
+ export class PryvError extends globalThis.Error {
172
+ constructor(message: string, innerObject?: globalThis.Error | object);
173
+ name: 'PryvError';
174
+ innerObject?: globalThis.Error | object;
175
+ }
176
+
145
177
  export type StreamsQuery = {
146
178
  any?: Identifier[];
147
179
  all?: Identifier[];
@@ -530,18 +562,14 @@ declare module 'pryv' {
530
562
  APICallMethods[K]['res'] & PossibleError;
531
563
 
532
564
  export type APICallResultHandler<K extends keyof APICallMethods> = (
533
- result: APICallResult<K>,
565
+ result: APICallResult<K>, apicall: APICall<K>
534
566
  ) => Promise<any>;
535
567
  export type StreamedEventsHandler = (event: Event) => void;
536
568
 
537
569
  export type StreamedEventsResult = {
538
570
  eventsCount?: number;
539
571
  eventsDeletionsCount?: number;
540
- meta: {
541
- apiVersion: string;
542
- serverTime: number;
543
- serial: string;
544
- };
572
+ meta: ApiMeta;
545
573
  };
546
574
 
547
575
  export type EventFileCreationParams = Partial<
@@ -604,21 +632,30 @@ declare module 'pryv' {
604
632
  filename: string,
605
633
  ): Promise<EventAPICallRes>;
606
634
  addPointsToHFEvent(
607
- id: Identifier,
635
+ eventId: Identifier,
608
636
  fields: string[],
609
- values: Array<string | number>,
610
- ): Promise<any>;
637
+ points: Array<Array<number | string>>,
638
+ ): Promise<HFSeriesAddResult>;
611
639
  accessInfo(): Promise<AccessInfo>;
612
- revoke(throwOnFail?: boolean, usingConnection?: Connection)
640
+ revoke(throwOnFail?: boolean, usingConnection?: Connection): Promise<any>;
613
641
  readonly deltaTime: number;
614
642
  readonly apiEndpoint: string;
643
+ readonly token: string | null;
644
+ readonly endpoint: string;
645
+ options: { chunkSize: number };
615
646
 
616
647
  post(
617
648
  path: string,
618
649
  data: Object | any[],
619
- queryParams: Object,
620
650
  ): Promise<Object | Object[]>;
621
- get(path: string, queryParams: Object): Promise<Object | Object[]>;
651
+ get(path: string, queryParams?: Object): Promise<Object | Object[]>;
652
+
653
+ /** @internal */
654
+ _chunkedBatchCall(
655
+ apiCalls: APICall[],
656
+ progress?: APICallProgressHandler,
657
+ httpHandler?: (batch: any[]) => Promise<any>
658
+ ): Promise<any[]>;
622
659
  }
623
660
 
624
661
  export type serviceCustomizations = {
@@ -637,11 +674,15 @@ declare module 'pryv' {
637
674
  support: string;
638
675
  terms: string;
639
676
  eventTypes: string;
640
- version: string;
641
- assets: {
677
+ version?: string;
678
+ assets?: {
642
679
  definitions: string;
643
680
  };
644
- serial: string;
681
+ serial?: string;
682
+ features?: {
683
+ noHF?: boolean;
684
+ [key: string]: any;
685
+ };
645
686
  };
646
687
 
647
688
  export type AssetsConfig = {
@@ -684,7 +725,7 @@ declare module 'pryv' {
684
725
  setServiceInfo(serviceInfo: Partial<ServiceInfo>): void;
685
726
  assets(forceFetch?: boolean): Promise<ServiceAssets | null>;
686
727
  infoSync(): ServiceInfo | null;
687
- apiEndpointFor(username: string, token: string): Promise<string>;
728
+ apiEndpointFor(username: string, token?: string): Promise<string>;
688
729
  login(
689
730
  username: string,
690
731
  password: string,
@@ -694,6 +735,12 @@ declare module 'pryv' {
694
735
 
695
736
  supportsHF(): Promise<boolean>;
696
737
  isDnsLess(): Promise<boolean>;
738
+
739
+ static buildAPIEndpoint(
740
+ serviceInfo: ServiceInfo,
741
+ username: string,
742
+ token?: string,
743
+ ): string;
697
744
  }
698
745
 
699
746
  export type AuthRequestedPermission = {
@@ -703,24 +750,30 @@ declare module 'pryv' {
703
750
  };
704
751
 
705
752
  export type States =
753
+ | 'ERROR'
706
754
  | 'LOADING'
707
755
  | 'INITIALIZED'
708
756
  | 'NEED_SIGNIN'
709
757
  | 'ACCEPTED'
710
- | 'SIGNOUT';
758
+ | 'SIGNOUT'
759
+ | 'REFUSED';
711
760
 
712
761
  export type StateChangeTypes = {
762
+ ERROR: {
763
+ message?: string;
764
+ error?: Error | unknown;
765
+ };
713
766
  LOADING: {};
714
767
  INITIALIZED: {
715
768
  serviceInfo: ServiceInfo;
716
769
  };
717
770
  NEED_SIGNIN: {
718
771
  authUrl: string;
719
- clientData: any;
720
- code: number;
772
+ clientData?: KeyValue;
773
+ code?: number;
721
774
  key: string;
722
775
  lang: string;
723
- oauthState: any;
776
+ oauthState?: string;
724
777
  poll: string;
725
778
  poll_rate_ms: number;
726
779
  requestedPermissions: Array<{
@@ -729,16 +782,21 @@ declare module 'pryv' {
729
782
  defaultName: string;
730
783
  }>;
731
784
  requestingAppId: string;
732
- returnUrl: any;
733
- serviceInfo: ServiceInfo;
785
+ returnUrl?: string | null;
786
+ serviceInfo?: ServiceInfo;
734
787
  };
735
788
  ACCEPTED: {
736
- serviceInfo: ServiceInfo;
789
+ serviceInfo?: ServiceInfo;
737
790
  apiEndpoint: string;
738
791
  username: string;
739
- token: string;
792
+ token?: string;
740
793
  };
741
794
  SIGNOUT: {};
795
+ REFUSED: {
796
+ reasonID?: string;
797
+ message?: string;
798
+ serviceInfo?: ServiceInfo;
799
+ };
742
800
  };
743
801
 
744
802
  export type StateChange<K extends States> = StateChangeTypes[K] & {
@@ -746,6 +804,26 @@ declare module 'pryv' {
746
804
  status: K;
747
805
  };
748
806
 
807
+ /**
808
+ * Response from auth-request POST endpoint
809
+ * @see https://pryv.github.io/reference/#auth-request
810
+ */
811
+ export type AuthRequestResponse = {
812
+ status: 'NEED_SIGNIN';
813
+ authUrl: string;
814
+ /** @deprecated Use authUrl instead */
815
+ url?: string;
816
+ key: string;
817
+ poll: string;
818
+ poll_rate_ms: number;
819
+ requestingAppId: string;
820
+ requestedPermissions: AuthRequestedPermission[];
821
+ lang?: string;
822
+ returnURL?: string;
823
+ clientData?: KeyValue;
824
+ serviceInfo?: ServiceInfo;
825
+ };
826
+
749
827
  export type AuthSettings = {
750
828
  spanButtonID?: string;
751
829
  onStateChange?: (state: StateChange<States>) => void;
@@ -756,15 +834,23 @@ declare module 'pryv' {
756
834
  requestedPermissions: AuthRequestedPermission[];
757
835
  returnUrl?: string | boolean;
758
836
  referer?: string;
759
- clientData?: Object;
837
+ clientData?: KeyValue;
838
+ deviceName?: string;
839
+ expireAfter?: number;
840
+ serviceInfo?: Partial<ServiceInfo>;
760
841
  };
761
842
  };
762
843
 
844
+ export type LoginButtonConstructor = new (
845
+ authSettings: AuthSettings,
846
+ service: Service,
847
+ ) => CustomLoginButton;
848
+
763
849
  export type SetupAuth = (
764
850
  settings: AuthSettings,
765
851
  serviceInfoUrl: string,
766
852
  serviceCustomizations?: serviceCustomizations,
767
- humanInteraction?: any,
853
+ humanInteraction?: LoginButtonConstructor,
768
854
  ) => Promise<Service>;
769
855
 
770
856
  export type AuthStates = {
@@ -780,16 +866,44 @@ declare module 'pryv' {
780
866
  type AuthStatePayload = {
781
867
  status: AuthStates[keyof AuthStates];
782
868
  message?: string;
869
+ error?: Error | unknown;
783
870
  };
784
871
 
872
+ export type StoredAuthorizationData = {
873
+ apiEndpoint: string;
874
+ username: string;
875
+ } | null;
876
+
785
877
  export type CustomLoginButton = {
786
878
  init?: () => Promise<Service>;
787
- getAuthorizationData(): any;
879
+ getAuthorizationData(): StoredAuthorizationData;
788
880
  onStateChange(state: AuthStatePayload): Promise<void>;
789
881
  onClick(): void;
790
- saveAuthorizationData?: (authData: any) => void;
882
+ saveAuthorizationData?: (authData: StoredAuthorizationData) => void;
791
883
  deleteAuthorizationData?: () => Promise<void>;
792
884
  finishAuthProcessAfterRedirection?: (authController: AuthController) => Promise<void>;
885
+ };
886
+
887
+ export class LoginButton implements CustomLoginButton {
888
+ constructor(authSettings: AuthSettings, service: Service);
889
+ auth: AuthController;
890
+ authSettings: AuthSettings;
891
+ service: Service;
892
+ serviceInfo: ServiceInfo;
893
+ languageCode: string;
894
+ messages: KeyValue;
895
+ text: string;
896
+ popup?: Window | null;
897
+ loginButtonSpan?: HTMLElement;
898
+ loginButtonText?: HTMLElement;
899
+
900
+ init(): Promise<Service>;
901
+ onClick(): void;
902
+ onStateChange(state: AuthStatePayload): Promise<void>;
903
+ getAuthorizationData(): StoredAuthorizationData;
904
+ saveAuthorizationData(authData: StoredAuthorizationData): void;
905
+ deleteAuthorizationData(): Promise<void>;
906
+ finishAuthProcessAfterRedirection(authController: AuthController): Promise<void>;
793
907
  }
794
908
 
795
909
  export class AuthController {
@@ -798,15 +912,24 @@ declare module 'pryv' {
798
912
  service: Service,
799
913
  loginButton: CustomLoginButton,
800
914
  );
915
+ settings: AuthSettings;
916
+ service: Service;
917
+ serviceInfo: ServiceInfo | null;
918
+ assets: ServiceAssets | null;
919
+ loginButton: CustomLoginButton;
920
+ languageCode: string;
921
+ messages: KeyValue;
922
+ stateChangeListeners: Array<(state: AuthStatePayload) => void>;
923
+
801
924
  init(): Promise<Service>;
802
925
  stopAuthRequest(msg: string): void;
803
926
  handleClick(): Promise<void>;
804
927
  getReturnURL(
805
- returnURL: string,
928
+ returnURL?: string,
806
929
  windowLocationForTest?: string,
807
930
  navigatorForTests?: string,
808
931
  ): string | boolean;
809
- startAuthRequest(): Promise<any>;
932
+ startAuthRequest(): Promise<AuthRequestResponse>;
810
933
  set state(newState: AuthStatePayload);
811
934
  get state(): AuthStatePayload;
812
935
  }
@@ -814,16 +937,16 @@ declare module 'pryv' {
814
937
  export const Auth: {
815
938
  setupAuth: SetupAuth;
816
939
  AuthStates: AuthStates;
817
- AuthController: AuthController;
940
+ AuthController: typeof AuthController;
818
941
  }
819
942
 
820
943
  export type getServiceInfoFromURL = (url: string) => string;
821
944
 
822
945
  export const Browser: {
823
- LoginButton: CustomLoginButton;
946
+ LoginButton: typeof LoginButton;
824
947
  CookieUtils: {
825
- set(cookieKey: string, value: any, expireInDays: number): void;
826
- get(cookieKey: string): any;
948
+ set<T = unknown>(cookieKey: string, value: T, expireInDays?: number): void;
949
+ get<T = unknown>(cookieKey: string): T | undefined;
827
950
  del(cookieKey: string): void;
828
951
  };
829
952
  AuthStates: AuthStates;
@@ -840,9 +963,13 @@ declare module 'pryv' {
840
963
  isBrowser(): boolean;
841
964
  extractTokenAndAPIEndpoint(apiEndpoint: string): TokenAndAPIEndpoint;
842
965
  buildAPIEndpoint(tokenAndAPI: TokenAndAPIEndpoint): string;
843
- browserIsMobileOrTablet(navigator: string): boolean;
966
+ browserIsMobileOrTablet(navigator?: string | Navigator): boolean;
844
967
  cleanURLFromPrYvParams(url: string): string;
845
968
  getQueryParamsFromURL(url: string): KeyValue;
969
+ /** @deprecated Use extractTokenAndAPIEndpoint instead */
970
+ extractTokenAndApiEndpoint(apiEndpoint: string): TokenAndAPIEndpoint;
971
+ /** @deprecated Use buildAPIEndpoint instead */
972
+ buildPryvApiEndpoint(tokenAndAPI: TokenAndAPIEndpoint): string;
846
973
  }
847
974
 
848
975
  type version = string;
@@ -856,10 +983,10 @@ declare module 'pryv' {
856
983
  AuthController: typeof AuthController;
857
984
  };
858
985
  Browser: {
859
- LoginButton: CustomLoginButton;
986
+ LoginButton: typeof LoginButton;
860
987
  CookieUtils: {
861
- set(cookieKey: string, value: any, expireInDays: number): void;
862
- get(cookieKey: string): any;
988
+ set<T = unknown>(cookieKey: string, value: T, expireInDays?: number): void;
989
+ get<T = unknown>(cookieKey: string): T | undefined;
863
990
  del(cookieKey: string): void;
864
991
  };
865
992
  AuthStates: AuthStates;
@@ -870,10 +997,11 @@ declare module 'pryv' {
870
997
  isBrowser(): boolean;
871
998
  extractTokenAndAPIEndpoint(apiEndpoint: string): TokenAndAPIEndpoint;
872
999
  buildAPIEndpoint(tokenAndAPI: TokenAndAPIEndpoint): string;
873
- browserIsMobileOrTablet(navigator: string): boolean;
1000
+ browserIsMobileOrTablet(navigator?: string | Navigator): boolean;
874
1001
  cleanURLFromPrYvParams(url: string): string;
875
1002
  getQueryParamsFromURL(url: string): KeyValue;
876
1003
  };
1004
+ PryvError: typeof PryvError;
877
1005
  version: version;
878
1006
  };
879
1007
 
package/src/index.js CHANGED
@@ -8,7 +8,8 @@
8
8
  * @property {pryv.Service} Service - To interact with Pryv.io at a "Platform level"
9
9
  * @property {pryv.Connection} Connection - To interact with an individual's (user) data set
10
10
  * @property {pryv.Browser} Browser - Browser Tools - Access request helpers and visuals (button)
11
- * @property {pryv.utils} utils - Exposes **superagent** for HTTP calls and tools to manipulate Pryv's API endpoints
11
+ * @property {pryv.utils} utils - Exposes some utils for HTTP calls and tools to manipulate Pryv's API endpoints
12
+ * @property {pryv.PryvError} PryvError - Custom error class with innerObject support
12
13
  */
13
14
  module.exports = {
14
15
  Service: require('./Service'),
@@ -16,5 +17,6 @@ module.exports = {
16
17
  Auth: require('./Auth'),
17
18
  Browser: require('./Browser'),
18
19
  utils: require('./utils'),
20
+ PryvError: require('./lib/PryvError'),
19
21
  version: require('../package.json').version
20
22
  };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @license
3
+ * [BSD-3-Clause](https://github.com/pryv/lib-js/blob/master/LICENSE)
4
+ */
5
+
6
+ /**
7
+ * Custom error class for Pryv library errors.
8
+ * Includes an innerObject property for wrapping underlying errors.
9
+ * @extends Error
10
+ */
11
+ class PryvError extends Error {
12
+ /**
13
+ * Create a PryvError
14
+ * @param {string} message - Error message
15
+ * @param {Error|Object} [innerObject] - The underlying error or object that caused this error
16
+ */
17
+ constructor (message, innerObject) {
18
+ super(message);
19
+ this.name = 'PryvError';
20
+ /** @type {Error|Object|undefined} */
21
+ this.innerObject = innerObject;
22
+
23
+ // Maintains proper stack trace for where error was thrown (only in V8)
24
+ if (Error.captureStackTrace) {
25
+ Error.captureStackTrace(this, PryvError);
26
+ }
27
+ }
28
+ }
29
+
30
+ module.exports = PryvError;
@@ -6,12 +6,6 @@
6
6
 
7
7
  module.exports = getEventStreamed;
8
8
 
9
- /**
10
- * @private
11
- * Replacement for getEventStreamed for Browser
12
- * To be used as long as superagent does not propose it.
13
- *
14
- */
15
9
  async function getEventStreamed (conn, queryParam, parser) {
16
10
  /**
17
11
  * Holds Parser's settings
@@ -49,7 +43,7 @@ async function getEventStreamed (conn, queryParam, parser) {
49
43
 
50
44
  // ------------ fetch ------------------- //
51
45
  const url = new URL(conn.endpoint + 'events');
52
- url.search = new URLSearchParams(queryParam);
46
+ url.search = new URLSearchParams(queryParam).toString();
53
47
  const fetchParams = { method: 'GET', headers: { Accept: 'application/json' } };
54
48
  if (conn.token) fetchParams.headers.Authorization = conn.token;
55
49
 
@@ -74,6 +68,7 @@ async function getEventStreamed (conn, queryParam, parser) {
74
68
  headers: {}
75
69
  };
76
70
  // add headers to result
71
+ // @ts-ignore - Headers.entries() exists in modern environments
77
72
  for (const pair of response.headers.entries()) {
78
73
  result.headers[pair[0]] = pair[1];
79
74
  }
@@ -6,8 +6,7 @@
6
6
  const EVENTMARKERS = ['"events":[', '"eventDeletions":['];
7
7
 
8
8
  /**
9
- * Customize superagent parser
10
- * Work on 'node.js' and use by browser-getEventStreamed
9
+ * Stremed JSON parser for events
11
10
  */
12
11
  module.exports = function (foreachEvent, includeDeletions) {
13
12
  let eventOrEventDeletions = 0; // start with event
package/src/utils.js CHANGED
@@ -7,17 +7,61 @@ const regexSchemaAndPath = /(.+):\/\/(.+)/gm;
7
7
 
8
8
  /**
9
9
  * Utilities to access Pryv API.
10
- * Exposes superagent and methods to manipulate API endpoints
11
10
  * @memberof pryv
12
11
  * @namespace pryv.utils
13
12
  */
14
13
  const utils = module.exports = {
15
14
  /**
16
- * Exposes superagent https://visionmedia.github.io/superagent/
17
- * @memberof pryv.utils
18
- * @property {Superagent} superagent
15
+ * Perform a GET request and parse JSON response
16
+ * @param {string} url - URL to fetch
17
+ * @param {Object} [queryParams={}] - Query parameters to append
18
+ * @param {Object} [headers={}] - Additional headers
19
+ * @returns {Promise<{response: Response, body: Object}>} Promise resolving to response and parsed body
20
+ */
21
+ async fetchGet (url, queryParams = {}, headers = {}) {
22
+ let queryStr = '';
23
+ if (queryParams && Object.keys(queryParams).length > 0) {
24
+ queryStr = '?' + new URLSearchParams(queryParams).toString();
25
+ }
26
+ const myHeaders = Object.assign({ Accept: 'application/json' }, headers);
27
+ const response = await fetch(url + queryStr, { headers: myHeaders });
28
+ const body = await response.json();
29
+ return { response, body };
30
+ },
31
+
32
+ /**
33
+ * Perform a GET request and return text response
34
+ * @param {string} url - URL to fetch
35
+ * @param {Object} [headers={}] - Additional headers
36
+ * @returns {Promise<{response: Response, text: string}>} Promise resolving to response and text body
37
+ */
38
+ async fetchGetText (url, headers = {}) {
39
+ const myHeaders = Object.assign({ Accept: 'text/html' }, headers);
40
+ const response = await fetch(url, { headers: myHeaders });
41
+ const text = await response.text();
42
+ return { response, text };
43
+ },
44
+
45
+ /**
46
+ * Perform a POST request with JSON data
47
+ * @param {string} url - URL to post to
48
+ * @param {Object} [data] - Data to send as JSON
49
+ * @param {Object} [headers={}] - Additional headers
50
+ * @returns {Promise<{response: Response, body: Object}>} Promise resolving to response and parsed body
19
51
  */
20
- superagent: require('superagent'),
52
+ async fetchPost (url, data, headers = {}) {
53
+ const myHeaders = Object.assign({
54
+ Accept: 'application/json',
55
+ 'Content-Type': 'application/json'
56
+ }, headers);
57
+ const response = await fetch(url, {
58
+ method: 'POST',
59
+ headers: myHeaders,
60
+ body: JSON.stringify(data)
61
+ });
62
+ const body = await response.json();
63
+ return { response, body };
64
+ },
21
65
 
22
66
  /**
23
67
  * Returns true is run in a browser
@@ -83,28 +127,45 @@ const utils = module.exports = {
83
127
  },
84
128
 
85
129
  /**
86
- *
87
- * @param {Object} [navigatorForTests] mock navigator var only for testing purposes
130
+ * Check if the browser is running on a mobile device or tablet
131
+ * @memberof pryv.utils
132
+ * @param {string|Navigator} [navigator] - Navigator object or user agent string (for testing)
133
+ * @returns {boolean} True if mobile or tablet
88
134
  */
89
135
  browserIsMobileOrTablet: function (navigator) {
90
136
  if (navigator == null) {
91
137
  return false;
92
138
  }
93
139
  let check = false;
140
+ // @ts-ignore - navigator is Navigator when not null
94
141
  // eslint-disable-next-line no-useless-escape
95
142
  (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true; })(navigator.userAgent || navigator.vendor || navigator.opera);
96
143
  return check;
97
144
  },
98
145
 
146
+ /**
147
+ * Remove Pryv-specific query parameters from URL
148
+ * @memberof pryv.utils
149
+ * @param {string} url - URL to clean
150
+ * @returns {string} URL without prYv* parameters
151
+ */
99
152
  cleanURLFromPrYvParams: function (url) {
100
153
  const PRYV_REGEXP = /[?#&]+prYv([^=&]+)=([^&]*)/g;
101
154
  return url.replace(PRYV_REGEXP, '');
102
155
  },
103
156
 
157
+ /**
158
+ * Extract query parameters from a URL
159
+ * @memberof pryv.utils
160
+ * @param {string} url - URL to parse
161
+ * @returns {Object.<string, string>} Object with key-value pairs of query parameters
162
+ */
104
163
  getQueryParamsFromURL: function (url) {
164
+ /** @type {Object.<string, string>} */
105
165
  const vars = {};
106
166
  const QUERY_REGEXP = /[?#&]+([^=&]+)=([^&]*)/g;
107
167
  url.replace(QUERY_REGEXP,
168
+ // @ts-ignore - replace callback is used for side effects
108
169
  function (m, key, value) {
109
170
  vars[key] = decodeURIComponent(value);
110
171
  });