active-connect-ng2 0.2.39 → 0.2.41

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