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