active-connect-ng2 0.2.49 → 0.3.0

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