@interopio/browser-platform 3.0.1

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 (97) hide show
  1. package/browser.platform.d.ts +455 -0
  2. package/changelog.md +69 -0
  3. package/dist/browser.platform.es.js +46074 -0
  4. package/dist/browser.platform.es.js.map +1 -0
  5. package/dist/browser.platform.umd.js +46082 -0
  6. package/dist/browser.platform.umd.js.map +1 -0
  7. package/license.md +21 -0
  8. package/package.json +78 -0
  9. package/readme.md +9 -0
  10. package/rollup.config.js +45 -0
  11. package/src/common/constants.ts +46 -0
  12. package/src/common/defaultConfig.ts +56 -0
  13. package/src/common/gateway.d.ts +32 -0
  14. package/src/common/types.ts +222 -0
  15. package/src/connection/gateway.ts +132 -0
  16. package/src/connection/no-gateway.ts +1 -0
  17. package/src/connection/portsBridge.ts +441 -0
  18. package/src/connection/preferred.ts +247 -0
  19. package/src/controllers/domains.ts +156 -0
  20. package/src/controllers/glue.ts +604 -0
  21. package/src/controllers/interception.ts +53 -0
  22. package/src/controllers/license.ts +50 -0
  23. package/src/controllers/main.ts +256 -0
  24. package/src/controllers/plugins.ts +121 -0
  25. package/src/controllers/serviceWorker.ts +193 -0
  26. package/src/controllers/state.ts +84 -0
  27. package/src/controllers/system.ts +99 -0
  28. package/src/controllers/transactions.ts +80 -0
  29. package/src/factory.ts +40 -0
  30. package/src/fallbacks/browser.ts +47 -0
  31. package/src/fallbacks/dekstop.ts +21 -0
  32. package/src/index.ts +18 -0
  33. package/src/libs/applications/appStore/directory.ts +235 -0
  34. package/src/libs/applications/appStore/remoteWatcher.ts +112 -0
  35. package/src/libs/applications/controller.ts +469 -0
  36. package/src/libs/applications/decoders.ts +98 -0
  37. package/src/libs/applications/defaults.ts +6 -0
  38. package/src/libs/applications/types.ts +98 -0
  39. package/src/libs/channels/controller.ts +109 -0
  40. package/src/libs/channels/decoders.ts +19 -0
  41. package/src/libs/extension/controller.ts +120 -0
  42. package/src/libs/extension/decoders.ts +18 -0
  43. package/src/libs/extension/types.ts +11 -0
  44. package/src/libs/intents/constants.ts +9 -0
  45. package/src/libs/intents/controller.ts +500 -0
  46. package/src/libs/intents/decoders.ts +96 -0
  47. package/src/libs/intents/resolverHelper.ts +264 -0
  48. package/src/libs/intents/types.ts +119 -0
  49. package/src/libs/layouts/constants.ts +3 -0
  50. package/src/libs/layouts/controller.ts +476 -0
  51. package/src/libs/layouts/decoders.ts +132 -0
  52. package/src/libs/layouts/global/builder.ts +400 -0
  53. package/src/libs/layouts/global/resetter.ts +116 -0
  54. package/src/libs/layouts/global/restorer.ts +217 -0
  55. package/src/libs/layouts/global/validator.ts +169 -0
  56. package/src/libs/layouts/idbStore.ts +63 -0
  57. package/src/libs/layouts/types.ts +133 -0
  58. package/src/libs/manager/controller.ts +175 -0
  59. package/src/libs/manager/decoders.ts +6 -0
  60. package/src/libs/manager/defaults.ts +5 -0
  61. package/src/libs/manager/identity.ts +92 -0
  62. package/src/libs/manager/session.ts +195 -0
  63. package/src/libs/manager/types.ts +51 -0
  64. package/src/libs/notifications/controller.ts +447 -0
  65. package/src/libs/notifications/decoders.ts +166 -0
  66. package/src/libs/notifications/types.ts +49 -0
  67. package/src/libs/notifications/utils.ts +7 -0
  68. package/src/libs/search/controller.ts +232 -0
  69. package/src/libs/search/decoders.ts +6 -0
  70. package/src/libs/search/repositories/applications.ts +62 -0
  71. package/src/libs/search/repositories/layouts.ts +48 -0
  72. package/src/libs/search/repositories/workspaces.ts +47 -0
  73. package/src/libs/search/types.ts +9 -0
  74. package/src/libs/themes/constants.ts +9 -0
  75. package/src/libs/themes/controller.ts +153 -0
  76. package/src/libs/themes/decoders.ts +28 -0
  77. package/src/libs/themes/types.ts +28 -0
  78. package/src/libs/windows/controller.ts +498 -0
  79. package/src/libs/windows/decoders.ts +64 -0
  80. package/src/libs/windows/types.ts +59 -0
  81. package/src/libs/workspaces/controller.ts +922 -0
  82. package/src/libs/workspaces/decoders.ts +868 -0
  83. package/src/libs/workspaces/defaultConfig.ts +11 -0
  84. package/src/libs/workspaces/frames.ts +239 -0
  85. package/src/libs/workspaces/hibernationWatcher.ts +231 -0
  86. package/src/libs/workspaces/types.ts +506 -0
  87. package/src/platform.ts +156 -0
  88. package/src/shared/decoders.ts +479 -0
  89. package/src/shared/fetchTimeout.ts +25 -0
  90. package/src/shared/ioc.ts +580 -0
  91. package/src/shared/logger.ts +19 -0
  92. package/src/shared/promisePlus.ts +62 -0
  93. package/src/shared/sequelizer.ts +48 -0
  94. package/src/shared/utils.ts +86 -0
  95. package/src/storage/local.ts +111 -0
  96. package/src/storage/session.ts +436 -0
  97. package/tsconfig.json +16 -0
@@ -0,0 +1,50 @@
1
+ import { KJUR, b64utoutf8 } from "jsrsasign";
2
+ import { LicenseTypes } from "../common/types";
3
+
4
+ export class LicenseController {
5
+ private _key = [52, 50, 52, 50, 52, 50];
6
+
7
+ public verifyLicense(token?: string): { valid: boolean } {
8
+
9
+ if (!token || typeof token !== "string") {
10
+ return { valid: false };
11
+ }
12
+
13
+ const isValid = KJUR.jws.JWS.verifyJWT(token, this.key, { alg: ["HS256"] });
14
+
15
+ return { valid: isValid };
16
+ }
17
+
18
+ public getLicensePayload(token?: string): { type: LicenseTypes, expiration: number } {
19
+
20
+ if (!token) {
21
+ throw new Error("No license key was provided");
22
+ }
23
+
24
+ const payload = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(token.split(".")[1])) as { type: LicenseTypes, expiration: number };
25
+
26
+ if (!payload || typeof payload.type !== "string" || typeof payload.expiration !== "number") {
27
+ throw new Error("The license key payload is invalid");
28
+ }
29
+
30
+ payload.type = payload.type.toLowerCase() as LicenseTypes;
31
+
32
+ return payload;
33
+
34
+ }
35
+
36
+ public checkExpired(expiration: number): boolean {
37
+
38
+ if (!expiration || typeof expiration !== "number") {
39
+ return false;
40
+ }
41
+
42
+ const secondsSinceEpoch = Math.floor((new Date()).getTime() / 1000);
43
+
44
+ return expiration <= secondsSinceEpoch;
45
+ }
46
+
47
+ private get key(): string {
48
+ return String.fromCharCode(...this._key);
49
+ }
50
+ }
@@ -0,0 +1,256 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { IOConnectBrowser } from "@interopio/browser";
3
+ import { UnsubscribeFunction } from "callback-registry";
4
+ import { CoreClientData, InternalPlatformConfig } from "../common/types";
5
+ import { GlueController } from "./glue";
6
+ import { PortsBridge } from "../connection/portsBridge";
7
+ import { WindowsStateController } from "./state";
8
+ import logger from "../shared/logger";
9
+ import { generate } from "shortid";
10
+ import { IOConnectBrowserPlatform } from "../../browser.platform";
11
+ import { ServiceWorkerController } from "./serviceWorker";
12
+ import { PreferredConnectionController } from "../connection/preferred";
13
+ import { IOConnectCore } from "@interopio/core";
14
+ import { InterceptionController } from "./interception";
15
+ import { PluginsController } from "./plugins";
16
+ import { DomainsController } from "./domains";
17
+ import { SessionStorageController } from "../storage/session";
18
+ import { extractErrorMsg } from "../shared/utils";
19
+ import { LicenseController } from "./license";
20
+ import { LocalStoreController } from "../storage/local";
21
+
22
+ export class PlatformController {
23
+
24
+ private _platformApi!: IOConnectBrowserPlatform.API;
25
+
26
+ constructor(
27
+ private readonly domainsController: DomainsController,
28
+ private readonly glueController: GlueController,
29
+ private readonly portsBridge: PortsBridge,
30
+ private readonly stateController: WindowsStateController,
31
+ private readonly serviceWorkerController: ServiceWorkerController,
32
+ private readonly preferredConnectionController: PreferredConnectionController,
33
+ private readonly interceptionController: InterceptionController,
34
+ private readonly pluginsController: PluginsController,
35
+ private readonly sessionController: SessionStorageController,
36
+ private readonly licenseController: LicenseController,
37
+ private readonly localStorageController: LocalStoreController
38
+ ) {}
39
+
40
+ private get logger(): IOConnectBrowser.Logger.API | undefined {
41
+ return logger.get("main.web.platform");
42
+ }
43
+
44
+ public get ctxTrackingGlue(): IOConnectCore.API | undefined {
45
+ return this.glueController.contextsTrackingGlue;
46
+ }
47
+
48
+ public get systemGlue(): IOConnectCore.API | undefined {
49
+ return this.glueController.systemGlue;
50
+ }
51
+
52
+ public get platformApi(): IOConnectBrowserPlatform.API {
53
+ return this._platformApi;
54
+ }
55
+
56
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
57
+ public async start(config: InternalPlatformConfig): Promise<void> {
58
+ this.verifyLicense(config.licenseKey);
59
+
60
+ this.localStorageController.start(config.user);
61
+
62
+ await this.portsBridge.configure(config);
63
+
64
+ this.portsBridge.onClientUnloaded(this.handleClientUnloaded.bind(this));
65
+
66
+ await this.glueController.start(config);
67
+
68
+ await Promise.all([
69
+ this.glueController.createPlatformSystemMethod(this.handleClientMessage.bind(this)),
70
+ this.glueController.createPlatformSystemStream()
71
+ ]);
72
+
73
+ this.stateController.start();
74
+
75
+ await this.domainsController.startAllDomains(config);
76
+
77
+ this._platformApi = this.buildPlatformApi();
78
+
79
+ await this.glueController.initClientGlue(config?.browser, config?.browserFactory, config?.workspaces?.isFrame, this._platformApi);
80
+
81
+ await this.serviceWorkerController.connect(config);
82
+
83
+ await this.domainsController.configurePostStartAllDomains();
84
+
85
+ await this.pluginsController.start({
86
+ platformConfig: config,
87
+ plugins: config.plugins?.definitions,
88
+ api: this.platformApi,
89
+ handlePluginMessage: this.handlePluginMessage.bind(this)
90
+ });
91
+
92
+ if (config.connection) {
93
+ await this.preferredConnectionController.start(config.connection);
94
+ }
95
+
96
+ this.serviceWorkerController.notifyReady();
97
+
98
+ this.portsBridge.start();
99
+ }
100
+
101
+ public getClientGlue(): IOConnectBrowser.API {
102
+ return this.glueController.clientGlue;
103
+ }
104
+
105
+ private handleClientMessage(args: IOConnectBrowserPlatform.ControlMessage, caller: IOConnectBrowser.Interop.Instance, success: (args?: IOConnectBrowserPlatform.ControlMessage) => void, error: (error?: string | object) => void): void {
106
+ this.processControllerCommand(args, "client", caller.instance as string)
107
+ .then((result) => success(result))
108
+ .catch((err) => error(err));
109
+ }
110
+
111
+ private async handlePluginMessage(args: IOConnectBrowserPlatform.Plugins.BaseControlMessage, pluginName: string): Promise<any> {
112
+ return this.processControllerCommand(args, "plugin", pluginName);
113
+ }
114
+
115
+ private async processControllerCommand(args: IOConnectBrowserPlatform.Plugins.BaseControlMessage, callerType: "plugin" | "client", callerId: string): Promise<any> {
116
+ try {
117
+ this.domainsController.validateDomain(args.domain);
118
+ } catch (error) {
119
+ const errString = extractErrorMsg(error);
120
+
121
+ this.logger?.trace(`rejecting execution of a command issued by a ${callerType}: ${callerId}, because of a domain validation error: ${errString}`);
122
+
123
+ throw new Error(`Cannot execute this platform control, because of domain validation error: ${errString}`);
124
+ }
125
+
126
+ const controlMessage: IOConnectBrowserPlatform.ControlMessage = Object.assign({}, args, {
127
+ commandId: generate(),
128
+ callerId, callerType
129
+ });
130
+
131
+ this.logger?.trace(`[${controlMessage.commandId}] received a command for a valid domain: ${args.domain} from ${callerType}: ${callerId}, forwarding to the appropriate controller`);
132
+
133
+ try {
134
+ const result = await this.executeCommand(controlMessage);
135
+
136
+ this.logger?.trace(`[${controlMessage.commandId}] this command was executed successfully, sending the result to the caller.`);
137
+
138
+ return result;
139
+ } catch (error: any) {
140
+ const stringError = typeof error === "string" ?
141
+ error :
142
+ error.message ? JSON.stringify(error.message) :
143
+ JSON.stringify(error);
144
+
145
+ this.logger?.trace(`[${controlMessage.commandId}] this command's execution was rejected, reason: ${stringError}`);
146
+
147
+ throw new Error(`The platform rejected operation ${controlMessage.operation} for domain: ${args.domain} with reason: ${stringError}`);
148
+ }
149
+ }
150
+
151
+ private handleClientUnloaded(client: CoreClientData): void {
152
+ this.domainsController.notifyDomainsClientUnloaded(client);
153
+ }
154
+
155
+ private executeCommand(controlMessage: IOConnectBrowserPlatform.ControlMessage): Promise<any> {
156
+ const interceptor = this.interceptionController.getOperationInterceptor({ domain: controlMessage.domain, operation: controlMessage.operation });
157
+
158
+ if (interceptor && !controlMessage.settings?.skipInterception) {
159
+ this.logger?.trace(`[${controlMessage.commandId}] The operation is being intercepted and executed by: ${interceptor.name}`);
160
+
161
+ return interceptor.intercept(controlMessage);
162
+ }
163
+
164
+ return this.domainsController.executeControlMessage(controlMessage);
165
+ }
166
+
167
+ private buildPlatformApi(): IOConnectBrowserPlatform.API {
168
+ return {
169
+ version: this.glueController.platformVersion,
170
+ contextTrackGlue: this.ctxTrackingGlue,
171
+ systemGlue: this.systemGlue,
172
+ connectExtClient: (client: any, port: any) => {
173
+ return this.connectExtClient(client, port);
174
+ },
175
+ onSystemReconnect: (callback: () => void): UnsubscribeFunction => {
176
+ return this.onSystemReconnect(callback);
177
+ },
178
+ system: {
179
+ shutdown: this.shutDown.bind(this),
180
+ connection: {
181
+ switchGW: this.preferredConnectionController.connectPreferred.bind(this.preferredConnectionController),
182
+ switchToInternal: this.preferredConnectionController.revertToDefault.bind(this.preferredConnectionController),
183
+ }
184
+ }
185
+ } as IOConnectBrowserPlatform.API;
186
+ }
187
+
188
+ private async connectExtClient(client: any, port: any): Promise<void> {
189
+ await this.portsBridge.handleExtConnectionRequest(client, port);
190
+ }
191
+
192
+ private onSystemReconnect(callback: () => void): UnsubscribeFunction {
193
+ return this.preferredConnectionController.onReconnect(callback);
194
+ }
195
+
196
+ private async shutDown(): Promise<void> {
197
+ await this.glueController.sendShutDownSignals();
198
+
199
+ this.stateController.cancel();
200
+
201
+ this.portsBridge.shutdown();
202
+
203
+ this.domainsController.shutdown();
204
+
205
+ this.serviceWorkerController.shutdown();
206
+
207
+ await this.pluginsController.shutdown();
208
+
209
+ this.interceptionController.shutdown();
210
+
211
+ this.preferredConnectionController.shutdown();
212
+
213
+ this.glueController.shutdown();
214
+
215
+ this.sessionController.shutdown();
216
+
217
+ this.localStorageController.stop();
218
+
219
+ (window as any).iobrowser = { webStarted: false };
220
+ }
221
+
222
+ private verifyLicense(licenseKey: string): void {
223
+ if (!licenseKey || typeof licenseKey !== "string" || !licenseKey.length) {
224
+ throw new Error("The provided license key is not a valid string");
225
+ }
226
+
227
+ const licenseValidation = this.licenseController.verifyLicense(licenseKey);
228
+
229
+ if (!licenseValidation.valid) {
230
+ this.logExpirationErrors();
231
+ throw new Error("Glue42 Core Plus cannot initialize, because there was no license token provided or it was invalid. Please contact Glue42 Sales team at licensing@glue42.com");
232
+ }
233
+
234
+ const licensePayload = this.licenseController.getLicensePayload(licenseKey);
235
+
236
+ if (licensePayload.type === "trial" && this.licenseController.checkExpired(licensePayload.expiration)) {
237
+ this.logExpirationErrors();
238
+ throw new Error("Glue42 Core Plus cannot initialize, because the provided trial license has expired. Please contact Glue42 Sales team at licensing@glue42.com");
239
+ }
240
+
241
+ if (this.licenseController.checkExpired(licensePayload.expiration)) {
242
+ this.logExpirationErrors();
243
+ }
244
+
245
+ this.logger?.info(`This Glue42 Core Plus is running with a ${licensePayload.type} license, which expires on: ${(new Date(licensePayload.expiration * 1000)).toString()}`);
246
+
247
+ }
248
+
249
+ private logExpirationErrors(): void {
250
+ this.logger?.error("***********************************************************************************************************");
251
+ this.logger?.error("***********************************************************************************************************");
252
+ this.logger?.error("********************** This is Glue42 Core Plus has an expired in invalid license **************************");
253
+ this.logger?.error("***********************************************************************************************************");
254
+ this.logger?.error("***********************************************************************************************************");
255
+ }
256
+ }
@@ -0,0 +1,121 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { IOConnectBrowserPlatform } from "../../browser.platform";
3
+ import { PluginsConfig } from "../common/types";
4
+ import { GlueController } from "./glue";
5
+ import { InterceptionController } from "./interception";
6
+ import logger from "../shared/logger";
7
+ import { IOConnectBrowser } from "@interopio/browser";
8
+ import { extractErrorMsg } from "../shared/utils";
9
+
10
+ export class PluginsController {
11
+
12
+ private handlePluginMessage!: (args: IOConnectBrowserPlatform.Plugins.BaseControlMessage, pluginName: string) => Promise<any>;
13
+ private platformApi!: IOConnectBrowserPlatform.API;
14
+ private allPlugins!: IOConnectBrowserPlatform.Plugins.PluginDefinition[];
15
+ public registeredPlugins: Array<{ name: string, version: string }> = [];
16
+
17
+ constructor(
18
+ private readonly interceptionController: InterceptionController,
19
+ private readonly glueController: GlueController,
20
+ ) {}
21
+
22
+ private get logger(): IOConnectBrowser.Logger.API | undefined {
23
+ return logger.get("plugins.controller");
24
+ }
25
+
26
+ public async shutdown(): Promise<void> {
27
+ this.allPlugins.forEach((plugin) => {
28
+ if (!plugin.stop) {
29
+ return;
30
+ }
31
+
32
+ try {
33
+ plugin.stop();
34
+ } catch (error) {
35
+ this.logger?.warn(`Plugin: ${plugin.name} threw while onPlatformShutdown -> ${extractErrorMsg(error)}`);
36
+ }
37
+ });
38
+
39
+ this.allPlugins = [];
40
+ this.registeredPlugins = [];
41
+
42
+ }
43
+
44
+ public async start(config: PluginsConfig): Promise<void> {
45
+
46
+ if (!config.plugins) {
47
+ return;
48
+ }
49
+
50
+ this.allPlugins = config.plugins;
51
+
52
+ this.handlePluginMessage = config.handlePluginMessage;
53
+
54
+ this.platformApi = config.api;
55
+
56
+ if (!config.plugins || !config.plugins.length) {
57
+ return;
58
+ }
59
+
60
+ const criticalPlugins: Array<Promise<void>> = [];
61
+
62
+ for (const plugin of config.plugins) {
63
+ const startPromise = this.startPlugin(plugin);
64
+
65
+ if (plugin.critical) {
66
+ criticalPlugins.push(startPromise);
67
+ }
68
+ }
69
+
70
+ await Promise.all(criticalPlugins);
71
+ }
72
+
73
+ private async startPlugin(definition: IOConnectBrowserPlatform.Plugins.PluginDefinition): Promise<void> {
74
+ try {
75
+ const platformControls: IOConnectBrowserPlatform.Plugins.PlatformControls = this.buildPlatformControls(definition.name, this.platformApi);
76
+
77
+ await definition.start(this.glueController.clientGlue, definition.config, platformControls);
78
+
79
+ this.registerPlugin(definition.name, definition.version ?? "N/A");
80
+
81
+ } catch (error: any) {
82
+ const stringError = typeof error === "string" ? error : JSON.stringify(error.message);
83
+ const message = `Plugin: ${definition.name} threw while initiating: ${stringError}`;
84
+
85
+ if (definition.critical) {
86
+ throw new Error(message);
87
+ } else {
88
+ this.logger?.warn(message);
89
+ }
90
+ }
91
+ }
92
+
93
+ private buildPlatformControls(pluginName: string, api: IOConnectBrowserPlatform.API): IOConnectBrowserPlatform.Plugins.PlatformControls {
94
+ return {
95
+ // control is deprecated, but remains here for backwards compatibility
96
+ control: (args: IOConnectBrowserPlatform.Plugins.BaseControlMessage): Promise<any> => this.handlePluginMessage(args, pluginName),
97
+ logger: logger.get(pluginName),
98
+ platformApi: api,
99
+ interception: {
100
+ register: (request: IOConnectBrowserPlatform.Plugins.InterceptorRegistrationRequest) => this.interceptionController.registerInterceptor(request, pluginName)
101
+ },
102
+ system: {
103
+ sendControl: (args: IOConnectBrowserPlatform.Plugins.BaseControlMessage): Promise<any> => this.handlePluginMessage(args, pluginName)
104
+ }
105
+ };
106
+ }
107
+
108
+ private registerPlugin(name: string, version: string): void {
109
+ if (typeof name !== "string" || !name.length) {
110
+ return;
111
+ }
112
+
113
+ const existingPlugin = this.registeredPlugins.some((plugin) => plugin.name === name);
114
+
115
+ if (existingPlugin) {
116
+ return;
117
+ }
118
+
119
+ this.registeredPlugins.push({ name, version });
120
+ }
121
+ }
@@ -0,0 +1,193 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { IOConnectBrowser } from "@interopio/browser";
3
+ import { serviceWorkerBroadcastChannelName } from "../common/constants";
4
+ import { InternalPlatformConfig } from "../common/types";
5
+ import logger from "../shared/logger";
6
+ import {
7
+ default as CallbackRegistryFactory,
8
+ CallbackRegistry,
9
+ UnsubscribeFunction,
10
+ } from "callback-registry";
11
+ import { GlueNotificationData } from "../libs/notifications/types";
12
+ import { IoC } from "../shared/ioc";
13
+
14
+ export class ServiceWorkerController {
15
+ private readonly registry: CallbackRegistry = CallbackRegistryFactory();
16
+ private _serviceWorkerRegistration: ServiceWorkerRegistration | undefined;
17
+ private channel!: BroadcastChannel;
18
+ private _broadcastMessageHandler!: (event: MessageEvent<any>) => void;
19
+
20
+ constructor(private readonly ioc: IoC) { }
21
+
22
+ private get logger(): IOConnectBrowser.Logger.API | undefined {
23
+ return logger.get("service.worker.web.platform");
24
+ }
25
+
26
+ private get serviceWorkerRegistration(): ServiceWorkerRegistration {
27
+ if (!this._serviceWorkerRegistration) {
28
+ throw new Error("Accessing missing service worker registration object. This is caused because the application is trying to raise a persistent notification, which requires a service worker. Please provide a service worker config when initializing GlueWebPlatform.");
29
+ }
30
+
31
+ return this._serviceWorkerRegistration;
32
+ }
33
+
34
+ public shutdown(): void {
35
+ this.channel?.removeEventListener("message", this._broadcastMessageHandler);
36
+
37
+ this.registry.clear();
38
+ }
39
+
40
+ public async connect(config: InternalPlatformConfig): Promise<void> {
41
+ if (!config.serviceWorker) {
42
+ return;
43
+ }
44
+
45
+ this.logger?.info("Detected service worker definition, connecting...");
46
+
47
+ if (!config.serviceWorker.url && !config.serviceWorker.registrationPromise) {
48
+ throw new Error("The service worker config is defined, but it is missing a url or a registration promise, please provide one or the other");
49
+ }
50
+
51
+ if (config.serviceWorker.url && config.serviceWorker.registrationPromise) {
52
+ throw new Error("The service worker is over-specified, there is both defined url and a registration promise, please provide one or the other");
53
+ }
54
+
55
+ await this.prepareSwDb();
56
+
57
+ this._serviceWorkerRegistration = config.serviceWorker.url ?
58
+ await this.registerWorker(config.serviceWorker.url) :
59
+ await this.waitRegistration(config.serviceWorker.registrationPromise as Promise<ServiceWorkerRegistration>);
60
+
61
+ if (this._serviceWorkerRegistration) {
62
+ this.setUpBroadcastChannelConnection();
63
+ }
64
+
65
+ this.logger?.info("Service worker connection completed.");
66
+ }
67
+
68
+ public async showNotification(settings: IOConnectBrowser.Notifications.RaiseOptions, id: string): Promise<void> {
69
+
70
+ const options: NotificationOptions = Object.assign({}, settings, { title: undefined, clickInterop: undefined, actions: undefined });
71
+
72
+ options.actions = settings.actions?.map((action) => {
73
+ return {
74
+ action: action.action,
75
+ title: action.title,
76
+ icon: action.icon
77
+ };
78
+ });
79
+
80
+ const glueData: GlueNotificationData = {
81
+ focusPlatformOnDefaultClick: settings.focusPlatformOnDefaultClick,
82
+ clickInterop: settings.clickInterop,
83
+ actions: settings.actions,
84
+ id
85
+ };
86
+
87
+ if (options.data) {
88
+ options.data.glueData = glueData;
89
+ } else {
90
+ options.data = { glueData };
91
+ }
92
+
93
+ await this.serviceWorkerRegistration.showNotification(settings.title, options);
94
+ }
95
+
96
+ public notifyReady(): void {
97
+ if (this._serviceWorkerRegistration) {
98
+ this.channel.postMessage({ platformStarted: true });
99
+ }
100
+ }
101
+
102
+ public onNotificationClick(callback: (clickData: { action: string; glueData: GlueNotificationData; }) => void): UnsubscribeFunction {
103
+ return this.registry.add("notification-click", callback);
104
+ }
105
+
106
+ public onNotificationClose(callback: (clickData: { action: string; glueData: GlueNotificationData; }) => void): UnsubscribeFunction {
107
+ return this.registry.add("notification-close", callback);
108
+ }
109
+
110
+ private setUpBroadcastChannelConnection(): void {
111
+ this.channel = new BroadcastChannel(serviceWorkerBroadcastChannelName);
112
+
113
+ this._broadcastMessageHandler = this.broadcastMessageHandler.bind(this);
114
+
115
+ this.channel.addEventListener("message", this._broadcastMessageHandler);
116
+ }
117
+
118
+ private broadcastMessageHandler(event: MessageEvent<any>): void {
119
+ const eventData = event.data;
120
+ const messageType: string = eventData?.messageType;
121
+
122
+ if (!messageType) {
123
+ return;
124
+ }
125
+
126
+ if (messageType === "ping") {
127
+ this.channel.postMessage({ pong: true });
128
+ return;
129
+ }
130
+
131
+ if (messageType === "notificationClick") {
132
+ const action = eventData.action as string;
133
+ const glueData = eventData.glueData;
134
+
135
+ this.registry.execute("notification-click", { action, glueData });
136
+ return;
137
+ }
138
+
139
+ if (messageType === "notificationClose") {
140
+ const action = eventData.action as string;
141
+ const glueData = eventData.glueData;
142
+
143
+ this.registry.execute("notification-close", { action, glueData });
144
+ return;
145
+ }
146
+
147
+ if (messageType === "notificationError") {
148
+ this.logger?.error(`Service worker error when raising notification: ${eventData.error}`);
149
+ return;
150
+ }
151
+ }
152
+
153
+ private async registerWorker(workerUrl: string): Promise<ServiceWorkerRegistration | undefined> {
154
+
155
+ if (!("serviceWorker" in navigator)) {
156
+ this.logger?.warn(`A defined service worker has not been registered at ${workerUrl} because this browser does not support it.`);
157
+ return;
158
+ }
159
+
160
+ try {
161
+ const registration = await navigator.serviceWorker.register(workerUrl);
162
+
163
+ return registration;
164
+ } catch (error: any) {
165
+ const stringError = typeof error === "string" ? error : JSON.stringify(error.message);
166
+
167
+ this.logger?.warn(stringError);
168
+ }
169
+ }
170
+
171
+ private async waitRegistration(registrationPromise: Promise<ServiceWorkerRegistration>): Promise<ServiceWorkerRegistration> {
172
+
173
+ if (typeof registrationPromise.then !== "function" || typeof registrationPromise.catch !== "function") {
174
+ throw new Error("The provided service worker registration promise is not a promise");
175
+ }
176
+
177
+ const registration = await registrationPromise;
178
+
179
+ if (typeof registration.showNotification !== "function") {
180
+ throw new Error("The provided registration promise is a promise, but it resolved with an object which does not appear to be a ServiceWorkerRegistration");
181
+ }
182
+
183
+ return registration;
184
+ }
185
+
186
+ private async prepareSwDb(): Promise<void> {
187
+ const db = await this.ioc.getDatabase();
188
+
189
+ await db.clear("serviceWorker" as never);
190
+
191
+ await db.put("serviceWorker" as never, { platformUrl: window.location.href }, "workerData");
192
+ }
193
+ }