@auxilium/datalynk-client 1.5.2 → 1.6.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.
package/dist/chat.cjs ADDED
@@ -0,0 +1,2202 @@
1
+ (function(global, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.DatalynkChat = {}));
3
+ })(this, function(exports2) {
4
+ "use strict";var __defProp = Object.defineProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+
8
+ var extendStatics = function(d, b) {
9
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
10
+ d2.__proto__ = b2;
11
+ } || function(d2, b2) {
12
+ for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
13
+ };
14
+ return extendStatics(d, b);
15
+ };
16
+ function __extends(d, b) {
17
+ if (typeof b !== "function" && b !== null)
18
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
19
+ extendStatics(d, b);
20
+ function __() {
21
+ this.constructor = d;
22
+ }
23
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24
+ }
25
+ function __awaiter(thisArg, _arguments, P, generator) {
26
+ function adopt(value) {
27
+ return value instanceof P ? value : new P(function(resolve) {
28
+ resolve(value);
29
+ });
30
+ }
31
+ return new (P || (P = Promise))(function(resolve, reject) {
32
+ function fulfilled(value) {
33
+ try {
34
+ step(generator.next(value));
35
+ } catch (e) {
36
+ reject(e);
37
+ }
38
+ }
39
+ function rejected(value) {
40
+ try {
41
+ step(generator["throw"](value));
42
+ } catch (e) {
43
+ reject(e);
44
+ }
45
+ }
46
+ function step(result) {
47
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
48
+ }
49
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
50
+ });
51
+ }
52
+ function __generator(thisArg, body) {
53
+ var _ = { label: 0, sent: function() {
54
+ if (t[0] & 1) throw t[1];
55
+ return t[1];
56
+ }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
57
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
58
+ return this;
59
+ }), g;
60
+ function verb(n) {
61
+ return function(v) {
62
+ return step([n, v]);
63
+ };
64
+ }
65
+ function step(op) {
66
+ if (f) throw new TypeError("Generator is already executing.");
67
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
68
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
69
+ if (y = 0, t) op = [op[0] & 2, t.value];
70
+ switch (op[0]) {
71
+ case 0:
72
+ case 1:
73
+ t = op;
74
+ break;
75
+ case 4:
76
+ _.label++;
77
+ return { value: op[1], done: false };
78
+ case 5:
79
+ _.label++;
80
+ y = op[1];
81
+ op = [0];
82
+ continue;
83
+ case 7:
84
+ op = _.ops.pop();
85
+ _.trys.pop();
86
+ continue;
87
+ default:
88
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
89
+ _ = 0;
90
+ continue;
91
+ }
92
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
93
+ _.label = op[1];
94
+ break;
95
+ }
96
+ if (op[0] === 6 && _.label < t[1]) {
97
+ _.label = t[1];
98
+ t = op;
99
+ break;
100
+ }
101
+ if (t && _.label < t[2]) {
102
+ _.label = t[2];
103
+ _.ops.push(op);
104
+ break;
105
+ }
106
+ if (t[2]) _.ops.pop();
107
+ _.trys.pop();
108
+ continue;
109
+ }
110
+ op = body.call(thisArg, _);
111
+ } catch (e) {
112
+ op = [6, e];
113
+ y = 0;
114
+ } finally {
115
+ f = t = 0;
116
+ }
117
+ if (op[0] & 5) throw op[1];
118
+ return { value: op[0] ? op[1] : void 0, done: true };
119
+ }
120
+ }
121
+ function __values(o) {
122
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
123
+ if (m) return m.call(o);
124
+ if (o && typeof o.length === "number") return {
125
+ next: function() {
126
+ if (o && i >= o.length) o = void 0;
127
+ return { value: o && o[i++], done: !o };
128
+ }
129
+ };
130
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
131
+ }
132
+ function __read(o, n) {
133
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
134
+ if (!m) return o;
135
+ var i = m.call(o), r, ar = [], e;
136
+ try {
137
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
138
+ } catch (error) {
139
+ e = { error };
140
+ } finally {
141
+ try {
142
+ if (r && !r.done && (m = i["return"])) m.call(i);
143
+ } finally {
144
+ if (e) throw e.error;
145
+ }
146
+ }
147
+ return ar;
148
+ }
149
+ function __spreadArray(to, from2, pack) {
150
+ if (pack || arguments.length === 2) for (var i = 0, l = from2.length, ar; i < l; i++) {
151
+ if (ar || !(i in from2)) {
152
+ if (!ar) ar = Array.prototype.slice.call(from2, 0, i);
153
+ ar[i] = from2[i];
154
+ }
155
+ }
156
+ return to.concat(ar || Array.prototype.slice.call(from2));
157
+ }
158
+ function __await(v) {
159
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
160
+ }
161
+ function __asyncGenerator(thisArg, _arguments, generator) {
162
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
163
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
164
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
165
+ return this;
166
+ }, i;
167
+ function awaitReturn(f) {
168
+ return function(v) {
169
+ return Promise.resolve(v).then(f, reject);
170
+ };
171
+ }
172
+ function verb(n, f) {
173
+ if (g[n]) {
174
+ i[n] = function(v) {
175
+ return new Promise(function(a, b) {
176
+ q.push([n, v, a, b]) > 1 || resume(n, v);
177
+ });
178
+ };
179
+ if (f) i[n] = f(i[n]);
180
+ }
181
+ }
182
+ function resume(n, v) {
183
+ try {
184
+ step(g[n](v));
185
+ } catch (e) {
186
+ settle(q[0][3], e);
187
+ }
188
+ }
189
+ function step(r) {
190
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
191
+ }
192
+ function fulfill(value) {
193
+ resume("next", value);
194
+ }
195
+ function reject(value) {
196
+ resume("throw", value);
197
+ }
198
+ function settle(f, v) {
199
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
200
+ }
201
+ }
202
+ function __asyncValues(o) {
203
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
204
+ var m = o[Symbol.asyncIterator], i;
205
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
206
+ return this;
207
+ }, i);
208
+ function verb(n) {
209
+ i[n] = o[n] && function(v) {
210
+ return new Promise(function(resolve, reject) {
211
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
212
+ });
213
+ };
214
+ }
215
+ function settle(resolve, reject, d, v) {
216
+ Promise.resolve(v).then(function(v2) {
217
+ resolve({ value: v2, done: d });
218
+ }, reject);
219
+ }
220
+ }
221
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
222
+ var e = new Error(message);
223
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
224
+ };
225
+ function isFunction(value) {
226
+ return typeof value === "function";
227
+ }
228
+ function createErrorClass(createImpl) {
229
+ var _super = function(instance) {
230
+ Error.call(instance);
231
+ instance.stack = new Error().stack;
232
+ };
233
+ var ctorFunc = createImpl(_super);
234
+ ctorFunc.prototype = Object.create(Error.prototype);
235
+ ctorFunc.prototype.constructor = ctorFunc;
236
+ return ctorFunc;
237
+ }
238
+ var UnsubscriptionError = createErrorClass(function(_super) {
239
+ return function UnsubscriptionErrorImpl(errors) {
240
+ _super(this);
241
+ this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
242
+ return i + 1 + ") " + err.toString();
243
+ }).join("\n ") : "";
244
+ this.name = "UnsubscriptionError";
245
+ this.errors = errors;
246
+ };
247
+ });
248
+ function arrRemove(arr, item) {
249
+ if (arr) {
250
+ var index = arr.indexOf(item);
251
+ 0 <= index && arr.splice(index, 1);
252
+ }
253
+ }
254
+ var Subscription = function() {
255
+ function Subscription2(initialTeardown) {
256
+ this.initialTeardown = initialTeardown;
257
+ this.closed = false;
258
+ this._parentage = null;
259
+ this._finalizers = null;
260
+ }
261
+ Subscription2.prototype.unsubscribe = function() {
262
+ var e_1, _a, e_2, _b;
263
+ var errors;
264
+ if (!this.closed) {
265
+ this.closed = true;
266
+ var _parentage = this._parentage;
267
+ if (_parentage) {
268
+ this._parentage = null;
269
+ if (Array.isArray(_parentage)) {
270
+ try {
271
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
272
+ var parent_1 = _parentage_1_1.value;
273
+ parent_1.remove(this);
274
+ }
275
+ } catch (e_1_1) {
276
+ e_1 = { error: e_1_1 };
277
+ } finally {
278
+ try {
279
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
280
+ } finally {
281
+ if (e_1) throw e_1.error;
282
+ }
283
+ }
284
+ } else {
285
+ _parentage.remove(this);
286
+ }
287
+ }
288
+ var initialFinalizer = this.initialTeardown;
289
+ if (isFunction(initialFinalizer)) {
290
+ try {
291
+ initialFinalizer();
292
+ } catch (e) {
293
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
294
+ }
295
+ }
296
+ var _finalizers = this._finalizers;
297
+ if (_finalizers) {
298
+ this._finalizers = null;
299
+ try {
300
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
301
+ var finalizer = _finalizers_1_1.value;
302
+ try {
303
+ execFinalizer(finalizer);
304
+ } catch (err) {
305
+ errors = errors !== null && errors !== void 0 ? errors : [];
306
+ if (err instanceof UnsubscriptionError) {
307
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
308
+ } else {
309
+ errors.push(err);
310
+ }
311
+ }
312
+ }
313
+ } catch (e_2_1) {
314
+ e_2 = { error: e_2_1 };
315
+ } finally {
316
+ try {
317
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
318
+ } finally {
319
+ if (e_2) throw e_2.error;
320
+ }
321
+ }
322
+ }
323
+ if (errors) {
324
+ throw new UnsubscriptionError(errors);
325
+ }
326
+ }
327
+ };
328
+ Subscription2.prototype.add = function(teardown) {
329
+ var _a;
330
+ if (teardown && teardown !== this) {
331
+ if (this.closed) {
332
+ execFinalizer(teardown);
333
+ } else {
334
+ if (teardown instanceof Subscription2) {
335
+ if (teardown.closed || teardown._hasParent(this)) {
336
+ return;
337
+ }
338
+ teardown._addParent(this);
339
+ }
340
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
341
+ }
342
+ }
343
+ };
344
+ Subscription2.prototype._hasParent = function(parent) {
345
+ var _parentage = this._parentage;
346
+ return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
347
+ };
348
+ Subscription2.prototype._addParent = function(parent) {
349
+ var _parentage = this._parentage;
350
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
351
+ };
352
+ Subscription2.prototype._removeParent = function(parent) {
353
+ var _parentage = this._parentage;
354
+ if (_parentage === parent) {
355
+ this._parentage = null;
356
+ } else if (Array.isArray(_parentage)) {
357
+ arrRemove(_parentage, parent);
358
+ }
359
+ };
360
+ Subscription2.prototype.remove = function(teardown) {
361
+ var _finalizers = this._finalizers;
362
+ _finalizers && arrRemove(_finalizers, teardown);
363
+ if (teardown instanceof Subscription2) {
364
+ teardown._removeParent(this);
365
+ }
366
+ };
367
+ Subscription2.EMPTY = function() {
368
+ var empty = new Subscription2();
369
+ empty.closed = true;
370
+ return empty;
371
+ }();
372
+ return Subscription2;
373
+ }();
374
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
375
+ function isSubscription(value) {
376
+ return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
377
+ }
378
+ function execFinalizer(finalizer) {
379
+ if (isFunction(finalizer)) {
380
+ finalizer();
381
+ } else {
382
+ finalizer.unsubscribe();
383
+ }
384
+ }
385
+ var config = {
386
+ Promise: void 0
387
+ };
388
+ var timeoutProvider = {
389
+ setTimeout: function(handler, timeout) {
390
+ var args = [];
391
+ for (var _i = 2; _i < arguments.length; _i++) {
392
+ args[_i - 2] = arguments[_i];
393
+ }
394
+ return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
395
+ },
396
+ clearTimeout: function(handle) {
397
+ return clearTimeout(handle);
398
+ },
399
+ delegate: void 0
400
+ };
401
+ function reportUnhandledError(err) {
402
+ timeoutProvider.setTimeout(function() {
403
+ {
404
+ throw err;
405
+ }
406
+ });
407
+ }
408
+ function noop() {
409
+ }
410
+ function errorContext(cb) {
411
+ {
412
+ cb();
413
+ }
414
+ }
415
+ var Subscriber = function(_super) {
416
+ __extends(Subscriber2, _super);
417
+ function Subscriber2(destination) {
418
+ var _this = _super.call(this) || this;
419
+ _this.isStopped = false;
420
+ if (destination) {
421
+ _this.destination = destination;
422
+ if (isSubscription(destination)) {
423
+ destination.add(_this);
424
+ }
425
+ } else {
426
+ _this.destination = EMPTY_OBSERVER;
427
+ }
428
+ return _this;
429
+ }
430
+ Subscriber2.create = function(next, error, complete) {
431
+ return new SafeSubscriber(next, error, complete);
432
+ };
433
+ Subscriber2.prototype.next = function(value) {
434
+ if (this.isStopped) ;
435
+ else {
436
+ this._next(value);
437
+ }
438
+ };
439
+ Subscriber2.prototype.error = function(err) {
440
+ if (this.isStopped) ;
441
+ else {
442
+ this.isStopped = true;
443
+ this._error(err);
444
+ }
445
+ };
446
+ Subscriber2.prototype.complete = function() {
447
+ if (this.isStopped) ;
448
+ else {
449
+ this.isStopped = true;
450
+ this._complete();
451
+ }
452
+ };
453
+ Subscriber2.prototype.unsubscribe = function() {
454
+ if (!this.closed) {
455
+ this.isStopped = true;
456
+ _super.prototype.unsubscribe.call(this);
457
+ this.destination = null;
458
+ }
459
+ };
460
+ Subscriber2.prototype._next = function(value) {
461
+ this.destination.next(value);
462
+ };
463
+ Subscriber2.prototype._error = function(err) {
464
+ try {
465
+ this.destination.error(err);
466
+ } finally {
467
+ this.unsubscribe();
468
+ }
469
+ };
470
+ Subscriber2.prototype._complete = function() {
471
+ try {
472
+ this.destination.complete();
473
+ } finally {
474
+ this.unsubscribe();
475
+ }
476
+ };
477
+ return Subscriber2;
478
+ }(Subscription);
479
+ var ConsumerObserver = function() {
480
+ function ConsumerObserver2(partialObserver) {
481
+ this.partialObserver = partialObserver;
482
+ }
483
+ ConsumerObserver2.prototype.next = function(value) {
484
+ var partialObserver = this.partialObserver;
485
+ if (partialObserver.next) {
486
+ try {
487
+ partialObserver.next(value);
488
+ } catch (error) {
489
+ handleUnhandledError(error);
490
+ }
491
+ }
492
+ };
493
+ ConsumerObserver2.prototype.error = function(err) {
494
+ var partialObserver = this.partialObserver;
495
+ if (partialObserver.error) {
496
+ try {
497
+ partialObserver.error(err);
498
+ } catch (error) {
499
+ handleUnhandledError(error);
500
+ }
501
+ } else {
502
+ handleUnhandledError(err);
503
+ }
504
+ };
505
+ ConsumerObserver2.prototype.complete = function() {
506
+ var partialObserver = this.partialObserver;
507
+ if (partialObserver.complete) {
508
+ try {
509
+ partialObserver.complete();
510
+ } catch (error) {
511
+ handleUnhandledError(error);
512
+ }
513
+ }
514
+ };
515
+ return ConsumerObserver2;
516
+ }();
517
+ var SafeSubscriber = function(_super) {
518
+ __extends(SafeSubscriber2, _super);
519
+ function SafeSubscriber2(observerOrNext, error, complete) {
520
+ var _this = _super.call(this) || this;
521
+ var partialObserver;
522
+ if (isFunction(observerOrNext) || !observerOrNext) {
523
+ partialObserver = {
524
+ next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0,
525
+ error: error !== null && error !== void 0 ? error : void 0,
526
+ complete: complete !== null && complete !== void 0 ? complete : void 0
527
+ };
528
+ } else {
529
+ {
530
+ partialObserver = observerOrNext;
531
+ }
532
+ }
533
+ _this.destination = new ConsumerObserver(partialObserver);
534
+ return _this;
535
+ }
536
+ return SafeSubscriber2;
537
+ }(Subscriber);
538
+ function handleUnhandledError(error) {
539
+ {
540
+ reportUnhandledError(error);
541
+ }
542
+ }
543
+ function defaultErrorHandler(err) {
544
+ throw err;
545
+ }
546
+ var EMPTY_OBSERVER = {
547
+ closed: true,
548
+ next: noop,
549
+ error: defaultErrorHandler,
550
+ complete: noop
551
+ };
552
+ var observable = function() {
553
+ return typeof Symbol === "function" && Symbol.observable || "@@observable";
554
+ }();
555
+ function identity(x) {
556
+ return x;
557
+ }
558
+ function pipeFromArray(fns) {
559
+ if (fns.length === 0) {
560
+ return identity;
561
+ }
562
+ if (fns.length === 1) {
563
+ return fns[0];
564
+ }
565
+ return function piped(input) {
566
+ return fns.reduce(function(prev, fn) {
567
+ return fn(prev);
568
+ }, input);
569
+ };
570
+ }
571
+ var Observable = function() {
572
+ function Observable2(subscribe) {
573
+ if (subscribe) {
574
+ this._subscribe = subscribe;
575
+ }
576
+ }
577
+ Observable2.prototype.lift = function(operator) {
578
+ var observable2 = new Observable2();
579
+ observable2.source = this;
580
+ observable2.operator = operator;
581
+ return observable2;
582
+ };
583
+ Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
584
+ var _this = this;
585
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
586
+ errorContext(function() {
587
+ var _a = _this, operator = _a.operator, source = _a.source;
588
+ subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
589
+ });
590
+ return subscriber;
591
+ };
592
+ Observable2.prototype._trySubscribe = function(sink) {
593
+ try {
594
+ return this._subscribe(sink);
595
+ } catch (err) {
596
+ sink.error(err);
597
+ }
598
+ };
599
+ Observable2.prototype.forEach = function(next, promiseCtor) {
600
+ var _this = this;
601
+ promiseCtor = getPromiseCtor(promiseCtor);
602
+ return new promiseCtor(function(resolve, reject) {
603
+ var subscriber = new SafeSubscriber({
604
+ next: function(value) {
605
+ try {
606
+ next(value);
607
+ } catch (err) {
608
+ reject(err);
609
+ subscriber.unsubscribe();
610
+ }
611
+ },
612
+ error: reject,
613
+ complete: resolve
614
+ });
615
+ _this.subscribe(subscriber);
616
+ });
617
+ };
618
+ Observable2.prototype._subscribe = function(subscriber) {
619
+ var _a;
620
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
621
+ };
622
+ Observable2.prototype[observable] = function() {
623
+ return this;
624
+ };
625
+ Observable2.prototype.pipe = function() {
626
+ var operations = [];
627
+ for (var _i = 0; _i < arguments.length; _i++) {
628
+ operations[_i] = arguments[_i];
629
+ }
630
+ return pipeFromArray(operations)(this);
631
+ };
632
+ Observable2.prototype.toPromise = function(promiseCtor) {
633
+ var _this = this;
634
+ promiseCtor = getPromiseCtor(promiseCtor);
635
+ return new promiseCtor(function(resolve, reject) {
636
+ var value;
637
+ _this.subscribe(function(x) {
638
+ return value = x;
639
+ }, function(err) {
640
+ return reject(err);
641
+ }, function() {
642
+ return resolve(value);
643
+ });
644
+ });
645
+ };
646
+ Observable2.create = function(subscribe) {
647
+ return new Observable2(subscribe);
648
+ };
649
+ return Observable2;
650
+ }();
651
+ function getPromiseCtor(promiseCtor) {
652
+ var _a;
653
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
654
+ }
655
+ function isObserver(value) {
656
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
657
+ }
658
+ function isSubscriber(value) {
659
+ return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
660
+ }
661
+ function hasLift(source) {
662
+ return isFunction(source === null || source === void 0 ? void 0 : source.lift);
663
+ }
664
+ function operate(init) {
665
+ return function(source) {
666
+ if (hasLift(source)) {
667
+ return source.lift(function(liftedSource) {
668
+ try {
669
+ return init(liftedSource, this);
670
+ } catch (err) {
671
+ this.error(err);
672
+ }
673
+ });
674
+ }
675
+ throw new TypeError("Unable to lift unknown Observable type");
676
+ };
677
+ }
678
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
679
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
680
+ }
681
+ var OperatorSubscriber = function(_super) {
682
+ __extends(OperatorSubscriber2, _super);
683
+ function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
684
+ var _this = _super.call(this, destination) || this;
685
+ _this.onFinalize = onFinalize;
686
+ _this.shouldUnsubscribe = shouldUnsubscribe;
687
+ _this._next = onNext ? function(value) {
688
+ try {
689
+ onNext(value);
690
+ } catch (err) {
691
+ destination.error(err);
692
+ }
693
+ } : _super.prototype._next;
694
+ _this._error = onError ? function(err) {
695
+ try {
696
+ onError(err);
697
+ } catch (err2) {
698
+ destination.error(err2);
699
+ } finally {
700
+ this.unsubscribe();
701
+ }
702
+ } : _super.prototype._error;
703
+ _this._complete = onComplete ? function() {
704
+ try {
705
+ onComplete();
706
+ } catch (err) {
707
+ destination.error(err);
708
+ } finally {
709
+ this.unsubscribe();
710
+ }
711
+ } : _super.prototype._complete;
712
+ return _this;
713
+ }
714
+ OperatorSubscriber2.prototype.unsubscribe = function() {
715
+ var _a;
716
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
717
+ var closed_1 = this.closed;
718
+ _super.prototype.unsubscribe.call(this);
719
+ !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
720
+ }
721
+ };
722
+ return OperatorSubscriber2;
723
+ }(Subscriber);
724
+ var ObjectUnsubscribedError = createErrorClass(function(_super) {
725
+ return function ObjectUnsubscribedErrorImpl() {
726
+ _super(this);
727
+ this.name = "ObjectUnsubscribedError";
728
+ this.message = "object unsubscribed";
729
+ };
730
+ });
731
+ var Subject = function(_super) {
732
+ __extends(Subject2, _super);
733
+ function Subject2() {
734
+ var _this = _super.call(this) || this;
735
+ _this.closed = false;
736
+ _this.currentObservers = null;
737
+ _this.observers = [];
738
+ _this.isStopped = false;
739
+ _this.hasError = false;
740
+ _this.thrownError = null;
741
+ return _this;
742
+ }
743
+ Subject2.prototype.lift = function(operator) {
744
+ var subject = new AnonymousSubject(this, this);
745
+ subject.operator = operator;
746
+ return subject;
747
+ };
748
+ Subject2.prototype._throwIfClosed = function() {
749
+ if (this.closed) {
750
+ throw new ObjectUnsubscribedError();
751
+ }
752
+ };
753
+ Subject2.prototype.next = function(value) {
754
+ var _this = this;
755
+ errorContext(function() {
756
+ var e_1, _a;
757
+ _this._throwIfClosed();
758
+ if (!_this.isStopped) {
759
+ if (!_this.currentObservers) {
760
+ _this.currentObservers = Array.from(_this.observers);
761
+ }
762
+ try {
763
+ for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
764
+ var observer = _c.value;
765
+ observer.next(value);
766
+ }
767
+ } catch (e_1_1) {
768
+ e_1 = { error: e_1_1 };
769
+ } finally {
770
+ try {
771
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
772
+ } finally {
773
+ if (e_1) throw e_1.error;
774
+ }
775
+ }
776
+ }
777
+ });
778
+ };
779
+ Subject2.prototype.error = function(err) {
780
+ var _this = this;
781
+ errorContext(function() {
782
+ _this._throwIfClosed();
783
+ if (!_this.isStopped) {
784
+ _this.hasError = _this.isStopped = true;
785
+ _this.thrownError = err;
786
+ var observers = _this.observers;
787
+ while (observers.length) {
788
+ observers.shift().error(err);
789
+ }
790
+ }
791
+ });
792
+ };
793
+ Subject2.prototype.complete = function() {
794
+ var _this = this;
795
+ errorContext(function() {
796
+ _this._throwIfClosed();
797
+ if (!_this.isStopped) {
798
+ _this.isStopped = true;
799
+ var observers = _this.observers;
800
+ while (observers.length) {
801
+ observers.shift().complete();
802
+ }
803
+ }
804
+ });
805
+ };
806
+ Subject2.prototype.unsubscribe = function() {
807
+ this.isStopped = this.closed = true;
808
+ this.observers = this.currentObservers = null;
809
+ };
810
+ Object.defineProperty(Subject2.prototype, "observed", {
811
+ get: function() {
812
+ var _a;
813
+ return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
814
+ },
815
+ enumerable: false,
816
+ configurable: true
817
+ });
818
+ Subject2.prototype._trySubscribe = function(subscriber) {
819
+ this._throwIfClosed();
820
+ return _super.prototype._trySubscribe.call(this, subscriber);
821
+ };
822
+ Subject2.prototype._subscribe = function(subscriber) {
823
+ this._throwIfClosed();
824
+ this._checkFinalizedStatuses(subscriber);
825
+ return this._innerSubscribe(subscriber);
826
+ };
827
+ Subject2.prototype._innerSubscribe = function(subscriber) {
828
+ var _this = this;
829
+ var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
830
+ if (hasError || isStopped) {
831
+ return EMPTY_SUBSCRIPTION;
832
+ }
833
+ this.currentObservers = null;
834
+ observers.push(subscriber);
835
+ return new Subscription(function() {
836
+ _this.currentObservers = null;
837
+ arrRemove(observers, subscriber);
838
+ });
839
+ };
840
+ Subject2.prototype._checkFinalizedStatuses = function(subscriber) {
841
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
842
+ if (hasError) {
843
+ subscriber.error(thrownError);
844
+ } else if (isStopped) {
845
+ subscriber.complete();
846
+ }
847
+ };
848
+ Subject2.prototype.asObservable = function() {
849
+ var observable2 = new Observable();
850
+ observable2.source = this;
851
+ return observable2;
852
+ };
853
+ Subject2.create = function(destination, source) {
854
+ return new AnonymousSubject(destination, source);
855
+ };
856
+ return Subject2;
857
+ }(Observable);
858
+ var AnonymousSubject = function(_super) {
859
+ __extends(AnonymousSubject2, _super);
860
+ function AnonymousSubject2(destination, source) {
861
+ var _this = _super.call(this) || this;
862
+ _this.destination = destination;
863
+ _this.source = source;
864
+ return _this;
865
+ }
866
+ AnonymousSubject2.prototype.next = function(value) {
867
+ var _a, _b;
868
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
869
+ };
870
+ AnonymousSubject2.prototype.error = function(err) {
871
+ var _a, _b;
872
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
873
+ };
874
+ AnonymousSubject2.prototype.complete = function() {
875
+ var _a, _b;
876
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
877
+ };
878
+ AnonymousSubject2.prototype._subscribe = function(subscriber) {
879
+ var _a, _b;
880
+ return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
881
+ };
882
+ return AnonymousSubject2;
883
+ }(Subject);
884
+ var BehaviorSubject = function(_super) {
885
+ __extends(BehaviorSubject2, _super);
886
+ function BehaviorSubject2(_value) {
887
+ var _this = _super.call(this) || this;
888
+ _this._value = _value;
889
+ return _this;
890
+ }
891
+ Object.defineProperty(BehaviorSubject2.prototype, "value", {
892
+ get: function() {
893
+ return this.getValue();
894
+ },
895
+ enumerable: false,
896
+ configurable: true
897
+ });
898
+ BehaviorSubject2.prototype._subscribe = function(subscriber) {
899
+ var subscription = _super.prototype._subscribe.call(this, subscriber);
900
+ !subscription.closed && subscriber.next(this._value);
901
+ return subscription;
902
+ };
903
+ BehaviorSubject2.prototype.getValue = function() {
904
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
905
+ if (hasError) {
906
+ throw thrownError;
907
+ }
908
+ this._throwIfClosed();
909
+ return _value;
910
+ };
911
+ BehaviorSubject2.prototype.next = function(value) {
912
+ _super.prototype.next.call(this, this._value = value);
913
+ };
914
+ return BehaviorSubject2;
915
+ }(Subject);
916
+ function isScheduler(value) {
917
+ return value && isFunction(value.schedule);
918
+ }
919
+ function last(arr) {
920
+ return arr[arr.length - 1];
921
+ }
922
+ function popResultSelector(args) {
923
+ return isFunction(last(args)) ? args.pop() : void 0;
924
+ }
925
+ function popScheduler(args) {
926
+ return isScheduler(last(args)) ? args.pop() : void 0;
927
+ }
928
+ var isArrayLike = function(x) {
929
+ return x && typeof x.length === "number" && typeof x !== "function";
930
+ };
931
+ function isPromise(value) {
932
+ return isFunction(value === null || value === void 0 ? void 0 : value.then);
933
+ }
934
+ function isInteropObservable(input) {
935
+ return isFunction(input[observable]);
936
+ }
937
+ function isAsyncIterable(obj) {
938
+ return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
939
+ }
940
+ function createInvalidObservableTypeError(input) {
941
+ return new TypeError("You provided " + (input !== null && typeof input === "object" ? "an invalid object" : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
942
+ }
943
+ function getSymbolIterator() {
944
+ if (typeof Symbol !== "function" || !Symbol.iterator) {
945
+ return "@@iterator";
946
+ }
947
+ return Symbol.iterator;
948
+ }
949
+ var iterator = getSymbolIterator();
950
+ function isIterable(input) {
951
+ return isFunction(input === null || input === void 0 ? void 0 : input[iterator]);
952
+ }
953
+ function readableStreamLikeToAsyncGenerator(readableStream) {
954
+ return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
955
+ var reader, _a, value, done;
956
+ return __generator(this, function(_b) {
957
+ switch (_b.label) {
958
+ case 0:
959
+ reader = readableStream.getReader();
960
+ _b.label = 1;
961
+ case 1:
962
+ _b.trys.push([1, , 9, 10]);
963
+ _b.label = 2;
964
+ case 2:
965
+ return [4, __await(reader.read())];
966
+ case 3:
967
+ _a = _b.sent(), value = _a.value, done = _a.done;
968
+ if (!done) return [3, 5];
969
+ return [4, __await(void 0)];
970
+ case 4:
971
+ return [2, _b.sent()];
972
+ case 5:
973
+ return [4, __await(value)];
974
+ case 6:
975
+ return [4, _b.sent()];
976
+ case 7:
977
+ _b.sent();
978
+ return [3, 2];
979
+ case 8:
980
+ return [3, 10];
981
+ case 9:
982
+ reader.releaseLock();
983
+ return [7];
984
+ case 10:
985
+ return [2];
986
+ }
987
+ });
988
+ });
989
+ }
990
+ function isReadableStreamLike(obj) {
991
+ return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);
992
+ }
993
+ function innerFrom(input) {
994
+ if (input instanceof Observable) {
995
+ return input;
996
+ }
997
+ if (input != null) {
998
+ if (isInteropObservable(input)) {
999
+ return fromInteropObservable(input);
1000
+ }
1001
+ if (isArrayLike(input)) {
1002
+ return fromArrayLike(input);
1003
+ }
1004
+ if (isPromise(input)) {
1005
+ return fromPromise(input);
1006
+ }
1007
+ if (isAsyncIterable(input)) {
1008
+ return fromAsyncIterable(input);
1009
+ }
1010
+ if (isIterable(input)) {
1011
+ return fromIterable(input);
1012
+ }
1013
+ if (isReadableStreamLike(input)) {
1014
+ return fromReadableStreamLike(input);
1015
+ }
1016
+ }
1017
+ throw createInvalidObservableTypeError(input);
1018
+ }
1019
+ function fromInteropObservable(obj) {
1020
+ return new Observable(function(subscriber) {
1021
+ var obs = obj[observable]();
1022
+ if (isFunction(obs.subscribe)) {
1023
+ return obs.subscribe(subscriber);
1024
+ }
1025
+ throw new TypeError("Provided object does not correctly implement Symbol.observable");
1026
+ });
1027
+ }
1028
+ function fromArrayLike(array) {
1029
+ return new Observable(function(subscriber) {
1030
+ for (var i = 0; i < array.length && !subscriber.closed; i++) {
1031
+ subscriber.next(array[i]);
1032
+ }
1033
+ subscriber.complete();
1034
+ });
1035
+ }
1036
+ function fromPromise(promise) {
1037
+ return new Observable(function(subscriber) {
1038
+ promise.then(function(value) {
1039
+ if (!subscriber.closed) {
1040
+ subscriber.next(value);
1041
+ subscriber.complete();
1042
+ }
1043
+ }, function(err) {
1044
+ return subscriber.error(err);
1045
+ }).then(null, reportUnhandledError);
1046
+ });
1047
+ }
1048
+ function fromIterable(iterable) {
1049
+ return new Observable(function(subscriber) {
1050
+ var e_1, _a;
1051
+ try {
1052
+ for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
1053
+ var value = iterable_1_1.value;
1054
+ subscriber.next(value);
1055
+ if (subscriber.closed) {
1056
+ return;
1057
+ }
1058
+ }
1059
+ } catch (e_1_1) {
1060
+ e_1 = { error: e_1_1 };
1061
+ } finally {
1062
+ try {
1063
+ if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);
1064
+ } finally {
1065
+ if (e_1) throw e_1.error;
1066
+ }
1067
+ }
1068
+ subscriber.complete();
1069
+ });
1070
+ }
1071
+ function fromAsyncIterable(asyncIterable) {
1072
+ return new Observable(function(subscriber) {
1073
+ process(asyncIterable, subscriber).catch(function(err) {
1074
+ return subscriber.error(err);
1075
+ });
1076
+ });
1077
+ }
1078
+ function fromReadableStreamLike(readableStream) {
1079
+ return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
1080
+ }
1081
+ function process(asyncIterable, subscriber) {
1082
+ var asyncIterable_1, asyncIterable_1_1;
1083
+ var e_2, _a;
1084
+ return __awaiter(this, void 0, void 0, function() {
1085
+ var value, e_2_1;
1086
+ return __generator(this, function(_b) {
1087
+ switch (_b.label) {
1088
+ case 0:
1089
+ _b.trys.push([0, 5, 6, 11]);
1090
+ asyncIterable_1 = __asyncValues(asyncIterable);
1091
+ _b.label = 1;
1092
+ case 1:
1093
+ return [4, asyncIterable_1.next()];
1094
+ case 2:
1095
+ if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];
1096
+ value = asyncIterable_1_1.value;
1097
+ subscriber.next(value);
1098
+ if (subscriber.closed) {
1099
+ return [2];
1100
+ }
1101
+ _b.label = 3;
1102
+ case 3:
1103
+ return [3, 1];
1104
+ case 4:
1105
+ return [3, 11];
1106
+ case 5:
1107
+ e_2_1 = _b.sent();
1108
+ e_2 = { error: e_2_1 };
1109
+ return [3, 11];
1110
+ case 6:
1111
+ _b.trys.push([6, , 9, 10]);
1112
+ if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];
1113
+ return [4, _a.call(asyncIterable_1)];
1114
+ case 7:
1115
+ _b.sent();
1116
+ _b.label = 8;
1117
+ case 8:
1118
+ return [3, 10];
1119
+ case 9:
1120
+ if (e_2) throw e_2.error;
1121
+ return [7];
1122
+ case 10:
1123
+ return [7];
1124
+ case 11:
1125
+ subscriber.complete();
1126
+ return [2];
1127
+ }
1128
+ });
1129
+ });
1130
+ }
1131
+ function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
1132
+ if (delay === void 0) {
1133
+ delay = 0;
1134
+ }
1135
+ if (repeat === void 0) {
1136
+ repeat = false;
1137
+ }
1138
+ var scheduleSubscription = scheduler.schedule(function() {
1139
+ work();
1140
+ if (repeat) {
1141
+ parentSubscription.add(this.schedule(null, delay));
1142
+ } else {
1143
+ this.unsubscribe();
1144
+ }
1145
+ }, delay);
1146
+ parentSubscription.add(scheduleSubscription);
1147
+ if (!repeat) {
1148
+ return scheduleSubscription;
1149
+ }
1150
+ }
1151
+ function observeOn(scheduler, delay) {
1152
+ if (delay === void 0) {
1153
+ delay = 0;
1154
+ }
1155
+ return operate(function(source, subscriber) {
1156
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1157
+ return executeSchedule(subscriber, scheduler, function() {
1158
+ return subscriber.next(value);
1159
+ }, delay);
1160
+ }, function() {
1161
+ return executeSchedule(subscriber, scheduler, function() {
1162
+ return subscriber.complete();
1163
+ }, delay);
1164
+ }, function(err) {
1165
+ return executeSchedule(subscriber, scheduler, function() {
1166
+ return subscriber.error(err);
1167
+ }, delay);
1168
+ }));
1169
+ });
1170
+ }
1171
+ function subscribeOn(scheduler, delay) {
1172
+ if (delay === void 0) {
1173
+ delay = 0;
1174
+ }
1175
+ return operate(function(source, subscriber) {
1176
+ subscriber.add(scheduler.schedule(function() {
1177
+ return source.subscribe(subscriber);
1178
+ }, delay));
1179
+ });
1180
+ }
1181
+ function scheduleObservable(input, scheduler) {
1182
+ return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1183
+ }
1184
+ function schedulePromise(input, scheduler) {
1185
+ return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1186
+ }
1187
+ function scheduleArray(input, scheduler) {
1188
+ return new Observable(function(subscriber) {
1189
+ var i = 0;
1190
+ return scheduler.schedule(function() {
1191
+ if (i === input.length) {
1192
+ subscriber.complete();
1193
+ } else {
1194
+ subscriber.next(input[i++]);
1195
+ if (!subscriber.closed) {
1196
+ this.schedule();
1197
+ }
1198
+ }
1199
+ });
1200
+ });
1201
+ }
1202
+ function scheduleIterable(input, scheduler) {
1203
+ return new Observable(function(subscriber) {
1204
+ var iterator$1;
1205
+ executeSchedule(subscriber, scheduler, function() {
1206
+ iterator$1 = input[iterator]();
1207
+ executeSchedule(subscriber, scheduler, function() {
1208
+ var _a;
1209
+ var value;
1210
+ var done;
1211
+ try {
1212
+ _a = iterator$1.next(), value = _a.value, done = _a.done;
1213
+ } catch (err) {
1214
+ subscriber.error(err);
1215
+ return;
1216
+ }
1217
+ if (done) {
1218
+ subscriber.complete();
1219
+ } else {
1220
+ subscriber.next(value);
1221
+ }
1222
+ }, 0, true);
1223
+ });
1224
+ return function() {
1225
+ return isFunction(iterator$1 === null || iterator$1 === void 0 ? void 0 : iterator$1.return) && iterator$1.return();
1226
+ };
1227
+ });
1228
+ }
1229
+ function scheduleAsyncIterable(input, scheduler) {
1230
+ if (!input) {
1231
+ throw new Error("Iterable cannot be null");
1232
+ }
1233
+ return new Observable(function(subscriber) {
1234
+ executeSchedule(subscriber, scheduler, function() {
1235
+ var iterator2 = input[Symbol.asyncIterator]();
1236
+ executeSchedule(subscriber, scheduler, function() {
1237
+ iterator2.next().then(function(result) {
1238
+ if (result.done) {
1239
+ subscriber.complete();
1240
+ } else {
1241
+ subscriber.next(result.value);
1242
+ }
1243
+ });
1244
+ }, 0, true);
1245
+ });
1246
+ });
1247
+ }
1248
+ function scheduleReadableStreamLike(input, scheduler) {
1249
+ return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);
1250
+ }
1251
+ function scheduled(input, scheduler) {
1252
+ if (input != null) {
1253
+ if (isInteropObservable(input)) {
1254
+ return scheduleObservable(input, scheduler);
1255
+ }
1256
+ if (isArrayLike(input)) {
1257
+ return scheduleArray(input, scheduler);
1258
+ }
1259
+ if (isPromise(input)) {
1260
+ return schedulePromise(input, scheduler);
1261
+ }
1262
+ if (isAsyncIterable(input)) {
1263
+ return scheduleAsyncIterable(input, scheduler);
1264
+ }
1265
+ if (isIterable(input)) {
1266
+ return scheduleIterable(input, scheduler);
1267
+ }
1268
+ if (isReadableStreamLike(input)) {
1269
+ return scheduleReadableStreamLike(input, scheduler);
1270
+ }
1271
+ }
1272
+ throw createInvalidObservableTypeError(input);
1273
+ }
1274
+ function from(input, scheduler) {
1275
+ return scheduler ? scheduled(input, scheduler) : innerFrom(input);
1276
+ }
1277
+ function map(project, thisArg) {
1278
+ return operate(function(source, subscriber) {
1279
+ var index = 0;
1280
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1281
+ subscriber.next(project.call(thisArg, value, index++));
1282
+ }));
1283
+ });
1284
+ }
1285
+ var isArray$1 = Array.isArray;
1286
+ function callOrApply(fn, args) {
1287
+ return isArray$1(args) ? fn.apply(void 0, __spreadArray([], __read(args))) : fn(args);
1288
+ }
1289
+ function mapOneOrManyArgs(fn) {
1290
+ return map(function(args) {
1291
+ return callOrApply(fn, args);
1292
+ });
1293
+ }
1294
+ var isArray = Array.isArray;
1295
+ var getPrototypeOf = Object.getPrototypeOf, objectProto = Object.prototype, getKeys = Object.keys;
1296
+ function argsArgArrayOrObject(args) {
1297
+ if (args.length === 1) {
1298
+ var first_1 = args[0];
1299
+ if (isArray(first_1)) {
1300
+ return { args: first_1, keys: null };
1301
+ }
1302
+ if (isPOJO(first_1)) {
1303
+ var keys = getKeys(first_1);
1304
+ return {
1305
+ args: keys.map(function(key) {
1306
+ return first_1[key];
1307
+ }),
1308
+ keys
1309
+ };
1310
+ }
1311
+ }
1312
+ return { args, keys: null };
1313
+ }
1314
+ function isPOJO(obj) {
1315
+ return obj && typeof obj === "object" && getPrototypeOf(obj) === objectProto;
1316
+ }
1317
+ function createObject(keys, values) {
1318
+ return keys.reduce(function(result, key, i) {
1319
+ return result[key] = values[i], result;
1320
+ }, {});
1321
+ }
1322
+ function combineLatest() {
1323
+ var args = [];
1324
+ for (var _i = 0; _i < arguments.length; _i++) {
1325
+ args[_i] = arguments[_i];
1326
+ }
1327
+ var scheduler = popScheduler(args);
1328
+ var resultSelector = popResultSelector(args);
1329
+ var _a = argsArgArrayOrObject(args), observables = _a.args, keys = _a.keys;
1330
+ if (observables.length === 0) {
1331
+ return from([], scheduler);
1332
+ }
1333
+ var result = new Observable(combineLatestInit(observables, scheduler, keys ? function(values) {
1334
+ return createObject(keys, values);
1335
+ } : identity));
1336
+ return resultSelector ? result.pipe(mapOneOrManyArgs(resultSelector)) : result;
1337
+ }
1338
+ function combineLatestInit(observables, scheduler, valueTransform) {
1339
+ if (valueTransform === void 0) {
1340
+ valueTransform = identity;
1341
+ }
1342
+ return function(subscriber) {
1343
+ maybeSchedule(scheduler, function() {
1344
+ var length = observables.length;
1345
+ var values = new Array(length);
1346
+ var active = length;
1347
+ var remainingFirstValues = length;
1348
+ var _loop_1 = function(i2) {
1349
+ maybeSchedule(scheduler, function() {
1350
+ var source = from(observables[i2], scheduler);
1351
+ var hasFirstValue = false;
1352
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1353
+ values[i2] = value;
1354
+ if (!hasFirstValue) {
1355
+ hasFirstValue = true;
1356
+ remainingFirstValues--;
1357
+ }
1358
+ if (!remainingFirstValues) {
1359
+ subscriber.next(valueTransform(values.slice()));
1360
+ }
1361
+ }, function() {
1362
+ if (!--active) {
1363
+ subscriber.complete();
1364
+ }
1365
+ }));
1366
+ }, subscriber);
1367
+ };
1368
+ for (var i = 0; i < length; i++) {
1369
+ _loop_1(i);
1370
+ }
1371
+ }, subscriber);
1372
+ };
1373
+ }
1374
+ function maybeSchedule(scheduler, execute, subscription) {
1375
+ if (scheduler) {
1376
+ executeSchedule(subscription, scheduler, execute);
1377
+ } else {
1378
+ execute();
1379
+ }
1380
+ }
1381
+ class Chat {
1382
+ constructor(api) {
1383
+ __publicField(this, "users$", new BehaviorSubject([]));
1384
+ __publicField(this, "conversations$", new BehaviorSubject([]));
1385
+ __publicField(this, "selectedUser$", new BehaviorSubject(null));
1386
+ __publicField(this, "messages$", new BehaviorSubject([]));
1387
+ __publicField(this, "loading$", new BehaviorSubject(false));
1388
+ __publicField(this, "error$", new BehaviorSubject(null));
1389
+ __publicField(this, "typingUsers$", new BehaviorSubject(/* @__PURE__ */ new Set()));
1390
+ __publicField(this, "hasMore$", new BehaviorSubject(false));
1391
+ __publicField(this, "unread$", combineLatest([this.conversations$]).pipe(
1392
+ map(([rows]) => rows.reduce((total, row) => total + Number(row.unread || 0), 0))
1393
+ ));
1394
+ __publicField(this, "socketUnsubscribe");
1395
+ __publicField(this, "typingTimers", /* @__PURE__ */ new Map());
1396
+ __publicField(this, "initialized", false);
1397
+ this.api = api;
1398
+ }
1399
+ async initialize(force = false) {
1400
+ if (this.initialized && !force) return;
1401
+ this.initialized = true;
1402
+ this.connectRealtime();
1403
+ this.users$.next([]);
1404
+ try {
1405
+ await this.loadConversations();
1406
+ } catch (error) {
1407
+ this.initialized = false;
1408
+ throw error;
1409
+ }
1410
+ }
1411
+ async available() {
1412
+ if (!this.api.token) return false;
1413
+ try {
1414
+ const response = await this.run({ "$/chat/status": {} }, true);
1415
+ return Boolean(response == null ? void 0 : response.enabled);
1416
+ } catch {
1417
+ return false;
1418
+ }
1419
+ }
1420
+ async loadDirectory(search = "", cursor) {
1421
+ const query = search.trim();
1422
+ if (query.length < 2) {
1423
+ this.users$.next([]);
1424
+ return [];
1425
+ }
1426
+ const response = await this.run({
1427
+ "$/chat/directory": { query, cursor, limit: 25 }
1428
+ });
1429
+ const users = response.users || [];
1430
+ this.users$.next(users);
1431
+ const selected = this.selectedUser$.value;
1432
+ const replacement = selected && users.find((user) => user.id === selected.id);
1433
+ if (replacement) this.selectedUser$.next(replacement);
1434
+ return users;
1435
+ }
1436
+ async loadConversations() {
1437
+ const response = await this.run({ "$/chat/conversations": { limit: 75 } });
1438
+ const conversations = (response.conversations || []).map((row) => ({
1439
+ ...row,
1440
+ lastMessage: row.lastMessage ? { ...row.lastMessage, status: "sent" } : null
1441
+ }));
1442
+ this.conversations$.next(conversations);
1443
+ return conversations;
1444
+ }
1445
+ async selectUser(user) {
1446
+ this.selectedUser$.next(user);
1447
+ this.messages$.next([]);
1448
+ this.hasMore$.next(false);
1449
+ await this.loadHistory(user.id);
1450
+ await this.markLatestRead();
1451
+ }
1452
+ async loadHistory(userId, before) {
1453
+ this.loading$.next(true);
1454
+ try {
1455
+ const response = await this.run({
1456
+ "$/chat/history": { userId, before, limit: 75 }
1457
+ });
1458
+ const messages = (response.messages || []).map((message) => ({ ...message, status: "sent" }));
1459
+ this.messages$.next(before ? this.mergeMessages(messages, this.messages$.value) : messages);
1460
+ this.hasMore$.next(Boolean(response.hasMore));
1461
+ return messages;
1462
+ } finally {
1463
+ this.loading$.next(false);
1464
+ }
1465
+ }
1466
+ async send(userId, body, clientId = this.createClientId()) {
1467
+ const text = body.trim();
1468
+ if (!text) throw new Error("Message cannot be empty.");
1469
+ if (text.length > 4e3) throw new Error("Message cannot exceed 4,000 characters.");
1470
+ const existing = this.messages$.value.find((row) => row.clientId === clientId);
1471
+ const optimistic = existing ? { ...existing, status: "sending" } : {
1472
+ id: `pending:${clientId}`,
1473
+ conversationId: this.conversationId(this.currentUserId(), userId),
1474
+ senderId: this.currentUserId(),
1475
+ recipientId: userId,
1476
+ body: text,
1477
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1478
+ clientId,
1479
+ status: "sending"
1480
+ };
1481
+ this.upsertMessage(optimistic);
1482
+ try {
1483
+ const response = await this.run({
1484
+ "$/chat/send": { userId, body: text, clientMessageId: clientId }
1485
+ });
1486
+ const message = { ...response.message, status: "sent" };
1487
+ this.upsertMessage(message);
1488
+ void this.loadConversations();
1489
+ return message;
1490
+ } catch (error) {
1491
+ this.upsertMessage({ ...optimistic, status: "failed" });
1492
+ throw error;
1493
+ }
1494
+ }
1495
+ async retry(message) {
1496
+ if (!message.clientId) throw new Error("This message cannot be retried.");
1497
+ return this.send(message.recipientId, message.body, message.clientId);
1498
+ }
1499
+ async setTyping(userId, typing) {
1500
+ await this.run({ "$/chat/typing": { userId, typing } }, true);
1501
+ }
1502
+ async markLatestRead() {
1503
+ const peer = this.selectedUser$.value;
1504
+ const messages = this.messages$.value;
1505
+ const latest = [...messages].reverse().find((message) => message.senderId === (peer == null ? void 0 : peer.id) && !message.id.startsWith("pending:"));
1506
+ if (!peer || !latest) return;
1507
+ await this.run({ "$/chat/read": { userId: peer.id, messageId: latest.id } }, true);
1508
+ this.conversations$.next(this.conversations$.value.map(
1509
+ (row) => row.peer.id === peer.id ? { ...row, unread: 0 } : row
1510
+ ));
1511
+ }
1512
+ destroy() {
1513
+ var _a;
1514
+ (_a = this.socketUnsubscribe) == null ? void 0 : _a.call(this);
1515
+ this.socketUnsubscribe = void 0;
1516
+ this.typingTimers.forEach((timer) => clearTimeout(timer));
1517
+ this.typingTimers.clear();
1518
+ this.initialized = false;
1519
+ }
1520
+ connectRealtime() {
1521
+ if (this.socketUnsubscribe) return;
1522
+ this.socketUnsubscribe = this.api.socket.addListener(
1523
+ (event) => this.onSocketEvent(event),
1524
+ () => this.api.socket.send({ chat: { subscribe: true } })
1525
+ );
1526
+ }
1527
+ onSocketEvent(event) {
1528
+ var _a, _b, _c, _d, _e;
1529
+ if (!(event == null ? void 0 : event.type) || event.type.indexOf("chat.") !== 0) return;
1530
+ if (event.type === "chat.message") {
1531
+ const message = (_a = event.data) == null ? void 0 : _a.message;
1532
+ const selected = this.selectedUser$.value;
1533
+ if (message && selected && (message.senderId === selected.id || message.recipientId === selected.id)) {
1534
+ this.upsertMessage({ ...message, status: "sent" });
1535
+ if (message.senderId === selected.id) void this.markLatestRead();
1536
+ }
1537
+ void this.loadConversations();
1538
+ } else if (event.type === "chat.read") {
1539
+ this.applyReadReceipt(event.data);
1540
+ void this.loadConversations();
1541
+ } else if (event.type === "chat.conversation.updated") {
1542
+ void this.loadConversations();
1543
+ } else if (event.type === "chat.typing") {
1544
+ const userId = Number((_b = event.data) == null ? void 0 : _b.userId);
1545
+ if (!userId) return;
1546
+ const next = new Set(this.typingUsers$.value);
1547
+ if ((_c = event.data) == null ? void 0 : _c.typing) {
1548
+ next.add(userId);
1549
+ clearTimeout(this.typingTimers.get(userId));
1550
+ this.typingTimers.set(userId, setTimeout(() => {
1551
+ const later = new Set(this.typingUsers$.value);
1552
+ later.delete(userId);
1553
+ this.typingUsers$.next(later);
1554
+ }, 5e3));
1555
+ } else next.delete(userId);
1556
+ this.typingUsers$.next(next);
1557
+ } else if (event.type === "chat.presence") {
1558
+ const userId = Number((_d = event.data) == null ? void 0 : _d.userId);
1559
+ const online = Boolean((_e = event.data) == null ? void 0 : _e.online);
1560
+ this.users$.next(this.users$.value.map((user) => user.id === userId ? { ...user, online } : user));
1561
+ this.conversations$.next(this.conversations$.value.map(
1562
+ (row) => row.peer.id === userId ? { ...row, peer: { ...row.peer, online } } : row
1563
+ ));
1564
+ const selected = this.selectedUser$.value;
1565
+ if ((selected == null ? void 0 : selected.id) === userId) this.selectedUser$.next({ ...selected, online });
1566
+ }
1567
+ }
1568
+ applyReadReceipt(data) {
1569
+ const readerId = Number(data == null ? void 0 : data.userId);
1570
+ const messageId = String((data == null ? void 0 : data.messageId) || "");
1571
+ const readAt = String((data == null ? void 0 : data.readAt) || (/* @__PURE__ */ new Date()).toISOString());
1572
+ const selected = this.selectedUser$.value;
1573
+ if (!readerId || !messageId || (selected == null ? void 0 : selected.id) !== readerId) return;
1574
+ this.messages$.next(this.messages$.value.map((message) => {
1575
+ if (message.senderId !== this.currentUserId() || message.recipientId !== readerId) return message;
1576
+ if (message.id.startsWith("pending:") || this.compareStreamIds(message.id, messageId) > 0) return message;
1577
+ return { ...message, status: "sent", readAt };
1578
+ }));
1579
+ }
1580
+ upsertMessage(message) {
1581
+ if (!message) return;
1582
+ const current = this.messages$.value;
1583
+ const index = current.findIndex((row) => row.id === message.id || Boolean(message.clientId && row.clientId === message.clientId));
1584
+ if (index < 0) this.messages$.next([...current, message]);
1585
+ else {
1586
+ const next = [...current];
1587
+ next[index] = { ...next[index], ...message };
1588
+ this.messages$.next(next);
1589
+ }
1590
+ }
1591
+ mergeMessages(first, second) {
1592
+ const out = [];
1593
+ const seen = /* @__PURE__ */ new Set();
1594
+ for (const message of [...first, ...second]) {
1595
+ const key = message.clientId || message.id;
1596
+ if (seen.has(key)) continue;
1597
+ seen.add(key);
1598
+ out.push(message);
1599
+ }
1600
+ return out;
1601
+ }
1602
+ async run(request, quiet = false) {
1603
+ if (!quiet) this.error$.next(null);
1604
+ try {
1605
+ return await this.api.request(request, { noOptimize: true });
1606
+ } catch (error) {
1607
+ if (!quiet) this.error$.next(String((error == null ? void 0 : error.message) || (error == null ? void 0 : error.error) || "Chat is temporarily unavailable."));
1608
+ throw error;
1609
+ }
1610
+ }
1611
+ currentUserId() {
1612
+ var _a;
1613
+ return Number(((_a = this.api.jwtPayload) == null ? void 0 : _a.uid) || 0);
1614
+ }
1615
+ conversationId(a, b) {
1616
+ return `${Math.min(a, b)}:${Math.max(a, b)}`;
1617
+ }
1618
+ compareStreamIds(a, b) {
1619
+ const [ams, aseq] = a.split("-").map(Number);
1620
+ const [bms, bseq] = b.split("-").map(Number);
1621
+ return ams === bms ? (aseq || 0) - (bseq || 0) : (ams || 0) - (bms || 0);
1622
+ }
1623
+ createClientId() {
1624
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
1625
+ return Date.now().toString(36) + "-" + Math.random().toString(36).slice(2);
1626
+ }
1627
+ }
1628
+ const icon = (path) => `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="${path}"/></svg>`;
1629
+ const CHAT_HTML = `
1630
+ <section class="dl-chat" role="dialog" aria-label="Datalynk Chat">
1631
+ <header class="dl-chat__titlebar">
1632
+ <div class="dl-chat__brand"><span class="dl-chat__mark">${icon("M4 5h16v11H9l-5 4V5zm3 4v2h2V9H7zm4 0v2h2V9h-2zm4 0v2h2V9h-2z")}</span><strong>Chat</strong></div>
1633
+ <div class="dl-chat__window-actions">
1634
+ <button class="dl-chat__icon-button dl-chat__popout" type="button" aria-label="Open chat in a separate window" title="Open in new window">${icon("M14 3h7v7h-2V6.41l-9.29 9.3-1.42-1.42 9.3-9.29H14V3zM5 5h6v2H5v12h12v-6h2v8H3V5h2z")}</button>
1635
+ <button class="dl-chat__icon-button dl-chat__minimize" type="button" aria-label="Minimize chat" title="Minimize">${icon("M5 11h14v2H5z")}</button>
1636
+ <button class="dl-chat__icon-button dl-chat__close" type="button" aria-label="Close chat" title="Close">${icon("M6.4 5 12 10.6 17.6 5 19 6.4 13.4 12 19 17.6 17.6 19 12 13.4 6.4 19 5 17.6 10.6 12 5 6.4z")}</button>
1637
+ </div>
1638
+ </header>
1639
+ <div class="dl-chat__connection" role="status" hidden></div>
1640
+ <div class="dl-chat__error" role="alert" hidden></div>
1641
+ <div class="dl-chat__body">
1642
+ <aside class="dl-chat__sidebar" aria-label="Conversations">
1643
+ <label class="dl-chat__search-wrap">
1644
+ <span class="sr-only">Search people</span>
1645
+ ${icon("M10 4a6 6 0 1 0 3.87 10.58L19.3 20 20.7 18.6l-5.42-5.43A6 6 0 0 0 10 4zm0 2a4 4 0 1 1 0 8 4 4 0 0 1 0-8z")}
1646
+ <input class="dl-chat__search" type="search" placeholder="Search people" autocomplete="off">
1647
+ </label>
1648
+ <div class="dl-chat__scroll">
1649
+ <h2>Recent</h2>
1650
+ <div class="dl-chat__conversations"></div>
1651
+ <h2>People</h2>
1652
+ <div class="dl-chat__people"></div>
1653
+ </div>
1654
+ </aside>
1655
+ <main class="dl-chat__main">
1656
+ <div class="dl-chat__empty">
1657
+ <span class="dl-chat__empty-icon">${icon("M4 4h16v12H8l-4 4V4zm2 2v9.17L7.17 14H18V6H6z")}</span>
1658
+ <h2>Your conversations</h2>
1659
+ <p>Choose someone from your organization to send a message.</p>
1660
+ </div>
1661
+ <section class="dl-chat__thread" hidden>
1662
+ <header class="dl-chat__thread-header">
1663
+ <button class="dl-chat__icon-button dl-chat__back" type="button" aria-label="Back to conversations">${icon("M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.42-1.41L7.83 13H20v-2z")}</button>
1664
+ <span class="dl-chat__avatar dl-chat__thread-avatar"></span>
1665
+ <div><strong class="dl-chat__thread-name"></strong><span class="dl-chat__thread-status"></span></div>
1666
+ </header>
1667
+ <button class="dl-chat__older" type="button">Load earlier messages</button>
1668
+ <div class="dl-chat__messages" aria-live="polite"></div>
1669
+ <div class="dl-chat__typing" aria-live="polite" hidden></div>
1670
+ <footer class="dl-chat__compose">
1671
+ <label class="sr-only" for="dl-chat-message">Message</label>
1672
+ <textarea id="dl-chat-message" class="dl-chat__composer" rows="1" maxlength="4000" placeholder="Write a message"></textarea>
1673
+ <button class="dl-chat__send" type="button" disabled aria-label="Send message" title="Send message">${icon("M3 20.4 21.85 12 3 3.6v6.53L16.46 12 3 13.87v6.53z")}</button>
1674
+ <span class="dl-chat__hint">Enter to send, Shift+Enter for a new line</span>
1675
+ </footer>
1676
+ </section>
1677
+ </main>
1678
+ </div>
1679
+ </section>`;
1680
+ const CHAT_CSS = `
1681
+ :host{all:initial;position:fixed;inset:0;z-index:2147483000;pointer-events:none;color:#17242b;font-family:"Segoe UI",Tahoma,Arial,sans-serif}
1682
+ *{box-sizing:border-box}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
1683
+ button,input,textarea{font:inherit}
1684
+ .dl-chat{--teal:#3f6f85;--teal-deep:#2f596d;--teal-soft:#e9f1f4;--red:#c42d27;--green:#599e21;--ink:#17242b;--muted:#60717a;--line:#d7e0e4;position:fixed;right:22px;bottom:22px;width:min(720px,calc(100vw - 32px));height:min(640px,calc(100dvh - 32px));min-width:360px;min-height:460px;display:flex;flex-direction:column;overflow:hidden;resize:both;pointer-events:auto;background:#fff;border:1px solid #c7d2d7;border-radius:10px;box-shadow:0 18px 54px rgba(23,36,43,.24),0 3px 10px rgba(23,36,43,.12);container-type:inline-size}
1685
+ .dl-chat.is-popout{inset:0;width:100%;height:100dvh;min-width:0;min-height:0;resize:none;border:0;border-radius:0;box-shadow:none}.dl-chat.is-popout .dl-chat__minimize{display:none}
1686
+ .dl-chat__titlebar{height:46px;flex:0 0 46px;display:flex;align-items:center;justify-content:space-between;padding:0 8px 0 14px;color:#fff;background:var(--teal);cursor:move;touch-action:none;user-select:none}
1687
+ .dl-chat__brand{display:flex;align-items:center;gap:9px;font-size:15px;letter-spacing:.01em}.dl-chat__mark{display:grid;place-items:center;width:24px;height:24px}.dl-chat__mark svg{width:22px;height:22px;fill:currentColor}
1688
+ .dl-chat__window-actions{display:flex;gap:2px}.dl-chat__icon-button{display:grid;place-items:center;width:34px;height:34px;padding:0;border:0;border-radius:5px;color:inherit;background:transparent;cursor:pointer;transition:background-color 120ms ease-out,color 120ms ease-out}.dl-chat__icon-button:hover{background:rgba(255,255,255,.14)}.dl-chat__icon-button:focus-visible,.dl-chat button:focus-visible,.dl-chat input:focus-visible,.dl-chat textarea:focus-visible{outline:2px solid #f2c94c;outline-offset:2px}.dl-chat__icon-button svg{width:18px;height:18px;fill:currentColor}
1689
+ .dl-chat__connection,.dl-chat__error{padding:7px 14px;font-size:12px;line-height:1.35}.dl-chat__connection{color:#654d00;background:#fff4c7;border-bottom:1px solid #e8d68c}.dl-chat__error{color:#7b201c;background:#fbe9e8;border-bottom:1px solid #efbfbc}
1690
+ .dl-chat__body{min-height:0;flex:1;display:grid;grid-template-columns:260px minmax(0,1fr)}.dl-chat__sidebar{min-width:0;display:flex;flex-direction:column;background:#f4f7f8;border-right:1px solid var(--line)}
1691
+ .dl-chat__search-wrap{position:relative;display:block;margin:14px 12px 9px}.dl-chat__search-wrap>svg{position:absolute;left:10px;top:50%;width:17px;height:17px;fill:#70818a;transform:translateY(-50%);pointer-events:none}.dl-chat__search{width:100%;height:36px;padding:0 10px 0 34px;color:var(--ink);background:#fff;border:1px solid #c7d2d7;border-radius:6px;outline:0}.dl-chat__search:focus,.dl-chat__composer:focus{border-color:var(--teal);box-shadow:0 0 0 2px rgba(63,111,133,.15)}
1692
+ .dl-chat__scroll{min-height:0;overflow:auto;padding:0 8px 16px}.dl-chat__scroll h2{margin:14px 8px 6px;color:#63757e;font-size:11px;font-weight:700;letter-spacing:.07em;text-transform:uppercase}
1693
+ .dl-chat__person{position:relative;width:100%;display:grid;grid-template-columns:38px minmax(0,1fr) 8px;align-items:center;gap:10px;padding:8px;border:0;border-radius:7px;text-align:left;color:var(--ink);background:transparent;cursor:pointer;transition:background-color 120ms ease-out}.dl-chat__person:hover{background:#e5edef}.dl-chat__person.is-selected{background:#dce8ed}.dl-chat__avatar{display:grid;place-items:center;width:38px;height:38px;border-radius:50%;color:#fff;background:var(--teal);font-size:12px;font-weight:700;letter-spacing:.03em}.dl-chat__person-copy{min-width:0}.dl-chat__person-top,.dl-chat__person-bottom{display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0}.dl-chat__person-top strong,.dl-chat__person-bottom>span:first-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-chat__person-top strong{font-size:13px;font-weight:600}.dl-chat__person-top time{flex:0 0 auto;color:#778891;font-size:10px}.dl-chat__person-bottom>span:first-child{color:var(--muted);font-size:11px}.dl-chat__presence{width:8px;height:8px;border:2px solid #87969d;border-radius:50%}.dl-chat__presence.is-online{border-color:var(--green);background:var(--green)}.dl-chat__unread{display:grid;place-items:center;min-width:18px;height:18px;padding:0 5px;border-radius:9px;color:#fff!important;background:var(--red);font-size:10px!important;font-weight:700}.dl-chat__list-empty{margin:6px 8px 12px;color:var(--muted);font-size:12px;line-height:1.45}
1694
+ .dl-chat__main{min-width:0;min-height:0}.dl-chat__empty{height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:36px;text-align:center}.dl-chat__empty-icon{display:grid;place-items:center;width:58px;height:58px;color:var(--teal);background:var(--teal-soft);border-radius:50%}.dl-chat__empty-icon svg{width:27px;height:27px;fill:currentColor}.dl-chat__empty h2{margin:17px 0 5px;font-size:17px}.dl-chat__empty p{max-width:280px;margin:0;color:var(--muted);font-size:13px;line-height:1.5}
1695
+ .dl-chat__thread{height:100%;display:grid;grid-template-rows:auto auto minmax(0,1fr) auto auto}.dl-chat__thread[hidden],.dl-chat__empty[hidden]{display:none}.dl-chat__thread-header{height:62px;display:flex;align-items:center;gap:10px;padding:0 16px;border-bottom:1px solid var(--line)}.dl-chat__thread-header .dl-chat__avatar{width:36px;height:36px;flex:0 0 36px}.dl-chat__thread-header>div{min-width:0;display:flex;flex-direction:column}.dl-chat__thread-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px}.dl-chat__thread-status{position:relative;padding-left:11px;color:var(--muted);font-size:11px}.dl-chat__thread-status:before{content:"";position:absolute;left:0;top:50%;width:7px;height:7px;border:1.5px solid #87969d;border-radius:50%;transform:translateY(-50%)}.dl-chat__thread-status.is-online:before{border-color:var(--green);background:var(--green)}.dl-chat__back{display:none;color:var(--teal)}
1696
+ .dl-chat__older{justify-self:center;margin:7px 0 0;padding:4px 8px;border:0;color:var(--teal-deep);background:transparent;font-size:11px;cursor:pointer}.dl-chat__older:hover{text-decoration:underline}.dl-chat__messages{min-height:0;overflow-y:auto;padding:12px 18px 18px;scroll-behavior:smooth}.dl-chat__date{display:flex;align-items:center;gap:10px;margin:12px 0;color:#71838c;font-size:10px}.dl-chat__date:before,.dl-chat__date:after{content:"";height:1px;flex:1;background:#e3e9ec}.dl-chat__message{display:flex;margin:4px 0}.dl-chat__message.is-mine{justify-content:flex-end}.dl-chat__bubble{max-width:min(76%,430px);padding:8px 10px 6px;color:var(--ink);background:#edf2f4;border-radius:5px 11px 11px 11px;font-size:13px;line-height:1.42;overflow-wrap:anywhere}.dl-chat__message.is-mine .dl-chat__bubble{color:#fff;background:var(--teal);border-radius:11px 5px 11px 11px}.dl-chat__bubble>span{white-space:pre-wrap}.dl-chat__bubble time{display:block;margin-top:3px;color:#6c7e87;font-size:9px;text-align:right}.dl-chat__message.is-mine time{color:rgba(255,255,255,.72)}.dl-chat__retry{display:block;margin:5px 0 0 auto;padding:2px 7px;border:1px solid rgba(255,255,255,.65);border-radius:4px;color:#fff;background:transparent;font-size:10px;cursor:pointer}.dl-chat__retry:hover{background:rgba(255,255,255,.12)}.dl-chat__thread-empty{max-width:300px;margin:auto;padding:24px;color:var(--muted);font-size:12px;line-height:1.5;text-align:center}.dl-chat__typing{height:20px;padding:0 18px;color:var(--muted);font-size:11px;font-style:italic}
1697
+ .dl-chat__compose{position:relative;display:grid;grid-template-columns:minmax(0,1fr) 38px;gap:8px;padding:10px 14px 22px;border-top:1px solid var(--line)}.dl-chat__composer{width:100%;min-height:38px;max-height:92px;resize:none;padding:9px 11px;color:var(--ink);border:1px solid #bdcbd1;border-radius:7px;line-height:1.35;outline:0}.dl-chat__send{display:grid;place-items:center;width:38px;height:38px;padding:0;border:0;border-radius:7px;color:#fff;background:var(--teal);cursor:pointer;transition:background-color 120ms ease-out}.dl-chat__send:hover{background:var(--teal-deep)}.dl-chat__send:disabled{cursor:not-allowed;opacity:.45}.dl-chat__send svg{width:19px;height:19px;fill:currentColor}.dl-chat__hint{position:absolute;left:15px;bottom:5px;color:#829098;font-size:9px}
1698
+ .dl-chat.is-minimized{left:auto!important;top:auto!important;right:22px!important;bottom:0!important;width:280px!important;height:46px!important;min-height:46px;resize:none;border-radius:9px 9px 0 0}.dl-chat.is-minimized .dl-chat__titlebar{cursor:pointer}.dl-chat.is-minimized .dl-chat__body,.dl-chat.is-minimized .dl-chat__connection,.dl-chat.is-minimized .dl-chat__error{display:none}
1699
+ @container (max-width:520px){.dl-chat__body{grid-template-columns:1fr}.dl-chat__main{display:none}.dl-chat.has-selection .dl-chat__sidebar{display:none}.dl-chat.has-selection .dl-chat__main{display:block}.dl-chat__back{display:grid}.dl-chat__hint{display:none}.dl-chat__compose{padding-bottom:10px}}
1700
+ @media(max-width:600px){.dl-chat{inset:0;width:100%;height:100dvh;min-width:0;min-height:0;border:0;border-radius:0;resize:none}.dl-chat.is-minimized{inset:auto 12px 0 auto!important;width:min(280px,calc(100vw - 24px))!important;border:1px solid #c7d2d7;border-bottom:0}.dl-chat__titlebar{cursor:default}.dl-chat__popout{display:none}}
1701
+ @media(prefers-reduced-motion:reduce){.dl-chat *{scroll-behavior:auto!important;transition-duration:.01ms!important;animation-duration:.01ms!important}}
1702
+ `;
1703
+ const windows = /* @__PURE__ */ new WeakMap();
1704
+ function openChat(chat, options = {}) {
1705
+ const doc = options.document || document;
1706
+ const existing = windows.get(doc);
1707
+ if (existing) {
1708
+ existing.show();
1709
+ return existing;
1710
+ }
1711
+ const view = new ChatWindow(chat, { ...options, document: doc });
1712
+ windows.set(doc, view);
1713
+ view.onDestroyed = () => windows.delete(doc);
1714
+ return view;
1715
+ }
1716
+ function closeChat(doc = document) {
1717
+ var _a;
1718
+ (_a = windows.get(doc)) == null ? void 0 : _a.destroy();
1719
+ }
1720
+ class ChatWindow {
1721
+ constructor(chat, options) {
1722
+ __publicField(this, "doc");
1723
+ __publicField(this, "host");
1724
+ __publicField(this, "root");
1725
+ __publicField(this, "subscriptions", []);
1726
+ __publicField(this, "selected", null);
1727
+ __publicField(this, "searchTimer");
1728
+ __publicField(this, "typingTimer");
1729
+ __publicField(this, "typingSent", false);
1730
+ __publicField(this, "resizeObserver");
1731
+ __publicField(this, "renderedMessageIds", "");
1732
+ __publicField(this, "destroyed", false);
1733
+ __publicField(this, "onDestroyed");
1734
+ this.chat = chat;
1735
+ this.options = options;
1736
+ this.doc = options.document || document;
1737
+ this.host = this.doc.createElement("div");
1738
+ this.host.className = "datalynk-chat-host";
1739
+ this.root = this.host.attachShadow({ mode: "open" });
1740
+ this.root.innerHTML = `<style>${CHAT_CSS}</style>${CHAT_HTML}`;
1741
+ this.doc.body.appendChild(this.host);
1742
+ this.bind();
1743
+ this.restoreGeometry();
1744
+ this.subscribe();
1745
+ this.restoreMinimized();
1746
+ void this.initializeGui();
1747
+ this.searchInput.focus();
1748
+ }
1749
+ get api() {
1750
+ return this.chat.api;
1751
+ }
1752
+ show() {
1753
+ this.host.hidden = false;
1754
+ this.setMinimized(false);
1755
+ this.searchInput.focus();
1756
+ }
1757
+ destroy() {
1758
+ var _a, _b, _c, _d, _e, _f;
1759
+ if (this.destroyed) return;
1760
+ this.destroyed = true;
1761
+ this.subscriptions.forEach((subscription) => subscription.unsubscribe());
1762
+ (_a = this.resizeObserver) == null ? void 0 : _a.disconnect();
1763
+ clearTimeout(this.searchTimer);
1764
+ clearTimeout(this.typingTimer);
1765
+ if (this.typingSent && this.selected) void this.chat.setTyping(this.selected.id, false).catch(() => void 0);
1766
+ this.host.remove();
1767
+ (_c = (_b = this.options).onClose) == null ? void 0 : _c.call(_b);
1768
+ (_d = this.onDestroyed) == null ? void 0 : _d.call(this);
1769
+ if (this.options.popout && !((_e = this.doc.defaultView) == null ? void 0 : _e.closed)) (_f = this.doc.defaultView) == null ? void 0 : _f.close();
1770
+ }
1771
+ get shell() {
1772
+ return this.query(".dl-chat");
1773
+ }
1774
+ get searchInput() {
1775
+ return this.query(".dl-chat__search");
1776
+ }
1777
+ get conversationList() {
1778
+ return this.query(".dl-chat__conversations");
1779
+ }
1780
+ get messageList() {
1781
+ return this.query(".dl-chat__messages");
1782
+ }
1783
+ get composer() {
1784
+ return this.query(".dl-chat__composer");
1785
+ }
1786
+ get sendButton() {
1787
+ return this.query(".dl-chat__send");
1788
+ }
1789
+ query(selector) {
1790
+ const node = this.root.querySelector(selector);
1791
+ if (!node) throw new Error(`Missing chat element: ${selector}`);
1792
+ return node;
1793
+ }
1794
+ bind() {
1795
+ var _a;
1796
+ this.query(".dl-chat__close").addEventListener("click", () => this.destroy());
1797
+ this.query(".dl-chat__minimize").addEventListener("click", () => this.setMinimized(!this.shell.classList.contains("is-minimized")));
1798
+ this.query(".dl-chat__popout").addEventListener("click", () => this.popout());
1799
+ this.query(".dl-chat__back").addEventListener("click", () => {
1800
+ this.shell.classList.remove("has-selection");
1801
+ this.searchInput.focus();
1802
+ });
1803
+ this.searchInput.addEventListener("input", () => {
1804
+ clearTimeout(this.searchTimer);
1805
+ this.searchTimer = setTimeout(() => void this.chat.loadDirectory(this.searchInput.value).catch(() => void 0), 220);
1806
+ });
1807
+ this.composer.addEventListener("input", () => this.onComposerInput());
1808
+ this.composer.addEventListener("keydown", (event) => {
1809
+ if (event.key === "Enter" && !event.shiftKey) {
1810
+ event.preventDefault();
1811
+ void this.send();
1812
+ }
1813
+ });
1814
+ this.sendButton.addEventListener("click", () => void this.send());
1815
+ this.query(".dl-chat__older").addEventListener("click", () => {
1816
+ const first = this.chat.messages$.value.find((row) => !row.id.startsWith("pending:"));
1817
+ if (this.selected && first) void this.chat.loadHistory(this.selected.id, first.id);
1818
+ });
1819
+ this.makeDraggable();
1820
+ if (typeof ResizeObserver !== "undefined") {
1821
+ this.resizeObserver = new ResizeObserver(() => this.saveGeometry());
1822
+ this.resizeObserver.observe(this.shell);
1823
+ }
1824
+ (_a = this.doc.defaultView) == null ? void 0 : _a.addEventListener("beforeunload", () => this.destroy(), { once: true });
1825
+ }
1826
+ subscribe() {
1827
+ this.subscriptions.push(
1828
+ this.chat.users$.subscribe((users) => this.renderPeople(users)),
1829
+ this.chat.conversations$.subscribe((rows) => this.renderConversations(rows)),
1830
+ this.chat.selectedUser$.subscribe((user) => {
1831
+ this.selected = user;
1832
+ this.renderSelectedUser(user);
1833
+ }),
1834
+ this.chat.messages$.subscribe((messages) => this.renderMessages(messages)),
1835
+ this.chat.typingUsers$.subscribe((users) => this.renderTyping(users)),
1836
+ this.chat.error$.subscribe((error) => this.renderError(error)),
1837
+ this.chat.hasMore$.subscribe((hasMore) => this.query(".dl-chat__older").toggleAttribute("hidden", !hasMore)),
1838
+ this.api.status$.subscribe((status) => this.renderConnection(status)),
1839
+ this.chat.unread$.subscribe((count) => {
1840
+ var _a, _b;
1841
+ return (_b = (_a = this.options).onUnreadChange) == null ? void 0 : _b.call(_a, count);
1842
+ })
1843
+ );
1844
+ }
1845
+ renderPeople(users) {
1846
+ const query = this.searchInput.value.trim().toLowerCase();
1847
+ const conversationIds = new Set(this.chat.conversations$.value.map((row) => row.peer.id));
1848
+ const filtered = users.filter((user) => query ? [user.displayName, user.login].join(" ").toLowerCase().includes(query) : !conversationIds.has(user.id));
1849
+ const target = this.query(".dl-chat__people");
1850
+ target.replaceChildren();
1851
+ if (!filtered.length) {
1852
+ const empty = this.doc.createElement("p");
1853
+ empty.className = "dl-chat__list-empty";
1854
+ empty.textContent = query ? "No matching people" : "Search for someone to start a conversation.";
1855
+ target.appendChild(empty);
1856
+ return;
1857
+ }
1858
+ filtered.slice(0, query ? 30 : 8).forEach((user) => target.appendChild(this.personButton(user)));
1859
+ }
1860
+ renderConversations(rows) {
1861
+ this.conversationList.replaceChildren();
1862
+ if (!rows.length) {
1863
+ const empty = this.doc.createElement("p");
1864
+ empty.className = "dl-chat__list-empty";
1865
+ empty.textContent = "No conversations yet.";
1866
+ this.conversationList.appendChild(empty);
1867
+ } else rows.forEach((row) => {
1868
+ var _a;
1869
+ const button = this.personButton(row.peer, row);
1870
+ if (((_a = this.selected) == null ? void 0 : _a.id) === row.peer.id) button.classList.add("is-selected");
1871
+ this.conversationList.appendChild(button);
1872
+ });
1873
+ this.renderPeople(this.chat.users$.value);
1874
+ }
1875
+ personButton(user, conversation) {
1876
+ var _a;
1877
+ const button = this.doc.createElement("button");
1878
+ button.type = "button";
1879
+ button.className = "dl-chat__person";
1880
+ button.setAttribute("aria-label", `Open conversation with ${user.displayName}`);
1881
+ const avatar = this.doc.createElement("span");
1882
+ avatar.className = "dl-chat__avatar";
1883
+ avatar.textContent = initials(user.displayName);
1884
+ const copy = this.doc.createElement("span");
1885
+ copy.className = "dl-chat__person-copy";
1886
+ const top = this.doc.createElement("span");
1887
+ top.className = "dl-chat__person-top";
1888
+ const name = this.doc.createElement("strong");
1889
+ name.textContent = user.displayName;
1890
+ const time = this.doc.createElement("time");
1891
+ time.textContent = (conversation == null ? void 0 : conversation.lastMessage) ? shortTime(conversation.lastMessage.createdAt) : "";
1892
+ top.append(name, time);
1893
+ const bottom = this.doc.createElement("span");
1894
+ bottom.className = "dl-chat__person-bottom";
1895
+ const preview = this.doc.createElement("span");
1896
+ preview.textContent = ((_a = conversation == null ? void 0 : conversation.lastMessage) == null ? void 0 : _a.body) || user.login || "Start a conversation";
1897
+ bottom.appendChild(preview);
1898
+ if (conversation == null ? void 0 : conversation.unread) {
1899
+ const badge = this.doc.createElement("span");
1900
+ badge.className = "dl-chat__unread";
1901
+ badge.textContent = String(conversation.unread);
1902
+ badge.setAttribute("aria-label", `${conversation.unread} unread messages`);
1903
+ bottom.appendChild(badge);
1904
+ }
1905
+ copy.append(top, bottom);
1906
+ button.append(avatar, copy, presence(user.online, this.doc));
1907
+ button.addEventListener("click", () => {
1908
+ this.shell.classList.add("has-selection");
1909
+ this.writeSelectedUser(user.id);
1910
+ void this.chat.selectUser(user).then(() => this.composer.focus()).catch(() => void 0);
1911
+ });
1912
+ return button;
1913
+ }
1914
+ renderSelectedUser(user) {
1915
+ this.query(".dl-chat__thread").toggleAttribute("hidden", !user);
1916
+ this.query(".dl-chat__empty").toggleAttribute("hidden", Boolean(user));
1917
+ if (!user) return;
1918
+ this.query(".dl-chat__thread-avatar").textContent = initials(user.displayName);
1919
+ this.query(".dl-chat__thread-name").textContent = user.displayName;
1920
+ const status = this.query(".dl-chat__thread-status");
1921
+ status.textContent = user.online ? "Online" : "Offline";
1922
+ status.classList.toggle("is-online", user.online);
1923
+ this.composer.placeholder = `Message ${user.firstName || user.displayName}`;
1924
+ this.composer.value = this.readDraft(user.id);
1925
+ this.onComposerInput();
1926
+ }
1927
+ renderMessages(messages) {
1928
+ const signature = messages.map((row) => [row.id, row.status || "", row.readAt || ""].join(":")).join(",");
1929
+ if (signature === this.renderedMessageIds) return;
1930
+ const oldHeight = this.messageList.scrollHeight;
1931
+ const oldTop = this.messageList.scrollTop;
1932
+ const pinned = oldHeight - oldTop - this.messageList.clientHeight < 90;
1933
+ this.renderedMessageIds = signature;
1934
+ this.messageList.replaceChildren();
1935
+ if (!messages.length && this.selected) {
1936
+ const note = this.doc.createElement("div");
1937
+ note.className = "dl-chat__thread-empty";
1938
+ note.textContent = `This is the beginning of your conversation with ${this.selected.displayName}.`;
1939
+ this.messageList.appendChild(note);
1940
+ return;
1941
+ }
1942
+ let lastDate = "";
1943
+ messages.forEach((message) => {
1944
+ var _a, _b;
1945
+ const date = new Date(message.createdAt);
1946
+ const dateLabel = date.toLocaleDateString(void 0, { weekday: "short", month: "short", day: "numeric" });
1947
+ if (dateLabel !== lastDate) {
1948
+ const separator = this.doc.createElement("div");
1949
+ separator.className = "dl-chat__date";
1950
+ separator.textContent = dateLabel;
1951
+ this.messageList.appendChild(separator);
1952
+ lastDate = dateLabel;
1953
+ }
1954
+ const row = this.doc.createElement("div");
1955
+ row.className = "dl-chat__message" + (message.senderId === Number((_a = this.api.jwtPayload) == null ? void 0 : _a.uid) ? " is-mine" : "");
1956
+ const bubble = this.doc.createElement("div");
1957
+ bubble.className = "dl-chat__bubble";
1958
+ const body = this.doc.createElement("span");
1959
+ body.textContent = message.body;
1960
+ const time = this.doc.createElement("time");
1961
+ time.dateTime = message.createdAt;
1962
+ const mine = message.senderId === Number((_b = this.api.jwtPayload) == null ? void 0 : _b.uid);
1963
+ const delivery = mine ? message.readAt ? "Read" : message.status === "failed" ? "Failed" : message.status === "sending" ? "Sending" : "Sent" : "";
1964
+ time.textContent = new Intl.DateTimeFormat(void 0, { hour: "numeric", minute: "2-digit" }).format(date) + (delivery ? ` · ${delivery}` : "");
1965
+ bubble.append(body, time);
1966
+ if (message.status === "failed" && mine) {
1967
+ const retry = this.doc.createElement("button");
1968
+ retry.type = "button";
1969
+ retry.className = "dl-chat__retry";
1970
+ retry.textContent = "Retry";
1971
+ retry.addEventListener("click", () => void this.chat.retry(message).catch(() => void 0));
1972
+ bubble.appendChild(retry);
1973
+ }
1974
+ row.appendChild(bubble);
1975
+ this.messageList.appendChild(row);
1976
+ });
1977
+ requestAnimationFrame(() => {
1978
+ if (pinned || messages.length < 15) this.messageList.scrollTop = this.messageList.scrollHeight;
1979
+ else this.messageList.scrollTop = oldTop + Math.max(0, this.messageList.scrollHeight - oldHeight);
1980
+ });
1981
+ }
1982
+ renderTyping(users) {
1983
+ var _a, _b;
1984
+ const active = Boolean(this.selected && users.has(this.selected.id));
1985
+ const node = this.query(".dl-chat__typing");
1986
+ node.toggleAttribute("hidden", !active);
1987
+ node.textContent = active ? `${((_a = this.selected) == null ? void 0 : _a.firstName) || ((_b = this.selected) == null ? void 0 : _b.displayName)} is typing...` : "";
1988
+ }
1989
+ renderError(error) {
1990
+ const node = this.query(".dl-chat__error");
1991
+ node.toggleAttribute("hidden", !error);
1992
+ node.textContent = error || "";
1993
+ }
1994
+ renderConnection(status) {
1995
+ const node = this.query(".dl-chat__connection");
1996
+ node.toggleAttribute("hidden", status === "online");
1997
+ node.textContent = status === "unauthorized" ? "Your session expired. Sign in again to continue chatting." : "Chat is reconnecting. Messages cannot be sent yet.";
1998
+ this.sendButton.disabled = status !== "online" || !this.composer.value.trim();
1999
+ }
2000
+ onComposerInput() {
2001
+ if (!this.selected) return;
2002
+ this.writeDraft(this.selected.id, this.composer.value);
2003
+ this.sendButton.disabled = !this.composer.value.trim() || this.api.status !== "online";
2004
+ if (!this.composer.value.trim()) return;
2005
+ if (!this.typingSent) {
2006
+ this.typingSent = true;
2007
+ void this.chat.setTyping(this.selected.id, true).catch(() => void 0);
2008
+ }
2009
+ clearTimeout(this.typingTimer);
2010
+ this.typingTimer = setTimeout(() => {
2011
+ if (this.selected) void this.chat.setTyping(this.selected.id, false).catch(() => void 0);
2012
+ this.typingSent = false;
2013
+ }, 1600);
2014
+ }
2015
+ async send() {
2016
+ const peer = this.selected;
2017
+ const body = this.composer.value.trim();
2018
+ if (!peer || !body || this.api.status !== "online") return;
2019
+ this.sendButton.disabled = true;
2020
+ this.composer.disabled = true;
2021
+ try {
2022
+ await this.chat.send(peer.id, body);
2023
+ this.composer.value = "";
2024
+ this.writeDraft(peer.id, "");
2025
+ if (this.typingSent) await this.chat.setTyping(peer.id, false).catch(() => void 0);
2026
+ this.typingSent = false;
2027
+ } finally {
2028
+ this.composer.disabled = false;
2029
+ this.sendButton.disabled = true;
2030
+ this.composer.focus();
2031
+ }
2032
+ }
2033
+ popout() {
2034
+ var _a;
2035
+ const popup = (_a = this.doc.defaultView) == null ? void 0 : _a.open("", "datalynk-chat", "popup,width=760,height=720,resizable=yes");
2036
+ if (!popup) {
2037
+ this.chat.error$.next("Allow pop-ups to open chat in a separate window.");
2038
+ return;
2039
+ }
2040
+ popup.document.title = this.options.title || "Datalynk Chat";
2041
+ popup.document.body.style.margin = "0";
2042
+ openChat(this.chat, { ...this.options, document: popup.document, popout: true });
2043
+ this.destroy();
2044
+ }
2045
+ makeDraggable() {
2046
+ if (this.options.popout) {
2047
+ this.shell.classList.add("is-popout");
2048
+ return;
2049
+ }
2050
+ const handle = this.query(".dl-chat__titlebar");
2051
+ handle.addEventListener("click", (event) => {
2052
+ if (this.shell.classList.contains("is-minimized") && !event.target.closest("button")) {
2053
+ this.setMinimized(false);
2054
+ }
2055
+ });
2056
+ handle.addEventListener("pointerdown", (event) => {
2057
+ if (event.target.closest("button")) return;
2058
+ if (this.shell.classList.contains("is-minimized")) return;
2059
+ const shell = this.shell;
2060
+ const rect = shell.getBoundingClientRect();
2061
+ const offsetX = event.clientX - rect.left;
2062
+ const offsetY = event.clientY - rect.top;
2063
+ handle.setPointerCapture(event.pointerId);
2064
+ const move = (next) => {
2065
+ var _a, _b;
2066
+ const maxX = Math.max(0, (((_a = this.doc.defaultView) == null ? void 0 : _a.innerWidth) || 0) - shell.offsetWidth);
2067
+ const maxY = Math.max(0, (((_b = this.doc.defaultView) == null ? void 0 : _b.innerHeight) || 0) - shell.offsetHeight);
2068
+ shell.style.left = Math.min(maxX, Math.max(0, next.clientX - offsetX)) + "px";
2069
+ shell.style.top = Math.min(maxY, Math.max(0, next.clientY - offsetY)) + "px";
2070
+ shell.style.right = "auto";
2071
+ shell.style.bottom = "auto";
2072
+ };
2073
+ const end = () => {
2074
+ handle.removeEventListener("pointermove", move);
2075
+ handle.removeEventListener("pointerup", end);
2076
+ handle.removeEventListener("pointercancel", end);
2077
+ this.saveGeometry();
2078
+ };
2079
+ handle.addEventListener("pointermove", move);
2080
+ handle.addEventListener("pointerup", end);
2081
+ handle.addEventListener("pointercancel", end);
2082
+ });
2083
+ }
2084
+ async initializeGui() {
2085
+ try {
2086
+ await this.chat.initialize();
2087
+ const selectedId = this.readSelectedUser();
2088
+ if (!selectedId || this.chat.selectedUser$.value) return;
2089
+ const conversation = this.chat.conversations$.value.find((row) => row.peer.id === selectedId);
2090
+ if (conversation) {
2091
+ this.shell.classList.add("has-selection");
2092
+ await this.chat.selectUser(conversation.peer);
2093
+ }
2094
+ } catch {
2095
+ }
2096
+ }
2097
+ restoreMinimized() {
2098
+ try {
2099
+ if (localStorage.getItem(this.storageKey("minimized")) === "1") this.setMinimized(true, false);
2100
+ } catch {
2101
+ }
2102
+ }
2103
+ setMinimized(minimized, persist = true) {
2104
+ var _a;
2105
+ if (this.options.popout) return;
2106
+ if (minimized && !this.shell.classList.contains("is-minimized")) this.saveGeometry();
2107
+ this.shell.classList.toggle("is-minimized", minimized);
2108
+ const button = this.query(".dl-chat__minimize");
2109
+ button.setAttribute("aria-label", minimized ? "Restore chat" : "Minimize chat");
2110
+ button.title = minimized ? "Restore" : "Minimize";
2111
+ (_a = button.querySelector("path")) == null ? void 0 : _a.setAttribute("d", minimized ? "M7.4 15.4 12 10.8l4.6 4.6L18 14l-6-6-6 6 1.4 1.4z" : "M5 11h14v2H5z");
2112
+ if (!minimized) this.restoreGeometry();
2113
+ if (persist) this.saveMinimized(minimized);
2114
+ }
2115
+ saveMinimized(value) {
2116
+ try {
2117
+ localStorage.setItem(this.storageKey("minimized"), value ? "1" : "0");
2118
+ } catch {
2119
+ }
2120
+ }
2121
+ readSelectedUser() {
2122
+ try {
2123
+ return Number(localStorage.getItem(this.storageKey("selected")) || 0);
2124
+ } catch {
2125
+ return 0;
2126
+ }
2127
+ }
2128
+ writeSelectedUser(userId) {
2129
+ try {
2130
+ localStorage.setItem(this.storageKey("selected"), String(userId));
2131
+ } catch {
2132
+ }
2133
+ }
2134
+ storageKey(suffix) {
2135
+ return `datalynk-chat:${this.api.spoke || "default"}:${suffix}`;
2136
+ }
2137
+ restoreGeometry() {
2138
+ var _a, _b;
2139
+ if (this.options.popout) return;
2140
+ try {
2141
+ const stored = JSON.parse(localStorage.getItem(this.storageKey("geometry")) || "null");
2142
+ if (!stored) return;
2143
+ const maxWidth = Math.max(360, (((_a = this.doc.defaultView) == null ? void 0 : _a.innerWidth) || 760) - 16);
2144
+ const maxHeight = Math.max(460, (((_b = this.doc.defaultView) == null ? void 0 : _b.innerHeight) || 720) - 16);
2145
+ this.shell.style.width = Math.min(maxWidth, Math.max(360, stored.width || 720)) + "px";
2146
+ this.shell.style.height = Math.min(maxHeight, Math.max(460, stored.height || 640)) + "px";
2147
+ this.shell.style.left = Math.max(0, Math.min(stored.left || 8, maxWidth - 120)) + "px";
2148
+ this.shell.style.top = Math.max(0, Math.min(stored.top || 8, maxHeight - 60)) + "px";
2149
+ this.shell.style.right = "auto";
2150
+ this.shell.style.bottom = "auto";
2151
+ } catch {
2152
+ }
2153
+ }
2154
+ saveGeometry() {
2155
+ if (this.options.popout || this.destroyed || this.shell.classList.contains("is-minimized")) return;
2156
+ const rect = this.shell.getBoundingClientRect();
2157
+ try {
2158
+ localStorage.setItem(this.storageKey("geometry"), JSON.stringify({
2159
+ left: rect.left,
2160
+ top: rect.top,
2161
+ width: rect.width,
2162
+ height: rect.height
2163
+ }));
2164
+ } catch {
2165
+ }
2166
+ }
2167
+ readDraft(userId) {
2168
+ try {
2169
+ return localStorage.getItem(this.storageKey("draft:" + userId)) || "";
2170
+ } catch {
2171
+ return "";
2172
+ }
2173
+ }
2174
+ writeDraft(userId, value) {
2175
+ try {
2176
+ if (value) localStorage.setItem(this.storageKey("draft:" + userId), value);
2177
+ else localStorage.removeItem(this.storageKey("draft:" + userId));
2178
+ } catch {
2179
+ }
2180
+ }
2181
+ }
2182
+ function initials(name) {
2183
+ return name.split(/\s+/).filter(Boolean).slice(0, 2).map((part) => part[0]).join("").toUpperCase() || "?";
2184
+ }
2185
+ function shortTime(value) {
2186
+ if (!value) return "";
2187
+ const date = new Date(value);
2188
+ return date.toDateString() === (/* @__PURE__ */ new Date()).toDateString() ? new Intl.DateTimeFormat(void 0, { hour: "numeric", minute: "2-digit" }).format(date) : new Intl.DateTimeFormat(void 0, { month: "short", day: "numeric" }).format(date);
2189
+ }
2190
+ function presence(online, doc) {
2191
+ const node = doc.createElement("span");
2192
+ node.className = "dl-chat__presence" + (online ? " is-online" : "");
2193
+ node.title = online ? "Online" : "Offline";
2194
+ node.setAttribute("aria-label", node.title);
2195
+ return node;
2196
+ }
2197
+ exports2.Chat = Chat;
2198
+ exports2.ChatWindow = ChatWindow;
2199
+ exports2.closeChat = closeChat;
2200
+ exports2.openChat = openChat;
2201
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
2202
+ });