@ibm-aspera/sdk 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/.editorconfig +13 -0
  2. package/.eslintrc.js +128 -0
  3. package/.github/CODE_OF_CONDUCT.md +128 -0
  4. package/.github/CONTRIBUTING.md +147 -0
  5. package/.github/workflows/ci.yml +36 -0
  6. package/.github/workflows/documentation.yml +43 -0
  7. package/.github/workflows/npm_upload.yml +30 -0
  8. package/.husky/pre-commit +4 -0
  9. package/CHANGELOG.md +124 -0
  10. package/LICENSE +201 -0
  11. package/README.md +25 -0
  12. package/dist/commonjs/app/core.d.ts +219 -0
  13. package/dist/commonjs/app/core.js +546 -0
  14. package/dist/commonjs/app/installer.d.ts +9 -0
  15. package/dist/commonjs/app/installer.js +50 -0
  16. package/dist/commonjs/constants/constants.d.ts +6 -0
  17. package/dist/commonjs/constants/constants.js +9 -0
  18. package/dist/commonjs/constants/messages.d.ts +29 -0
  19. package/dist/commonjs/constants/messages.js +32 -0
  20. package/dist/commonjs/helpers/client/client.d.ts +5 -0
  21. package/dist/commonjs/helpers/client/client.js +7 -0
  22. package/dist/commonjs/helpers/client/http-client.d.ts +42 -0
  23. package/dist/commonjs/helpers/client/http-client.js +84 -0
  24. package/dist/commonjs/helpers/client/safari-client.d.ts +99 -0
  25. package/dist/commonjs/helpers/client/safari-client.js +252 -0
  26. package/dist/commonjs/helpers/helpers.d.ts +84 -0
  27. package/dist/commonjs/helpers/helpers.js +197 -0
  28. package/dist/commonjs/helpers/http.d.ts +16 -0
  29. package/dist/commonjs/helpers/http.js +42 -0
  30. package/dist/commonjs/helpers/ws.d.ts +62 -0
  31. package/dist/commonjs/helpers/ws.js +182 -0
  32. package/dist/commonjs/index.d.ts +41 -0
  33. package/dist/commonjs/index.js +99 -0
  34. package/dist/commonjs/models/aspera-sdk.model.d.ts +213 -0
  35. package/dist/commonjs/models/aspera-sdk.model.js +288 -0
  36. package/dist/commonjs/models/models.d.ts +640 -0
  37. package/dist/commonjs/models/models.js +2 -0
  38. package/dist/js/aspera-sdk.js +3 -0
  39. package/dist/js/aspera-sdk.js.LICENSE.txt +7 -0
  40. package/dist/js/aspera-sdk.js.map +1 -0
  41. package/docs/DEVELOPMENT.md +38 -0
  42. package/jest.config.js +15 -0
  43. package/jest.setup.js +0 -0
  44. package/package.json +50 -0
  45. package/src/app/core.ts +610 -0
  46. package/src/app/installer.ts +53 -0
  47. package/src/constants/constants.ts +16 -0
  48. package/src/constants/messages.ts +29 -0
  49. package/src/helpers/client/client.ts +11 -0
  50. package/src/helpers/client/http-client.ts +92 -0
  51. package/src/helpers/client/safari-client.ts +318 -0
  52. package/src/helpers/helpers.ts +200 -0
  53. package/src/helpers/http.ts +39 -0
  54. package/src/helpers/ws.ts +215 -0
  55. package/src/index.html +404 -0
  56. package/src/index.ts +104 -0
  57. package/src/models/aspera-sdk.model.ts +360 -0
  58. package/src/models/models.ts +669 -0
  59. package/tests/client.spec.ts +52 -0
  60. package/tests/core.spec.ts +13 -0
  61. package/tests/helpers.spec.ts +124 -0
  62. package/tests/http.spec.ts +14 -0
  63. package/tests/installer.spec.ts +135 -0
  64. package/tests/mocks.ts +11 -0
  65. package/tsconfig.json +10 -0
  66. package/tsconfig.module.json +15 -0
  67. package/typedoc.js +17 -0
  68. package/webpack.config.js +53 -0
@@ -0,0 +1,11 @@
1
+ import {httpClient} from './http-client';
2
+ import {safariClient} from './safari-client';
3
+ import {isSafari} from '../helpers';
4
+
5
+ interface Client {
6
+ request(method: String, payload?: any): Promise<any>;
7
+ }
8
+
9
+ export const client: Client = isSafari() ? safariClient : httpClient;
10
+
11
+ export default Client;
@@ -0,0 +1,92 @@
1
+ import {JSONRPCClient, JSONRPCRequest} from 'json-rpc-2.0';
2
+ import Client from './client';
3
+ import {generatePromiseObjects} from '../helpers';
4
+ import {asperaSdk} from '../../index';
5
+
6
+ export const getRpcServerUrl = (): string => {
7
+ return `${asperaSdk.globals.asperaAppUrl}:${asperaSdk.globals.rpcPort}`;
8
+ };
9
+
10
+ /**
11
+ * Wraps a promise like object and returns a promise that supports catch.
12
+ *
13
+ * @param promise the HTTP promise like to wrap
14
+ *
15
+ * @returns promise for the HTTP connection with catch supporting error
16
+ */
17
+ export const handlePromiseLikeErrors = (promise: PromiseLike<any>): Promise<any> => {
18
+ const promiseInfo = generatePromiseObjects();
19
+
20
+ promise.then(response => {
21
+ promiseInfo.resolver(response);
22
+ }, error => {
23
+ promiseInfo.rejecter(error);
24
+ });
25
+
26
+ return promiseInfo.promise;
27
+ };
28
+
29
+ /**
30
+ * JSON RPC client using HTTP (fetch) as transport.
31
+ */
32
+ class JSONRPCHttpClient {
33
+ /** JSON-RPC client used to make requests */
34
+ client: JSONRPCClient;
35
+
36
+ constructor() {
37
+ this.client = new JSONRPCClient(this.handleRequest);
38
+ }
39
+
40
+ /**
41
+ * Request handler for the JSON-RPC client. This function is called by the JSON-RPC library
42
+ * after forming the RPC request.
43
+ *
44
+ * @param request JSON-RPC request to send to the server
45
+ */
46
+ private handleRequest = (request: JSONRPCRequest) => {
47
+ const options = {
48
+ method: 'POST',
49
+ headers: {
50
+ 'content-type': 'application/json',
51
+ },
52
+ body: JSON.stringify(request),
53
+ };
54
+
55
+ const rpcServerURL = getRpcServerUrl();
56
+
57
+ return fetch(rpcServerURL, options).then(response => {
58
+ if (response.ok) {
59
+ return response.json().then(rpcResponse => this.client.receive(rpcResponse));
60
+ } else if (request.id !== undefined) {
61
+ throw Promise.reject(response.statusText);
62
+ }
63
+ });
64
+ };
65
+
66
+ request = (method: string, data: any): PromiseLike<any> => {
67
+ return this.client.request(method, data);
68
+ };
69
+ }
70
+
71
+ /**
72
+ * Client used for making requests to Aspera.
73
+ */
74
+ class HttpClient implements Client {
75
+ /** HTTP client used to make requests */
76
+ httpClient: JSONRPCHttpClient;
77
+
78
+ constructor() {
79
+ this.httpClient = new JSONRPCHttpClient();
80
+ };
81
+
82
+ request = (method: string, payload: any = {}): Promise<any> => {
83
+ return handlePromiseLikeErrors(this.httpClient.request(method, payload));
84
+ };
85
+ }
86
+
87
+ export const httpClient = new HttpClient();
88
+
89
+ export default {
90
+ httpClient,
91
+ handlePromiseLikeErrors,
92
+ };
@@ -0,0 +1,318 @@
1
+ import Client from './client';
2
+ import {randomUUID} from '../helpers';
3
+ import {asperaSdk} from '../../index';
4
+
5
+ /**
6
+ * Enum defining different types of Safari extension events.
7
+ */
8
+ enum SafariExtensionEventType {
9
+ Monitor = 'Monitor',
10
+ Ping = 'Ping',
11
+ Request = 'Request'
12
+ }
13
+
14
+ /**
15
+ * Interface representing a JSON-RPC request object.
16
+ */
17
+ interface JSONRPCRequest {
18
+ id: string;
19
+ jsonrpc: string;
20
+ method: string;
21
+ params: any;
22
+ }
23
+
24
+ /**
25
+ * Interface representing a JSON-RPC response object.
26
+ */
27
+ interface JSONRPCResponse {
28
+ id: string;
29
+ jsonrpc: string;
30
+ result?: any;
31
+ error?: any;
32
+ }
33
+
34
+ /**
35
+ * Interface representing a promise executor used in a promise.
36
+ */
37
+ export interface PromiseExecutor {
38
+ resolve: (value: any) => void;
39
+ reject: (error: any) => void;
40
+ }
41
+
42
+ /**
43
+ * Global keep alive timeout to prevent recursion.
44
+ */
45
+ let keepAliveTimeout: ReturnType<typeof setTimeout>;
46
+
47
+ /**
48
+ * Handles communication with the Safari extension using JSON-RPC over custom events.
49
+ */
50
+ export class SafariClient implements Client {
51
+ private statusInterval = 100;
52
+ private keepAliveInterval = 1000;
53
+ private promiseExecutors: Map<string, PromiseExecutor>;
54
+
55
+ private isFirstPing = true;
56
+ private lastPing: number|null = null;
57
+ private lastPong: number|null = null;
58
+ private safariExtensionEnabled = false;
59
+ private subscribedTransferActivity = false;
60
+
61
+ /**
62
+ * Initializes the SafariExtensionHandler instance.
63
+ * Sets up the promise executor map and starts listening to extension events.
64
+ */
65
+ constructor() {
66
+ this.promiseExecutors = new Map();
67
+ this.listenResponseEvents();
68
+ this.listenTransferActivityEvents();
69
+ this.listenStatusEvents();
70
+ this.listenPongEvents();
71
+
72
+ if (keepAliveTimeout) {
73
+ clearTimeout(keepAliveTimeout);
74
+ }
75
+
76
+ this.keepAlive();
77
+ }
78
+
79
+ /**
80
+ * Sends a JSON-RPC request to the Safari extension.
81
+ * @param method The method name to invoke on the extension.
82
+ * @param payload Optional payload for the request.
83
+ * @returns A Promise that resolves with the response from the extension.
84
+ */
85
+ request = (method: string, payload: any = {}): Promise<any> => {
86
+ return this.dispatchPromiseEvent(
87
+ SafariExtensionEventType.Request,
88
+ method,
89
+ payload
90
+ );
91
+ };
92
+
93
+ /**
94
+ * Monitors transfer activity.
95
+ * @returns A Promise that resolves with the response from the extension.
96
+ */
97
+ public monitorTransferActivity(): Promise<unknown> {
98
+ const dispatchMonitorEvent = (): Promise<unknown> => {
99
+ const promise = this.dispatchPromiseEvent(
100
+ SafariExtensionEventType.Monitor,
101
+ 'subscribe_transfer_activity',
102
+ [asperaSdk.globals.appId]
103
+ );
104
+
105
+ return promise.then(() => {
106
+ this.subscribedTransferActivity = true;
107
+ });
108
+ };
109
+
110
+ if (this.safariExtensionEnabled) {
111
+ return dispatchMonitorEvent();
112
+ }
113
+
114
+ return new Promise((resolve, reject) => {
115
+ const extensionInterval = setInterval(() => {
116
+ if (!this.safariExtensionEnabled) {
117
+ return;
118
+ }
119
+
120
+ dispatchMonitorEvent()
121
+ .then(resolve)
122
+ .catch(reject);
123
+
124
+ clearInterval(extensionInterval);
125
+ }, 1000);
126
+ });
127
+ }
128
+
129
+ /**
130
+ * Builds a JSON-RPC request object with a unique identifier.
131
+ * @param method The method name to invoke on the extension.
132
+ * @param payload Optional parameters for the method.
133
+ * @returns The constructed JSON-RPC request object.
134
+ */
135
+ private buildRPCRequest(method: string, payload?: unknown): JSONRPCRequest {
136
+ return {
137
+ jsonrpc: '2.0',
138
+ method,
139
+ params: payload,
140
+ id: randomUUID()
141
+ };
142
+ }
143
+
144
+ /**
145
+ * Dispatches a custom event to the document to communicate with the Safari extension.
146
+ * @param type The type of Safari extension event to dispatch.
147
+ * @param request Optional JSON-RPC request payload to send with the event.
148
+ */
149
+ private dispatchEvent(type: SafariExtensionEventType, request?: JSONRPCRequest) {
150
+ const payload = {
151
+ detail: request ?? {}
152
+ };
153
+
154
+ document.dispatchEvent(new CustomEvent(`AsperaDesktop.${type}`, payload));
155
+ }
156
+
157
+ /**
158
+ * Dispatches a custom event to the document to communicate with the Safari extension.
159
+ * @param type The type of Safari extension event to dispatch.
160
+ * @param method The method name to invoke on the extension.
161
+ * @param payload Optional parameters for the method.
162
+ */
163
+ private dispatchPromiseEvent(type: SafariExtensionEventType, method: string, payload?: unknown): Promise<any> {
164
+ const request = this.buildRPCRequest(method, payload);
165
+
166
+ return new Promise<any>((resolve, reject) => {
167
+ if (this.safariExtensionEnabled) {
168
+ this.promiseExecutors.set(request.id, {resolve, reject});
169
+
170
+ this.dispatchEvent(type, request);
171
+ } else {
172
+ console.warn('The Safari extension is disabled or unresponsive (dispatch event)');
173
+ console.warn(`Failed event: ${JSON.stringify(request)}`);
174
+
175
+ reject('The Safari extension is disabled or unresponsive (dispatch event)');
176
+ }
177
+ });
178
+ }
179
+
180
+ /**
181
+ * Handles incoming JSON-RPC responses from the Safari extension.
182
+ * Resolves or rejects promises based on the response.
183
+ * @param response The JSON-RPC response object received from the extension.
184
+ */
185
+ private handleResponse(response: JSONRPCResponse) {
186
+ const requestId = response.id;
187
+ const executor = this.promiseExecutors.get(requestId);
188
+
189
+ if (!executor) {
190
+ console.warn(`Unable to find a promise executor for ${requestId}`);
191
+ console.warn(`Response: ${response}`);
192
+ return;
193
+ }
194
+
195
+ this.promiseExecutors.delete(requestId);
196
+
197
+ if (response.error) {
198
+ executor.reject(response.error);
199
+ return;
200
+ }
201
+
202
+ executor.resolve(response.result);
203
+ }
204
+
205
+ /**
206
+ * Listens for 'AsperaDesktop.Response' events.
207
+ */
208
+ private listenResponseEvents() {
209
+ document.addEventListener('AsperaDesktop.Response', (event: CustomEvent<JSONRPCResponse>) => {
210
+ this.handleResponse(event.detail);
211
+ });
212
+ }
213
+
214
+ /**
215
+ * Listens for 'AsperaDesktop.TransferActivity' events.
216
+ */
217
+ private listenTransferActivityEvents() {
218
+ document.addEventListener('AsperaDesktop.TransferActivity', (event: any) => {
219
+ asperaSdk.activityTracking.handleTransferActivity(event.detail);
220
+ });
221
+ }
222
+
223
+ /**
224
+ * Listens for 'AsperaDesktop.Status' events.
225
+ */
226
+ private listenStatusEvents() {
227
+ document.addEventListener('AsperaDesktop.Status', (event: any) => {
228
+ asperaSdk.activityTracking.handleWebSocketEvents(event.detail);
229
+ });
230
+ }
231
+
232
+ /**
233
+ * Listens for 'AsperaDesktop.Pong' events.
234
+ */
235
+ private listenPongEvents() {
236
+ document.addEventListener('AsperaDesktop.Pong', () => {
237
+ this.lastPong = Date.now();
238
+ this.safariExtensionStatusChanged(true);
239
+ });
240
+ }
241
+
242
+ /**
243
+ * Sends a keep alive ping according to the defined interval.
244
+ */
245
+ private keepAlive() {
246
+ this.lastPing = Date.now();
247
+ this.dispatchEvent(SafariExtensionEventType.Ping);
248
+
249
+ if (this.isFirstPing) {
250
+ this.isFirstPing = false;
251
+ } else {
252
+ setTimeout(() => {
253
+ this.checkSafariExtensionStatus();
254
+ }, this.statusInterval);
255
+ }
256
+
257
+ keepAliveTimeout = setTimeout(() => {
258
+ this.keepAlive();
259
+ }, this.keepAliveInterval);
260
+ }
261
+
262
+ /**
263
+ * Listens for Safari extension status changes.
264
+ * If the extension was disabled and enabled again after initializing the SDK, it
265
+ * will call 'monitorTransferActivity' to resume transfer activities.
266
+ */
267
+ private safariExtensionStatusChanged(isEnabled: boolean) {
268
+ if (isEnabled === this.safariExtensionEnabled) {
269
+ return;
270
+ }
271
+
272
+ this.safariExtensionEnabled = isEnabled;
273
+
274
+ if (isEnabled) {
275
+ if (this.subscribedTransferActivity) {
276
+ const resumeTransferActivity = () => {
277
+ this.monitorTransferActivity()
278
+ .catch(() => {
279
+ console.error('Failed to resume transfer activity, will try again in 1s');
280
+
281
+ setTimeout(() => {
282
+ resumeTransferActivity();
283
+ }, 1000);
284
+ });
285
+ };
286
+
287
+ resumeTransferActivity();
288
+ }
289
+ } else {
290
+ asperaSdk.activityTracking.handleWebSocketEvents('CLOSED');
291
+
292
+ this.promiseExecutors.forEach((promiseExecutor) => {
293
+ promiseExecutor.reject('The Safari extension is disabled or unresponsive (extension status)');
294
+ });
295
+
296
+ this.promiseExecutors.clear();
297
+ }
298
+
299
+ asperaSdk.activityTracking.handleSafariExtensionEvents(this.safariExtensionEnabled ? 'ENABLED' : 'DISABLED');
300
+ }
301
+
302
+ /**
303
+ * Checks if the last pong received was longer than the max interval.
304
+ */
305
+ private checkSafariExtensionStatus() {
306
+ const pingPongDiff = this.lastPong - this.lastPing;
307
+
308
+ if (this.lastPong == null || pingPongDiff < 0 || pingPongDiff > 500) {
309
+ this.safariExtensionStatusChanged(false);
310
+ }
311
+ }
312
+ }
313
+
314
+ export const safariClient = new SafariClient();
315
+
316
+ export default {
317
+ safariClient
318
+ };
@@ -0,0 +1,200 @@
1
+ import {ErrorResponse, PromiseObject, TransferSpec} from '../models/models';
2
+
3
+ /**
4
+ * Generates promise object that can be resolved or rejected via functions
5
+ *
6
+ * @returns an object containing the promise, the resolver and rejecter
7
+ */
8
+ export const generatePromiseObjects = (): PromiseObject => {
9
+ let resolver: (response: any) => void;
10
+ let rejecter: (response: any) => void;
11
+ const promise = new Promise((resolve, reject) => {
12
+ resolver = resolve;
13
+ rejecter = reject;
14
+ });
15
+ return {
16
+ promise,
17
+ resolver,
18
+ rejecter
19
+ };
20
+ };
21
+
22
+ /**
23
+ * Log errors from Aspera SDK
24
+ *
25
+ * @param message the message indicating the error encountered
26
+ * @param debugData the data with useful debugging information
27
+ */
28
+ export const errorLog = (message: string, debugData?: any): void => {
29
+ if (debugData && debugData.code && debugData.message) {
30
+ debugData = {
31
+ code: debugData.code,
32
+ message: debugData.message,
33
+ data: debugData.data
34
+ };
35
+ }
36
+
37
+ if (typeof (<any>window) === 'object') {
38
+ if (!Array.isArray((<any>window).asperaSdkLogs)) {
39
+ (<any>window).asperaSdkLogs = [];
40
+ }
41
+ (<any>window).asperaSdkLogs.push({message, debugData});
42
+ }
43
+
44
+ console.warn(`Aspera SDK: ${message}`, debugData);
45
+ };
46
+
47
+ /**
48
+ * Generate error object for rejecter responses
49
+ *
50
+ * @param message the message indicating the error encountered
51
+ * @param debugData the data with useful debugging information
52
+ *
53
+ * @returns object containing standardized error response
54
+ */
55
+ export const generateErrorBody = (message: string, debugData?: any): ErrorResponse => {
56
+ const errorResponse: ErrorResponse = {
57
+ error: true,
58
+ message
59
+ };
60
+
61
+ if (debugData && debugData.code && debugData.message) {
62
+ errorResponse.debugData = {
63
+ code: debugData.code,
64
+ message: debugData.message,
65
+ data: debugData.data
66
+ };
67
+ }
68
+
69
+ return errorResponse;
70
+ };
71
+
72
+ /**
73
+ * Validate if transferSpec is valid for server communication
74
+ *
75
+ * @param transferSpec the transferSpec to test
76
+ *
77
+ * @returns boolean indicating whether supplied transferSpec is valid
78
+ */
79
+ export const isValidTransferSpec = (transferSpec: TransferSpec): boolean => {
80
+ if (
81
+ transferSpec &&
82
+ typeof transferSpec === 'object' &&
83
+ typeof transferSpec.direction === 'string' &&
84
+ typeof transferSpec.remote_host === 'string' &&
85
+ Array.isArray(transferSpec.paths)
86
+ ) {
87
+ return true;
88
+ }
89
+
90
+ return false;
91
+ };
92
+
93
+ /**
94
+ * Returns a string indicating the websocket URL to use for talking to the server
95
+ *
96
+ * @returns a string of the full Websocket URL
97
+ */
98
+ export const getWebsocketUrl = (serverUrl: string): string => {
99
+ let wsProtocol;
100
+ if (serverUrl.indexOf('http:') === 0) {
101
+ wsProtocol = 'ws';
102
+ } else if (serverUrl.indexOf('https:') === 0) {
103
+ wsProtocol = 'wss';
104
+ }
105
+ const url = serverUrl.replace('http://', '//').replace('https://', '//');
106
+
107
+ return `${wsProtocol}:${url}`;
108
+ };
109
+
110
+ /**
111
+ * Simple function to get the current platform.
112
+ *
113
+ * @returns a string indicating the current platform
114
+ */
115
+ export const getCurrentPlatform = (): 'macos'|'windows'|'linux'|'unknown' => {
116
+ const ua = navigator.userAgent;
117
+
118
+ if (/Mac/.test(ua)) {
119
+ return 'macos';
120
+ } else if (/Win/.test(ua)) {
121
+ return 'windows';
122
+ } else if (/Linux/.test(ua)) {
123
+ return 'linux';
124
+ } else {
125
+ return 'unknown';
126
+ }
127
+ };
128
+
129
+ /**
130
+ * Function used to create a random UUID
131
+ *
132
+ * @returns string
133
+ */
134
+ export const randomUUID = (): string => {
135
+ const fallback = (): string => {
136
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
137
+ let r = Number(((new Date().getTime() + 16) * Math.random()).toFixed()) % 16;
138
+ if (c !== 'x') {
139
+ // eslint-disable-next-line no-bitwise
140
+ r = r & 0x3 | 0x8;
141
+ }
142
+ return r.toString(16);
143
+ });
144
+ };
145
+
146
+ return window.crypto?.randomUUID ? window.crypto.randomUUID() : fallback();
147
+ };
148
+
149
+ /**
150
+ * Return a rejected promise
151
+ *
152
+ * @param message the message indicating the error encountered
153
+ * @param debugData the data with useful debugging information
154
+ *
155
+ * @returns a rejected promise
156
+ */
157
+ export const throwError = (message: string, debugData?: any): Promise<any> => {
158
+ errorLog(message, debugData);
159
+ return new Promise((resolve, reject) => {
160
+ reject(generateErrorBody(message, debugData));
161
+ });
162
+ };
163
+
164
+ /**
165
+ * Check if the given string is a valid URL
166
+ *
167
+ * @param url string to check if valid URL
168
+ *
169
+ * @returns boolean
170
+ */
171
+ export const isValidURL = (url: string): boolean => {
172
+ try {
173
+ new URL(url);
174
+ return true;
175
+ } catch(error) {
176
+ return false;
177
+ }
178
+ };
179
+
180
+ /**
181
+ * Checks if the current browser is Safari.
182
+ * @returns {boolean} Whether the browser is Safari.
183
+ */
184
+ export const isSafari = (): boolean => {
185
+ // eslint-disable-next-line
186
+ return /^((?!chrome|android).)*safari/i.test(navigator.userAgent) && !(window as any).MSStream;
187
+ };
188
+
189
+ export default {
190
+ errorLog,
191
+ generateErrorBody,
192
+ generatePromiseObjects,
193
+ getCurrentPlatform,
194
+ getWebsocketUrl,
195
+ isSafari,
196
+ isValidURL,
197
+ isValidTransferSpec,
198
+ randomUUID,
199
+ throwError,
200
+ };
@@ -0,0 +1,39 @@
1
+ import {generatePromiseObjects} from './helpers';
2
+
3
+ /**
4
+ * Check HTTP promise response for server error response (non 2XX status) and reject promise is error
5
+ *
6
+ * @param promise the HTTP promise to check for HTTP status code of 2XX for success
7
+ *
8
+ * @returns promise for the HTTP connection with catch supporting error
9
+ */
10
+ export const handlePromiseErrors = (promise: Promise<any>): Promise<any> => {
11
+ const promiseInfo = generatePromiseObjects();
12
+ promise.then(response => {
13
+ if (response.ok) {
14
+ promiseInfo.resolver(response);
15
+ } else {
16
+ promiseInfo.rejecter(response);
17
+ }
18
+ return response;
19
+ }).catch(error => {
20
+ promiseInfo.rejecter(error);
21
+ });
22
+ return promiseInfo.promise;
23
+ };
24
+
25
+
26
+ /**
27
+ * Make a GET for retrieving data from a server
28
+ *
29
+ * @param url the url string of the resource on the server
30
+ *
31
+ * @returns a promise that will resolve with the response from the server or reject if network/server error
32
+ */
33
+ export const apiGet = (url: string): Promise<any> => {
34
+ return handlePromiseErrors(fetch(url, {
35
+ headers: {
36
+ 'Content-Type': 'application/json',
37
+ },
38
+ }));
39
+ };