active-connect-ng2 0.2.41 → 0.2.43

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 (53) hide show
  1. package/esm2020/active-connect-ng2.mjs +5 -0
  2. package/esm2020/lib/active-connect-ng2.module.mjs +42 -0
  3. package/esm2020/lib/websocket/client.mjs +353 -0
  4. package/esm2020/lib/websocket/decorators/function.mjs +40 -0
  5. package/esm2020/lib/websocket/decorators/websocket/handle.mjs +9 -0
  6. package/esm2020/lib/websocket/decorators/websocket/on-reconnect.mjs +6 -0
  7. package/esm2020/lib/websocket/decorators/websocket/on-success.mjs +8 -0
  8. package/esm2020/lib/websocket/decorators/websocket/outbound.mjs +213 -0
  9. package/esm2020/lib/websocket/decorators/websocket/route.mjs +31 -0
  10. package/esm2020/lib/websocket/decorators/websocket/shared.mjs +10 -0
  11. package/esm2020/lib/websocket/decorators/websocket/websocket-route-service.mjs +2 -0
  12. package/esm2020/lib/websocket/index.mjs +11 -0
  13. package/esm2020/lib/websocket/json/json-parser.mjs +23 -0
  14. package/esm2020/lib/websocket/lifecycle/loading-status.mjs +31 -0
  15. package/esm2020/lib/websocket/objects/outbound-object.mjs +398 -0
  16. package/esm2020/public-api.mjs +7 -0
  17. package/fesm2015/active-connect-ng2.mjs +1184 -0
  18. package/fesm2015/active-connect-ng2.mjs.map +1 -0
  19. package/fesm2020/active-connect-ng2.mjs +1166 -0
  20. package/fesm2020/active-connect-ng2.mjs.map +1 -0
  21. package/index.d.ts +5 -0
  22. package/lib/active-connect-ng2.module.d.ts +7 -0
  23. package/lib/websocket/client.d.ts +60 -0
  24. package/lib/websocket/decorators/function.d.ts +30 -0
  25. package/lib/websocket/decorators/websocket/handle.d.ts +1 -0
  26. package/lib/websocket/decorators/websocket/on-reconnect.d.ts +1 -0
  27. package/lib/websocket/decorators/websocket/on-success.d.ts +1 -0
  28. package/lib/websocket/decorators/websocket/outbound.d.ts +1 -0
  29. package/lib/websocket/decorators/websocket/route.d.ts +1 -0
  30. package/lib/websocket/decorators/websocket/shared.d.ts +4 -0
  31. package/{src/lib/websocket/decorators/websocket/websocket-route-service.ts → lib/websocket/decorators/websocket/websocket-route-service.d.ts} +2 -3
  32. package/lib/websocket/json/json-parser.d.ts +5 -0
  33. package/lib/websocket/lifecycle/loading-status.d.ts +9 -0
  34. package/lib/websocket/objects/outbound-object.d.ts +48 -0
  35. package/package.json +32 -13
  36. package/{src/public-api.ts → public-api.d.ts} +0 -4
  37. package/ng-package.json +0 -7
  38. package/src/lib/active-connect-ng2.module.ts +0 -34
  39. package/src/lib/websocket/client.ts +0 -438
  40. package/src/lib/websocket/decorators/function.ts +0 -44
  41. package/src/lib/websocket/decorators/websocket/handle.ts +0 -12
  42. package/src/lib/websocket/decorators/websocket/on-reconnect.ts +0 -6
  43. package/src/lib/websocket/decorators/websocket/on-success.ts +0 -11
  44. package/src/lib/websocket/decorators/websocket/outbound.ts +0 -212
  45. package/src/lib/websocket/decorators/websocket/route.ts +0 -32
  46. package/src/lib/websocket/decorators/websocket/shared.ts +0 -11
  47. package/src/lib/websocket/json/json-parser.ts +0 -26
  48. package/src/lib/websocket/lifecycle/loading-status.ts +0 -32
  49. package/src/lib/websocket/objects/outbound-object.ts +0 -430
  50. package/tsconfig.lib.json +0 -14
  51. package/tsconfig.lib.prod.json +0 -10
  52. package/tsconfig.spec.json +0 -14
  53. /package/{src/lib/websocket/index.ts → lib/websocket/index.d.ts} +0 -0
@@ -0,0 +1,1166 @@
1
+ import * as i0 from '@angular/core';
2
+ import { NgModule } from '@angular/core';
3
+ import * as i1 from 'ngx-indexed-db';
4
+ import { NgxIndexedDBModule } from 'ngx-indexed-db';
5
+ export { NgxIndexedDBService } from 'ngx-indexed-db';
6
+ import { Observable } from 'rxjs';
7
+
8
+ const dbConfig = {
9
+ name: 'activeconnect_cache',
10
+ version: 2,
11
+ objectStoresMeta: [
12
+ {
13
+ store: 'outbound',
14
+ storeConfig: { keyPath: 'method', autoIncrement: false },
15
+ storeSchema: [
16
+ { name: 'method', keypath: 'method', options: { unique: true } },
17
+ { name: 'data', keypath: 'data', options: { unique: false } },
18
+ {
19
+ name: 'specificHash',
20
+ keypath: 'specificHash',
21
+ options: { unique: false },
22
+ },
23
+ {
24
+ name: 'length',
25
+ keypath: 'length',
26
+ options: { unique: false },
27
+ },
28
+ ],
29
+ },
30
+ ],
31
+ };
32
+ class ActiveConnectNg2Module {
33
+ }
34
+ ActiveConnectNg2Module.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ActiveConnectNg2Module, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
35
+ ActiveConnectNg2Module.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.9", ngImport: i0, type: ActiveConnectNg2Module, imports: [i1.NgxIndexedDBModule], exports: [NgxIndexedDBModule] });
36
+ ActiveConnectNg2Module.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ActiveConnectNg2Module, imports: [NgxIndexedDBModule.forRoot(dbConfig), NgxIndexedDBModule] });
37
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ActiveConnectNg2Module, decorators: [{
38
+ type: NgModule,
39
+ args: [{
40
+ declarations: [],
41
+ imports: [NgxIndexedDBModule.forRoot(dbConfig)],
42
+ exports: [NgxIndexedDBModule],
43
+ }]
44
+ }] });
45
+
46
+ class JsonParser {
47
+ static stringify(obj) {
48
+ return JSON.stringify(obj);
49
+ }
50
+ static parsingFunction(key, value) {
51
+ var a;
52
+ if (typeof value === "string") {
53
+ a =
54
+ /^[0-9]{4}\-[0-9]{2}\-[0-9]{2}T[0-9]{2}\:[0-9]{2}\:[0-9]{2}\.[0-9]{3}Z$/.exec(value);
55
+ if (a) {
56
+ return new Date(a);
57
+ }
58
+ }
59
+ return value;
60
+ }
61
+ static parse(str) {
62
+ if (str && str != "undefined") {
63
+ return JSON.parse(str, JsonParser.parsingFunction);
64
+ }
65
+ return str;
66
+ }
67
+ }
68
+
69
+ class WebsocketClient {
70
+ constructor(url, supportsCache, dbService) {
71
+ this.url = url;
72
+ this.supportsCache = supportsCache;
73
+ this.dbService = dbService;
74
+ this.requestStack = [];
75
+ this.requestHistoryLogs = [];
76
+ this._token = '';
77
+ this.connectionEstablishedOnce = false;
78
+ this.messageId = 0;
79
+ this.rejectCallbacks = new Map();
80
+ this.expectedMethods = new Map();
81
+ this.closed = false;
82
+ if (supportsCache)
83
+ this.initCache();
84
+ this.setUrl(this.url);
85
+ }
86
+ setUrl(url) {
87
+ if (!url) {
88
+ let protocol;
89
+ let port;
90
+ switch (document.location.protocol) {
91
+ case 'https:': {
92
+ protocol = 'wss:';
93
+ port = ':443';
94
+ break;
95
+ }
96
+ default: {
97
+ protocol = 'ws:';
98
+ port = ':80';
99
+ break;
100
+ }
101
+ }
102
+ url = protocol + '//' + document.location.hostname + port + '/wss';
103
+ }
104
+ this.url = url;
105
+ this.disconnect();
106
+ this.connect(this.url);
107
+ }
108
+ connect(url) {
109
+ if (!this.subject) {
110
+ this.create(url);
111
+ }
112
+ return this.subject;
113
+ }
114
+ initTabSuspendedListener() {
115
+ if (document) {
116
+ document.addEventListener('visibilitychange', () => {
117
+ if (document.visibilityState === 'hidden') {
118
+ console.log('ActiveConnect: Closing WebSocket due to tab suspension...');
119
+ this.disconnect(true);
120
+ }
121
+ else if (document.visibilityState === 'visible') {
122
+ console.log('ActiveConnect: Reconnecting WebSocket...');
123
+ this.connect(this.url);
124
+ }
125
+ });
126
+ }
127
+ }
128
+ logEntry(method) {
129
+ this.requestHistoryLogs.push({ timestamp: new Date(Date.now()), method });
130
+ }
131
+ get logs() {
132
+ return this.requestHistoryLogs;
133
+ }
134
+ get Token() {
135
+ if (!this._token) {
136
+ if (window.localStorage)
137
+ this._token = window.localStorage.getItem('token') || '';
138
+ }
139
+ return this._token;
140
+ }
141
+ set Token(val) {
142
+ this._token = val;
143
+ if (window.localStorage)
144
+ window.localStorage.setItem('token', val);
145
+ }
146
+ set Connected(value) {
147
+ if (value) {
148
+ this.sendBrowserInfoToServer();
149
+ this.auth(this.Token).then(() => {
150
+ Promise.all(WebsocketClient.onReconnectCallback.map((c) => c.Func ? c.Func() : null)).then(() => {
151
+ setTimeout(() => {
152
+ this.resetRequestedState();
153
+ this.requestStack.forEach((e) => {
154
+ this.sendToSocket(e.method, e.data);
155
+ this.requestStack = this.requestStack.filter((e1) => e1 != e);
156
+ });
157
+ }, 2000);
158
+ });
159
+ });
160
+ }
161
+ if (this.pool && this.pool.WssConnected)
162
+ this.pool.WssConnected = value;
163
+ }
164
+ resetRequestedState() {
165
+ if (this.connectionEstablishedOnce) {
166
+ // reset requested state for outbounds
167
+ WebsocketClient.resetRequestedStateCallbacks.forEach((reset) => {
168
+ reset();
169
+ });
170
+ }
171
+ else {
172
+ this.connectionEstablishedOnce = true;
173
+ }
174
+ }
175
+ static addResetRequestingStateCallback(callback) {
176
+ WebsocketClient.resetRequestedStateCallbacks.push(callback);
177
+ }
178
+ create(url) {
179
+ // create new connection
180
+ this.logEntry('TCP/HTTP:CONNECT-SERVER');
181
+ this.ws = new WebSocket(url + (this.supportsCache ? '?cache=true' : ''));
182
+ this.ws.onerror = (err) => {
183
+ this.ws.close();
184
+ this.logEntry('TCP/HTTP:ERROR:' + err);
185
+ console.log('ActiveConnect: ' + err);
186
+ };
187
+ this.ws.onopen = () => {
188
+ this.logEntry('TCP/HTTP:CONNECTED');
189
+ this.Connected = true;
190
+ };
191
+ this.ws.onmessage = (e) => {
192
+ this.messageReceived(JsonParser.parse(e.data.toString()));
193
+ };
194
+ this.ws.onclose = () => {
195
+ this.logEntry('TCP/HTTP:CLOSED');
196
+ if (!this.closed) {
197
+ if (this.pool && this.pool.WssConnected)
198
+ this.pool.WssConnected = false;
199
+ this.logEntry('TCP/HTTP:RESET-REQUESTED-OUTBOUND-STATE');
200
+ this.resetRequestedState();
201
+ setTimeout(() => {
202
+ this.connect(url);
203
+ }, 1000);
204
+ }
205
+ };
206
+ }
207
+ sendToSocket(method, data, dontEnsureTransmission) {
208
+ const messageId = ++this.messageId;
209
+ if (this.ws.readyState != this.ws.OPEN) {
210
+ if (!dontEnsureTransmission)
211
+ this.requestStack.push({ method, data, messageId });
212
+ else
213
+ return false;
214
+ }
215
+ else {
216
+ this.ws.send(JsonParser.stringify({ method, value: data, messageId }));
217
+ }
218
+ return messageId;
219
+ }
220
+ async auth(token) {
221
+ return this.sendToSocket('auth.token', token);
222
+ }
223
+ send(method, data, dontEnsureTransmission) {
224
+ this.logEntry('SEND:' + method);
225
+ const messageId = this.sendToSocket(method, data, dontEnsureTransmission || false);
226
+ if (messageId) {
227
+ return this.expectMethod(`m.${method}`, messageId);
228
+ }
229
+ else {
230
+ return new Promise((resolve) => {
231
+ resolve(false);
232
+ });
233
+ }
234
+ }
235
+ expectMethod(method, messageId) {
236
+ return new Promise((resolve, reject) => {
237
+ if (messageId) {
238
+ this.expectedMethods.set(messageId, [resolve]);
239
+ this.rejectCallbacks.set(messageId, reject);
240
+ }
241
+ else {
242
+ if (this.expectedMethods.has(method)) {
243
+ let arr = this.expectedMethods.get(method);
244
+ arr.push(resolve);
245
+ }
246
+ else {
247
+ this.expectedMethods.set(method, [resolve]);
248
+ }
249
+ }
250
+ });
251
+ }
252
+ messageReceived({ method, value, messageId, specificHash, inserted, updated, deleted, length, }) {
253
+ this.logEntry('RECEIVED:' + method);
254
+ if (method == '___cache') {
255
+ this.handleOutboundCacheRequest(value);
256
+ }
257
+ if (messageId) {
258
+ if (method == 'm.error') {
259
+ const reject = this.rejectCallbacks.get(messageId);
260
+ if (reject) {
261
+ reject(value);
262
+ }
263
+ messageId = -1;
264
+ }
265
+ }
266
+ if (messageId != null) {
267
+ const callback = this.expectedMethods.get(messageId);
268
+ if (callback) {
269
+ const func = callback.shift();
270
+ if (func)
271
+ func(value);
272
+ this.invokeSuccessHandlers(method);
273
+ }
274
+ else {
275
+ const callback = this.expectedMethods.get(method);
276
+ if (callback && callback.length > 0) {
277
+ const func = callback.shift();
278
+ if (func)
279
+ func(value);
280
+ }
281
+ else {
282
+ const out = WebsocketClient.outbounds.get(method);
283
+ if (out) {
284
+ out(value, specificHash, inserted, updated, deleted, length, this);
285
+ }
286
+ const handle = WebsocketClient.handles.get(method);
287
+ if (handle) {
288
+ handle.Func(value);
289
+ }
290
+ }
291
+ }
292
+ }
293
+ else {
294
+ throw Error('No MessageId was provided, the connection is not supported.');
295
+ }
296
+ }
297
+ handleOutboundCacheRequest(method) {
298
+ if (this.dbService) {
299
+ try {
300
+ this.dbService.getByKey('outbound', method).subscribe((item) => {
301
+ if (item) {
302
+ this.send('___cache', {
303
+ method,
304
+ specificHash: item.specificHash || null,
305
+ });
306
+ }
307
+ else {
308
+ this.send('___cache', {
309
+ method,
310
+ specificHash: null,
311
+ });
312
+ }
313
+ });
314
+ }
315
+ catch (e) {
316
+ this.send('___cache', {
317
+ method,
318
+ specificHash: null,
319
+ });
320
+ console.error('ActiveConnect: ' + e);
321
+ }
322
+ }
323
+ else {
324
+ this.send('___cache', {
325
+ method,
326
+ specificHash: null,
327
+ });
328
+ console.error('Active-Connect: Caching not possible as the indexedDB has not been initialized');
329
+ }
330
+ }
331
+ static expectOutbound(method, callback) {
332
+ WebsocketClient.outbounds.set(method, callback);
333
+ }
334
+ static registerHandle(method, callback) {
335
+ WebsocketClient.handles.set(method, callback);
336
+ }
337
+ get isConnected() {
338
+ if (this.ws)
339
+ return this.ws.readyState == WebSocket.OPEN;
340
+ return true;
341
+ }
342
+ sendBrowserInfoToServer() {
343
+ // send browser / os information
344
+ const browser = this.getBrowser();
345
+ const os = this.getOS();
346
+ this.send('___browser', {
347
+ browser: `${browser.name} ${browser.version} ${os}`,
348
+ });
349
+ }
350
+ getBrowser() {
351
+ // https://www.gregoryvarghese.com/how-to-get-browser-name-and-version-via-javascript/
352
+ var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
353
+ if (/trident/i.test(M[1])) {
354
+ tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
355
+ return { name: 'IE ', version: tem[1] || '' };
356
+ }
357
+ if (M[1] === 'Chrome') {
358
+ tem = ua.match(/\bOPR\/(\d+)/);
359
+ if (tem != null) {
360
+ return { name: 'Opera', version: tem[1] };
361
+ }
362
+ }
363
+ M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
364
+ if ((tem = ua.match(/version\/(\d+)/i)) != null) {
365
+ M.splice(1, 1, tem[1]);
366
+ }
367
+ return {
368
+ name: M[0],
369
+ version: M[1],
370
+ };
371
+ }
372
+ getOS() {
373
+ var userAgent = window.navigator.userAgent, platform = window.navigator.platform, macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'], iosPlatforms = ['iPhone', 'iPad', 'iPod'], os = null;
374
+ if (macosPlatforms.indexOf(platform) !== -1) {
375
+ os = 'Mac OS';
376
+ }
377
+ else if (iosPlatforms.indexOf(platform) !== -1) {
378
+ os = 'iOS';
379
+ }
380
+ else if (windowsPlatforms.indexOf(platform) !== -1) {
381
+ os = 'Windows';
382
+ }
383
+ else if (/Android/.test(userAgent)) {
384
+ os = 'Android';
385
+ }
386
+ else if (!os && /Linux/.test(platform)) {
387
+ os = 'Linux';
388
+ }
389
+ return os || '';
390
+ }
391
+ static onSuccess(callback, regexp) {
392
+ this.onSuccessHandlers.push({ callback, regexp });
393
+ }
394
+ static onReconnect(callback) {
395
+ WebsocketClient.onReconnectCallback.push(callback);
396
+ }
397
+ invokeSuccessHandlers(method) {
398
+ WebsocketClient.onSuccessHandlers
399
+ .filter((e) => e.regexp.test(method))
400
+ .forEach((e) => {
401
+ var res = e.callback.Func();
402
+ if (res && res.then) {
403
+ res.then();
404
+ }
405
+ });
406
+ }
407
+ disconnect(restart) {
408
+ if (!restart)
409
+ this.closed = true;
410
+ if (this.ws)
411
+ this.ws.close();
412
+ }
413
+ initCache() { }
414
+ }
415
+ WebsocketClient.resetRequestedStateCallbacks = [];
416
+ WebsocketClient.outbounds = new Map();
417
+ WebsocketClient.handles = new Map();
418
+ WebsocketClient.onSuccessHandlers = [];
419
+ WebsocketClient.onReconnectCallback = [];
420
+
421
+ /**
422
+ * Represents the reference to an object method used for websocket routes and outbounds.
423
+ */
424
+ class DecorableFunction {
425
+ /**
426
+ * Creates an instance of DecorableFunction.
427
+ * @param objConfig - The configuration object for the object method.
428
+ * @param objConfig.target - The target object.
429
+ * @param objConfig.propertyKey - The property key of the target object.
430
+ */
431
+ constructor(objConfig) {
432
+ this.objConfig = objConfig;
433
+ // singelton service - fetch from angular
434
+ const prototype = this.objConfig.target.prototype || this.objConfig.target;
435
+ if (!prototype.___constructorOverridden) {
436
+ prototype.___constructorOverridden = true;
437
+ }
438
+ }
439
+ /**
440
+ * Returns the decorated function.
441
+ * @returns - The decorated function.
442
+ */
443
+ get Func() {
444
+ if (this.objConfig?.target &&
445
+ this.objConfig.target[this.objConfig.propertyKey]) {
446
+ return this.objConfig.target[this.objConfig.propertyKey].bind(this.getBindObject());
447
+ }
448
+ return null;
449
+ }
450
+ /**
451
+ * Returns the bind object.
452
+ * @private
453
+ * @returns - The bind object.
454
+ */
455
+ getBindObject() {
456
+ const prototype = this.objConfig.target.prototype || this.objConfig.target;
457
+ return prototype.___data._obj;
458
+ }
459
+ }
460
+
461
+ function Handle(method) {
462
+ return function _Handle(target, propertyKey) {
463
+ // method annotation
464
+ WebsocketClient.registerHandle(method, new DecorableFunction({ target, propertyKey }));
465
+ };
466
+ }
467
+
468
+ function OnSuccess(regexp) {
469
+ return function _Route(target, propertyKey) {
470
+ WebsocketClient.onSuccess(new DecorableFunction({ target, propertyKey }), regexp);
471
+ };
472
+ }
473
+
474
+ function OnReconnect(target, propertyKey) {
475
+ WebsocketClient.onReconnect(new DecorableFunction({ target, propertyKey }));
476
+ }
477
+
478
+ function Outbound(method, requestingRequired, cached, sortBy) {
479
+ return function _Outbound(target, propertyKey) {
480
+ target.loading = new Map();
481
+ // property annotation
482
+ WebsocketClient.expectOutbound(method, function setOutbound(data, specificHash, inserted, updated, deleted, length, _this) {
483
+ if (!target.___received)
484
+ target.___received = {};
485
+ if (!target.___data)
486
+ target.___data = {};
487
+ if (!target.___received)
488
+ target.___received = {};
489
+ if (!target.___requested)
490
+ target.___requested = {};
491
+ if (!cached) {
492
+ if (_this.dbService) {
493
+ try {
494
+ _this.dbService
495
+ .deleteByKey('outbound', method)
496
+ .subscribe(() => { });
497
+ }
498
+ catch (e) {
499
+ console.error('ActiveConnect: could not delete indexdb cache entry');
500
+ }
501
+ }
502
+ }
503
+ if (data == 'cache_restore') {
504
+ if (_this.dbService) {
505
+ try {
506
+ _this.dbService
507
+ .getByKey('outbound', method)
508
+ .subscribe((result) => {
509
+ target.___received[propertyKey] = true;
510
+ target.___data[propertyKey] = result.data;
511
+ target.loading.set(propertyKey, false);
512
+ });
513
+ }
514
+ catch (e) {
515
+ console.error('ActiveConnect: Unable to restore cached data.');
516
+ console.error(e);
517
+ }
518
+ }
519
+ else {
520
+ console.error('ActiveConnect: Caching / restore not possible as the indexedDB is not accessible');
521
+ }
522
+ }
523
+ else if (data == 'cache_delete') {
524
+ if (_this.dbService) {
525
+ try {
526
+ _this.dbService
527
+ .deleteByKey('outbound', method)
528
+ .subscribe(() => { });
529
+ }
530
+ catch (e) {
531
+ console.error('ActiveConnect: Unable to delete cached data');
532
+ console.error(e);
533
+ }
534
+ }
535
+ else {
536
+ console.error('ActiveConnect: Caching / restore not possible as the indexedDB is not accessible');
537
+ }
538
+ target.___received[propertyKey] = false;
539
+ target.___data[propertyKey] = undefined;
540
+ target.loading.set(propertyKey, false);
541
+ }
542
+ else if (data == 'data_delete') {
543
+ target.___data[propertyKey] = undefined;
544
+ target.loading.set(propertyKey, false);
545
+ target.___received[propertyKey] = false;
546
+ target.___requested[propertyKey] = false;
547
+ }
548
+ else if (data == 'data_diff') {
549
+ var data = target.___data[propertyKey] || [];
550
+ inserted?.forEach((e) => {
551
+ const matching = data.filter((d) => d.id == e.id);
552
+ if (matching.length > 0) {
553
+ data[data.indexOf(matching[0])] = e;
554
+ }
555
+ else {
556
+ data.push(e);
557
+ }
558
+ });
559
+ updated?.forEach((e) => {
560
+ const matching = data.filter((d) => d.id == e.id);
561
+ if (matching.length > 0) {
562
+ data[data.indexOf(matching[0])] = e;
563
+ }
564
+ else {
565
+ data.push(e);
566
+ }
567
+ });
568
+ deleted?.forEach((e) => {
569
+ data = data.filter((d) => d.id != e.id);
570
+ });
571
+ if (sortBy && data)
572
+ data = data.sort(sortBy);
573
+ target.___data[propertyKey] = data;
574
+ target.loading.set(propertyKey, false);
575
+ if (cached && specificHash) {
576
+ if (_this.dbService) {
577
+ if (data && data?.length > 0) {
578
+ try {
579
+ _this.dbService
580
+ .update('outbound', {
581
+ method,
582
+ data,
583
+ specificHash,
584
+ })
585
+ .subscribe(() => { });
586
+ }
587
+ catch (e) {
588
+ console.error('ActiveConnect: Unable to update cached data');
589
+ console.error(e);
590
+ }
591
+ }
592
+ else {
593
+ try {
594
+ _this.dbService
595
+ .deleteByKey('outbound', method)
596
+ .subscribe(() => { });
597
+ }
598
+ catch (e) {
599
+ console.error('ActiveConnect: Unable to delete cached data');
600
+ console.error(e);
601
+ }
602
+ }
603
+ }
604
+ else {
605
+ console.error('ActiveConnect: Caching not possible as the indexedDB has not been initialized');
606
+ }
607
+ }
608
+ }
609
+ else {
610
+ if (sortBy && data)
611
+ data = data.sort(sortBy);
612
+ target.___received[propertyKey] = true;
613
+ target.___data[propertyKey] = data;
614
+ target.loading.set(propertyKey, false);
615
+ if (cached && specificHash) {
616
+ if (_this.dbService) {
617
+ if (data && data?.length > 0) {
618
+ try {
619
+ _this.dbService
620
+ .update('outbound', {
621
+ method,
622
+ data,
623
+ specificHash,
624
+ })
625
+ .subscribe(() => { });
626
+ }
627
+ catch (e) {
628
+ console.error('ActiveConnect: Unable to update cached data');
629
+ console.error(e);
630
+ }
631
+ }
632
+ else {
633
+ try {
634
+ _this.dbService
635
+ .deleteByKey('outbound', method)
636
+ .subscribe(() => { });
637
+ }
638
+ catch (e) {
639
+ console.error('ActiveConnect: Unable to update cached data');
640
+ console.error(e);
641
+ }
642
+ }
643
+ }
644
+ else {
645
+ console.error('ActiveConnect: Caching not possible as the indexedDB has not been initialized');
646
+ }
647
+ }
648
+ }
649
+ });
650
+ if (requestingRequired) {
651
+ WebsocketClient.addResetRequestingStateCallback(function callback() {
652
+ if (target.___requested) {
653
+ target.___requested[propertyKey] = false;
654
+ }
655
+ });
656
+ }
657
+ const obj = {
658
+ configurable: true,
659
+ get() {
660
+ if (!target.___requested)
661
+ target.___requested = {};
662
+ if (requestingRequired && !target.___requested[propertyKey]) {
663
+ target.___requested[propertyKey] = true;
664
+ this.send('request.' + method, null).then();
665
+ }
666
+ if (!target.___data)
667
+ target.___data = {};
668
+ if (!target.___data[propertyKey]) {
669
+ target.loading.set(propertyKey, true);
670
+ }
671
+ else if (target.loading[propertyKey]) {
672
+ target.loading.set(propertyKey, false);
673
+ }
674
+ return target.___data[propertyKey];
675
+ },
676
+ set(val) {
677
+ if (!target.___data)
678
+ target.___data = {};
679
+ target.loading.set(propertyKey, false);
680
+ if (sortBy && val)
681
+ val = val.sort(sortBy);
682
+ return (target.___data[propertyKey] = val);
683
+ },
684
+ };
685
+ target[propertyKey] = obj;
686
+ return obj;
687
+ };
688
+ }
689
+
690
+ function Route(method, loadingKey, dontEnsureTransmission) {
691
+ return function _Route(target, propertyKey) {
692
+ // method annotation
693
+ const original = target[propertyKey];
694
+ target[propertyKey] = async function execRoute(...data) {
695
+ if (loadingKey) {
696
+ if (!this.loadingElements[loadingKey]) {
697
+ this.loadingElements[loadingKey] = 0;
698
+ }
699
+ this.loadingElements[loadingKey]++;
700
+ }
701
+ const promise = original.bind(this)(...data);
702
+ let res = null;
703
+ if (this.client) {
704
+ res = await this.client
705
+ .send(method, data[0], dontEnsureTransmission)
706
+ ?.catch((err) => {
707
+ if (loadingKey)
708
+ this.loadingElements[loadingKey]--;
709
+ throw err;
710
+ });
711
+ }
712
+ await promise;
713
+ if (loadingKey)
714
+ this.loadingElements[loadingKey]--;
715
+ return res;
716
+ };
717
+ return target;
718
+ };
719
+ }
720
+
721
+ /**
722
+ * @deprecated
723
+ */
724
+ function Shared(defaultValue) {
725
+ if (defaultValue) {
726
+ throw Error("Active-Connect/@Shared: defaultValue is no longer supported, please assign the value to the variable itself.");
727
+ }
728
+ return function _Shared(target, propertyKey) { };
729
+ }
730
+
731
+ class LoadingStatus extends WebsocketClient {
732
+ get isLoading() {
733
+ // return general loading
734
+ let anyTrue = false;
735
+ this.__proto__.loading.forEach((e) => {
736
+ anyTrue || (anyTrue = e);
737
+ });
738
+ if (!anyTrue)
739
+ this.__proto__.loading.clear();
740
+ return this.__proto__.loading.size > 0;
741
+ }
742
+ getLoadingMap() {
743
+ return this.__proto__.loading;
744
+ }
745
+ get getCurrent() {
746
+ let count = 0;
747
+ this.__proto__.loading.forEach((e) => {
748
+ if (e)
749
+ count++;
750
+ });
751
+ if (count == 0) {
752
+ this.__proto__.loading.clear();
753
+ }
754
+ return count;
755
+ }
756
+ get getTotal() {
757
+ return this.__proto__.loading.size;
758
+ }
759
+ }
760
+
761
+ class OutboundObject {
762
+ constructor(client, method, lazyLoaded, cached, initialLoadingCount, sortBy) {
763
+ this.client = client;
764
+ this.method = method;
765
+ this.lazyLoaded = lazyLoaded;
766
+ this.cached = cached;
767
+ this.initialLoadingCount = initialLoadingCount;
768
+ this.sortBy = sortBy;
769
+ this.dataMap = new Map();
770
+ this.data = undefined;
771
+ this.requested = false;
772
+ this._loading = false;
773
+ this._length = undefined;
774
+ this.requestedId = null;
775
+ this.loadedObservable = null;
776
+ this.loadedId = null;
777
+ this.loadedIdData = null;
778
+ this.loadedIdChanged = null;
779
+ this.requestedGroupId = null;
780
+ this.loadedGroupObservable = null;
781
+ this.loadedGroupId = null;
782
+ this.loadedGroupData = null;
783
+ this.loadedGroupChanged = null;
784
+ this.target.loading = new Map();
785
+ if (this.client.dbService) {
786
+ try {
787
+ this.client.dbService
788
+ .getByKey('outbound', method)
789
+ .subscribe((result) => {
790
+ if (result) {
791
+ this.previouslyCachedCount = result.data?.length || null;
792
+ }
793
+ });
794
+ }
795
+ catch (e) {
796
+ console.error('ActiveConnect: Unable to read cached data');
797
+ console.error(e);
798
+ }
799
+ }
800
+ const _this = this;
801
+ WebsocketClient.expectOutbound(method, function setOutbound(data, specificHash, insertedOrGroupData, updatedOrGroupId, deleted, length, _client) {
802
+ if (!cached) {
803
+ if (_client.dbService) {
804
+ try {
805
+ _client.dbService
806
+ .deleteByKey('outbound', method)
807
+ .subscribe(() => { });
808
+ }
809
+ catch (e) {
810
+ console.error('ActiveConnect: Unable to delete cached data');
811
+ console.error(e);
812
+ }
813
+ }
814
+ }
815
+ if (data == 'cache_restore') {
816
+ if (_client.dbService) {
817
+ try {
818
+ _client.dbService
819
+ .getByKey('outbound', method)
820
+ .subscribe((result) => {
821
+ _this.setData(result.data);
822
+ if (result.length)
823
+ _this._length = result.length;
824
+ _this.loading = false;
825
+ });
826
+ }
827
+ catch (e) {
828
+ console.error('ActiveConnect: Unable to restore cached data');
829
+ console.error(e);
830
+ }
831
+ }
832
+ else {
833
+ console.error('ActiveConnect: Caching / restore not possible as the indexedDB is not accessible');
834
+ }
835
+ }
836
+ else if (data == 'cache_delete') {
837
+ if (_client.dbService) {
838
+ try {
839
+ _client.dbService
840
+ .deleteByKey('outbound', method)
841
+ .subscribe(() => { });
842
+ }
843
+ catch (e) {
844
+ console.error('ActiveConnect: Unable to delete cached data');
845
+ console.error(e);
846
+ }
847
+ }
848
+ else {
849
+ console.error('ActiveConnect: Caching / restore not possible as the indexedDB is not accessible');
850
+ }
851
+ _this.loading = false;
852
+ _this.requested = false;
853
+ }
854
+ else if (data == 'data_delete') {
855
+ _this.data = undefined;
856
+ _this.dataMap = new Map();
857
+ _this.requested = false;
858
+ _this.loadedGroupData = null;
859
+ _this.loadedGroupId = null;
860
+ _this._length = undefined;
861
+ _this.loading = false;
862
+ }
863
+ else if (data == 'data_group') {
864
+ if (_this.requestedGroupId ==
865
+ (updatedOrGroupId ? updatedOrGroupId[0] : 0)) {
866
+ _this.loadedGroupData = insertedOrGroupData;
867
+ _this.loadedGroupId = updatedOrGroupId ? updatedOrGroupId[0] : 0;
868
+ _this.loadedGroupChanged?.next(insertedOrGroupData);
869
+ _this.loading = false;
870
+ }
871
+ }
872
+ else if (data == 'data_id') {
873
+ if (_this.requestedId == (updatedOrGroupId ? updatedOrGroupId[0] : 0)) {
874
+ _this.loadedIdData =
875
+ (insertedOrGroupData?.length || 0) > 0
876
+ ? insertedOrGroupData[0]
877
+ : null;
878
+ _this.loadedId = updatedOrGroupId ? updatedOrGroupId[0] : 0;
879
+ _this.loadedIdChanged?.next(_this.loadedIdData);
880
+ _this.loading = false;
881
+ }
882
+ }
883
+ else if (data == 'data_diff') {
884
+ insertedOrGroupData?.forEach((e) => {
885
+ _this.dataMap.set(e.id, e);
886
+ if (e.id == _this.loadedId) {
887
+ _this.loadedIdChanged?.next(e);
888
+ }
889
+ });
890
+ updatedOrGroupId?.forEach((e) => {
891
+ _this.dataMap.set(e.id, e);
892
+ if (e.id == _this.loadedId) {
893
+ _this.loadedIdChanged?.next(e);
894
+ }
895
+ });
896
+ deleted?.forEach((e) => {
897
+ _this.dataMap.delete(e.id);
898
+ if (e.id == _this.loadedId) {
899
+ _this.loadedIdChanged?.next(null);
900
+ }
901
+ });
902
+ _this.data = Array.from(_this.dataMap.values());
903
+ if (_this.data && _this.sortBy)
904
+ _this.data = _this.data.sort(_this.sortBy);
905
+ _this.loading = false;
906
+ if (cached && specificHash) {
907
+ if (_client.dbService) {
908
+ try {
909
+ if (_this.data && _this.data?.length > 0) {
910
+ _client.dbService
911
+ .update('outbound', {
912
+ method,
913
+ data: _this.data,
914
+ specificHash,
915
+ length,
916
+ })
917
+ .subscribe(() => { });
918
+ }
919
+ else {
920
+ _client.dbService
921
+ .deleteByKey('outbound', method)
922
+ .subscribe(() => { });
923
+ }
924
+ }
925
+ catch (e) {
926
+ console.error('ActiveConnect: Unable to update cached data.');
927
+ console.error(e);
928
+ }
929
+ }
930
+ else {
931
+ console.error('ActiveConnect: Caching not possible as the indexedDB has not been initialized');
932
+ }
933
+ }
934
+ }
935
+ else {
936
+ _this.setData(data);
937
+ if (_this.loadedId) {
938
+ const loadedValue = _this.dataMap.get(_this.loadedId);
939
+ if (loadedValue) {
940
+ _this.loadedIdData = loadedValue;
941
+ _this.loadedIdChanged?.next(_this.loadedIdData);
942
+ }
943
+ }
944
+ _this.loading = false;
945
+ if (cached && specificHash) {
946
+ if (_client.dbService) {
947
+ try {
948
+ if (data && data?.length > 0) {
949
+ _client.dbService
950
+ .update('outbound', {
951
+ method,
952
+ data,
953
+ specificHash,
954
+ length,
955
+ })
956
+ .subscribe(() => { });
957
+ }
958
+ else {
959
+ _client.dbService
960
+ .deleteByKey('outbound', method)
961
+ .subscribe(() => { });
962
+ }
963
+ }
964
+ catch (e) {
965
+ console.error('ActiveConnect: Unable to update cached data.');
966
+ console.error(e);
967
+ }
968
+ }
969
+ else {
970
+ console.error('ActiveConnect: Caching not possible as the indexedDB has not been initialized');
971
+ }
972
+ }
973
+ }
974
+ if (length)
975
+ _this._length = length;
976
+ });
977
+ WebsocketClient.addResetRequestingStateCallback(() => {
978
+ this.afterServerReconnected();
979
+ });
980
+ }
981
+ get target() {
982
+ return this.client.__proto__;
983
+ }
984
+ get(id) {
985
+ if (this.requestedId == id && this.loadedObservable && this.loadedIdData) {
986
+ if (this.loadedIdData)
987
+ setTimeout(() => {
988
+ if (this.loadedIdData)
989
+ this.loadedIdChanged?.next(this.loadedIdData);
990
+ }, 50);
991
+ return this.loadedObservable;
992
+ }
993
+ let observablePromise;
994
+ if (this.requestedId != id || !this.loadedObservable) {
995
+ observablePromise = new Promise((resolve) => {
996
+ this.loadedObservable = new Observable((observer) => {
997
+ this.loadedIdChanged = observer;
998
+ resolve();
999
+ });
1000
+ });
1001
+ }
1002
+ Promise.all([observablePromise]).then(() => {
1003
+ new Promise(async (resolve) => {
1004
+ if (!this.requested && this.lazyLoaded) {
1005
+ this.load().then();
1006
+ }
1007
+ if (this.data) {
1008
+ const res = this.dataMap.get(id);
1009
+ if (res) {
1010
+ this.loadedIdChanged?.next(res);
1011
+ resolve();
1012
+ return;
1013
+ }
1014
+ }
1015
+ if (this.loadedId == id) {
1016
+ this.loadedIdChanged?.next(this.loadedIdData);
1017
+ }
1018
+ else {
1019
+ await this.requestById(id);
1020
+ }
1021
+ resolve();
1022
+ }).then();
1023
+ });
1024
+ return this.loadedObservable;
1025
+ }
1026
+ getForGroup(groupId) {
1027
+ if (this.requestedGroupId == groupId &&
1028
+ this.loadedGroupObservable &&
1029
+ this.loadedGroupData) {
1030
+ setTimeout(() => {
1031
+ if (this.loadedGroupData)
1032
+ this.loadedGroupChanged?.next(this.loadedGroupData);
1033
+ }, 50);
1034
+ return this.loadedGroupObservable;
1035
+ }
1036
+ let observablePromise;
1037
+ if (this.requestedGroupId != groupId || !this.loadedGroupObservable) {
1038
+ observablePromise = new Promise((resolve) => {
1039
+ this.loadedGroupObservable = new Observable((observer) => {
1040
+ this.loadedGroupChanged = observer;
1041
+ resolve();
1042
+ });
1043
+ });
1044
+ }
1045
+ Promise.all([observablePromise]).then(() => {
1046
+ new Promise(async (resolve) => {
1047
+ if (!this.requested && this.lazyLoaded) {
1048
+ this.load().then();
1049
+ }
1050
+ if (this.loadedGroupId == groupId && this.loadedGroupData) {
1051
+ this.loadedGroupChanged?.next(this.loadedGroupData);
1052
+ }
1053
+ else {
1054
+ await this.requestForGroup(groupId);
1055
+ }
1056
+ resolve();
1057
+ }).then();
1058
+ });
1059
+ return this.loadedGroupObservable;
1060
+ }
1061
+ get all() {
1062
+ if (!this.requested && this.lazyLoaded) {
1063
+ this.load().then();
1064
+ }
1065
+ return this.data;
1066
+ }
1067
+ async load(count) {
1068
+ if (this.lazyLoaded) {
1069
+ const hasBeenRequestedBefore = this.requested;
1070
+ this._loading = true;
1071
+ if (!this.requested) {
1072
+ this.loading = true;
1073
+ }
1074
+ this.requested = true;
1075
+ await this.client.send('request.' + this.method, {
1076
+ count: hasBeenRequestedBefore
1077
+ ? this.data
1078
+ ? count || this.initialLoadingCount
1079
+ ? (count || this.initialLoadingCount) +
1080
+ this.loadedLength
1081
+ : undefined
1082
+ : undefined
1083
+ : this.previouslyCachedCount || this.initialLoadingCount,
1084
+ loaded: this.loadedLength,
1085
+ });
1086
+ }
1087
+ else {
1088
+ throw Error('Active-Connect: Cannot run loading request as this outbound is not lazy-loaded.');
1089
+ }
1090
+ }
1091
+ set loading(value) {
1092
+ this._loading = value;
1093
+ this.target.loading.set(this.method, value);
1094
+ }
1095
+ get loading() {
1096
+ return this._loading;
1097
+ }
1098
+ get loadedLength() {
1099
+ return this.data?.length || 0;
1100
+ }
1101
+ get length() {
1102
+ return this._length;
1103
+ }
1104
+ requestById(id) {
1105
+ this.loading = true;
1106
+ this.requestedId = id;
1107
+ return this.client.send('request.' + this.method, { id });
1108
+ }
1109
+ requestForGroup(groupId) {
1110
+ this.loading = true;
1111
+ this.requestedGroupId = groupId;
1112
+ return this.client.send('request.' + this.method, { groupId });
1113
+ }
1114
+ setData(data) {
1115
+ this.data = data;
1116
+ if (this.data && this.sortBy)
1117
+ this.data = this.data.sort(this.sortBy);
1118
+ this._length = data.length;
1119
+ this.dataMap = new Map();
1120
+ this.data.forEach((d) => {
1121
+ this.dataMap.set(d.id, d);
1122
+ });
1123
+ }
1124
+ get isEmpty() {
1125
+ return this.data == undefined;
1126
+ }
1127
+ /**
1128
+ * The contained data can be modified within the callback method
1129
+ */
1130
+ update(callback) {
1131
+ if (this.data) {
1132
+ const updateLengthVariable = this.data.length == this._length;
1133
+ const length = this.length;
1134
+ callback(this.data);
1135
+ this.setData(this.data);
1136
+ if (!updateLengthVariable) {
1137
+ this._length = length;
1138
+ }
1139
+ }
1140
+ }
1141
+ afterServerReconnected() {
1142
+ if (this.requested && this.lazyLoaded) {
1143
+ this.requested = false;
1144
+ this.load(1).then();
1145
+ }
1146
+ if (this.loadedId) {
1147
+ this.loadedIdData = null;
1148
+ this.get(this.loadedId);
1149
+ }
1150
+ if (this.loadedGroupId) {
1151
+ this.loadedGroupData = null;
1152
+ this.getForGroup(this.loadedGroupId);
1153
+ }
1154
+ }
1155
+ }
1156
+
1157
+ /*
1158
+ * Public API Surface of active-connect-ng2
1159
+ */
1160
+
1161
+ /**
1162
+ * Generated bundle index. Do not edit.
1163
+ */
1164
+
1165
+ export { ActiveConnectNg2Module, Handle, LoadingStatus, OnReconnect, OnSuccess, Outbound, OutboundObject, Route, Shared, WebsocketClient };
1166
+ //# sourceMappingURL=active-connect-ng2.mjs.map