@ibm-aspera/sdk 0.2.9 → 0.2.29

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 (110) hide show
  1. package/.editorconfig +13 -0
  2. package/.github/CODEOWNERS +1 -0
  3. package/.github/CODE_OF_CONDUCT.md +128 -0
  4. package/.github/CONTRIBUTING.md +147 -0
  5. package/.github/dependabot.yml +10 -0
  6. package/.github/workflows/ci.yml +39 -0
  7. package/.github/workflows/documentation.yml +44 -0
  8. package/.github/workflows/publish.yml +23 -0
  9. package/.github/workflows/version.yml +32 -0
  10. package/CHANGELOG.md +204 -0
  11. package/docs/DEVELOPMENT.md +38 -0
  12. package/eslint.config.js +104 -0
  13. package/example/README.md +7 -0
  14. package/example/index.html +14 -0
  15. package/example/package-lock.json +2989 -0
  16. package/example/package.json +30 -0
  17. package/example/public/404.html +5 -0
  18. package/example/public/sdk-code.js +326 -0
  19. package/example/src/App/App.scss +40 -0
  20. package/example/src/App/index.tsx +196 -0
  21. package/example/src/Views/AllTogether.tsx +26 -0
  22. package/example/src/Views/DragDrop.tsx +23 -0
  23. package/example/src/Views/Home.tsx +10 -0
  24. package/example/src/Views/Initialize.tsx +31 -0
  25. package/example/src/Views/Installer.tsx +154 -0
  26. package/example/src/Views/MonitorTransfers.tsx +88 -0
  27. package/example/src/Views/Other.tsx +24 -0
  28. package/example/src/Views/SelectItems.tsx +46 -0
  29. package/example/src/Views/StartTransfer.tsx +37 -0
  30. package/example/src/Views/Test.tsx +20 -0
  31. package/example/src/Views/Views.scss +111 -0
  32. package/example/src/helpers/index.ts +19 -0
  33. package/example/src/index.scss +47 -0
  34. package/example/src/main.tsx +17 -0
  35. package/example/src/vite-env.d.ts +2 -0
  36. package/example/tsconfig.json +30 -0
  37. package/example/vite.config.ts +23 -0
  38. package/jest.config.js +19 -0
  39. package/jest.setup.js +0 -0
  40. package/package.json +15 -21
  41. package/renovate.json +12 -0
  42. package/scripts/version.sh +24 -0
  43. package/src/app/core.ts +765 -0
  44. package/src/app/installer.ts +53 -0
  45. package/src/connect/core.ts +83 -0
  46. package/src/constants/constants.ts +19 -0
  47. package/src/constants/messages.ts +35 -0
  48. package/src/helpers/client/client.ts +11 -0
  49. package/src/helpers/client/http-client.ts +92 -0
  50. package/src/helpers/client/safari-client.ts +334 -0
  51. package/src/helpers/helpers.ts +253 -0
  52. package/src/helpers/http.ts +39 -0
  53. package/src/helpers/ws.ts +191 -0
  54. package/src/http-gateway/core.ts +273 -0
  55. package/src/http-gateway/download.ts +217 -0
  56. package/src/http-gateway/index.ts +19 -0
  57. package/src/http-gateway/models.ts +20 -0
  58. package/src/http-gateway/upload.ts +148 -0
  59. package/src/index.ts +72 -0
  60. package/src/models/aspera-sdk.model.ts +446 -0
  61. package/src/models/models.ts +740 -0
  62. package/tests/client.spec.ts +52 -0
  63. package/tests/core.spec.ts +13 -0
  64. package/tests/helpers.spec.ts +127 -0
  65. package/tests/http.spec.ts +14 -0
  66. package/tests/installer.spec.ts +135 -0
  67. package/tests/mocks.ts +11 -0
  68. package/tsconfig.json +14 -0
  69. package/tsconfig.module.json +16 -0
  70. package/typedoc.js +7 -0
  71. package/webpack.config.js +35 -0
  72. package/dist/commonjs/app/core.d.ts +0 -205
  73. package/dist/commonjs/app/core.js +0 -615
  74. package/dist/commonjs/app/installer.d.ts +0 -9
  75. package/dist/commonjs/app/installer.js +0 -50
  76. package/dist/commonjs/constants/constants.d.ts +0 -8
  77. package/dist/commonjs/constants/constants.js +0 -11
  78. package/dist/commonjs/constants/messages.d.ts +0 -35
  79. package/dist/commonjs/constants/messages.js +0 -38
  80. package/dist/commonjs/helpers/client/client.d.ts +0 -5
  81. package/dist/commonjs/helpers/client/client.js +0 -7
  82. package/dist/commonjs/helpers/client/http-client.d.ts +0 -42
  83. package/dist/commonjs/helpers/client/http-client.js +0 -84
  84. package/dist/commonjs/helpers/client/safari-client.d.ts +0 -101
  85. package/dist/commonjs/helpers/client/safari-client.js +0 -264
  86. package/dist/commonjs/helpers/helpers.d.ts +0 -109
  87. package/dist/commonjs/helpers/helpers.js +0 -249
  88. package/dist/commonjs/helpers/http.d.ts +0 -16
  89. package/dist/commonjs/helpers/http.js +0 -42
  90. package/dist/commonjs/helpers/ws.d.ts +0 -62
  91. package/dist/commonjs/helpers/ws.js +0 -176
  92. package/dist/commonjs/http-gateway/core.d.ts +0 -76
  93. package/dist/commonjs/http-gateway/core.js +0 -254
  94. package/dist/commonjs/http-gateway/download.d.ts +0 -14
  95. package/dist/commonjs/http-gateway/download.js +0 -186
  96. package/dist/commonjs/http-gateway/index.d.ts +0 -11
  97. package/dist/commonjs/http-gateway/index.js +0 -11
  98. package/dist/commonjs/http-gateway/models.d.ts +0 -16
  99. package/dist/commonjs/http-gateway/models.js +0 -2
  100. package/dist/commonjs/http-gateway/upload.d.ts +0 -14
  101. package/dist/commonjs/http-gateway/upload.js +0 -124
  102. package/dist/commonjs/index.d.ts +0 -8
  103. package/dist/commonjs/index.js +0 -104
  104. package/dist/commonjs/models/aspera-sdk.model.d.ts +0 -244
  105. package/dist/commonjs/models/aspera-sdk.model.js +0 -324
  106. package/dist/commonjs/models/models.d.ts +0 -692
  107. package/dist/commonjs/models/models.js +0 -2
  108. package/dist/js/aspera-sdk.js +0 -3
  109. package/dist/js/aspera-sdk.js.LICENSE.txt +0 -15
  110. package/dist/js/aspera-sdk.js.map +0 -1
@@ -0,0 +1,53 @@
1
+ import {asperaSdk} from '../index';
2
+ import {errorLog, generateErrorBody, generatePromiseObjects, getCurrentPlatform, isValidURL, throwError} from '../helpers/helpers';
3
+ import {apiGet} from '../helpers/http';
4
+ import {messages} from '../constants/messages';
5
+ import {InstallerInfoResponse, InstallerOptions} from '../models/models';
6
+
7
+ /**
8
+ * Get the latest Aspera SDK installer information such as download URL and version.
9
+ *
10
+ * @param options Installer info options
11
+ *
12
+ * @returns a promise that resolves with the installer info and rejects if there is an error
13
+ */
14
+ export const getInstallerInfo = (options: InstallerOptions = {}): Promise<InstallerInfoResponse> => {
15
+ let url = options.endpoint || asperaSdk.globals.installerUrl;
16
+
17
+ if (url.endsWith('/latest.json')) {
18
+ url = url.replace('/latest.json', '');
19
+ }
20
+
21
+ if (!isValidURL(url)) {
22
+ return throwError(messages.invalidEndpoint, {url});
23
+ }
24
+
25
+ const promiseInfo = generatePromiseObjects();
26
+
27
+ apiGet(`${url}/latest.json`).then(response => {
28
+ response.json().then((data: InstallerInfoResponse) => {
29
+ if (options.endpoint) {
30
+ for (const entry of data.entries) {
31
+ if (!isValidURL(entry.url)) {
32
+ entry.url = `${options.endpoint}/${entry.url}`;
33
+ }
34
+ }
35
+ }
36
+
37
+ if (options.all) {
38
+ promiseInfo.resolver(data);
39
+ } else {
40
+ const platform = getCurrentPlatform();
41
+ data.entries = data.entries.filter(entry => entry.platform === platform);
42
+
43
+ promiseInfo.resolver(data);
44
+ }
45
+ });
46
+ }).catch(error => {
47
+ errorLog(messages.getInstallerError, error);
48
+
49
+ promiseInfo.rejecter(generateErrorBody(messages.getInstallerError, error));
50
+ });
51
+
52
+ return promiseInfo.promise;
53
+ };
@@ -0,0 +1,83 @@
1
+ import {asperaSdk} from '../index';
2
+ import {Connect} from '@ibm-aspera/connect-sdk-js';
3
+ import * as ConnectTypes from '@ibm-aspera/connect-sdk-js/dist/esm/core/types';
4
+
5
+ let transferMonitorActivated = false;
6
+ let installerFlowActivated = false;
7
+
8
+ /**
9
+ * Connect Core Logic
10
+ *
11
+ * @remarks
12
+ * Most logic is called directly by Desktop SDK functions
13
+ * You may not need to import anything from this file.
14
+ */
15
+
16
+ export const handleTransfers = (transfers: ConnectTypes.TransferInfo[]): void => {
17
+ asperaSdk.activityTracking.handleTransferActivity({
18
+ type: 'transferUpdated',
19
+ data: {transfers},
20
+ });
21
+ };
22
+
23
+ export const connectInstallationFlow = (): void => {
24
+ if (installerFlowActivated) {
25
+ return;
26
+ }
27
+
28
+ installerFlowActivated = true;
29
+
30
+ const handleInstallerEvent = (eventType: ConnectTypes.EventString, eventStatus: ConnectTypes.ConnectStatusStrings) => {
31
+ // Verify that the event matches
32
+ if (asperaSdk.globals.connectAW4.Connect.EVENT.STATUS !== eventType) {
33
+ return;
34
+ }
35
+
36
+ // Depending on status show the proper installer screen
37
+ switch (eventStatus) {
38
+ case asperaSdk.globals.connectAW4.Connect.STATUS.INITIALIZING:
39
+ asperaSdk.globals.connectInstaller.showLaunching();
40
+ break;
41
+ case asperaSdk.globals.connectAW4.Connect.STATUS.EXTENSION_INSTALL:
42
+ asperaSdk.globals.connectInstaller.showExtensionInstall();
43
+ break;
44
+ case asperaSdk.globals.connectAW4.Connect.STATUS.FAILED:
45
+ asperaSdk.globals.connectInstaller.showDownload();
46
+ break;
47
+ case asperaSdk.globals.connectAW4.Connect.STATUS.OUTDATED:
48
+ asperaSdk.globals.connectInstaller.showUpdate();
49
+ break;
50
+ case asperaSdk.globals.connectAW4.Connect.STATUS.RUNNING:
51
+ asperaSdk.globals.connectInstaller.connected();
52
+ break;
53
+ }
54
+ };
55
+
56
+ asperaSdk.globals.connect.addEventListener(asperaSdk.globals.connectAW4.Connect.EVENT.STATUS, handleInstallerEvent);
57
+ };
58
+
59
+ export const initConnect = (useIncludedInstaller?: boolean): Promise<unknown> => {
60
+ asperaSdk.globals.connect.addEventListener(Connect.EVENT.STATUS, (eventType, eventStatus: ConnectTypes.ConnectStatusStrings) => {
61
+ if (eventType === Connect.EVENT.STATUS) {
62
+ asperaSdk.globals.connectStatus = eventStatus;
63
+
64
+ asperaSdk.activityTracking.sendManualEventCallback(eventStatus);
65
+
66
+ if (eventStatus === 'RUNNING' && !transferMonitorActivated) {
67
+ transferMonitorActivated = true;
68
+ asperaSdk.globals.connect.addEventListener(Connect.EVENT.TRANSFER, (_event, data: ConnectTypes.AllTransfersInfo) => {
69
+ handleTransfers(data.transfers);
70
+ });
71
+ }
72
+ }
73
+ });
74
+
75
+ asperaSdk.globals.connect.initSession(asperaSdk.globals.appId);
76
+
77
+ if (useIncludedInstaller) {
78
+ connectInstallationFlow();
79
+ }
80
+
81
+
82
+ return Promise.resolve({connectMode: true});
83
+ };
@@ -0,0 +1,19 @@
1
+ /** @ignore */
2
+ export const hiddenStyleList = `
3
+ display: none !important;
4
+ width: 1px !important;
5
+ height: 1px !important;
6
+ position: fixed !important;
7
+ z-index: -99 !important;
8
+ bottom: 0px !important;
9
+ right: 0px !important;
10
+ `;
11
+
12
+ /** @ignore */
13
+ export const protocol = 'aspera://';
14
+
15
+ /** @ignore */
16
+ export const baseInstallerUrl = 'https://downloads.ibmaspera.com/downloads/desktop';
17
+
18
+ /** @ignore */
19
+ export const installerUrl = `${baseInstallerUrl}/latest/stable`;
@@ -0,0 +1,35 @@
1
+ /** @ignore */
2
+ export const messages = {
3
+ callbackIsNotFunction: 'The provided callback is not a function',
4
+ dragDropInitFailed: 'Unable to initialize drag-drop',
5
+ dragDropInitFailedInit: 'Unable to initialize drag-drop as part of init flow',
6
+ failedToGenerateIframe: 'Unable to generate IFRAME for download. Using new window',
7
+ getInstallerError: 'Unable to get latest installers',
8
+ getAllTransfersFailed: 'Unable to get all transfers',
9
+ getTransferFailed: 'Unable to get transfer',
10
+ invalidEndpoint: 'The specified endpoint is not a valid URL',
11
+ loadingProtocol: 'Launching IBM Aspera for Desktop',
12
+ modifyTransferFailed: 'Unable to modify transfer',
13
+ notValidTransferSpec: 'The supplied transferSpec is not valid',
14
+ removeTransferFailed: 'Unable to remove transfer',
15
+ resumeTransferFailed: 'Unable to resume transfer',
16
+ serverError: 'Unable to connect to IBM Aspera for Desktop server',
17
+ serverNotVerified: 'IBM Aspera SDK has not been verified. Run test or init first',
18
+ setBrandingFailed: 'Unable to set custom branding',
19
+ showDirectoryFailed: 'Unable to show transfer directory',
20
+ showSelectFileDialogFailed: 'Unable to show select file dialog',
21
+ showSelectFolderDialogFailed: 'Unable to show select folder dialog',
22
+ showPreferencesFailed: 'Unable to show preferences',
23
+ stopTransferFailed: 'Unable to stop transfer',
24
+ transferFailed: 'The transfer failed to initiate',
25
+ unableToFindElementOnPage: 'Unable to find the element on the current page',
26
+ unableToReadDropped: 'The dropped item could not be parsed. Please try selecting via the select file/folder option',
27
+ websocketClosedError: 'The websocket was closed due to an error',
28
+ websocketClosedUnexpect: 'The websocket was closed unexpectedly',
29
+ websocketNotReady: 'The websocket is not ready. Run init first',
30
+ httpNotAvailable: 'IBM Aspera HTTP Gateway is not available',
31
+ httpInitFail: 'IBM Aspera HTTP Gateway could not be started',
32
+ filePickerCancel: 'User canceled the select file or folder dialog.',
33
+ fileNotAllowed: 'TransferSpec contained file not selected by user.',
34
+ httpNetworkFail: 'HTTP network encountered unknown error.',
35
+ };
@@ -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, safeJsonString} 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: safeJsonString(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,334 @@
1
+ import Client from './client';
2
+ import {randomUUID, safeJsonString} 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 keepAliveInterval = 1000;
52
+ private promiseExecutors: Map<string, PromiseExecutor>;
53
+
54
+ private lastPing: number|null = null;
55
+ private lastPong: number|null = null;
56
+ private safariExtensionEnabled = false;
57
+ private subscribedTransferActivity = false;
58
+
59
+ /**
60
+ * Initializes the SafariExtensionHandler instance.
61
+ * Sets up the promise executor map and starts listening to extension events.
62
+ */
63
+ constructor() {
64
+ this.promiseExecutors = new Map();
65
+ this.listenResponseEvents();
66
+ this.listenTransferActivityEvents();
67
+ this.listenStatusEvents();
68
+ this.listenClientStatusEvents();
69
+ this.listenPongEvents();
70
+
71
+ if (keepAliveTimeout) {
72
+ clearTimeout(keepAliveTimeout);
73
+ }
74
+
75
+ this.keepAlive();
76
+ }
77
+
78
+ /**
79
+ * Sends a JSON-RPC request to the Safari extension.
80
+ * @param method The method name to invoke on the extension.
81
+ * @param payload Optional payload for the request.
82
+ * @returns A Promise that resolves with the response from the extension.
83
+ */
84
+ request = (method: string, payload: any = {}): Promise<any> => {
85
+ return this.dispatchPromiseEvent(
86
+ SafariExtensionEventType.Request,
87
+ method,
88
+ payload
89
+ );
90
+ };
91
+
92
+ /**
93
+ * Monitors transfer activity.
94
+ * @returns A Promise that resolves with the response from the extension.
95
+ */
96
+ public monitorTransferActivity(): Promise<unknown> {
97
+ const dispatchMonitorEvent = (): Promise<unknown> => {
98
+ const promise = this.dispatchPromiseEvent(
99
+ SafariExtensionEventType.Monitor,
100
+ 'subscribe_transfer_activity',
101
+ [asperaSdk.globals.appId]
102
+ );
103
+
104
+ return promise.then(() => {
105
+ this.subscribedTransferActivity = true;
106
+ });
107
+ };
108
+
109
+ if (this.safariExtensionEnabled) {
110
+ return dispatchMonitorEvent();
111
+ }
112
+
113
+ return new Promise((resolve, reject) => {
114
+ const extensionInterval = setInterval(() => {
115
+ if (!this.safariExtensionEnabled) {
116
+ return;
117
+ }
118
+
119
+ dispatchMonitorEvent()
120
+ .then(resolve)
121
+ .catch(reject);
122
+
123
+ clearInterval(extensionInterval);
124
+ }, 1000);
125
+ });
126
+ }
127
+
128
+ /**
129
+ * Builds a JSON-RPC request object with a unique identifier.
130
+ * @param method The method name to invoke on the extension.
131
+ * @param payload Optional parameters for the method.
132
+ * @returns The constructed JSON-RPC request object.
133
+ */
134
+ private buildRPCRequest(method: string, payload?: unknown): JSONRPCRequest {
135
+ return {
136
+ jsonrpc: '2.0',
137
+ method,
138
+ params: payload,
139
+ id: randomUUID()
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Dispatches a custom event to the document to communicate with the Safari extension.
145
+ * @param type The type of Safari extension event to dispatch.
146
+ * @param request Optional JSON-RPC request payload to send with the event.
147
+ */
148
+ private dispatchEvent(type: SafariExtensionEventType, request?: JSONRPCRequest) {
149
+ const payload = {
150
+ detail: request ?? {}
151
+ };
152
+
153
+ document.dispatchEvent(new CustomEvent(`AsperaDesktop.${type}`, payload));
154
+ }
155
+
156
+ /**
157
+ * Dispatches a custom event to the document to communicate with the Safari extension.
158
+ * @param type The type of Safari extension event to dispatch.
159
+ * @param method The method name to invoke on the extension.
160
+ * @param payload Optional parameters for the method.
161
+ */
162
+ private dispatchPromiseEvent(type: SafariExtensionEventType, method: string, payload?: unknown): Promise<any> {
163
+ const request = this.buildRPCRequest(method, payload);
164
+
165
+ return new Promise<any>((resolve, reject) => {
166
+ if (this.safariExtensionEnabled) {
167
+ this.promiseExecutors.set(request.id, {resolve, reject});
168
+
169
+ this.dispatchEvent(type, request);
170
+ } else {
171
+ console.warn('The Safari extension is disabled or unresponsive (dispatch event)');
172
+ console.warn(`Failed event: ${safeJsonString(request)}`);
173
+
174
+ reject('The Safari extension is disabled or unresponsive (dispatch event)');
175
+ }
176
+ });
177
+ }
178
+
179
+ /**
180
+ * Handles incoming JSON-RPC responses from the Safari extension.
181
+ * Resolves or rejects promises based on the response.
182
+ * @param response The JSON-RPC response object received from the extension.
183
+ */
184
+ private handleResponse(response: JSONRPCResponse) {
185
+ const requestId = response.id;
186
+ const executor = this.promiseExecutors.get(requestId);
187
+
188
+ if (!executor) {
189
+ console.warn(`Unable to find a promise executor for ${requestId}`);
190
+ console.warn(`Response: ${response}`);
191
+ return;
192
+ }
193
+
194
+ this.promiseExecutors.delete(requestId);
195
+
196
+ if (response.error) {
197
+ executor.reject(response.error);
198
+ return;
199
+ }
200
+
201
+ executor.resolve(response.result);
202
+ }
203
+
204
+ /**
205
+ * Listens for 'AsperaDesktop.Response' events.
206
+ */
207
+ private listenResponseEvents() {
208
+ document.addEventListener('AsperaDesktop.Response', (event: CustomEvent<JSONRPCResponse>) => {
209
+ if (!event.detail) {
210
+ return;
211
+ }
212
+
213
+ this.handleResponse(event.detail);
214
+ });
215
+ }
216
+
217
+ /**
218
+ * Listens for 'AsperaDesktop.TransferActivity' events.
219
+ */
220
+ private listenTransferActivityEvents() {
221
+ document.addEventListener('AsperaDesktop.TransferActivity', (event: any) => {
222
+ if (!event.detail) {
223
+ return;
224
+ }
225
+
226
+ asperaSdk.activityTracking.handleTransferActivity(event.detail);
227
+ });
228
+ }
229
+
230
+ /**
231
+ * Listens for 'AsperaDesktop.Status' events.
232
+ */
233
+ private listenStatusEvents() {
234
+ document.addEventListener('AsperaDesktop.Status', (event: any) => {
235
+ if (!event.detail) {
236
+ return;
237
+ }
238
+
239
+ asperaSdk.activityTracking.handleWebSocketEvents(event.detail);
240
+ });
241
+ }
242
+
243
+ /**
244
+ * Listens for 'isAppAlive' events. This was introduced in version 1.0.9.
245
+ */
246
+ private listenClientStatusEvents() {
247
+ document.addEventListener('isAppAlive', (event: any) => {
248
+ if (!event.detail?.running) {
249
+ return;
250
+ }
251
+
252
+ asperaSdk.activityTracking.handleClientEvents(event.detail.running);
253
+ });
254
+ }
255
+
256
+ /**
257
+ * Listens for 'AsperaDesktop.Pong' events.
258
+ */
259
+ private listenPongEvents() {
260
+ document.addEventListener('AsperaDesktop.Pong', () => {
261
+ this.lastPong = Date.now();
262
+ this.safariExtensionStatusChanged(true);
263
+ });
264
+ }
265
+
266
+ /**
267
+ * Sends a keep alive ping according to the defined interval.
268
+ */
269
+ private keepAlive() {
270
+ this.lastPing = Date.now();
271
+ this.dispatchEvent(SafariExtensionEventType.Ping);
272
+
273
+ keepAliveTimeout = setTimeout(() => {
274
+ this.keepAlive();
275
+ }, this.keepAliveInterval);
276
+ }
277
+
278
+ /**
279
+ * Listens for Safari extension status changes.
280
+ * If the extension was disabled and enabled again after initializing the SDK, it
281
+ * will call 'monitorTransferActivity' to resume transfer activities.
282
+ */
283
+ private safariExtensionStatusChanged(isEnabled: boolean) {
284
+ if (isEnabled === this.safariExtensionEnabled) {
285
+ return;
286
+ }
287
+
288
+ this.safariExtensionEnabled = isEnabled;
289
+
290
+ if (isEnabled) {
291
+ if (this.subscribedTransferActivity) {
292
+ const resumeTransferActivity = () => {
293
+ this.monitorTransferActivity()
294
+ .catch(() => {
295
+ console.error('Failed to resume transfer activity, will try again in 1s');
296
+
297
+ setTimeout(() => {
298
+ resumeTransferActivity();
299
+ }, 1000);
300
+ });
301
+ };
302
+
303
+ resumeTransferActivity();
304
+ }
305
+ } else {
306
+ asperaSdk.activityTracking.handleWebSocketEvents('CLOSED');
307
+
308
+ this.promiseExecutors.forEach((promiseExecutor) => {
309
+ promiseExecutor.reject('The Safari extension is disabled or unresponsive (extension status)');
310
+ });
311
+
312
+ this.promiseExecutors.clear();
313
+ }
314
+
315
+ asperaSdk.activityTracking.handleSafariExtensionEvents(this.safariExtensionEnabled ? 'ENABLED' : 'DISABLED');
316
+ }
317
+
318
+ /**
319
+ * Checks if the last pong received was longer than the max interval.
320
+ */
321
+ private checkSafariExtensionStatus() {
322
+ const pingPongDiff = this.lastPong - this.lastPing;
323
+
324
+ if (this.lastPong == null || pingPongDiff < 0 || pingPongDiff > 500) {
325
+ this.safariExtensionStatusChanged(false);
326
+ }
327
+ }
328
+ }
329
+
330
+ export const safariClient = new SafariClient();
331
+
332
+ export default {
333
+ safariClient
334
+ };