@auxilium/datalynk-client 1.3.3 → 1.3.4

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/index.cjs ADDED
@@ -0,0 +1,3897 @@
1
+ (function(global2, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.utils = {}));
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 __defProp2 = Object.defineProperty;
9
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
11
+ function clean(obj, undefinedOnly = false) {
12
+ if (obj == null) throw new Error("Cannot clean a NULL value");
13
+ if (Array.isArray(obj)) {
14
+ obj = obj.filter((o) => undefinedOnly ? o !== void 0 : o != null);
15
+ } else {
16
+ Object.entries(obj).forEach(([key, value]) => {
17
+ if (undefinedOnly && value === void 0 || !undefinedOnly && value == null) delete obj[key];
18
+ });
19
+ }
20
+ return obj;
21
+ }
22
+ function deepCopy(value) {
23
+ try {
24
+ return structuredClone(value);
25
+ } catch {
26
+ return JSON.parse(JSONSanitize(value));
27
+ }
28
+ }
29
+ function dotNotation(obj, prop, set) {
30
+ if (obj == null || !prop) return void 0;
31
+ return prop.split(/[.[\]]/g).filter((prop2) => prop2.length).reduce((obj2, prop2, i, arr) => {
32
+ if (prop2[0] == '"' || prop2[0] == "'") prop2 = prop2.slice(1, -1);
33
+ if (!(obj2 == null ? void 0 : obj2.hasOwnProperty(prop2))) {
34
+ return void 0;
35
+ }
36
+ return obj2[prop2];
37
+ }, obj);
38
+ }
39
+ function isEqual(a, b) {
40
+ const ta = typeof a, tb = typeof b;
41
+ if (ta != "object" || a == null || (tb != "object" || b == null))
42
+ return ta == "function" && tb == "function" ? a.toString() == b.toString() : a === b;
43
+ const keys = Object.keys(a);
44
+ if (keys.length != Object.keys(b).length) return false;
45
+ return Object.keys(a).every((key) => isEqual(a[key], b[key]));
46
+ }
47
+ function JSONAttemptParse(json) {
48
+ try {
49
+ return JSON.parse(json);
50
+ } catch {
51
+ return json;
52
+ }
53
+ }
54
+ function JSONSanitize(obj, space) {
55
+ const cache = [];
56
+ return JSON.stringify(obj, (key, value) => {
57
+ if (typeof value === "object" && value !== null) {
58
+ if (cache.includes(value)) return "[Circular]";
59
+ cache.push(value);
60
+ }
61
+ return value;
62
+ }, space);
63
+ }
64
+ class ASet extends Array {
65
+ /** Number of elements in set */
66
+ get size() {
67
+ return this.length;
68
+ }
69
+ /**
70
+ * Array to create set from, duplicate values will be removed
71
+ * @param {T[]} elements Elements which will be added to set
72
+ */
73
+ constructor(elements = []) {
74
+ super();
75
+ if (!!(elements == null ? void 0 : elements["forEach"]))
76
+ elements.forEach((el) => this.add(el));
77
+ }
78
+ /**
79
+ * Add elements to set if unique
80
+ * @param items
81
+ */
82
+ add(...items) {
83
+ items.filter((el) => !this.has(el)).forEach((el) => this.push(el));
84
+ return this;
85
+ }
86
+ /**
87
+ * Remove all elements
88
+ */
89
+ clear() {
90
+ this.splice(0, this.length);
91
+ return this;
92
+ }
93
+ /**
94
+ * Delete elements from set
95
+ * @param items Elements that will be deleted
96
+ */
97
+ delete(...items) {
98
+ items.forEach((el) => {
99
+ const index = this.indexOf(el);
100
+ if (index != -1) this.splice(index, 1);
101
+ });
102
+ return this;
103
+ }
104
+ /**
105
+ * Create list of elements this set has which the comparison set does not
106
+ * @param {ASet<T>} set Set to compare against
107
+ * @return {ASet<T>} Different elements
108
+ */
109
+ difference(set) {
110
+ return new ASet(this.filter((el) => !set.has(el)));
111
+ }
112
+ /**
113
+ * Check if set includes element
114
+ * @param {T} el Element to look for
115
+ * @return {boolean} True if element was found, false otherwise
116
+ */
117
+ has(el) {
118
+ return this.indexOf(el) != -1;
119
+ }
120
+ /**
121
+ * Find index number of element, or -1 if it doesn't exist. Matches by equality not reference
122
+ *
123
+ * @param {T} search Element to find
124
+ * @param {number} fromIndex Starting index position
125
+ * @return {number} Element index number or -1 if missing
126
+ */
127
+ indexOf(search2, fromIndex) {
128
+ return super.findIndex((el) => isEqual(el, search2), fromIndex);
129
+ }
130
+ /**
131
+ * Create list of elements this set has in common with the comparison set
132
+ * @param {ASet<T>} set Set to compare against
133
+ * @return {boolean} Set of common elements
134
+ */
135
+ intersection(set) {
136
+ return new ASet(this.filter((el) => set.has(el)));
137
+ }
138
+ /**
139
+ * Check if this set has no elements in common with the comparison set
140
+ * @param {ASet<T>} set Set to compare against
141
+ * @return {boolean} True if nothing in common, false otherwise
142
+ */
143
+ isDisjointFrom(set) {
144
+ return this.intersection(set).size == 0;
145
+ }
146
+ /**
147
+ * Check if all elements in this set are included in the comparison set
148
+ * @param {ASet<T>} set Set to compare against
149
+ * @return {boolean} True if all elements are included, false otherwise
150
+ */
151
+ isSubsetOf(set) {
152
+ return this.findIndex((el) => !set.has(el)) == -1;
153
+ }
154
+ /**
155
+ * Check if all elements from comparison set are included in this set
156
+ * @param {ASet<T>} set Set to compare against
157
+ * @return {boolean} True if all elements are included, false otherwise
158
+ */
159
+ isSuperset(set) {
160
+ return set.findIndex((el) => !this.has(el)) == -1;
161
+ }
162
+ /**
163
+ * Create list of elements that are only in one set but not both (XOR)
164
+ * @param {ASet<T>} set Set to compare against
165
+ * @return {ASet<T>} New set of unique elements
166
+ */
167
+ symmetricDifference(set) {
168
+ return new ASet([...this.difference(set), ...set.difference(this)]);
169
+ }
170
+ /**
171
+ * Create joined list of elements included in this & the comparison set
172
+ * @param {ASet<T>} set Set join
173
+ * @return {ASet<T>} New set of both previous sets combined
174
+ */
175
+ union(set) {
176
+ return new ASet([...this, ...set]);
177
+ }
178
+ }
179
+ function sortByProp(prop, reverse = false) {
180
+ return function(a, b) {
181
+ const aVal = dotNotation(a, prop);
182
+ const bVal = dotNotation(b, prop);
183
+ if (typeof aVal == "number" && typeof bVal == "number")
184
+ return (reverse ? -1 : 1) * (aVal - bVal);
185
+ if (aVal > bVal) return reverse ? -1 : 1;
186
+ if (aVal < bVal) return reverse ? 1 : -1;
187
+ return 0;
188
+ };
189
+ }
190
+ function makeArray(value) {
191
+ return Array.isArray(value) ? value : [value];
192
+ }
193
+ class Database {
194
+ constructor(database, tables, version2) {
195
+ __publicField2(this, "connection");
196
+ __publicField2(this, "tables");
197
+ this.database = database;
198
+ this.version = version2;
199
+ this.connection = new Promise((resolve, reject) => {
200
+ const req = indexedDB.open(this.database, this.version);
201
+ this.tables = tables.map((t) => {
202
+ t = typeof t == "object" ? t : { name: t };
203
+ return { ...t, name: t.name.toString() };
204
+ });
205
+ const tableNames = new ASet(this.tables.map((t) => t.name));
206
+ req.onerror = () => reject(req.error);
207
+ req.onsuccess = () => {
208
+ const db = req.result;
209
+ if (tableNames.symmetricDifference(new ASet(Array.from(db.objectStoreNames))).length) {
210
+ db.close();
211
+ Object.assign(this, new Database(this.database, this.tables, db.version + 1));
212
+ } else {
213
+ this.version = db.version;
214
+ resolve(db);
215
+ }
216
+ };
217
+ req.onupgradeneeded = () => {
218
+ const db = req.result;
219
+ const existingTables = new ASet(Array.from(db.objectStoreNames));
220
+ existingTables.difference(tableNames).forEach((name) => db.deleteObjectStore(name));
221
+ tableNames.difference(existingTables).forEach((name) => db.createObjectStore(name));
222
+ };
223
+ });
224
+ }
225
+ includes(name) {
226
+ return !!this.tables.find((t) => t.name == name.toString());
227
+ }
228
+ table(name) {
229
+ return new Table(this, name.toString());
230
+ }
231
+ }
232
+ class Table {
233
+ constructor(database, name) {
234
+ this.database = database;
235
+ this.name = name;
236
+ }
237
+ async tx(table, fn2, readonly = false) {
238
+ const db = await this.database.connection;
239
+ const tx = db.transaction(table, readonly ? "readonly" : "readwrite");
240
+ const store = tx.objectStore(table);
241
+ return new Promise((resolve, reject) => {
242
+ const request = fn2(store);
243
+ request.onsuccess = () => resolve(request.result);
244
+ request.onerror = () => reject(request.error);
245
+ });
246
+ }
247
+ add(value, key) {
248
+ return this.tx(this.name, (store) => store.add(value, key));
249
+ }
250
+ count() {
251
+ return this.tx(this.name, (store) => store.count(), true);
252
+ }
253
+ put(key, value) {
254
+ return this.tx(this.name, (store) => store.put(value, key));
255
+ }
256
+ getAll() {
257
+ return this.tx(this.name, (store) => store.getAll(), true);
258
+ }
259
+ getAllKeys() {
260
+ return this.tx(this.name, (store) => store.getAllKeys(), true);
261
+ }
262
+ get(key) {
263
+ return this.tx(this.name, (store) => store.get(key), true);
264
+ }
265
+ delete(key) {
266
+ return this.tx(this.name, (store) => store.delete(key));
267
+ }
268
+ clear() {
269
+ return this.tx(this.name, (store) => store.clear());
270
+ }
271
+ }
272
+ function contrast(background) {
273
+ const exploded = background == null ? void 0 : background.match(background.length >= 6 ? /[0-9a-fA-F]{2}/g : /[0-9a-fA-F]/g);
274
+ if (!exploded || (exploded == null ? void 0 : exploded.length) < 3) return "black";
275
+ const [r, g, b] = exploded.map((hex) => parseInt(hex.length == 1 ? `${hex}${hex}` : hex, 16));
276
+ const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
277
+ return luminance > 0.5 ? "black" : "white";
278
+ }
279
+ const LETTER_LIST = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
280
+ const NUMBER_LIST = "0123456789";
281
+ const SYMBOL_LIST = "~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/";
282
+ function randomStringBuilder(length, letters = false, numbers = false, symbols = false) {
283
+ if (!letters && !numbers && !symbols) throw new Error("Must enable at least one: letters, numbers, symbols");
284
+ return Array(length).fill(null).map(() => {
285
+ let c;
286
+ do {
287
+ const type = ~~(Math.random() * 3);
288
+ if (letters && type == 0) {
289
+ c = LETTER_LIST[~~(Math.random() * LETTER_LIST.length)];
290
+ } else if (numbers && type == 1) {
291
+ c = NUMBER_LIST[~~(Math.random() * NUMBER_LIST.length)];
292
+ } else if (symbols && type == 2) {
293
+ c = SYMBOL_LIST[~~(Math.random() * SYMBOL_LIST.length)];
294
+ }
295
+ } while (!c);
296
+ return c;
297
+ }).join("");
298
+ }
299
+ class PromiseProgress extends Promise {
300
+ constructor(executor) {
301
+ super((resolve, reject) => executor(
302
+ (value) => resolve(value),
303
+ (reason) => reject(reason),
304
+ (progress) => this.progress = progress
305
+ ));
306
+ __publicField2(this, "listeners", []);
307
+ __publicField2(this, "_progress", 0);
308
+ }
309
+ get progress() {
310
+ return this._progress;
311
+ }
312
+ set progress(p) {
313
+ if (p == this._progress) return;
314
+ this._progress = p;
315
+ this.listeners.forEach((l) => l(p));
316
+ }
317
+ static from(promise) {
318
+ if (promise instanceof PromiseProgress) return promise;
319
+ return new PromiseProgress((res, rej) => promise.then((...args) => res(...args)).catch((...args) => rej(...args)));
320
+ }
321
+ from(promise) {
322
+ const newPromise = PromiseProgress.from(promise);
323
+ this.onProgress((p) => newPromise.progress = p);
324
+ return newPromise;
325
+ }
326
+ onProgress(callback) {
327
+ this.listeners.push(callback);
328
+ return this;
329
+ }
330
+ then(res, rej) {
331
+ const resp = super.then(res, rej);
332
+ return this.from(resp);
333
+ }
334
+ catch(rej) {
335
+ return this.from(super.catch(rej));
336
+ }
337
+ finally(res) {
338
+ return this.from(super.finally(res));
339
+ }
340
+ }
341
+ class TypedEmitter {
342
+ constructor() {
343
+ __publicField2(this, "listeners", {});
344
+ }
345
+ static emit(event, ...args) {
346
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
347
+ (this.listeners[event.toString()] || []).forEach((l) => l(...args));
348
+ }
349
+ static off(event, listener) {
350
+ const e = event.toString();
351
+ this.listeners[e] = (this.listeners[e] || []).filter((l) => l != listener);
352
+ }
353
+ static on(event, listener) {
354
+ var _a;
355
+ const e = event.toString();
356
+ if (!this.listeners[e]) this.listeners[e] = [];
357
+ (_a = this.listeners[e]) == null ? void 0 : _a.push(listener);
358
+ return () => this.off(event, listener);
359
+ }
360
+ static once(event, listener) {
361
+ return new Promise((res) => {
362
+ const unsubscribe = this.on(event, (...args) => {
363
+ res(args.length == 1 ? args[0] : args);
364
+ if (listener) listener(...args);
365
+ unsubscribe();
366
+ });
367
+ });
368
+ }
369
+ emit(event, ...args) {
370
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
371
+ (this.listeners[event] || []).forEach((l) => l(...args));
372
+ }
373
+ off(event, listener) {
374
+ this.listeners[event] = (this.listeners[event] || []).filter((l) => l != listener);
375
+ }
376
+ on(event, listener) {
377
+ var _a;
378
+ if (!this.listeners[event]) this.listeners[event] = [];
379
+ (_a = this.listeners[event]) == null ? void 0 : _a.push(listener);
380
+ return () => this.off(event, listener);
381
+ }
382
+ once(event, listener) {
383
+ return new Promise((res) => {
384
+ const unsubscribe = this.on(event, (...args) => {
385
+ res(args.length == 1 ? args[0] : args);
386
+ if (listener) listener(...args);
387
+ unsubscribe();
388
+ });
389
+ });
390
+ }
391
+ }
392
+ __publicField2(TypedEmitter, "listeners", {});
393
+ class CustomError extends Error {
394
+ constructor(message, code) {
395
+ super(message);
396
+ __publicField2(this, "_code");
397
+ if (code != null) this._code = code;
398
+ }
399
+ get code() {
400
+ return this._code || this.constructor.code;
401
+ }
402
+ set code(c) {
403
+ this._code = c;
404
+ }
405
+ static from(err) {
406
+ const code = Number(err.statusCode) ?? Number(err.code);
407
+ const newErr = new this(err.message || err.toString());
408
+ return Object.assign(newErr, {
409
+ stack: err.stack,
410
+ ...err,
411
+ code: code ?? void 0
412
+ });
413
+ }
414
+ static instanceof(err) {
415
+ return err.constructor.code != void 0;
416
+ }
417
+ toString() {
418
+ return this.message || super.toString();
419
+ }
420
+ }
421
+ __publicField2(CustomError, "code", 500);
422
+ class BadRequestError extends CustomError {
423
+ constructor(message = "Bad Request") {
424
+ super(message);
425
+ }
426
+ static instanceof(err) {
427
+ return err.constructor.code == this.code;
428
+ }
429
+ }
430
+ __publicField2(BadRequestError, "code", 400);
431
+ class UnauthorizedError extends CustomError {
432
+ constructor(message = "Unauthorized") {
433
+ super(message);
434
+ }
435
+ static instanceof(err) {
436
+ return err.constructor.code == this.code;
437
+ }
438
+ }
439
+ __publicField2(UnauthorizedError, "code", 401);
440
+ class PaymentRequiredError extends CustomError {
441
+ constructor(message = "Payment Required") {
442
+ super(message);
443
+ }
444
+ static instanceof(err) {
445
+ return err.constructor.code == this.code;
446
+ }
447
+ }
448
+ __publicField2(PaymentRequiredError, "code", 402);
449
+ class ForbiddenError extends CustomError {
450
+ constructor(message = "Forbidden") {
451
+ super(message);
452
+ }
453
+ static instanceof(err) {
454
+ return err.constructor.code == this.code;
455
+ }
456
+ }
457
+ __publicField2(ForbiddenError, "code", 403);
458
+ class NotFoundError extends CustomError {
459
+ constructor(message = "Not Found") {
460
+ super(message);
461
+ }
462
+ static instanceof(err) {
463
+ return err.constructor.code == this.code;
464
+ }
465
+ }
466
+ __publicField2(NotFoundError, "code", 404);
467
+ class MethodNotAllowedError extends CustomError {
468
+ constructor(message = "Method Not Allowed") {
469
+ super(message);
470
+ }
471
+ static instanceof(err) {
472
+ return err.constructor.code == this.code;
473
+ }
474
+ }
475
+ __publicField2(MethodNotAllowedError, "code", 405);
476
+ class NotAcceptableError extends CustomError {
477
+ constructor(message = "Not Acceptable") {
478
+ super(message);
479
+ }
480
+ static instanceof(err) {
481
+ return err.constructor.code == this.code;
482
+ }
483
+ }
484
+ __publicField2(NotAcceptableError, "code", 406);
485
+ class InternalServerError extends CustomError {
486
+ constructor(message = "Internal Server Error") {
487
+ super(message);
488
+ }
489
+ static instanceof(err) {
490
+ return err.constructor.code == this.code;
491
+ }
492
+ }
493
+ __publicField2(InternalServerError, "code", 500);
494
+ class NotImplementedError extends CustomError {
495
+ constructor(message = "Not Implemented") {
496
+ super(message);
497
+ }
498
+ static instanceof(err) {
499
+ return err.constructor.code == this.code;
500
+ }
501
+ }
502
+ __publicField2(NotImplementedError, "code", 501);
503
+ class BadGatewayError extends CustomError {
504
+ constructor(message = "Bad Gateway") {
505
+ super(message);
506
+ }
507
+ static instanceof(err) {
508
+ return err.constructor.code == this.code;
509
+ }
510
+ }
511
+ __publicField2(BadGatewayError, "code", 502);
512
+ class ServiceUnavailableError extends CustomError {
513
+ constructor(message = "Service Unavailable") {
514
+ super(message);
515
+ }
516
+ static instanceof(err) {
517
+ return err.constructor.code == this.code;
518
+ }
519
+ }
520
+ __publicField2(ServiceUnavailableError, "code", 503);
521
+ class GatewayTimeoutError extends CustomError {
522
+ constructor(message = "Gateway Timeout") {
523
+ super(message);
524
+ }
525
+ static instanceof(err) {
526
+ return err.constructor.code == this.code;
527
+ }
528
+ }
529
+ __publicField2(GatewayTimeoutError, "code", 504);
530
+ function errorFromCode(code, message) {
531
+ switch (code) {
532
+ case 400:
533
+ return new BadRequestError(message);
534
+ case 401:
535
+ return new UnauthorizedError(message);
536
+ case 402:
537
+ return new PaymentRequiredError(message);
538
+ case 403:
539
+ return new ForbiddenError(message);
540
+ case 404:
541
+ return new NotFoundError(message);
542
+ case 405:
543
+ return new MethodNotAllowedError(message);
544
+ case 406:
545
+ return new NotAcceptableError(message);
546
+ case 500:
547
+ return new InternalServerError(message);
548
+ case 501:
549
+ return new NotImplementedError(message);
550
+ case 502:
551
+ return new BadGatewayError(message);
552
+ case 503:
553
+ return new ServiceUnavailableError(message);
554
+ case 504:
555
+ return new GatewayTimeoutError(message);
556
+ default:
557
+ return new CustomError(message, code);
558
+ }
559
+ }
560
+ class HttpResponse extends Response {
561
+ constructor(resp, stream) {
562
+ const body = [204, 205, 304].includes(resp.status) ? null : stream;
563
+ super(body, {
564
+ headers: resp.headers,
565
+ status: resp.status,
566
+ statusText: resp.statusText
567
+ });
568
+ __publicField2(this, "data");
569
+ __publicField2(this, "ok");
570
+ __publicField2(this, "redirected");
571
+ __publicField2(this, "type");
572
+ __publicField2(this, "url");
573
+ this.ok = resp.ok;
574
+ this.redirected = resp.redirected;
575
+ this.type = resp.type;
576
+ this.url = resp.url;
577
+ }
578
+ }
579
+ const _Http = class _Http2 {
580
+ constructor(defaults = {}) {
581
+ __publicField2(this, "interceptors", {});
582
+ __publicField2(this, "headers", {});
583
+ __publicField2(this, "url");
584
+ this.url = defaults.url ?? null;
585
+ this.headers = defaults.headers || {};
586
+ if (defaults.interceptors) {
587
+ defaults.interceptors.forEach((i) => _Http2.addInterceptor(i));
588
+ }
589
+ }
590
+ static addInterceptor(fn2) {
591
+ const key = Object.keys(_Http2.interceptors).length.toString();
592
+ _Http2.interceptors[key] = fn2;
593
+ return () => {
594
+ _Http2.interceptors[key] = null;
595
+ };
596
+ }
597
+ addInterceptor(fn2) {
598
+ const key = Object.keys(this.interceptors).length.toString();
599
+ this.interceptors[key] = fn2;
600
+ return () => {
601
+ this.interceptors[key] = null;
602
+ };
603
+ }
604
+ request(opts = {}) {
605
+ var _a;
606
+ if (!this.url && !opts.url) throw new Error("URL needs to be set");
607
+ let url = ((_a = opts.url) == null ? void 0 : _a.startsWith("http")) ? opts.url : (this.url || "") + (opts.url || "");
608
+ url = url.replaceAll(/([^:]\/)\/+/g, "$1");
609
+ if (opts.fragment) url.includes("#") ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : `${url}#${opts.fragment}`;
610
+ if (opts.query) {
611
+ const q = Array.isArray(opts.query) ? opts.query : Object.keys(opts.query).map((k) => ({ key: k, value: opts.query[k] }));
612
+ url += (url.includes("?") ? "&" : "?") + q.map((q2) => `${q2.key}=${q2.value}`).join("&");
613
+ }
614
+ const headers = clean({
615
+ "Content-Type": !opts.body ? void 0 : opts.body instanceof FormData ? "multipart/form-data" : "application/json",
616
+ ..._Http2.headers,
617
+ ...this.headers,
618
+ ...opts.headers
619
+ });
620
+ if (typeof opts.body == "object" && opts.body != null && headers["Content-Type"] == "application/json")
621
+ opts.body = JSON.stringify(opts.body);
622
+ return new PromiseProgress((res, rej, prog) => {
623
+ try {
624
+ fetch(url, {
625
+ headers,
626
+ method: opts.method || (opts.body ? "POST" : "GET"),
627
+ body: opts.body
628
+ }).then(async (resp) => {
629
+ var _a2, _b;
630
+ for (let fn2 of [...Object.values(_Http2.interceptors), ...Object.values(this.interceptors)]) {
631
+ await new Promise((res2) => fn2(resp, () => res2()));
632
+ }
633
+ const contentLength = resp.headers.get("Content-Length");
634
+ const total = contentLength ? parseInt(contentLength, 10) : 0;
635
+ let loaded = 0;
636
+ const reader = (_a2 = resp.body) == null ? void 0 : _a2.getReader();
637
+ const stream = new ReadableStream({
638
+ start(controller) {
639
+ function push() {
640
+ reader == null ? void 0 : reader.read().then((event) => {
641
+ if (event.done) return controller.close();
642
+ loaded += event.value.byteLength;
643
+ prog(loaded / total);
644
+ controller.enqueue(event.value);
645
+ push();
646
+ }).catch((error) => controller.error(error));
647
+ }
648
+ push();
649
+ }
650
+ });
651
+ resp = new HttpResponse(resp, stream);
652
+ if (opts.decode !== false) {
653
+ const content = (_b = resp.headers.get("Content-Type")) == null ? void 0 : _b.toLowerCase();
654
+ if (content == null ? void 0 : content.includes("form")) resp.data = await resp.formData();
655
+ else if (content == null ? void 0 : content.includes("json")) resp.data = await resp.json();
656
+ else if (content == null ? void 0 : content.includes("text")) resp.data = await resp.text();
657
+ else if (content == null ? void 0 : content.includes("application")) resp.data = await resp.blob();
658
+ }
659
+ if (resp.ok) res(resp);
660
+ else rej(resp);
661
+ }).catch((err) => rej(err));
662
+ } catch (err) {
663
+ rej(err);
664
+ }
665
+ });
666
+ }
667
+ };
668
+ __publicField2(_Http, "interceptors", {});
669
+ __publicField2(_Http, "headers", {});
670
+ function decodeJwt(token) {
671
+ const base64 = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
672
+ return JSONAttemptParse(decodeURIComponent(atob(base64).split("").map(function(c) {
673
+ return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
674
+ }).join("")));
675
+ }
676
+ const CliEffects = {
677
+ CLEAR: "\x1B[0m"
678
+ };
679
+ const CliForeground = {
680
+ RED: "\x1B[31m",
681
+ YELLOW: "\x1B[33m",
682
+ BLUE: "\x1B[34m",
683
+ LIGHT_GREY: "\x1B[37m"
684
+ };
685
+ const _Logger = class _Logger2 extends TypedEmitter {
686
+ constructor(namespace) {
687
+ super();
688
+ this.namespace = namespace;
689
+ }
690
+ format(...text) {
691
+ const now = /* @__PURE__ */ new Date();
692
+ const timestamp = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}.${now.getMilliseconds().toString().padEnd(3, "0")}`;
693
+ return `${timestamp}${this.namespace ? ` [${this.namespace}]` : ""} ${text.map((t) => typeof t == "string" ? t : JSONSanitize(t, 2)).join(" ")}`;
694
+ }
695
+ debug(...args) {
696
+ if (_Logger2.LOG_LEVEL < 4) return;
697
+ const str = this.format(...args);
698
+ _Logger2.emit(4, str);
699
+ console.debug(CliForeground.LIGHT_GREY + str + CliEffects.CLEAR);
700
+ }
701
+ log(...args) {
702
+ if (_Logger2.LOG_LEVEL < 3) return;
703
+ const str = this.format(...args);
704
+ _Logger2.emit(3, str);
705
+ console.log(CliEffects.CLEAR + str);
706
+ }
707
+ info(...args) {
708
+ if (_Logger2.LOG_LEVEL < 2) return;
709
+ const str = this.format(...args);
710
+ _Logger2.emit(2, str);
711
+ console.info(CliForeground.BLUE + str + CliEffects.CLEAR);
712
+ }
713
+ warn(...args) {
714
+ if (_Logger2.LOG_LEVEL < 1) return;
715
+ const str = this.format(...args);
716
+ _Logger2.emit(1, str);
717
+ console.warn(CliForeground.YELLOW + str + CliEffects.CLEAR);
718
+ }
719
+ error(...args) {
720
+ if (_Logger2.LOG_LEVEL < 0) return;
721
+ const str = this.format(...args);
722
+ _Logger2.emit(0, str);
723
+ console.error(CliForeground.RED + str + CliEffects.CLEAR);
724
+ }
725
+ };
726
+ __publicField2(_Logger, "LOG_LEVEL", 4);
727
+ var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
728
+ var dist = {};
729
+ var persist$1 = {};
730
+ Object.defineProperty(persist$1, "__esModule", { value: true });
731
+ persist$1.persist = persist$1.Persist = void 0;
732
+ class Persist {
733
+ /**
734
+ * @param {string} key Primary key value will be stored under
735
+ * @param {PersistOptions<T>} options Configure using {@link PersistOptions}
736
+ */
737
+ constructor(key, options = {}) {
738
+ __publicField2(this, "key");
739
+ __publicField2(this, "options");
740
+ __publicField2(this, "storage");
741
+ __publicField2(this, "watches", {});
742
+ __publicField2(this, "_value");
743
+ this.key = key;
744
+ this.options = options;
745
+ this.storage = options.storage || localStorage;
746
+ this.load();
747
+ }
748
+ /** Current value or default if undefined */
749
+ get value() {
750
+ var _a;
751
+ return this._value !== void 0 ? this._value : (_a = this.options) == null ? void 0 : _a.default;
752
+ }
753
+ /** Set value with proxy object wrapper to sync future changes */
754
+ set value(v) {
755
+ if (v == null || typeof v != "object")
756
+ this._value = v;
757
+ else
758
+ this._value = new Proxy(v, {
759
+ get: (target, p) => {
760
+ const f = typeof target[p] == "function";
761
+ if (!f)
762
+ return target[p];
763
+ return (...args) => {
764
+ const value = target[p](...args);
765
+ this.save();
766
+ return value;
767
+ };
768
+ },
769
+ set: (target, p, newValue) => {
770
+ target[p] = newValue;
771
+ this.save();
772
+ return true;
773
+ }
774
+ });
775
+ this.save();
776
+ }
777
+ /** Notify listeners of change */
778
+ notify(value) {
779
+ Object.values(this.watches).forEach((watch) => watch(value));
780
+ }
781
+ /** Delete value from storage */
782
+ clear() {
783
+ this.storage.removeItem(this.key);
784
+ }
785
+ /** Save current value to storage */
786
+ save() {
787
+ if (this._value === void 0)
788
+ this.clear();
789
+ else
790
+ this.storage.setItem(this.key, JSON.stringify(this._value));
791
+ this.notify(this.value);
792
+ }
793
+ /** Load value from storage */
794
+ load() {
795
+ if (this.storage[this.key] != void 0) {
796
+ let value = JSON.parse(this.storage.getItem(this.key));
797
+ if (value != null && typeof value == "object" && this.options.type)
798
+ value.__proto__ = this.options.type.prototype;
799
+ this.value = value;
800
+ } else
801
+ this.value = this.options.default || void 0;
802
+ }
803
+ /**
804
+ * Callback function which is run when there are changes
805
+ *
806
+ * @param {(value: T) => any} fn Callback will run on each change; it's passed the next value & it's return is ignored
807
+ * @returns {() => void} Function which will unsubscribe the watch/callback when called
808
+ */
809
+ watch(fn2) {
810
+ const index = Object.keys(this.watches).length;
811
+ this.watches[index] = fn2;
812
+ return () => {
813
+ delete this.watches[index];
814
+ };
815
+ }
816
+ /**
817
+ * Return value as JSON string
818
+ *
819
+ * @returns {string} Stringified object as JSON
820
+ */
821
+ toString() {
822
+ return JSON.stringify(this.value);
823
+ }
824
+ /**
825
+ * Return current value
826
+ *
827
+ * @returns {T} Current value
828
+ */
829
+ valueOf() {
830
+ return this.value;
831
+ }
832
+ }
833
+ persist$1.Persist = Persist;
834
+ function persist(options) {
835
+ return (target, prop) => {
836
+ const key = (options == null ? void 0 : options.key) || `${target.constructor.name}.${prop.toString()}`;
837
+ const wrapper = new Persist(key, options);
838
+ Object.defineProperty(target, prop, {
839
+ get: function() {
840
+ return wrapper.value;
841
+ },
842
+ set: function(v) {
843
+ wrapper.value = v;
844
+ }
845
+ });
846
+ };
847
+ }
848
+ persist$1.persist = persist;
849
+ var memoryStorage = {};
850
+ Object.defineProperty(memoryStorage, "__esModule", { value: true });
851
+ memoryStorage.MemoryStorage = void 0;
852
+ class MemoryStorage {
853
+ get length() {
854
+ return Object.keys(this).length;
855
+ }
856
+ clear() {
857
+ Object.keys(this).forEach((k) => this.removeItem(k));
858
+ }
859
+ getItem(key) {
860
+ return this[key];
861
+ }
862
+ key(index) {
863
+ return Object.keys(this)[index];
864
+ }
865
+ removeItem(key) {
866
+ delete this[key];
867
+ }
868
+ setItem(key, value) {
869
+ this[key] = value;
870
+ }
871
+ }
872
+ memoryStorage.MemoryStorage = MemoryStorage;
873
+ (function(exports3) {
874
+ var __createBinding = commonjsGlobal && commonjsGlobal.__createBinding || (Object.create ? function(o, m, k, k2) {
875
+ if (k2 === void 0) k2 = k;
876
+ var desc = Object.getOwnPropertyDescriptor(m, k);
877
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
878
+ desc = { enumerable: true, get: function() {
879
+ return m[k];
880
+ } };
881
+ }
882
+ Object.defineProperty(o, k2, desc);
883
+ } : function(o, m, k, k2) {
884
+ if (k2 === void 0) k2 = k;
885
+ o[k2] = m[k];
886
+ });
887
+ var __exportStar = commonjsGlobal && commonjsGlobal.__exportStar || function(m, exports22) {
888
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports22, p)) __createBinding(exports22, m, p);
889
+ };
890
+ Object.defineProperty(exports3, "__esModule", { value: true });
891
+ __exportStar(persist$1, exports3);
892
+ __exportStar(memoryStorage, exports3);
893
+ })(dist);
894
+ var extendStatics = function(d, b) {
895
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
896
+ d2.__proto__ = b2;
897
+ } || function(d2, b2) {
898
+ for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
899
+ };
900
+ return extendStatics(d, b);
901
+ };
902
+ function __extends(d, b) {
903
+ if (typeof b !== "function" && b !== null)
904
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
905
+ extendStatics(d, b);
906
+ function __() {
907
+ this.constructor = d;
908
+ }
909
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
910
+ }
911
+ function __values(o) {
912
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
913
+ if (m) return m.call(o);
914
+ if (o && typeof o.length === "number") return {
915
+ next: function() {
916
+ if (o && i >= o.length) o = void 0;
917
+ return { value: o && o[i++], done: !o };
918
+ }
919
+ };
920
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
921
+ }
922
+ function __read(o, n) {
923
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
924
+ if (!m) return o;
925
+ var i = m.call(o), r, ar = [], e;
926
+ try {
927
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
928
+ } catch (error) {
929
+ e = { error };
930
+ } finally {
931
+ try {
932
+ if (r && !r.done && (m = i["return"])) m.call(i);
933
+ } finally {
934
+ if (e) throw e.error;
935
+ }
936
+ }
937
+ return ar;
938
+ }
939
+ function __spreadArray(to, from, pack) {
940
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
941
+ if (ar || !(i in from)) {
942
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
943
+ ar[i] = from[i];
944
+ }
945
+ }
946
+ return to.concat(ar || Array.prototype.slice.call(from));
947
+ }
948
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
949
+ var e = new Error(message);
950
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
951
+ };
952
+ function isFunction(value) {
953
+ return typeof value === "function";
954
+ }
955
+ function createErrorClass(createImpl) {
956
+ var _super = function(instance) {
957
+ Error.call(instance);
958
+ instance.stack = new Error().stack;
959
+ };
960
+ var ctorFunc = createImpl(_super);
961
+ ctorFunc.prototype = Object.create(Error.prototype);
962
+ ctorFunc.prototype.constructor = ctorFunc;
963
+ return ctorFunc;
964
+ }
965
+ var UnsubscriptionError = createErrorClass(function(_super) {
966
+ return function UnsubscriptionErrorImpl(errors) {
967
+ _super(this);
968
+ this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
969
+ return i + 1 + ") " + err.toString();
970
+ }).join("\n ") : "";
971
+ this.name = "UnsubscriptionError";
972
+ this.errors = errors;
973
+ };
974
+ });
975
+ function arrRemove(arr, item) {
976
+ if (arr) {
977
+ var index = arr.indexOf(item);
978
+ 0 <= index && arr.splice(index, 1);
979
+ }
980
+ }
981
+ var Subscription = function() {
982
+ function Subscription2(initialTeardown) {
983
+ this.initialTeardown = initialTeardown;
984
+ this.closed = false;
985
+ this._parentage = null;
986
+ this._finalizers = null;
987
+ }
988
+ Subscription2.prototype.unsubscribe = function() {
989
+ var e_1, _a, e_2, _b;
990
+ var errors;
991
+ if (!this.closed) {
992
+ this.closed = true;
993
+ var _parentage = this._parentage;
994
+ if (_parentage) {
995
+ this._parentage = null;
996
+ if (Array.isArray(_parentage)) {
997
+ try {
998
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
999
+ var parent_1 = _parentage_1_1.value;
1000
+ parent_1.remove(this);
1001
+ }
1002
+ } catch (e_1_1) {
1003
+ e_1 = { error: e_1_1 };
1004
+ } finally {
1005
+ try {
1006
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
1007
+ } finally {
1008
+ if (e_1) throw e_1.error;
1009
+ }
1010
+ }
1011
+ } else {
1012
+ _parentage.remove(this);
1013
+ }
1014
+ }
1015
+ var initialFinalizer = this.initialTeardown;
1016
+ if (isFunction(initialFinalizer)) {
1017
+ try {
1018
+ initialFinalizer();
1019
+ } catch (e) {
1020
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
1021
+ }
1022
+ }
1023
+ var _finalizers = this._finalizers;
1024
+ if (_finalizers) {
1025
+ this._finalizers = null;
1026
+ try {
1027
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
1028
+ var finalizer = _finalizers_1_1.value;
1029
+ try {
1030
+ execFinalizer(finalizer);
1031
+ } catch (err) {
1032
+ errors = errors !== null && errors !== void 0 ? errors : [];
1033
+ if (err instanceof UnsubscriptionError) {
1034
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
1035
+ } else {
1036
+ errors.push(err);
1037
+ }
1038
+ }
1039
+ }
1040
+ } catch (e_2_1) {
1041
+ e_2 = { error: e_2_1 };
1042
+ } finally {
1043
+ try {
1044
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
1045
+ } finally {
1046
+ if (e_2) throw e_2.error;
1047
+ }
1048
+ }
1049
+ }
1050
+ if (errors) {
1051
+ throw new UnsubscriptionError(errors);
1052
+ }
1053
+ }
1054
+ };
1055
+ Subscription2.prototype.add = function(teardown) {
1056
+ var _a;
1057
+ if (teardown && teardown !== this) {
1058
+ if (this.closed) {
1059
+ execFinalizer(teardown);
1060
+ } else {
1061
+ if (teardown instanceof Subscription2) {
1062
+ if (teardown.closed || teardown._hasParent(this)) {
1063
+ return;
1064
+ }
1065
+ teardown._addParent(this);
1066
+ }
1067
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
1068
+ }
1069
+ }
1070
+ };
1071
+ Subscription2.prototype._hasParent = function(parent2) {
1072
+ var _parentage = this._parentage;
1073
+ return _parentage === parent2 || Array.isArray(_parentage) && _parentage.includes(parent2);
1074
+ };
1075
+ Subscription2.prototype._addParent = function(parent2) {
1076
+ var _parentage = this._parentage;
1077
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent2), _parentage) : _parentage ? [_parentage, parent2] : parent2;
1078
+ };
1079
+ Subscription2.prototype._removeParent = function(parent2) {
1080
+ var _parentage = this._parentage;
1081
+ if (_parentage === parent2) {
1082
+ this._parentage = null;
1083
+ } else if (Array.isArray(_parentage)) {
1084
+ arrRemove(_parentage, parent2);
1085
+ }
1086
+ };
1087
+ Subscription2.prototype.remove = function(teardown) {
1088
+ var _finalizers = this._finalizers;
1089
+ _finalizers && arrRemove(_finalizers, teardown);
1090
+ if (teardown instanceof Subscription2) {
1091
+ teardown._removeParent(this);
1092
+ }
1093
+ };
1094
+ Subscription2.EMPTY = function() {
1095
+ var empty = new Subscription2();
1096
+ empty.closed = true;
1097
+ return empty;
1098
+ }();
1099
+ return Subscription2;
1100
+ }();
1101
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
1102
+ function isSubscription(value) {
1103
+ return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
1104
+ }
1105
+ function execFinalizer(finalizer) {
1106
+ if (isFunction(finalizer)) {
1107
+ finalizer();
1108
+ } else {
1109
+ finalizer.unsubscribe();
1110
+ }
1111
+ }
1112
+ var config = {
1113
+ Promise: void 0
1114
+ };
1115
+ var timeoutProvider = {
1116
+ setTimeout: function(handler, timeout) {
1117
+ var args = [];
1118
+ for (var _i = 2; _i < arguments.length; _i++) {
1119
+ args[_i - 2] = arguments[_i];
1120
+ }
1121
+ return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
1122
+ },
1123
+ clearTimeout: function(handle) {
1124
+ return clearTimeout(handle);
1125
+ },
1126
+ delegate: void 0
1127
+ };
1128
+ function reportUnhandledError(err) {
1129
+ timeoutProvider.setTimeout(function() {
1130
+ {
1131
+ throw err;
1132
+ }
1133
+ });
1134
+ }
1135
+ function noop() {
1136
+ }
1137
+ function errorContext(cb) {
1138
+ {
1139
+ cb();
1140
+ }
1141
+ }
1142
+ var Subscriber = function(_super) {
1143
+ __extends(Subscriber2, _super);
1144
+ function Subscriber2(destination) {
1145
+ var _this = _super.call(this) || this;
1146
+ _this.isStopped = false;
1147
+ if (destination) {
1148
+ _this.destination = destination;
1149
+ if (isSubscription(destination)) {
1150
+ destination.add(_this);
1151
+ }
1152
+ } else {
1153
+ _this.destination = EMPTY_OBSERVER;
1154
+ }
1155
+ return _this;
1156
+ }
1157
+ Subscriber2.create = function(next, error, complete) {
1158
+ return new SafeSubscriber(next, error, complete);
1159
+ };
1160
+ Subscriber2.prototype.next = function(value) {
1161
+ if (this.isStopped) ;
1162
+ else {
1163
+ this._next(value);
1164
+ }
1165
+ };
1166
+ Subscriber2.prototype.error = function(err) {
1167
+ if (this.isStopped) ;
1168
+ else {
1169
+ this.isStopped = true;
1170
+ this._error(err);
1171
+ }
1172
+ };
1173
+ Subscriber2.prototype.complete = function() {
1174
+ if (this.isStopped) ;
1175
+ else {
1176
+ this.isStopped = true;
1177
+ this._complete();
1178
+ }
1179
+ };
1180
+ Subscriber2.prototype.unsubscribe = function() {
1181
+ if (!this.closed) {
1182
+ this.isStopped = true;
1183
+ _super.prototype.unsubscribe.call(this);
1184
+ this.destination = null;
1185
+ }
1186
+ };
1187
+ Subscriber2.prototype._next = function(value) {
1188
+ this.destination.next(value);
1189
+ };
1190
+ Subscriber2.prototype._error = function(err) {
1191
+ try {
1192
+ this.destination.error(err);
1193
+ } finally {
1194
+ this.unsubscribe();
1195
+ }
1196
+ };
1197
+ Subscriber2.prototype._complete = function() {
1198
+ try {
1199
+ this.destination.complete();
1200
+ } finally {
1201
+ this.unsubscribe();
1202
+ }
1203
+ };
1204
+ return Subscriber2;
1205
+ }(Subscription);
1206
+ var ConsumerObserver = function() {
1207
+ function ConsumerObserver2(partialObserver) {
1208
+ this.partialObserver = partialObserver;
1209
+ }
1210
+ ConsumerObserver2.prototype.next = function(value) {
1211
+ var partialObserver = this.partialObserver;
1212
+ if (partialObserver.next) {
1213
+ try {
1214
+ partialObserver.next(value);
1215
+ } catch (error) {
1216
+ handleUnhandledError(error);
1217
+ }
1218
+ }
1219
+ };
1220
+ ConsumerObserver2.prototype.error = function(err) {
1221
+ var partialObserver = this.partialObserver;
1222
+ if (partialObserver.error) {
1223
+ try {
1224
+ partialObserver.error(err);
1225
+ } catch (error) {
1226
+ handleUnhandledError(error);
1227
+ }
1228
+ } else {
1229
+ handleUnhandledError(err);
1230
+ }
1231
+ };
1232
+ ConsumerObserver2.prototype.complete = function() {
1233
+ var partialObserver = this.partialObserver;
1234
+ if (partialObserver.complete) {
1235
+ try {
1236
+ partialObserver.complete();
1237
+ } catch (error) {
1238
+ handleUnhandledError(error);
1239
+ }
1240
+ }
1241
+ };
1242
+ return ConsumerObserver2;
1243
+ }();
1244
+ var SafeSubscriber = function(_super) {
1245
+ __extends(SafeSubscriber2, _super);
1246
+ function SafeSubscriber2(observerOrNext, error, complete) {
1247
+ var _this = _super.call(this) || this;
1248
+ var partialObserver;
1249
+ if (isFunction(observerOrNext) || !observerOrNext) {
1250
+ partialObserver = {
1251
+ next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0,
1252
+ error: error !== null && error !== void 0 ? error : void 0,
1253
+ complete: complete !== null && complete !== void 0 ? complete : void 0
1254
+ };
1255
+ } else {
1256
+ {
1257
+ partialObserver = observerOrNext;
1258
+ }
1259
+ }
1260
+ _this.destination = new ConsumerObserver(partialObserver);
1261
+ return _this;
1262
+ }
1263
+ return SafeSubscriber2;
1264
+ }(Subscriber);
1265
+ function handleUnhandledError(error) {
1266
+ {
1267
+ reportUnhandledError(error);
1268
+ }
1269
+ }
1270
+ function defaultErrorHandler(err) {
1271
+ throw err;
1272
+ }
1273
+ var EMPTY_OBSERVER = {
1274
+ closed: true,
1275
+ next: noop,
1276
+ error: defaultErrorHandler,
1277
+ complete: noop
1278
+ };
1279
+ var observable = function() {
1280
+ return typeof Symbol === "function" && Symbol.observable || "@@observable";
1281
+ }();
1282
+ function identity(x) {
1283
+ return x;
1284
+ }
1285
+ function pipeFromArray(fns) {
1286
+ if (fns.length === 0) {
1287
+ return identity;
1288
+ }
1289
+ if (fns.length === 1) {
1290
+ return fns[0];
1291
+ }
1292
+ return function piped(input) {
1293
+ return fns.reduce(function(prev, fn) {
1294
+ return fn(prev);
1295
+ }, input);
1296
+ };
1297
+ }
1298
+ var Observable = function() {
1299
+ function Observable2(subscribe) {
1300
+ if (subscribe) {
1301
+ this._subscribe = subscribe;
1302
+ }
1303
+ }
1304
+ Observable2.prototype.lift = function(operator) {
1305
+ var observable2 = new Observable2();
1306
+ observable2.source = this;
1307
+ observable2.operator = operator;
1308
+ return observable2;
1309
+ };
1310
+ Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
1311
+ var _this = this;
1312
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
1313
+ errorContext(function() {
1314
+ var _a = _this, operator = _a.operator, source = _a.source;
1315
+ subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
1316
+ });
1317
+ return subscriber;
1318
+ };
1319
+ Observable2.prototype._trySubscribe = function(sink) {
1320
+ try {
1321
+ return this._subscribe(sink);
1322
+ } catch (err) {
1323
+ sink.error(err);
1324
+ }
1325
+ };
1326
+ Observable2.prototype.forEach = function(next, promiseCtor) {
1327
+ var _this = this;
1328
+ promiseCtor = getPromiseCtor(promiseCtor);
1329
+ return new promiseCtor(function(resolve, reject) {
1330
+ var subscriber = new SafeSubscriber({
1331
+ next: function(value) {
1332
+ try {
1333
+ next(value);
1334
+ } catch (err) {
1335
+ reject(err);
1336
+ subscriber.unsubscribe();
1337
+ }
1338
+ },
1339
+ error: reject,
1340
+ complete: resolve
1341
+ });
1342
+ _this.subscribe(subscriber);
1343
+ });
1344
+ };
1345
+ Observable2.prototype._subscribe = function(subscriber) {
1346
+ var _a;
1347
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
1348
+ };
1349
+ Observable2.prototype[observable] = function() {
1350
+ return this;
1351
+ };
1352
+ Observable2.prototype.pipe = function() {
1353
+ var operations = [];
1354
+ for (var _i = 0; _i < arguments.length; _i++) {
1355
+ operations[_i] = arguments[_i];
1356
+ }
1357
+ return pipeFromArray(operations)(this);
1358
+ };
1359
+ Observable2.prototype.toPromise = function(promiseCtor) {
1360
+ var _this = this;
1361
+ promiseCtor = getPromiseCtor(promiseCtor);
1362
+ return new promiseCtor(function(resolve, reject) {
1363
+ var value;
1364
+ _this.subscribe(function(x) {
1365
+ return value = x;
1366
+ }, function(err) {
1367
+ return reject(err);
1368
+ }, function() {
1369
+ return resolve(value);
1370
+ });
1371
+ });
1372
+ };
1373
+ Observable2.create = function(subscribe) {
1374
+ return new Observable2(subscribe);
1375
+ };
1376
+ return Observable2;
1377
+ }();
1378
+ function getPromiseCtor(promiseCtor) {
1379
+ var _a;
1380
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
1381
+ }
1382
+ function isObserver(value) {
1383
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
1384
+ }
1385
+ function isSubscriber(value) {
1386
+ return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
1387
+ }
1388
+ function hasLift(source) {
1389
+ return isFunction(source === null || source === void 0 ? void 0 : source.lift);
1390
+ }
1391
+ function operate(init) {
1392
+ return function(source) {
1393
+ if (hasLift(source)) {
1394
+ return source.lift(function(liftedSource) {
1395
+ try {
1396
+ return init(liftedSource, this);
1397
+ } catch (err) {
1398
+ this.error(err);
1399
+ }
1400
+ });
1401
+ }
1402
+ throw new TypeError("Unable to lift unknown Observable type");
1403
+ };
1404
+ }
1405
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
1406
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
1407
+ }
1408
+ var OperatorSubscriber = function(_super) {
1409
+ __extends(OperatorSubscriber2, _super);
1410
+ function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
1411
+ var _this = _super.call(this, destination) || this;
1412
+ _this.onFinalize = onFinalize;
1413
+ _this.shouldUnsubscribe = shouldUnsubscribe;
1414
+ _this._next = onNext ? function(value) {
1415
+ try {
1416
+ onNext(value);
1417
+ } catch (err) {
1418
+ destination.error(err);
1419
+ }
1420
+ } : _super.prototype._next;
1421
+ _this._error = onError ? function(err) {
1422
+ try {
1423
+ onError(err);
1424
+ } catch (err2) {
1425
+ destination.error(err2);
1426
+ } finally {
1427
+ this.unsubscribe();
1428
+ }
1429
+ } : _super.prototype._error;
1430
+ _this._complete = onComplete ? function() {
1431
+ try {
1432
+ onComplete();
1433
+ } catch (err) {
1434
+ destination.error(err);
1435
+ } finally {
1436
+ this.unsubscribe();
1437
+ }
1438
+ } : _super.prototype._complete;
1439
+ return _this;
1440
+ }
1441
+ OperatorSubscriber2.prototype.unsubscribe = function() {
1442
+ var _a;
1443
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
1444
+ var closed_1 = this.closed;
1445
+ _super.prototype.unsubscribe.call(this);
1446
+ !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
1447
+ }
1448
+ };
1449
+ return OperatorSubscriber2;
1450
+ }(Subscriber);
1451
+ var ObjectUnsubscribedError = createErrorClass(function(_super) {
1452
+ return function ObjectUnsubscribedErrorImpl() {
1453
+ _super(this);
1454
+ this.name = "ObjectUnsubscribedError";
1455
+ this.message = "object unsubscribed";
1456
+ };
1457
+ });
1458
+ var Subject = function(_super) {
1459
+ __extends(Subject2, _super);
1460
+ function Subject2() {
1461
+ var _this = _super.call(this) || this;
1462
+ _this.closed = false;
1463
+ _this.currentObservers = null;
1464
+ _this.observers = [];
1465
+ _this.isStopped = false;
1466
+ _this.hasError = false;
1467
+ _this.thrownError = null;
1468
+ return _this;
1469
+ }
1470
+ Subject2.prototype.lift = function(operator) {
1471
+ var subject = new AnonymousSubject(this, this);
1472
+ subject.operator = operator;
1473
+ return subject;
1474
+ };
1475
+ Subject2.prototype._throwIfClosed = function() {
1476
+ if (this.closed) {
1477
+ throw new ObjectUnsubscribedError();
1478
+ }
1479
+ };
1480
+ Subject2.prototype.next = function(value) {
1481
+ var _this = this;
1482
+ errorContext(function() {
1483
+ var e_1, _a;
1484
+ _this._throwIfClosed();
1485
+ if (!_this.isStopped) {
1486
+ if (!_this.currentObservers) {
1487
+ _this.currentObservers = Array.from(_this.observers);
1488
+ }
1489
+ try {
1490
+ for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
1491
+ var observer = _c.value;
1492
+ observer.next(value);
1493
+ }
1494
+ } catch (e_1_1) {
1495
+ e_1 = { error: e_1_1 };
1496
+ } finally {
1497
+ try {
1498
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1499
+ } finally {
1500
+ if (e_1) throw e_1.error;
1501
+ }
1502
+ }
1503
+ }
1504
+ });
1505
+ };
1506
+ Subject2.prototype.error = function(err) {
1507
+ var _this = this;
1508
+ errorContext(function() {
1509
+ _this._throwIfClosed();
1510
+ if (!_this.isStopped) {
1511
+ _this.hasError = _this.isStopped = true;
1512
+ _this.thrownError = err;
1513
+ var observers = _this.observers;
1514
+ while (observers.length) {
1515
+ observers.shift().error(err);
1516
+ }
1517
+ }
1518
+ });
1519
+ };
1520
+ Subject2.prototype.complete = function() {
1521
+ var _this = this;
1522
+ errorContext(function() {
1523
+ _this._throwIfClosed();
1524
+ if (!_this.isStopped) {
1525
+ _this.isStopped = true;
1526
+ var observers = _this.observers;
1527
+ while (observers.length) {
1528
+ observers.shift().complete();
1529
+ }
1530
+ }
1531
+ });
1532
+ };
1533
+ Subject2.prototype.unsubscribe = function() {
1534
+ this.isStopped = this.closed = true;
1535
+ this.observers = this.currentObservers = null;
1536
+ };
1537
+ Object.defineProperty(Subject2.prototype, "observed", {
1538
+ get: function() {
1539
+ var _a;
1540
+ return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
1541
+ },
1542
+ enumerable: false,
1543
+ configurable: true
1544
+ });
1545
+ Subject2.prototype._trySubscribe = function(subscriber) {
1546
+ this._throwIfClosed();
1547
+ return _super.prototype._trySubscribe.call(this, subscriber);
1548
+ };
1549
+ Subject2.prototype._subscribe = function(subscriber) {
1550
+ this._throwIfClosed();
1551
+ this._checkFinalizedStatuses(subscriber);
1552
+ return this._innerSubscribe(subscriber);
1553
+ };
1554
+ Subject2.prototype._innerSubscribe = function(subscriber) {
1555
+ var _this = this;
1556
+ var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
1557
+ if (hasError || isStopped) {
1558
+ return EMPTY_SUBSCRIPTION;
1559
+ }
1560
+ this.currentObservers = null;
1561
+ observers.push(subscriber);
1562
+ return new Subscription(function() {
1563
+ _this.currentObservers = null;
1564
+ arrRemove(observers, subscriber);
1565
+ });
1566
+ };
1567
+ Subject2.prototype._checkFinalizedStatuses = function(subscriber) {
1568
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
1569
+ if (hasError) {
1570
+ subscriber.error(thrownError);
1571
+ } else if (isStopped) {
1572
+ subscriber.complete();
1573
+ }
1574
+ };
1575
+ Subject2.prototype.asObservable = function() {
1576
+ var observable2 = new Observable();
1577
+ observable2.source = this;
1578
+ return observable2;
1579
+ };
1580
+ Subject2.create = function(destination, source) {
1581
+ return new AnonymousSubject(destination, source);
1582
+ };
1583
+ return Subject2;
1584
+ }(Observable);
1585
+ var AnonymousSubject = function(_super) {
1586
+ __extends(AnonymousSubject2, _super);
1587
+ function AnonymousSubject2(destination, source) {
1588
+ var _this = _super.call(this) || this;
1589
+ _this.destination = destination;
1590
+ _this.source = source;
1591
+ return _this;
1592
+ }
1593
+ AnonymousSubject2.prototype.next = function(value) {
1594
+ var _a, _b;
1595
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
1596
+ };
1597
+ AnonymousSubject2.prototype.error = function(err) {
1598
+ var _a, _b;
1599
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1600
+ };
1601
+ AnonymousSubject2.prototype.complete = function() {
1602
+ var _a, _b;
1603
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
1604
+ };
1605
+ AnonymousSubject2.prototype._subscribe = function(subscriber) {
1606
+ var _a, _b;
1607
+ return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
1608
+ };
1609
+ return AnonymousSubject2;
1610
+ }(Subject);
1611
+ var BehaviorSubject = function(_super) {
1612
+ __extends(BehaviorSubject2, _super);
1613
+ function BehaviorSubject2(_value) {
1614
+ var _this = _super.call(this) || this;
1615
+ _this._value = _value;
1616
+ return _this;
1617
+ }
1618
+ Object.defineProperty(BehaviorSubject2.prototype, "value", {
1619
+ get: function() {
1620
+ return this.getValue();
1621
+ },
1622
+ enumerable: false,
1623
+ configurable: true
1624
+ });
1625
+ BehaviorSubject2.prototype._subscribe = function(subscriber) {
1626
+ var subscription = _super.prototype._subscribe.call(this, subscriber);
1627
+ !subscription.closed && subscriber.next(this._value);
1628
+ return subscription;
1629
+ };
1630
+ BehaviorSubject2.prototype.getValue = function() {
1631
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
1632
+ if (hasError) {
1633
+ throw thrownError;
1634
+ }
1635
+ this._throwIfClosed();
1636
+ return _value;
1637
+ };
1638
+ BehaviorSubject2.prototype.next = function(value) {
1639
+ _super.prototype.next.call(this, this._value = value);
1640
+ };
1641
+ return BehaviorSubject2;
1642
+ }(Subject);
1643
+ var EmptyError = createErrorClass(function(_super) {
1644
+ return function EmptyErrorImpl() {
1645
+ _super(this);
1646
+ this.name = "EmptyError";
1647
+ this.message = "no elements in sequence";
1648
+ };
1649
+ });
1650
+ function lastValueFrom(source, config2) {
1651
+ return new Promise(function(resolve, reject) {
1652
+ var _hasValue = false;
1653
+ var _value;
1654
+ source.subscribe({
1655
+ next: function(value) {
1656
+ _value = value;
1657
+ _hasValue = true;
1658
+ },
1659
+ error: reject,
1660
+ complete: function() {
1661
+ if (_hasValue) {
1662
+ resolve(_value);
1663
+ } else {
1664
+ reject(new EmptyError());
1665
+ }
1666
+ }
1667
+ });
1668
+ });
1669
+ }
1670
+ function filter(predicate, thisArg) {
1671
+ return operate(function(source, subscriber) {
1672
+ var index = 0;
1673
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1674
+ return predicate.call(thisArg, value, index++) && subscriber.next(value);
1675
+ }));
1676
+ });
1677
+ }
1678
+ function distinctUntilChanged(comparator, keySelector) {
1679
+ if (keySelector === void 0) {
1680
+ keySelector = identity;
1681
+ }
1682
+ comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare;
1683
+ return operate(function(source, subscriber) {
1684
+ var previousKey;
1685
+ var first = true;
1686
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1687
+ var currentKey = keySelector(value);
1688
+ if (first || !comparator(previousKey, currentKey)) {
1689
+ first = false;
1690
+ previousKey = currentKey;
1691
+ subscriber.next(value);
1692
+ }
1693
+ }));
1694
+ });
1695
+ }
1696
+ function defaultCompare(a, b) {
1697
+ return a === b;
1698
+ }
1699
+ function skip(count) {
1700
+ return filter(function(_, index) {
1701
+ return count <= index;
1702
+ });
1703
+ }
1704
+ function takeWhile(predicate, inclusive) {
1705
+ return operate(function(source, subscriber) {
1706
+ var index = 0;
1707
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1708
+ var result = predicate(value, index++);
1709
+ (result || inclusive) && subscriber.next(value);
1710
+ !result && subscriber.complete();
1711
+ }));
1712
+ });
1713
+ }
1714
+ async function getTheme(spoke, scope) {
1715
+ let theme = await fetch(`https://${spoke}.auxiliumgroup.com/static/js/auxilium/dijits/templates/login/${spoke}/theme.json`).then((res) => res.json()).catch(() => null);
1716
+ if (scope && theme != null && theme[scope]) theme = { ...theme, ...theme[scope] };
1717
+ return {
1718
+ found: !!theme,
1719
+ background: `https://${spoke}.auxiliumgroup.com/static/js/auxilium/dijits/templates/login/${spoke}/background.jpg`,
1720
+ backgroundColor: void 0,
1721
+ color: "#c83232",
1722
+ glow: "#c83232",
1723
+ logo: `https://${spoke}.auxiliumgroup.com/static/js/auxilium/dijits/templates/login/${spoke}/logo.png`,
1724
+ logoPosition: "left",
1725
+ hideLogo: false,
1726
+ hideApps: false,
1727
+ persist: true,
1728
+ title: spoke.toUpperCase(),
1729
+ textColor: "white",
1730
+ titleFontFamily: "sans-serif",
1731
+ titleFontUrl: "https://fonts.cdnfonts.com/css/ar-blanca",
1732
+ titleFontSize: "45px",
1733
+ titleTextShadow: "0 0 3px black",
1734
+ subtitle: "",
1735
+ subtitleFontFamily: "sans-serif",
1736
+ subtitleFontUrl: "",
1737
+ subtitleFontSize: "36px",
1738
+ subtitleTextColor: "white",
1739
+ subtitleTextShadow: "0 0 3px black",
1740
+ ...theme || {}
1741
+ };
1742
+ }
1743
+ const _LoginPrompt = class _LoginPrompt {
1744
+ constructor(api, spoke, options = {}) {
1745
+ __publicField(this, "alert");
1746
+ __publicField(this, "button");
1747
+ __publicField(this, "form");
1748
+ __publicField(this, "password");
1749
+ __publicField(this, "persist");
1750
+ __publicField(this, "username");
1751
+ __publicField(this, "_done");
1752
+ /** Promise which resolves once login is complete */
1753
+ __publicField(this, "done", new Promise((res) => {
1754
+ this._done = res;
1755
+ }));
1756
+ this.api = api;
1757
+ this.spoke = spoke;
1758
+ this.options = options;
1759
+ this.themeDefaults().then(() => this.render());
1760
+ }
1761
+ async render() {
1762
+ this.close();
1763
+ document.head.innerHTML += _LoginPrompt.css(this.options);
1764
+ const div = document.createElement("div");
1765
+ div.innerHTML = _LoginPrompt.template(this.options);
1766
+ document.body.appendChild(div);
1767
+ this.alert = document.querySelector("#datalynk-login-alert");
1768
+ this.button = document.querySelector("#datalynk-login-form button");
1769
+ this.form = document.querySelector("#datalynk-login-form");
1770
+ this.password = document.querySelector('#datalynk-login-form input[name="password"]');
1771
+ this.persist = document.querySelector('#datalynk-login-form input[name="persist"]');
1772
+ this.username = document.querySelector('#datalynk-login-form input[name="username"]');
1773
+ if (this.options.persist === false) this.persist.parentElement.remove();
1774
+ this.form.onsubmit = (event) => this.login(event);
1775
+ const pwaLink = document.querySelector("#pwa-install-link");
1776
+ if (pwaLink) {
1777
+ pwaLink.addEventListener("click", async (e) => {
1778
+ var _a;
1779
+ e.preventDefault();
1780
+ if ((_a = this.api.pwa) == null ? void 0 : _a.deferredPrompt) {
1781
+ this.api.pwa.deferredPrompt.prompt();
1782
+ const choice = await this.api.pwa.deferredPrompt.userChoice;
1783
+ if (choice.outcome === "accepted") {
1784
+ console.log("PWA installed via login link");
1785
+ }
1786
+ this.api.pwa.deferredPrompt = null;
1787
+ } else {
1788
+ this.api.pwa.prompt();
1789
+ }
1790
+ });
1791
+ }
1792
+ }
1793
+ async themeDefaults() {
1794
+ const theme = await getTheme(this.spoke, "login");
1795
+ const cleaned = clean(this.options, true);
1796
+ this.options = {
1797
+ ...theme,
1798
+ ...cleaned,
1799
+ logoOnly: !this.options.title && !theme.found,
1800
+ logoPosition: cleaned.logoPosition ?? theme.logoPosition ?? "left",
1801
+ hideLogo: cleaned.hideLogo ?? theme.hideLogo ?? false,
1802
+ platform: this.api.pwa.platform,
1803
+ ...Object.prototype.hasOwnProperty.call(this.api.options, "pwaSettings") && {
1804
+ pwaSettings: this.api.options.pwaSettings
1805
+ }
1806
+ };
1807
+ }
1808
+ /** Close the login prompt */
1809
+ close() {
1810
+ var _a, _b;
1811
+ (_a = document.querySelector("#datalynk-login-styles")) == null ? void 0 : _a.remove();
1812
+ (_b = document.querySelector("#datalynk-login")) == null ? void 0 : _b.remove();
1813
+ }
1814
+ /** Check if login prompt is still open */
1815
+ isOpen() {
1816
+ return !!document.querySelector("#datalynk-login");
1817
+ }
1818
+ /** Login form submit event */
1819
+ login(event) {
1820
+ event.preventDefault();
1821
+ const data = new FormData(event.target);
1822
+ this.alert.classList.add("hidden");
1823
+ this.username.disabled = true;
1824
+ this.password.disabled = true;
1825
+ this.persist.disabled = true;
1826
+ this.button.disabled = true;
1827
+ return this.api.auth.login(
1828
+ this.spoke,
1829
+ data.get("username"),
1830
+ data.get("password"),
1831
+ { expire: this.persist.checked ? null : void 0 }
1832
+ ).then((data2) => {
1833
+ this.close();
1834
+ this._done();
1835
+ return data2;
1836
+ }).catch((err) => {
1837
+ this.alert.classList.remove("hidden");
1838
+ this.alert.innerHTML = err.message;
1839
+ this.password.value = "";
1840
+ this.username.disabled = false;
1841
+ this.password.disabled = false;
1842
+ this.persist.disabled = false;
1843
+ this.button.disabled = false;
1844
+ });
1845
+ }
1846
+ };
1847
+ /** Dynamically create CSS style */
1848
+ __publicField(_LoginPrompt, "css", (options) => `
1849
+ <style id="datalynk-login-styles">
1850
+ @import url('https://fonts.cdnfonts.com/css/ar-blanca');
1851
+ ${options.titleFontUrl ? `@import url('${options.titleFontUrl}');` : ""}
1852
+ ${options.subtitleFontUrl ? `@import url('${options.subtitleFontUrl}');` : ""}
1853
+
1854
+ #datalynk-login {
1855
+ --theme-background: ${options.backgroundColor ? options.backgroundColor : `url(${options.background})`};
1856
+ --theme-container: #000000cc;
1857
+ --theme-glow: ${options.glow || options.color};
1858
+ --theme-primary: ${options.color};
1859
+ --theme-text: ${options.textColor};
1860
+
1861
+ position: fixed;
1862
+ left: 0;
1863
+ top: 0;
1864
+ right: 0;
1865
+ bottom: 0;
1866
+ background: var(--theme-background);
1867
+ background-repeat: no-repeat;
1868
+ background-size: cover;
1869
+ font-family: sans-serif;
1870
+ z-index: 1000;
1871
+ }
1872
+
1873
+ #datalynk-login .added-links {
1874
+ color: var(--theme-text);
1875
+ position: fixed;
1876
+ bottom: 0;
1877
+ right: 0;
1878
+ padding: 0.25rem;
1879
+ }
1880
+
1881
+ #datalynk-login .added-links a, #datalynk-login .added-links a:hover, #datalynk-login .added-links a:visited {
1882
+ color: var(--theme-text);
1883
+ text-shadow: 0 0 10px black;
1884
+ }
1885
+
1886
+ #datalynk-login-alert {
1887
+ padding: 0.75rem;
1888
+ background: rgba(0,0,0,0.5);
1889
+ color: white;
1890
+ border-radius: 5px;
1891
+ margin-bottom: 1rem;
1892
+ border: grey 1px solid;
1893
+ }
1894
+
1895
+ #datalynk-login label {
1896
+ color: white;
1897
+ font-size: 20px;
1898
+ }
1899
+
1900
+ #datalynk-login input {
1901
+ width: calc(100% - 20px);
1902
+ padding: 12px 9px 9px 9px;
1903
+ margin: 1px;
1904
+ border: 1px solid #ddd;
1905
+ border-radius: 5px;
1906
+ background-color: white;
1907
+ color: black;
1908
+ }
1909
+
1910
+ #datalynk-login .login-container {
1911
+ position: fixed;
1912
+ top: 50%;
1913
+ left: 0;
1914
+ right: 0;
1915
+ transform: translateY(-50%);
1916
+ }
1917
+
1918
+ #datalynk-login .login-header {
1919
+ display: flex;
1920
+ justify-content: center;
1921
+ align-items: center;
1922
+ color: var(--theme-text);
1923
+ text-align: center;
1924
+ font-size: 32px;
1925
+ margin-bottom: 2rem;
1926
+ }
1927
+
1928
+ #datalynk-login .login-title {
1929
+ font-family: ${options.titleFontFamily || "sans-serif"};
1930
+ font-size: ${options.titleFontSize || "32px"};
1931
+ ${options.titleTextShadow ? `text-shadow: ${options.titleTextShadow};` : ""}
1932
+ }
1933
+
1934
+ #datalynk-login .login-subtitle {
1935
+ font-family: ${options.subtitleFontFamily || "sans-serif"};
1936
+ font-size: ${options.subtitleFontSize || "20px"};
1937
+ color: ${options.subtitleTextColor || "white"};
1938
+ ${options.subtitleTextShadow ? `text-shadow: ${options.subtitleTextShadow};` : ""}
1939
+ margin-top: 0.5rem;
1940
+ }
1941
+
1942
+ #datalynk-login .login-content {
1943
+ display: flex;
1944
+ flex-direction: column;
1945
+ align-items: center;
1946
+ background: var(--theme-container);
1947
+ border-top: var(--theme-glow) 1px solid;
1948
+ box-shadow: 0 -10px 20px -10px var(--theme-glow);
1949
+ }
1950
+
1951
+ #datalynk-login .login-body {
1952
+ padding: ${options.hideApps ? "3.5rem 0" : "3.5rem 0 1.5rem 0"};
1953
+ width: 100%;
1954
+ max-width: 400px;;
1955
+ color: white;
1956
+ }
1957
+
1958
+ #datalynk-login input:disabled {
1959
+ color: #333;
1960
+ background-color: #ccc;
1961
+ }
1962
+
1963
+ #datalynk-login input[type="checkbox"] {
1964
+ height: 15px;
1965
+ margin: 0;
1966
+ padding: 0;
1967
+ accent-color: var(--theme-primary);
1968
+ }
1969
+
1970
+ #datalynk-login button {
1971
+ background-color: var(--theme-primary);
1972
+ background-image: none;
1973
+ border: 0;
1974
+ color: ${contrast(options.color)};
1975
+ padding: 8px 24px;
1976
+ border-radius: 5px;
1977
+ }
1978
+
1979
+ #datalynk-login button:disabled {
1980
+ cursor: pointer;
1981
+ filter: brightness(90%);
1982
+ }
1983
+
1984
+ #datalynk-login button:hover:not(:disabled) {
1985
+ cursor: pointer;
1986
+ filter: ${contrast(options.color) == "black" ? "brightness(105%)" : "brightness(80%)"};
1987
+ }
1988
+
1989
+ #datalynk-login .login-links{
1990
+ display: flex;
1991
+ padding: 0 0 1.5rem 0;
1992
+ }
1993
+
1994
+ #datalynk-login .login-links a {
1995
+ text-decoration: none;
1996
+ }
1997
+
1998
+ #datalynk-login #pwa-install-link {
1999
+ display: inline-flex;
2000
+ align-items: center;
2001
+ gap: 0.4rem; /* space between icon and text */
2002
+ font-size: 16px;
2003
+ text-decoration: none;
2004
+ color: var(--theme-text);
2005
+ text-shadow: 0 0 10px black;
2006
+ }
2007
+
2008
+ #datalynk-login .login-links img {
2009
+ width: 150px;
2010
+ height: auto;
2011
+ }
2012
+
2013
+ #datalynk-login .hidden {
2014
+ display: none;
2015
+ }
2016
+
2017
+ #datalynk-login .login-footer {
2018
+ transform: translateY(-18px);
2019
+ }
2020
+
2021
+ #datalynk-login .sloped-div {
2022
+ position: absolute;
2023
+ height: 45px;
2024
+ width: 200px;
2025
+ background: var(--theme-container);
2026
+ clip-path: polygon(0 20px, 100% 20px, 85% 60px, 15% 60px);
2027
+ }
2028
+ </style>`);
2029
+ /** Dynamically create HTML */
2030
+ __publicField(_LoginPrompt, "template", (options) => {
2031
+ var _a;
2032
+ return `
2033
+ <div id="datalynk-login">
2034
+ ${!options.backgroundColor ? `<img src="${options.background}" onerror="document.querySelector('#datalynk-login').style.backgroundImage = 'url(https://datalynk.auxiliumgroup.com/static/js/auxilium/dijits/templates/login/datalynk/background.jpg)'" style="width: 0; height: 0;"/>` : ""}
2035
+ <div class="added-links">
2036
+ ${(options.addLinks || []).map((link) => `<a href="${link.url || "#"}" target="_blank">${link.text}</a>`).join(" | ")}
2037
+ </div>
2038
+ <div class="login-container">
2039
+ <div class="login-header" style="flex-direction: ${["aboveTitle", "belowTitle", "belowSubtitle"].includes(options.logoPosition || "") ? "column" : "row"};">
2040
+ ${!options.hideLogo && options.logo && options.logoPosition === "aboveTitle" ? `<img alt="Logo" src="${options.logo}" class="login-logo" style="height: 100px; width: auto; margin-bottom: 0.5rem;" onerror="this.style.display='none'">` : ""}
2041
+
2042
+ ${!options.hideLogo && options.logo && options.logoPosition === "left" ? `<img alt="Logo" src="${options.logo}" class="login-logo" style="height: 100px; width: auto; margin-right: 0.5rem;" onerror="this.style.display='none'">` : ""}
2043
+
2044
+ <div style="display: flex; flex-direction: column; align-items: center;">
2045
+ <span class="login-title">${options.title || ""}</span>
2046
+ ${options.logo && !options.hideLogo && options.logoPosition === "belowTitle" ? `<img alt="Logo" src="${options.logo}" class="login-logo" style="height: 100px; width: auto; margin-top: 0.5rem;" onerror="this.style.display='none'">` : ""}
2047
+ ${options.subtitle ? `<span class="login-subtitle">${options.subtitle}</span>` : ""}
2048
+ ${options.logo && !options.hideLogo && options.logoPosition === "belowSubtitle" ? `<img alt="Logo" src="${options.logo}" class="login-logo" style="height: 100px; width: auto; margin-top: 0.5rem;" onerror="this.style.display='none'">` : ""}
2049
+ </div>
2050
+
2051
+ ${!options.hideLogo && options.logo && options.logoPosition === "right" ? `<img alt="Logo" src="${options.logo}" class="login-logo" style="height: 100px; width: auto; margin-left: 0.5rem;" onerror="this.style.display='none'">` : ""}
2052
+ </div>
2053
+ <div class="login-content">
2054
+ <div class="login-body" style="max-width: 300px">
2055
+ <div id="datalynk-login-alert" class="hidden"></div>
2056
+ <form id="datalynk-login-form">
2057
+ <div>
2058
+ <label for="username">Email or Username</label>
2059
+ <input id="username" name="username" type="text" autocomplete="username">
2060
+ </div>
2061
+ <br>
2062
+ <div>
2063
+ <label for="password">Password</label>
2064
+ <input id="password" name="password" type="password" autocomplete="current-password">
2065
+ </div>
2066
+ <br>
2067
+ <label style="display: block; margin-bottom: 0.75rem;">
2068
+ <input type="checkbox" name="persist" style="width: 20px"> Stay Logged In
2069
+ </label>
2070
+ <button type="submit">Login</button>
2071
+ </form>
2072
+ </div>
2073
+ <div class="login-links" style="text-align: center">
2074
+ ${((_a = options == null ? void 0 : options.pwaSettings) == null ? void 0 : _a.loginLink) === true && !["ios", "mac"].includes(options.platform) ? `
2075
+ <a href="#" id="pwa-install-link" style="margin-right: 1rem;" title="Install App">
2076
+ <svg xmlns="http://www.w3.org/2000/svg" height="40px" viewBox="0 0 24 24" width="40px" fill="${options.color || "#0B76FC"}">
2077
+ <path d="M12 16l4-5h-3V4h-2v7H8z"/><path d="M20 18H4v-2h16v2z"/>
2078
+ </svg> Download App
2079
+ </a>` : ""}
2080
+ ${options.hideApps ? "" : `
2081
+ <a href="https://itunes.apple.com/ca/app/auxilium-mobile/id1166379280?mt=8" target="_blank">
2082
+ <img alt="App Store" src="https://datalynk.auxiliumgroup.com/api/js/auxilium/dijits/templates/login/_common/mobile_apple_transparent.png">
2083
+ </a>
2084
+ <a href="https://play.google.com/store/apps/details?id=com.auxilium.auxiliummobilesolutions&amp;hl=en" target="_blank">
2085
+ <img alt="Playstore" src="https://datalynk.auxiliumgroup.com/api/js/auxilium/dijits/templates/login/_common/mobile_google_transparent.png">
2086
+ </a>`}
2087
+ </div>
2088
+ </div>
2089
+ <div class="login-footer" style="position: relative; display: flex; align-items: center; justify-content: center;">
2090
+ <div class="sloped-div"></div>
2091
+ <a href="https://auxiliumgroup.com" target="_blank" style="position: relative; height: 40px; display: flex; align-items: center; text-decoration: none; font-family: 'AR BLANCA', serif; font-size: 26px; color: white;">
2092
+ Au<span style="font-size: 52px; color: #c83232; margin-bottom: 5px; font-family: 'AR BLANCA', serif;">x</span>ilium
2093
+ <span style="position: absolute; font-size: 10px; color: #c83232; top: 2px; right: 2px; font-family: 'AR BLANCA', serif;">Group</span>
2094
+ </a>
2095
+ </div>
2096
+ </div>
2097
+ </div>
2098
+ `;
2099
+ });
2100
+ let LoginPrompt = _LoginPrompt;
2101
+ class Auth {
2102
+ constructor(api) {
2103
+ __publicField(this, "onlinePrompt");
2104
+ /** Current user as an observable */
2105
+ __publicField(this, "user$", new BehaviorSubject(void 0));
2106
+ var _a;
2107
+ this.api = api;
2108
+ this.api.token$.subscribe(async (token) => {
2109
+ if (token === void 0) return;
2110
+ this.user = await this.current(token);
2111
+ });
2112
+ if ((_a = this.api.options.offline) == null ? void 0 : _a.length)
2113
+ this.user$.pipe(filter((u) => u !== void 0)).subscribe((u) => localStorage.setItem("datalynk-user", JSON.stringify(u)));
2114
+ }
2115
+ /** Current user */
2116
+ get user() {
2117
+ return this.user$.getValue();
2118
+ }
2119
+ /** Set current user info */
2120
+ set user(user) {
2121
+ this.user$.next(user);
2122
+ }
2123
+ get spoke() {
2124
+ var _a;
2125
+ return ((_a = this.api.jwtPayload) == null ? void 0 : _a.realm) || null;
2126
+ }
2127
+ /**
2128
+ * Get current user associated with API token
2129
+ *
2130
+ * @return {Promise<User | null>}
2131
+ */
2132
+ async current(token = this.api.token) {
2133
+ var _a;
2134
+ if (!token) return null;
2135
+ else if (token == ((_a = this.user) == null ? void 0 : _a.token)) return this.user;
2136
+ else if (typeof navigator != "undefined" && !navigator.onLine && typeof localStorage != "undefined" && localStorage.getItem("datalynk-user"))
2137
+ return JSON.parse(localStorage.getItem("datalynk-user"));
2138
+ return this.api.request([{ "$/auth/current": {} }, { "$/env/me": {} }], { token }).then((resp) => resp[0] || resp[1] ? { ...resp[0], ...resp[1] } : null);
2139
+ }
2140
+ /**
2141
+ * Automatically handle sessions by checking localStorage & URL parameters for a token & prompting
2142
+ * user with a login screen if required
2143
+ *
2144
+ * @param {string} spoke Desired spoke
2145
+ * @param {LoginPromptOptions} options Aesthetic options
2146
+ * @return {Promise<void>} Login complete
2147
+ */
2148
+ async handleLogin(spoke, options) {
2149
+ var _a, _b;
2150
+ if (this.onlinePrompt) window.removeEventListener("online", this.onlinePrompt);
2151
+ if ((_a = this.api.options.offline) == null ? void 0 : _a.length) window.removeEventListener("online", this.onlinePrompt = () => this.handleLogin(spoke, options));
2152
+ const urlToken = new URLSearchParams(location.search).get("datalynkToken");
2153
+ if (urlToken) {
2154
+ this.api.token = urlToken;
2155
+ location.href = location.href.replace(/datalynkToken=.*?(&|$)/gm, "");
2156
+ } else if (this.api.token && !this.api.expired) {
2157
+ if (((_b = this.api.jwtPayload) == null ? void 0 : _b.realm) != spoke) {
2158
+ this.api.token = null;
2159
+ location.reload();
2160
+ }
2161
+ } else {
2162
+ this.api.token = null;
2163
+ await this.loginPrompt(spoke, options).done;
2164
+ location.reload();
2165
+ }
2166
+ }
2167
+ /**
2168
+ * Check whether user has a token
2169
+ *
2170
+ * @return {boolean} True if session token authenticated
2171
+ */
2172
+ isAuthenticated() {
2173
+ return !!this.user && !this.user.guest;
2174
+ }
2175
+ /**
2176
+ * Check if the current user is a guest
2177
+ *
2178
+ * @return {boolean} True if guest
2179
+ */
2180
+ isGuest() {
2181
+ var _a;
2182
+ return !!((_a = this.user) == null ? void 0 : _a.guest);
2183
+ }
2184
+ /**
2185
+ * Check if user is a system administrator
2186
+ *
2187
+ * @return {Promise<boolean>} True if system administrator
2188
+ */
2189
+ async isSysAdmin() {
2190
+ return !!(await this.api.slice("sysadmin").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
2191
+ }
2192
+ /**
2193
+ * Check if user is a table administrator
2194
+ *
2195
+ * @return {Promise<boolean>} True if table administrator
2196
+ */
2197
+ async isTableAdmin() {
2198
+ return !!(await this.api.slice("tableadmins").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
2199
+ }
2200
+ /**
2201
+ * Check if user is a user administrator
2202
+ *
2203
+ * @return {Promise<boolean>} True if user administrator
2204
+ */
2205
+ async isUserAdmin() {
2206
+ return !!(await this.api.slice("useradmins").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
2207
+ }
2208
+ /**
2209
+ * Perform login and save the session token
2210
+ *
2211
+ * @param {string} login Login username or email
2212
+ * @param {string} password Password for account
2213
+ * @param {string} spoke Override login spoke
2214
+ * @param {twoFactor?: string, expire?: string} opts 2FA code & expire date (YYYY-MM-DD)
2215
+ * @returns {Promise<User>} User account
2216
+ */
2217
+ login(spoke, login, password, opts) {
2218
+ const date = /* @__PURE__ */ new Date();
2219
+ date.setFullYear(date.getFullYear() + 1);
2220
+ return fetch(`${this.api.url}login`, {
2221
+ method: "POST",
2222
+ headers: { "Content-Type": "application/json" },
2223
+ body: JSON.stringify(clean({
2224
+ realm: spoke.trim(),
2225
+ login: login.trim(),
2226
+ password: password.trim(),
2227
+ secret: opts == null ? void 0 : opts.twoFactor,
2228
+ expireAt: (opts == null ? void 0 : opts.expire) == null ? `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}` : opts == null ? void 0 : opts.expire,
2229
+ dateFormat: "ISO8601"
2230
+ }))
2231
+ }).then(async (resp) => {
2232
+ const data = await resp.json().catch(() => ({}));
2233
+ if (!resp.ok || data["error"]) throw Object.assign(errorFromCode(resp.status, data.error) || {}, data);
2234
+ this.api.token = data["token"];
2235
+ return data;
2236
+ });
2237
+ }
2238
+ /**
2239
+ * Login as guest user
2240
+ *
2241
+ * @return {Promise<User>} Guest account
2242
+ */
2243
+ loginGuest() {
2244
+ return fetch(`${this.api.url}guest`).then(async (resp) => {
2245
+ const data = await resp.json().catch(() => ({}));
2246
+ if (!resp.ok || data["error"]) throw Object.assign(errorFromCode(resp.status, data.error) || {}, data);
2247
+ this.api.token = data["token"];
2248
+ return data;
2249
+ });
2250
+ }
2251
+ /**
2252
+ * Create Login UI
2253
+ *
2254
+ * @param {string} spoke Desired spoke
2255
+ * @param {LoginPromptOptions} options Aesthetic options
2256
+ * @return {LoginPrompt} Login prompt
2257
+ */
2258
+ loginPrompt(spoke, options) {
2259
+ return new LoginPrompt(this.api, spoke, options);
2260
+ }
2261
+ /**
2262
+ * Logout current user
2263
+ *
2264
+ * @return {Promise<{closed: string, new: string}>}
2265
+ */
2266
+ logout(reload = true) {
2267
+ localStorage.removeItem("datalynk-user");
2268
+ return this.api.request({ "$/auth/logout": {} }).then((resp) => {
2269
+ if (reload) location.reload();
2270
+ this.api.token = null;
2271
+ return resp;
2272
+ });
2273
+ }
2274
+ /**
2275
+ * Reset user account password
2276
+ *
2277
+ * @param {string} login User login
2278
+ * @param {string} newPassword New password
2279
+ * @param {string} code Reset code sent with `resetRequest`
2280
+ * @return {Promise<any>} New session
2281
+ */
2282
+ reset(login, newPassword, code) {
2283
+ return this.api.request({
2284
+ "$/auth/mobile/rescue": {
2285
+ user: login,
2286
+ password: newPassword,
2287
+ pin: code
2288
+ }
2289
+ }).then((resp) => {
2290
+ if (resp.token) this.api.token = resp.token;
2291
+ return resp;
2292
+ });
2293
+ }
2294
+ /**
2295
+ * Request reset code for user
2296
+ *
2297
+ * @param {string} login User to reset
2298
+ * @param {"email" | "sms" | "voice"} mode Method of sending reset code
2299
+ * @return {Promise<any>} Unknown
2300
+ */
2301
+ resetRequest(login, mode) {
2302
+ if (mode == "email") return this.api.request({ "$/auth/rescue_email": { user: { $or: { login, email: login } } } });
2303
+ return this.api.request({ "$/auth/mobile/generate": { user: login, method: mode } });
2304
+ }
2305
+ }
2306
+ class PWA {
2307
+ constructor(api) {
2308
+ __publicField(this, "deferredPrompt", null);
2309
+ this.api = api;
2310
+ }
2311
+ // Holds the beforeinstallprompt event
2312
+ get headless() {
2313
+ return typeof window == "undefined";
2314
+ }
2315
+ get iframe() {
2316
+ return (parent == null ? void 0 : parent.location) != location;
2317
+ }
2318
+ get mobile() {
2319
+ return ["android", "ios"].includes(this.platform);
2320
+ }
2321
+ get platform() {
2322
+ const userAgent = navigator.userAgent || navigator.vendor;
2323
+ if (/windows/i.test(userAgent)) return "windows";
2324
+ else if (/android/i.test(userAgent)) return "android";
2325
+ else if (/iPad|iPhone|iPod/.test(userAgent)) return "ios";
2326
+ else if (/macintosh|mac os x/i.test(userAgent)) return "mac";
2327
+ else if (/linux/i.test(userAgent)) return "linux";
2328
+ else return "unknown";
2329
+ }
2330
+ get pwa() {
2331
+ return matchMedia("(display-mode: standalone)").matches || (navigator == null ? void 0 : navigator.standalone) || document.referrer.includes("android-app://");
2332
+ }
2333
+ bindInstallButton() {
2334
+ const installBtn = document.querySelector("#installPwaBtn");
2335
+ if (!installBtn) return;
2336
+ installBtn.onclick = async () => {
2337
+ var _a;
2338
+ this.deferredPrompt.prompt();
2339
+ const choice = await this.deferredPrompt.userChoice;
2340
+ if (choice.outcome === "accepted") {
2341
+ console.log("PWA installed");
2342
+ localStorage.removeItem(`${this.api.options.name}:pwa`);
2343
+ }
2344
+ this.deferredPrompt = null;
2345
+ (_a = document.querySelector(".pwa-prompt")) == null ? void 0 : _a.remove();
2346
+ };
2347
+ }
2348
+ /** Setup the PWA */
2349
+ async setup(manifest = {}) {
2350
+ var _a, _b, _c;
2351
+ window.addEventListener("beforeinstallprompt", (e) => {
2352
+ e.preventDefault();
2353
+ this.deferredPrompt = e;
2354
+ const actions = document.querySelector(".pwa-prompt-actions");
2355
+ if (actions && !actions.querySelector("#installPwaBtn")) {
2356
+ actions.innerHTML = `<button id="installPwaBtn">Install App</button>`;
2357
+ this.bindInstallButton();
2358
+ }
2359
+ });
2360
+ const settings = {
2361
+ timeout: (((_a = this.api.options.pwaSettings) == null ? void 0 : _a.timeout) ?? 30) * 1e3,
2362
+ // default 30s
2363
+ dismissExpiry: ((_b = this.api.options.pwaSettings) == null ? void 0 : _b.dismissExpiry) ?? 7,
2364
+ // default 7 days
2365
+ loginLink: ((_c = this.api.options.pwaSettings) == null ? void 0 : _c.loginLink) ?? false
2366
+ };
2367
+ const meta = (key, name, value) => {
2368
+ const exists = document.querySelector(`meta[${key}="${name}"]`);
2369
+ if (value === void 0 || exists) return exists;
2370
+ const meta2 = document.createElement("meta");
2371
+ meta2.setAttribute(key, name);
2372
+ meta2.content = value;
2373
+ document.head.append(meta2);
2374
+ };
2375
+ meta("name", "mobile-web-app-capable", "yes");
2376
+ meta("name", "apple-mobile-web-app-status-bar-style", "default");
2377
+ meta("name", "apple-mobile-web-app-title", this.api.options.name);
2378
+ meta("name", "apple-touch-icon", `https://datalynk-client.scarborough.auxilium.world/logo.png`);
2379
+ meta("name", "apple-touch-startup-image", `https://datalynk-client.scarborough.auxilium.world/logo.png`);
2380
+ if (!document.querySelector('link[rel="manifest"]')) {
2381
+ const link = document.createElement("link");
2382
+ link.rel = "manifest";
2383
+ const base = String(this.api.url).replace(/\/+$/, "");
2384
+ const startUrl = location.pathname;
2385
+ const scopePath = startUrl.endsWith("/") ? startUrl : startUrl.replace(/[^/]+$/, "");
2386
+ const manifestObj = {
2387
+ name: this.api.options.name,
2388
+ short_name: this.api.options.name,
2389
+ start_url: startUrl,
2390
+ scope: scopePath || "/",
2391
+ display: "standalone",
2392
+ ...this.api.options.manifest || {},
2393
+ ...manifest || {}
2394
+ };
2395
+ link.href = `${base}/manifest?json=${encodeURIComponent(JSON.stringify(manifestObj))}`;
2396
+ document.head.append(link);
2397
+ }
2398
+ if (!this.headless && !this.iframe && !this.pwa && this.platform != "mac") setTimeout(() => {
2399
+ const dismissedDate = localStorage.getItem(`${this.api.options.name}:pwa`);
2400
+ if (settings.dismissExpiry > 0 && dismissedDate) {
2401
+ const diffDays = (Date.now() - new Date(dismissedDate).getTime()) / (1e3 * 60 * 60 * 24);
2402
+ if (diffDays < settings.dismissExpiry) return;
2403
+ } else if (settings.dismissExpiry === 0) {
2404
+ localStorage.removeItem(`${this.api.options.name}:pwa`);
2405
+ }
2406
+ this.prompt();
2407
+ }, settings.timeout);
2408
+ }
2409
+ /** Prompt user to install the app */
2410
+ async prompt(platform) {
2411
+ var _a;
2412
+ if (document.querySelector(".pwa-prompt")) return;
2413
+ const android = (platform || this.platform) == "android";
2414
+ let style = document.querySelector("style.pwa");
2415
+ if (!style) {
2416
+ style = document.createElement("style");
2417
+ style.classList.add("pwa");
2418
+ style.innerHTML = `
2419
+ .pwa-prompt {
2420
+ position: fixed;
2421
+ bottom: 0;
2422
+ left: 50%;
2423
+ transform: translateX(-50%);
2424
+ background: #fff;
2425
+ color: #222;
2426
+ width: min(100vw, 450px);
2427
+ border-radius: 8px 8px 0 0;
2428
+ box-shadow: 0 -4px 12px rgba(0,0,0,0.2);
2429
+ font-family: system-ui, sans-serif;
2430
+ animation: slideUp 0.35s ease forwards;
2431
+ z-index: 10000;
2432
+ box-shadow: 0px 10px 5px 3px #0000007d;
2433
+ }
2434
+ .pwa-prompt-header {
2435
+ display: flex;
2436
+ align-items: center;
2437
+ background: linear-gradient(140deg, #080808, #454242bf);
2438
+ color: #fff;
2439
+ padding: 0.75rem 1rem;
2440
+ position: relative;
2441
+ border-radius: 10px 10px 0px 0px;
2442
+ }
2443
+ .pwa-prompt-header img {
2444
+ height: 28px;
2445
+ margin-right: 0.5rem;
2446
+ }
2447
+ .pwa-prompt-header h1 {
2448
+ font-size: 1rem;
2449
+ margin: 0;
2450
+ flex-grow: 1;
2451
+ }
2452
+ .pwa-prompt-close {
2453
+ position: absolute;
2454
+ right: 12px;
2455
+ top: 10px;
2456
+ background: transparent;
2457
+ border: none;
2458
+ color: #fff;
2459
+ font-size: 18px;
2460
+ cursor: pointer;
2461
+ }
2462
+ .pwa-prompt-body {
2463
+ padding: 1rem;
2464
+ font-size: 0.9rem;
2465
+ text-align: center;
2466
+ }
2467
+ .pwa-prompt-actions {
2468
+ text-align: center;
2469
+ padding: 0.75rem 1rem 1rem;
2470
+ }
2471
+ .pwa-prompt-actions button {
2472
+ background: #c33031;
2473
+ color: #fff;
2474
+ border: none;
2475
+ padding: 0.6rem 1.2rem;
2476
+ border-radius: 6px;
2477
+ cursor: pointer;
2478
+ font-size: 0.9rem;
2479
+ }
2480
+ .pwa-steps ol {
2481
+ padding-left: 1.25rem;
2482
+ text-align: left;
2483
+ }
2484
+ .pwa-prompt-actions table {
2485
+ width: 100%;
2486
+ margin: 0;
2487
+ }
2488
+ .pwa-prompt-actions td {
2489
+ padding: 0.5rem;
2490
+ }
2491
+ @keyframes slideUp {
2492
+ from { transform: translate(-50%, 100%); opacity: 0; }
2493
+ to { transform: translate(-50%, 0); opacity: 1; }
2494
+ }`;
2495
+ document.head.append(style);
2496
+ }
2497
+ const prompt = document.createElement("div");
2498
+ prompt.classList.add("pwa-prompt");
2499
+ prompt.innerHTML = `
2500
+ <div class="pwa-prompt-header">
2501
+ <img src="https://datalynk-client.scarborough.auxilium.world/logo.png" alt="Logo" />
2502
+ <h1>Install ${this.api.options.name}</h1>
2503
+ <button class="pwa-prompt-close">&times;</button>
2504
+ </div>
2505
+ <div class="pwa-prompt-body">
2506
+ ${this.deferredPrompt ? "Click below to install the app directly to your device." : "Add this app to your home screen for a faster, fullscreen experience."}
2507
+ </div>
2508
+ <div class="pwa-prompt-actions">
2509
+ ${this.deferredPrompt ? `<button id="installPwaBtn">Install App</button>` : `
2510
+ <table>
2511
+ <tr>
2512
+ <td style="width:40px;text-align:center">
2513
+ ${android ? '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="black" style="transform: scale(1.5)"><path d="M480-160q-33 0-56.5-23.5T400-240q0-33 23.5-56.5T480-320q33 0 56.5 23.5T560-240q0 33-23.5 56.5T480-160Zm0-240q-33 0-56.5-23.5T400-480q0-33 23.5-56.5T480-560q33 0 56.5 23.5T560-480q0 33-23.5 56.5T480-400Zm0-240q-33 0-56.5-23.5T400-720q0-33 23.5-56.5T480-800q33 0 56.5 23.5T560-720q0 33-23.5 56.5T480-640Z"/></svg>' : '<svg viewBox="0 0 566 670" xmlns="http://www.w3.org/2000/svg" fill="#c33031" height="40px"><path d="M255 12c4-4 10-8 16-8s12 3 16 8l94 89c3 4 6 7 8 12 2 6 0 14-5 19-7 8-20 9-28 2l-7-7-57-60 2 54v276c0 12-10 22-22 22-12 1-24-10-23-22V110l1-43-60 65c-5 5-13 8-21 6a19 19 0 0 1-16-17c-1-7 2-13 7-18l95-91z" /><path d="M43 207c16-17 40-23 63-23h83v46h-79c-12 0-25 3-33 13-8 9-10 21-10 33v260c0 13 0 27 6 38 5 12 18 18 30 19l14 1h302c14 0 28 0 40-8 11-7 16-21 16-34V276c0-11-2-24-9-33-8-10-22-13-34-13h-78v-46h75c13 0 25 1 37 4 16 4 31 13 41 27 11 17 14 37 14 57v280c0 20-3 41-15 58a71 71 0 0 1-45 27c-11 2-23 3-34 3H109c-19-1-40-4-56-15-14-9-23-23-27-38-4-12-5-25-5-38V270c1-22 6-47 22-63z" /></svg>'}
2514
+ </td>
2515
+ <td>1) ${android ? "Open the dropdown menu" : 'Tap the "Share" button'}</td>
2516
+ </tr>
2517
+ <tr>
2518
+ <td style="width:40px;text-align:center">
2519
+ ${android ? '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="black" style="transform: scale(-1.5, 1.5)"><path d="M280-40q-33 0-56.5-23.5T200-120v-720q0-33 23.5-56.5T280-920h280v80H280v40h280v80H280v480h400v-80h80v200q0 33-23.5 56.5T680-40H280Zm0-120v40h400v-40H280Zm440-240L520-600l56-56 104 104v-288h80v288l104-104 56 56-200 200ZM280-800v-40 40Zm0 640v40-40Z"/></svg>' : '<svg viewBox="0 0 578 584" xmlns="http://www.w3.org/2000/svg" fill="black" height="34px"><path d="M101 35l19-1h333c12 0 23 0 35 3 17 3 34 12 44 27 13 16 16 38 16 58v329c0 19 0 39-8 57a65 65 0 0 1-37 37c-18 7-38 7-57 7H130c-21 1-44 0-63-10-14-7-25-20-30-34-6-15-8-30-8-45V121c1-21 5-44 19-61 13-16 33-23 53-25m7 46c-10 1-19 6-24 14-7 8-9 20-9 31v334c0 12 2 25 10 34 9 10 23 12 35 12h336c14 1 30-3 38-15 6-9 8-20 8-31V125c0-12-2-24-10-33-9-9-22-12-35-12H121l-13 1z" /><path d="M271 161c9-11 31-10 38 4 3 5 3 11 3 17v87h88c7 0 16 1 21 7 6 6 7 14 6 22a21 21 0 0 1-10 14c-5 4-11 5-17 5h-88v82c0 7-1 15-6 20-10 10-29 10-37-2-3-6-4-13-4-19v-81h-87c-8-1-17-3-23-9-5-6-6-15-4-22a21 21 0 0 1 11-14c6-3 13-3 19-3h84v-88c0-7 1-14 6-20z" /></svg>'}
2520
+ </td>
2521
+ <td>2) Select "Add to Home Screen"</td>
2522
+ </tr>
2523
+ </table>
2524
+ `}
2525
+ </div>
2526
+ `;
2527
+ const closeBtn = prompt.querySelector(".pwa-prompt-close");
2528
+ const dismissExpiry = ((_a = this.api.options.pwaSettings) == null ? void 0 : _a.dismissExpiry) ?? 7;
2529
+ closeBtn.onclick = () => {
2530
+ dismissExpiry > 0 ? localStorage.setItem(`${this.api.options.name}:pwa`, (/* @__PURE__ */ new Date()).toISOString()) : localStorage.removeItem(`${this.api.options.name}:pwa`);
2531
+ prompt.remove();
2532
+ };
2533
+ document.body.append(prompt);
2534
+ if (this.deferredPrompt) this.bindInstallButton();
2535
+ }
2536
+ }
2537
+ class Files {
2538
+ constructor(api) {
2539
+ this.api = api;
2540
+ }
2541
+ associate(fileIds, slice, row, field, execute = true) {
2542
+ const req = { [`${execute ? "!" : "$"}/tools/file/update`]: { slice, row, field, ids: fileIds } };
2543
+ if (execute) return this.api.request(req);
2544
+ return req;
2545
+ }
2546
+ /**
2547
+ * Get an authenticated URL to fetch files from
2548
+ *
2549
+ * @param {number} id File ID
2550
+ * @param {boolean} ignoreToken Ignore authentication
2551
+ * @return {string} URL file can be viewed at
2552
+ */
2553
+ get(id, ignoreToken) {
2554
+ return `${this.api.url}file?id=${id}${ignoreToken ? "" : `&token=${this.api.token}`}`;
2555
+ }
2556
+ /**
2557
+ * Upload file(s) to the API & optionally associate them with a row
2558
+ *
2559
+ * @param {FileList | File | File[]} files Files to be uploaded
2560
+ * @param {{slice: number, row: any, field: string, pk?: string}} associate Row to associate with
2561
+ */
2562
+ upload(files, associate) {
2563
+ let f = files instanceof FileList ? Array.from(files) : makeArray(files);
2564
+ return Promise.all(f.map((file) => {
2565
+ const data = new FormData();
2566
+ data.append("uploadedfiles[]", file, file.name);
2567
+ return fetch(`${this.api.url}upload.php`, {
2568
+ method: "POST",
2569
+ headers: clean({ "Authorization": this.api.token ? `Bearer ${this.api.token}` : "" }),
2570
+ body: data
2571
+ }).then(async (resp) => {
2572
+ const data2 = await resp.json().catch(() => ({}));
2573
+ if (!resp.ok || data2["error"]) throw Object.assign(errorFromCode(resp.status, data2.error) || {}, data2);
2574
+ return data2.files.uploadedfiles[0];
2575
+ });
2576
+ })).then(async (files2) => {
2577
+ if (associate) {
2578
+ let id = typeof associate.row == "number" ? associate.row : associate.row[associate.pk || "id"];
2579
+ if (!id) id = await this.api.slice(associate.slice).insert(associate.row).id().exec();
2580
+ await this.associate(files2.map((f2) => f2.id), associate == null ? void 0 : associate.slice, associate == null ? void 0 : associate.row, associate == null ? void 0 : associate.field);
2581
+ }
2582
+ return files2;
2583
+ });
2584
+ }
2585
+ }
2586
+ class Pdf {
2587
+ constructor(api) {
2588
+ this.api = api;
2589
+ }
2590
+ /**
2591
+ * Create a PDF from a public URL
2592
+ * @param {string} url Target URL address
2593
+ * @param {{slice: number, row: number, field: string} | null} associate Optionally associate PDF with a slice row
2594
+ * @param {PdfOptions} options PDF options for rendering & uploading
2595
+ * @return {Promise<any>} Either the PDF file number or the updated slice row response if associated
2596
+ */
2597
+ async fromUrl(url, associate, options = {}) {
2598
+ return this.api.request({ "$/slice/utils/urlToPdf": { url, ...options } }).then((file) => {
2599
+ if (associate) return this.api.files.associate(file, associate.slice, associate.row, associate.field);
2600
+ return file;
2601
+ });
2602
+ }
2603
+ }
2604
+ const Serializer = {
2605
+ /**
2606
+ * From Datalynk syntax to JS
2607
+ */
2608
+ deserialize: {
2609
+ /**
2610
+ * Convert date time string to javascript date object
2611
+ *
2612
+ * @param {string} datetime datetime string (YYYY/MM/DD hh:mm:ss)
2613
+ * @returns {Date} JS Date object
2614
+ */
2615
+ "$/tools/date": (datetime) => {
2616
+ let a = datetime.split(/[^0-9]+/).map((part) => Number(part));
2617
+ return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
2618
+ },
2619
+ /**
2620
+ * Convert date string to javascript date object
2621
+ *
2622
+ * @param {string} date date string (YYYY/MM/DD)
2623
+ * @returns {Date} JS Date object
2624
+ */
2625
+ "$/tools/date_strict": (date) => {
2626
+ let a = date.split(/[^0-9]+/).map((part) => Number(part));
2627
+ let d = new Date(a[0], a[1] - 1, a[2], 0, 0, 0);
2628
+ d["hint"] = "date";
2629
+ return d;
2630
+ },
2631
+ /**
2632
+ * Convert time string to javascript date object
2633
+ *
2634
+ * @param {string} time time string (YYYY/MM/DD)
2635
+ * @returns {Date} JS Date object
2636
+ */
2637
+ "$/tools/time_strict": (time) => {
2638
+ let a = time.split(/[^0-9]+/).map((part) => Number(part));
2639
+ let d = /* @__PURE__ */ new Date();
2640
+ d.setHours(a[0]);
2641
+ d.setMinutes(a[1]);
2642
+ d.setSeconds(a[2]);
2643
+ d["hint"] = "time";
2644
+ return d;
2645
+ },
2646
+ /**
2647
+ * Convert string to constant
2648
+ *
2649
+ * @param {string} constant string to be converted
2650
+ * @returns {any} the actual constant
2651
+ */
2652
+ "$/tools/const": (constant) => {
2653
+ let types = {
2654
+ "infinity": Infinity,
2655
+ "-infinity": -Infinity,
2656
+ "nan": NaN
2657
+ };
2658
+ try {
2659
+ return types[constant["$/tools/const"].toLowerCase()];
2660
+ } catch (ignored) {
2661
+ return void 0;
2662
+ }
2663
+ },
2664
+ /**
2665
+ * Large requests are formatted into parallel arrays
2666
+ *
2667
+ * @param {object} obj Object of metadata and data
2668
+ * @returns {Array} Actual object reconstructed
2669
+ */
2670
+ "$/tools/dltable": function(obj) {
2671
+ let meta = obj["meta"];
2672
+ let col;
2673
+ let fn = [];
2674
+ for (let i in meta) {
2675
+ col = meta[i];
2676
+ fn.push("this['" + col.name + "'] = ");
2677
+ if (col.cast == null) {
2678
+ fn.push("a[" + i + "];\n");
2679
+ } else if (col.cast === "num") {
2680
+ fn.push("a[" + i + "] && parseFloat(a[" + i + "]);\n");
2681
+ } else {
2682
+ if (col["native"] === "date") {
2683
+ fn.push("a[" + i + "] && dateParse(a[" + i + "]);\n");
2684
+ fn.push("a[" + i + "] && (this['" + col.name + "'].hint = 'date');\n");
2685
+ } else if (col["native"] === "time") {
2686
+ fn.push("a[" + i + "] && timeParse(a[" + i + "]);\n");
2687
+ fn.push("a[" + i + "] && (this['" + col.name + "'].hint = 'time');\n");
2688
+ } else {
2689
+ fn.push("a[" + i + "] && datetimeParse(a[" + i + "]);\n");
2690
+ }
2691
+ }
2692
+ }
2693
+ let dateTimeParse, dateParse, timeParse;
2694
+ let now = /* @__PURE__ */ new Date();
2695
+ let yyyy = now.getFullYear();
2696
+ let mm = now.getMonth();
2697
+ let dd = now.getDate();
2698
+ dateTimeParse = function(dt) {
2699
+ dt = dt.split(/[^0-9]+/);
2700
+ return new Date(dt[0], dt[1] - 1, dt[2], dt[3], dt[4], dt[5]);
2701
+ };
2702
+ dateParse = function(d) {
2703
+ d = d.split(/[- :]/);
2704
+ let res2 = new Date(d[0], d[1] - 1, d[2], 0, 0, 0);
2705
+ res2["hint"] = "date";
2706
+ return res2;
2707
+ };
2708
+ timeParse = function(t) {
2709
+ t = t.split(/[^0-9]+/, t);
2710
+ let res2 = new Date(yyyy, mm, dd, t[0], t[1], t[2]);
2711
+ res2["hint"] = "time";
2712
+ return res2;
2713
+ };
2714
+ let ctor = Function("datetimeParse", "dateParse", "timeParse", "a", fn.join(""));
2715
+ let res = [];
2716
+ let rows = obj["rows"];
2717
+ for (let i in rows) {
2718
+ res[i] = new ctor(dateTimeParse, dateParse, timeParse, rows[i]);
2719
+ }
2720
+ res["meta"] = meta;
2721
+ res["rowConstructor"] = ctor;
2722
+ return res;
2723
+ }
2724
+ },
2725
+ /**
2726
+ * From JS to Datalynk syntax
2727
+ */
2728
+ serialize: {
2729
+ /**
2730
+ * Convert JS date to datalynk datetime string
2731
+ */
2732
+ "Date": (date) => {
2733
+ return {
2734
+ "$/tools/date": [date.getFullYear(), date.getMonth() + 1, date.getDate()].join("/") + " " + [date.getHours(), date.getMinutes(), date.getSeconds()].join(":")
2735
+ };
2736
+ }
2737
+ }
2738
+ };
2739
+ class ApiCall {
2740
+ constructor(api, slice) {
2741
+ __publicField(this, "operation");
2742
+ __publicField(this, "popField");
2743
+ __publicField(this, "request", {});
2744
+ /** Log response automatically */
2745
+ __publicField(this, "debugging");
2746
+ /**
2747
+ * Whitelist and alias fields. Alias of `fields()`
2748
+ * @example
2749
+ * ```ts
2750
+ * const id: {id: number, field2: any}[] = await new Slice<T>(12345)
2751
+ * .select().alias({id: 'id', field1: 'field2'}).exec().keys();
2752
+ * ```
2753
+ * @param {object} aliasKeyVals List of properties to whitelist and what to rename them to
2754
+ * @return {Slice<T>}
2755
+ */
2756
+ __publicField(this, "alias", this.fields);
2757
+ this.api = api;
2758
+ this.slice = slice;
2759
+ }
2760
+ /** Get raw API request */
2761
+ get raw() {
2762
+ return clean({
2763
+ [this.operation]: {
2764
+ ...this.request,
2765
+ slice: this.slice
2766
+ },
2767
+ "$pop": this.popField ? this.popField : void 0
2768
+ });
2769
+ }
2770
+ /**
2771
+ * Add an 'AND' condition inside the where argument
2772
+ * @example
2773
+ * ```ts
2774
+ * const rows: T[] = await new Slice<T>(12345).select()
2775
+ * .where('field1', '>', 1)
2776
+ * .and()
2777
+ * .where({field2: 2, field3: 3})
2778
+ * .exec().rows();
2779
+ * ```
2780
+ * @return {Slice<T>}
2781
+ */
2782
+ and() {
2783
+ var _a;
2784
+ if (((_a = this.request.where) == null ? void 0 : _a[0]) == "$and") return this;
2785
+ if (this.request.where) this.request.where = ["$and", this.request.where];
2786
+ else this.request.where = ["$and"];
2787
+ return this;
2788
+ }
2789
+ /**
2790
+ * Count the returned rows
2791
+ * @example
2792
+ * ```ts
2793
+ * const count = await new Slice(12345).count()
2794
+ * .where({field1: 1})
2795
+ * .exec().count();
2796
+ * ```
2797
+ * @param {object | string} arg Count argument
2798
+ * @return {Slice<T>}
2799
+ */
2800
+ count(arg = "id") {
2801
+ this.operation = "$/slice/report";
2802
+ this.request.fields = { count: ["$count", typeof arg == "object" ? arg : ["$field", arg]] };
2803
+ return this.pop("rows:0:count");
2804
+ }
2805
+ /**
2806
+ * Output the formed request to the console for inspection
2807
+ * @param {boolean} enabled Enable/Disable console logging
2808
+ * @return {Slice<T>}
2809
+ */
2810
+ debug(enabled = true) {
2811
+ this.debugging = enabled;
2812
+ return this;
2813
+ }
2814
+ /**
2815
+ * Set the request type to delete
2816
+ * @example
2817
+ * ```ts
2818
+ * await new Slice(12345).delete(id).exec();
2819
+ * ```
2820
+ * @param {number | number[]} id ID(s) to delete
2821
+ * @return {Slice<T>}
2822
+ */
2823
+ delete(id) {
2824
+ this.operation = "$/slice/delete";
2825
+ if (id) {
2826
+ if (Array.isArray(id)) this.where("id", "$in", id);
2827
+ else this.where("id", "==", id);
2828
+ }
2829
+ return this;
2830
+ }
2831
+ /**
2832
+ * Filter rows from slice based on an excel expression
2833
+ * @example
2834
+ * ```ts
2835
+ * const rows: T[] = await new Slice<T>(12345).select()
2836
+ * .excel('contains({property}, foobar)')
2837
+ * .exec().rows();
2838
+ * ```
2839
+ * @param formula Excel formula to use as where clause
2840
+ * @return {Slice<T>}
2841
+ */
2842
+ excel(formula) {
2843
+ this.where(["$excel", formula]);
2844
+ return this;
2845
+ }
2846
+ /**
2847
+ * Compile the request and send it
2848
+ * @param {ApiRequestOptions} options API Request options
2849
+ * @return {Promise<T = any>} API response
2850
+ */
2851
+ exec(options) {
2852
+ if (!this.operation) throw new Error("No operation chosen");
2853
+ const request = this.raw;
2854
+ return this.api.request(request, options).then((resp) => {
2855
+ if (this.debugging) console.log(resp);
2856
+ return resp;
2857
+ });
2858
+ }
2859
+ fields(keys) {
2860
+ this.request.fields = Array.isArray(keys) ? keys.reduce((acc, key) => ({ ...acc, [key]: key }), {}) : keys;
2861
+ return this;
2862
+ }
2863
+ /**
2864
+ * Unwrap response returning the first ID
2865
+ * @return {Slice<T>}
2866
+ */
2867
+ id() {
2868
+ return this.pop("rows:0:id");
2869
+ }
2870
+ /**
2871
+ * Set the request type to insert
2872
+ * @example
2873
+ * ```ts
2874
+ * const id: number = await new Slice<T>(12345).insert([
2875
+ * {field1: 1},
2876
+ * {field1: 2}
2877
+ * ]).exec().keys();
2878
+ * ```
2879
+ * @param {T | T[]} rows Rows to be inserted into the slice
2880
+ * @return {Slice<T>}
2881
+ */
2882
+ insert(rows) {
2883
+ this.operation = "$/slice/xinsert";
2884
+ if (!this.request.rows) this.request.rows = [];
2885
+ if (Array.isArray(rows)) this.request.rows = this.request.rows.concat(rows);
2886
+ else this.request.rows.push(rows);
2887
+ return this;
2888
+ }
2889
+ /**
2890
+ * Limit number of rows returned
2891
+ * @example
2892
+ * ```ts
2893
+ * const rows: T[] = await new Slice<T>(12345).select().limit(10)
2894
+ * .exec().rows();
2895
+ * ```
2896
+ * @param {number} num Number of rows to return
2897
+ * @return {Slice<T>}
2898
+ */
2899
+ limit(num) {
2900
+ this.request.limit = num;
2901
+ return this;
2902
+ }
2903
+ /**
2904
+ * Add an 'OR' condition inside the where argument
2905
+ * @example
2906
+ * ```ts
2907
+ * const rows: T[] = await new Slice<T>(12345).select()
2908
+ * .where('field1', '>', 1)
2909
+ * .or()
2910
+ * .where({field2: 2, field3: 3})
2911
+ * .or()
2912
+ * .where(['$gt', ['$field', field4], 4)
2913
+ * .exec().rows();
2914
+ * ```
2915
+ * @return {Slice<T>}
2916
+ */
2917
+ or() {
2918
+ var _a;
2919
+ if (((_a = this.request.where) == null ? void 0 : _a[0]) == "$or") {
2920
+ this.request.where.push(null);
2921
+ return this;
2922
+ }
2923
+ if (this.request.where) this.request.where = ["$or", this.request.where, null];
2924
+ else this.request.where = ["$or", null];
2925
+ return this;
2926
+ }
2927
+ /**
2928
+ * Order rows by a field
2929
+ * @example
2930
+ * ```ts
2931
+ * const rows: T[] = new Slice<T>(12345).select().order('field1', true) // true = ascending
2932
+ * .exec().rows();
2933
+ * ```
2934
+ * @param {string} field property name
2935
+ * @param {boolean} ascending Sort in ascending or descending order
2936
+ * @return {Slice<T>}
2937
+ */
2938
+ order(field, ascending = true) {
2939
+ if (!this.request.order) this.request.order = [];
2940
+ this.request.order.push([ascending ? "$asc" : "$desc", ["$field", field]]);
2941
+ return this;
2942
+ }
2943
+ /**
2944
+ * Unwrap response, returning the field
2945
+ * @param {string} field Colon seperated path: `rows:0`
2946
+ * @return {Slice<T>}
2947
+ */
2948
+ pop(field) {
2949
+ this.popField = field;
2950
+ return this;
2951
+ }
2952
+ /**
2953
+ * Unwrap response returning the first row
2954
+ * @return {Slice<T>}
2955
+ */
2956
+ row() {
2957
+ return this.pop("rows:0");
2958
+ }
2959
+ /**
2960
+ * Unwrap response returning the rows
2961
+ * @return {Slice<T>}
2962
+ */
2963
+ rows() {
2964
+ return this.pop("rows");
2965
+ }
2966
+ /**
2967
+ * Save multiple rows to the slice, automatically inserts/updates
2968
+ * @param {T} rows Rows to add to slice
2969
+ * @returns {this<T>}
2970
+ */
2971
+ save(rows) {
2972
+ this.operation = "$/slice/multisave";
2973
+ this.request.rows = makeArray(rows);
2974
+ return this;
2975
+ }
2976
+ /**
2977
+ * Set the request type to select
2978
+ * @example
2979
+ * ```ts
2980
+ * const rows: T[] = new Slice<T>(12345).select().exec().rows();
2981
+ * const row: T = new Slice<T>(12345).select(id).exec().row();
2982
+ * ```
2983
+ * @param {number | number[]} id ID(s) to select, leaving blank will return all rows
2984
+ * @return {Slice<T>}
2985
+ */
2986
+ select(id) {
2987
+ this.operation = "$/slice/report";
2988
+ if (id) {
2989
+ if (Array.isArray(id)) this.where("id", "$in", id);
2990
+ else this.where("id", "==", id);
2991
+ }
2992
+ return this;
2993
+ }
2994
+ /**
2995
+ * Set the request type to update
2996
+ * @example
2997
+ * ```ts
2998
+ * const ids: number[] = await new Slice<Type>(12345).update([
2999
+ * {id: 1, field1: 1},
3000
+ * {id: 2, field1: 1}
3001
+ * ]).exec().keys();
3002
+ * ```
3003
+ * @param {T | T[]} rows Rows to be updated, each row must have an ID
3004
+ * @return {Slice<T>}
3005
+ */
3006
+ update(rows) {
3007
+ this.operation = "$/slice/xupdate";
3008
+ if (!this.request.rows) this.request.rows = [];
3009
+ if (Array.isArray(rows)) this.request.rows = this.request.rows.concat(rows);
3010
+ else this.request.rows.push(rows);
3011
+ return this;
3012
+ }
3013
+ /**
3014
+ * Add where condition to request
3015
+ * @example
3016
+ * ```ts
3017
+ * const rows: T[] = await new Slice<T>(12345).select()
3018
+ * .where('field1', '>', 1)
3019
+ * .where({field2: 2, field3: 3}) // Automatic AND
3020
+ * .or()
3021
+ * .where(['$gt', ['$field', field4], 4)
3022
+ * .exec().rows();
3023
+ * ```
3024
+ * @param {string | object} field property to compare or a map of equality comparisons
3025
+ * @param {string} operator Operation to compare with. Accepts JS operators (>=, ==, !=, ...) as well as datalynk styax ($gte, $eq, $is, $not, ...)
3026
+ * @param {any} value value to compare against
3027
+ * @return {Slice<T>}
3028
+ */
3029
+ where(field, operator, value) {
3030
+ if (this.request.where && this.request.where[0] != "$or") this.and();
3031
+ const raw = Array.isArray(field);
3032
+ if (typeof field == "object" && !raw) {
3033
+ Object.entries(field).forEach(([key, value2]) => this.where(key, "==", value2));
3034
+ } else {
3035
+ const w = raw ? field : [(() => {
3036
+ if (operator == null ? void 0 : operator.startsWith("$")) return operator;
3037
+ if (operator == "==") return "$eq";
3038
+ if (operator == "!=") return "$neq";
3039
+ if (operator == ">") return "$gt";
3040
+ if (operator == ">=") return "$gte";
3041
+ if (operator == "<") return "$lt";
3042
+ if (operator == "<=") return "$lte";
3043
+ if (operator == "!") return "$not";
3044
+ if (operator == "%") return "$mod";
3045
+ if (operator == null ? void 0 : operator.startsWith("$")) return operator;
3046
+ throw new Error(`Unknown operator: ${operator}`);
3047
+ })(), ["$field", field], value];
3048
+ if (!this.request.where) this.request.where = w;
3049
+ else {
3050
+ if (this.request.where[0] == "$or") {
3051
+ const i = this.request.where.length - 1;
3052
+ if (this.request.where[i] == null) this.request.where[i] = w;
3053
+ else {
3054
+ if (this.request.where[i][0] == "$and") this.request.where[i].push(w);
3055
+ else this.request.where[i] = ["$and", this.request.where[i], w];
3056
+ }
3057
+ } else this.request.where.push(w);
3058
+ }
3059
+ }
3060
+ return this;
3061
+ }
3062
+ }
3063
+ class Slice {
3064
+ /**
3065
+ * An object to aid in constructing requests
3066
+ *
3067
+ * @param {number} slice Slice ID to interact with
3068
+ * @param {Api} api Api to send the requests through
3069
+ */
3070
+ constructor(slice, api) {
3071
+ __publicField(this, "table");
3072
+ __publicField(this, "info");
3073
+ __publicField(this, "pendingInsert", 0);
3074
+ /** Unsubscribe from changes, undefined if not subscribed */
3075
+ __publicField(this, "unsubscribe");
3076
+ /** Cached slice data as an observable */
3077
+ __publicField(this, "cache$", new BehaviorSubject([]));
3078
+ var _a;
3079
+ this.slice = slice;
3080
+ this.api = api;
3081
+ if (this.offlineEnabled) {
3082
+ this.table = (_a = api.database) == null ? void 0 : _a.table(slice.toString());
3083
+ this.table.getAll().then((resp) => this.cache = resp);
3084
+ this.cache$.pipe(skip(1)).subscribe(async (cache) => {
3085
+ var _a2;
3086
+ await ((_a2 = this.table) == null ? void 0 : _a2.clear());
3087
+ await Promise.all(cache.map((c) => {
3088
+ var _a3;
3089
+ return (_a3 = this.table) == null ? void 0 : _a3.put(c.id, c);
3090
+ }));
3091
+ this.fixIncrement();
3092
+ });
3093
+ this.sync();
3094
+ window.addEventListener("online", async () => {
3095
+ if (this.api.expired) await lastValueFrom(this.api.auth.user$.pipe(skip(1), takeWhile((u) => !u || this.api.expired, true)));
3096
+ this.pushChanges();
3097
+ });
3098
+ }
3099
+ }
3100
+ /** Cached slice data */
3101
+ get cache() {
3102
+ return this.cache$.getValue();
3103
+ }
3104
+ /** Set cached data & alert subscribers */
3105
+ set cache(cache) {
3106
+ this.cache$.next(cache);
3107
+ }
3108
+ /** Is slice offline support enabled */
3109
+ get offlineEnabled() {
3110
+ var _a;
3111
+ return (_a = this.api.database) == null ? void 0 : _a.includes(this.slice.toString());
3112
+ }
3113
+ fixIncrement() {
3114
+ var _a;
3115
+ this.pendingInsert = ((_a = this.cache.toSorted(sortByProp("id")).pop()) == null ? void 0 : _a["id"]) || 0;
3116
+ }
3117
+ execWrapper(call) {
3118
+ const onlineExec = call.exec.bind(call);
3119
+ return () => {
3120
+ if (this.offlineEnabled && navigator && !(navigator == null ? void 0 : navigator.onLine)) {
3121
+ const where = (row, condition) => {
3122
+ if (Array.isArray(condition) ? !condition.length : condition == null) return true;
3123
+ if (!Array.isArray(condition)) return condition;
3124
+ if (condition[0] == "$field") return row[condition[1]];
3125
+ if (condition[0] == "$not") return !where(row, condition.slice(1));
3126
+ if (condition[0] == "$and") return condition.slice(1).filter((v) => where(row, v)).length == condition.length - 1;
3127
+ if (condition[0] == "$or") return !!condition.slice(1).find((v) => where(row, v));
3128
+ if (condition[0] == "$eq") return where(row, condition[1]) == where(row, condition[2]);
3129
+ if (condition[0] == "$neq") return where(row, condition[1]) != where(row, condition[2]);
3130
+ if (condition[0] == "$gt") return where(row, condition[1]) > where(row, condition[2]);
3131
+ if (condition[0] == "$gte") return where(row, condition[1]) >= where(row, condition[2]);
3132
+ if (condition[0] == "$lt") return where(row, condition[1]) < where(row, condition[2]);
3133
+ if (condition[0] == "$lte") return where(row, condition[1]) <= where(row, condition[2]);
3134
+ if (condition[0] == "$mod") return where(row, condition[1]) % where(row, condition[2]);
3135
+ return condition[0];
3136
+ };
3137
+ let request = call.raw, resp = {};
3138
+ if (request["$/slice/delete"]) {
3139
+ const found = this.cache.filter((r) => where(r, request["$/slice/delete"]["where"])).map((r) => r.id);
3140
+ this.cache = this.cache.map((r) => found.includes(r.id) ? { ...r, _sync: "delete" } : r);
3141
+ resp = {
3142
+ affected: found.length,
3143
+ "ignored-keys": [],
3144
+ keys: found,
3145
+ tx: null
3146
+ };
3147
+ } else if (request["$/slice/report"]) {
3148
+ resp["rows"] = deepCopy(this.cache).filter((r) => (r == null ? void 0 : r._sync) != "delete").filter((r) => r && where(r, request["$/slice/report"]["where"]));
3149
+ if (request["order"]) resp["rows"] = resp["rows"].toSorted(sortByProp(request["order"][1][1], request["order"] == "$desc"));
3150
+ if (request["limit"]) resp["rows"] = resp["rows"].slice(0, request["limit"]);
3151
+ if (request["fields"]) {
3152
+ if (request["fields"]["$count"]) resp["rows"] = { count: resp["rows"].length };
3153
+ else resp["rows"] = resp["rows"].map((r) => Object.entries(request["fields"]).reduce((acc, [k, v]) => ({
3154
+ ...acc,
3155
+ [v]: r[k]
3156
+ }), {}));
3157
+ }
3158
+ } else if (request["$/slice/xinsert"]) {
3159
+ const rows = request["$/slice/xinsert"]["rows"].map((r) => ({
3160
+ ...r,
3161
+ id: -++this.pendingInsert,
3162
+ _sync: "insert"
3163
+ }));
3164
+ this.cache = [...this.cache, ...rows];
3165
+ resp = {
3166
+ failed: [],
3167
+ granted: rows.map((r) => Object.keys(r).reduce((acc, key) => ({ ...acc, [key]: true }), {})),
3168
+ "ignored-fields": [],
3169
+ keys: rows.map((r) => r.id),
3170
+ publish: 1,
3171
+ tx: null
3172
+ };
3173
+ } else if (request["$/slice/xupdate"]) {
3174
+ const ids = request["$/slice/xupdate"]["rows"].map((r) => r.id);
3175
+ this.cache = [
3176
+ ...this.cache.filter((c) => !ids.includes(c.id)),
3177
+ ...request["$/slice/xupdate"]["rows"].map((r) => ({ ...r, _sync: "update" }))
3178
+ ].toSorted(sortByProp("id"));
3179
+ resp = {
3180
+ failed: [],
3181
+ granted: request["$/slice/xupdate"]["rows"].map((r) => Object.keys(r).reduce((acc, key) => ({
3182
+ ...acc,
3183
+ [key]: true
3184
+ }), {})),
3185
+ "ignored-fields": [],
3186
+ keys: request["$/slice/xupdate"]["rows"].map((r) => r.id),
3187
+ publish: 1,
3188
+ tx: null
3189
+ };
3190
+ }
3191
+ if (request["$pop"]) {
3192
+ resp = request["$pop"].split(":").reduce((acc, key) => acc[JSONAttemptParse(key)], resp);
3193
+ }
3194
+ return Promise.resolve(resp);
3195
+ } else {
3196
+ return onlineExec();
3197
+ }
3198
+ };
3199
+ }
3200
+ async pushChanges() {
3201
+ if (this.offlineEnabled && navigator && navigator.onLine) {
3202
+ await Promise.allSettled(
3203
+ this.cache.values().map((value) => {
3204
+ if (value._sync == "delete") {
3205
+ return this.delete(value.id).exec();
3206
+ } else if (value._sync == "insert") {
3207
+ return this.insert({ ...value, id: void 0, _sync: void 0 }).exec();
3208
+ } else if (value._sync == "update") {
3209
+ return this.update({
3210
+ ...value,
3211
+ _sync: void 0
3212
+ }).where("_updatedDate", "==", value.modified).exec();
3213
+ }
3214
+ }).filter((r) => !!r)
3215
+ );
3216
+ }
3217
+ }
3218
+ /**
3219
+ * Get slice information
3220
+ * @param reload Ignore cache & reload info
3221
+ * @return {Promise<SliceInfo>}
3222
+ */
3223
+ async getInfo(reload) {
3224
+ var _a, _b, _c;
3225
+ const getType = (field) => {
3226
+ if (field.options) {
3227
+ let t = field.options.split("|").map((o) => `'${o}'`).join(" | ");
3228
+ if (field.type == "control_checkbox") t = `(${t})[]`;
3229
+ return t;
3230
+ }
3231
+ if (field.type == "control_checkbox" || field.type == "boolean") return "boolean";
3232
+ if (field.type == "control_new_date" || field.type == "control_new_time" || field.type == "control_new_datetime" || field.type == "Date")
3233
+ return "Date";
3234
+ if (field.type == "control_number" || field.type == "number") return "number";
3235
+ return "string";
3236
+ };
3237
+ if (this.info && !reload) return Promise.resolve(this.info);
3238
+ this.info = await this.api.request({ "$/slice/fetch": { slice: this.slice } });
3239
+ const fields = ((_c = (_b = (_a = this.info) == null ? void 0 : _a.meta) == null ? void 0 : _b.presentation) == null ? void 0 : _c.fields) ? Object.values(this.info.meta.presentation.fields) : [];
3240
+ this.info.types = fields.filter((value) => value.id != void 0).map((value) => {
3241
+ var _a2;
3242
+ return {
3243
+ key: value.id.toString(),
3244
+ options: (_a2 = value.options) == null ? void 0 : _a2.split("|"),
3245
+ readonly: !!value.readonly || value.id.startsWith("fid") || ["id", "creatorRef", "created", "modifierRef", "modified"].includes(value.id),
3246
+ required: !!value.required,
3247
+ type: getType(value)
3248
+ };
3249
+ });
3250
+ return this.info;
3251
+ }
3252
+ /**
3253
+ * Synchronize cache with server
3254
+ * @example
3255
+ * ```ts
3256
+ * const slice: Slice = new Slice<T>(Slices.Contact);
3257
+ * slice.sync().subscribe((rows: T[]) => {});
3258
+ * ```
3259
+ * @param {boolean} on Enable/disable events
3260
+ * @return {BehaviorSubject<T[]>} Cache which can be subscribed to
3261
+ */
3262
+ sync(on = true) {
3263
+ if (on) {
3264
+ this.pushChanges().then(() => this.select().rows().exec().then((rows) => this.cache = rows));
3265
+ if (!this.unsubscribe) this.unsubscribe = this.api.socket.sliceEvents(this.slice, (event) => {
3266
+ const ids = [...event.data.new, ...event.data.changed];
3267
+ this.select(ids).rows().exec().then((rows) => this.cache = [...this.cache.filter((c) => c.id != null && !ids.includes(c.id)), ...rows]);
3268
+ this.cache = this.cache.filter((v) => v.id && !event.data.lost.includes(v.id));
3269
+ });
3270
+ return this.cache$;
3271
+ } else if (this.unsubscribe) {
3272
+ this.unsubscribe();
3273
+ this.unsubscribe = null;
3274
+ }
3275
+ }
3276
+ // Transaction wrapper =============================================================================================
3277
+ /**
3278
+ * {@inheritDoc ApiCall.count}
3279
+ */
3280
+ count(arg = "id") {
3281
+ const call = new ApiCall(this.api, this.slice);
3282
+ call.exec = this.execWrapper(call);
3283
+ return call.count(arg);
3284
+ }
3285
+ /**
3286
+ * {@inheritDoc ApiCall.delete}
3287
+ */
3288
+ delete(id) {
3289
+ const call = new ApiCall(this.api, this.slice);
3290
+ call.exec = this.execWrapper(call);
3291
+ return call.delete(id);
3292
+ }
3293
+ /**
3294
+ * {@inheritDoc ApiCall.insert}
3295
+ */
3296
+ insert(rows) {
3297
+ const call = new ApiCall(this.api, this.slice);
3298
+ call.exec = this.execWrapper(call);
3299
+ return call.insert(rows);
3300
+ }
3301
+ /**
3302
+ * {@inheritDoc ApiCall.save}
3303
+ */
3304
+ save(rows) {
3305
+ const call = new ApiCall(this.api, this.slice);
3306
+ call.exec = this.execWrapper(call);
3307
+ return call.save(rows);
3308
+ }
3309
+ /**
3310
+ * {@inheritDoc ApiCall.select}
3311
+ */
3312
+ select(id) {
3313
+ const call = new ApiCall(this.api, this.slice);
3314
+ call.exec = this.execWrapper(call);
3315
+ return call.select(id);
3316
+ }
3317
+ /**
3318
+ * {@inheritDoc ApiCall.update}
3319
+ */
3320
+ update(rows) {
3321
+ const call = new ApiCall(this.api, this.slice);
3322
+ call.exec = this.execWrapper(call);
3323
+ return call.update(rows);
3324
+ }
3325
+ }
3326
+ class Socket {
3327
+ constructor(api, options = {}) {
3328
+ __publicField(this, "listeners", []);
3329
+ // [ Callback, Re-subscribe ]
3330
+ __publicField(this, "retry");
3331
+ __publicField(this, "socket");
3332
+ __publicField(this, "open", false);
3333
+ this.api = api;
3334
+ this.options = options;
3335
+ if (!options.url && options.url !== false) {
3336
+ const origin = new URL(this.api.url).origin;
3337
+ this.options.url = origin.replace("http", "ws").replace(/:\d+/g, "") + `:9390`;
3338
+ }
3339
+ if (this.options.url !== false)
3340
+ api.token$.pipe(filter((u) => u !== void 0), distinctUntilChanged()).subscribe(() => this.connect());
3341
+ }
3342
+ /**
3343
+ * Add listener for all socket events
3344
+ *
3345
+ * @param {SocketListener} fn Callback function
3346
+ *
3347
+ *
3348
+ *
3349
+ *
3350
+ * @return {Unsubscribe} Function to unsubscribe callback
3351
+ */
3352
+ addListener(fn, reconnect) {
3353
+ this.listeners.push([fn, reconnect]);
3354
+ if (this.open) reconnect();
3355
+ return () => this.listeners = this.listeners.filter((l) => l[0] != fn);
3356
+ }
3357
+ /**
3358
+ * Close socket connection
3359
+ */
3360
+ close() {
3361
+ var _a;
3362
+ if (this.open) console.debug("Datalynk socket: disconnected");
3363
+ this.open = false;
3364
+ (_a = this.socket) == null ? void 0 : _a.close();
3365
+ this.socket = void 0;
3366
+ if (this.retry) clearTimeout(this.retry);
3367
+ this.retry = null;
3368
+ }
3369
+ /**
3370
+ * Connect socket client to socket server
3371
+ * @param {number} timeout Retry to connect every x seconds
3372
+ */
3373
+ connect(timeout = 30) {
3374
+ if (this.options.url === false) return console.warn("Datalynk socket disabled");
3375
+ if (this.open) this.close();
3376
+ this.retry = setTimeout(() => {
3377
+ if (this.open) return;
3378
+ this.close();
3379
+ this.connect();
3380
+ }, timeout * 1e3);
3381
+ if (navigator.onLine) {
3382
+ this.socket = new WebSocket(this.options.url + (this.api.token ? `?token=${this.api.token}&origin=${location.href}` : ""));
3383
+ this.socket.onopen = () => clearTimeout(this.retry);
3384
+ this.socket.onclose = () => {
3385
+ if (this.open) this.connect(timeout);
3386
+ };
3387
+ this.socket.onmessage = (message) => {
3388
+ const payload = JSON.parse(message.data);
3389
+ if (payload.connected != void 0) {
3390
+ if (payload.connected) {
3391
+ this.open = true;
3392
+ console.debug("Datalynk socket: connected");
3393
+ this.listeners.forEach((l) => l[1]());
3394
+ } else {
3395
+ throw new Error(`Datalynk socket failed: ${payload.error}`);
3396
+ }
3397
+ } else {
3398
+ this.listeners.forEach((l) => l[0](payload));
3399
+ }
3400
+ };
3401
+ }
3402
+ }
3403
+ /**
3404
+ * Send data to socket server
3405
+ *
3406
+ * @param payload Data that will be serialized
3407
+ */
3408
+ send(payload) {
3409
+ var _a;
3410
+ if (!this.open) throw new Error("Datalynk socket not connected");
3411
+ (_a = this.socket) == null ? void 0 : _a.send(JSON.stringify(payload));
3412
+ }
3413
+ /**
3414
+ * Run callback whenever the server notifies us of slice changes
3415
+ *
3416
+ * @param {number | number[]} slice Slice to subscribe to
3417
+ * @param {SocketListener<SocketEventSlice>} callback Function to run on changes
3418
+ * @return {Unsubscribe} Run returned function to unsubscribe callback
3419
+ */
3420
+ sliceEvents(slice, callback) {
3421
+ const unsubscribe = this.addListener((event) => {
3422
+ if (event.type == "sliceEvents" && event.data.slice == slice) callback(event);
3423
+ }, () => this.send({ onSliceEvents: slice }));
3424
+ return () => {
3425
+ this.send({ offSliceEvents: slice });
3426
+ unsubscribe();
3427
+ };
3428
+ }
3429
+ }
3430
+ class Superuser {
3431
+ constructor(api) {
3432
+ this.api = api;
3433
+ }
3434
+ /**
3435
+ * Switch to another user by ID
3436
+ *
3437
+ * @param {number} userId User ID
3438
+ * @return {Promise<any>} New session
3439
+ */
3440
+ assume(userId) {
3441
+ return this.api.request({ "$/report/users/become": { id: userId } }).then((resp) => {
3442
+ if (resp.token) this.api.token = resp.token;
3443
+ return resp;
3444
+ });
3445
+ }
3446
+ /**
3447
+ * Enable the superuser flag, required to make any of the requests in this helper
3448
+ *
3449
+ * @param {string} username Superuser account
3450
+ * @param {string} password Superuser password
3451
+ * @return {Promise<any>} Unknown
3452
+ */
3453
+ enable(username, password) {
3454
+ return this.api.request({ "$/superuser/validate": {
3455
+ name: username,
3456
+ password
3457
+ } });
3458
+ }
3459
+ }
3460
+ const version = "1.3.4";
3461
+ class WebRtc {
3462
+ constructor(api) {
3463
+ __publicField(this, "ice");
3464
+ var _a, _b, _c, _d, _e, _f;
3465
+ this.api = api;
3466
+ this.ice = [
3467
+ ...((_b = (_a = api.options) == null ? void 0 : _a.webrtc) == null ? void 0 : _b.ice) || [],
3468
+ { urls: ["stun:" + ((_c = this.api.options.webrtc) == null ? void 0 : _c.url)] },
3469
+ clean({
3470
+ urls: ["turn:" + ((_d = this.api.options.webrtc) == null ? void 0 : _d.url)],
3471
+ username: (_e = this.api.options.webrtc) == null ? void 0 : _e.username,
3472
+ credential: (_f = this.api.options.webrtc) == null ? void 0 : _f.password
3473
+ })
3474
+ ];
3475
+ }
3476
+ async answer(offer, stream) {
3477
+ const rtc = new RTCPeerConnection({ iceServers: this.ice });
3478
+ stream.getTracks().forEach((track) => rtc.addTrack(track, stream));
3479
+ await rtc.setRemoteDescription(new RTCSessionDescription(offer));
3480
+ const answer = await rtc.createAnswer();
3481
+ await rtc.setLocalDescription(answer);
3482
+ await new Promise((res) => {
3483
+ if (rtc.iceGatheringState === "complete") return res();
3484
+ rtc.onicegatheringstatechange = () => {
3485
+ if (rtc.iceGatheringState === "complete") res();
3486
+ };
3487
+ });
3488
+ return rtc;
3489
+ }
3490
+ async offer(stream) {
3491
+ const rtc = new RTCPeerConnection({ iceServers: this.ice });
3492
+ stream.getTracks().forEach((track) => rtc.addTrack(track, stream));
3493
+ await rtc.setLocalDescription(await rtc.createOffer());
3494
+ await new Promise((res) => {
3495
+ if (rtc.iceGatheringState === "complete") return res();
3496
+ rtc.onicegatheringstatechange = () => {
3497
+ if (rtc.iceGatheringState === "complete") res();
3498
+ };
3499
+ });
3500
+ return rtc;
3501
+ }
3502
+ /**
3503
+ * Create a new WebRTC connection to a room
3504
+ * @param {string} id Room ID
3505
+ * @param {boolean} audio Stream local audio to room/peers
3506
+ * @param {boolean} video Stream local video to room/peers
3507
+ * @returns {Promise<WebRTCSession>} Connection session
3508
+ */
3509
+ async connect(id = randomStringBuilder(16, true, true), audio = true, video = true) {
3510
+ const session = {
3511
+ open: true,
3512
+ id,
3513
+ uid: randomStringBuilder(8, true, true),
3514
+ peers: {},
3515
+ stream: await navigator.mediaDevices.getUserMedia({ audio, video }),
3516
+ disconnect: null,
3517
+ onConnected: null
3518
+ };
3519
+ const handleTracks = (session2, uid) => {
3520
+ if (!session2.open || !session2.onConnected) return;
3521
+ const peer = session2.peers[uid];
3522
+ const streams = peer.connection.getRemoteStreams();
3523
+ if (streams[0]) session2.onConnected(peer, streams[0]);
3524
+ else peer.connection.ontrack = ({ streams: streams2 }) => {
3525
+ if (session2.open && session2.onConnected) session2.onConnected(peer, streams2[0]);
3526
+ };
3527
+ };
3528
+ const unsubscribe = this.api.socket.addListener(async (event) => {
3529
+ var _a, _b, _c, _d;
3530
+ const key = Object.keys(event)[0];
3531
+ if (key == `webrtc/${id}`) {
3532
+ if (event[key].connected) {
3533
+ const payload = event[key].connected;
3534
+ session.peers[payload.uid] = {
3535
+ uid: payload.uid,
3536
+ username: payload.username,
3537
+ connection: await this.offer(session.stream)
3538
+ };
3539
+ this.api.socket.send({ [`webrtc/${id}`]: { offer: {
3540
+ to: payload.uid,
3541
+ uid: session.uid,
3542
+ username: (_a = this.api.auth.user) == null ? void 0 : _a.login,
3543
+ offer: session.peers[payload.uid].connection.localDescription
3544
+ } } });
3545
+ } else if (event[key].disconnected) {
3546
+ session.peers[event[key].disconnected.uid].connection.close();
3547
+ delete session.peers[event[key].disconnected.uid];
3548
+ } else if (event[key].offer && event[key].offer.to == session.uid) {
3549
+ const payload = event[key].offer;
3550
+ session.peers[payload.uid] = {
3551
+ uid: payload.uid,
3552
+ username: payload.username,
3553
+ connection: await this.answer(payload.offer, session.stream)
3554
+ };
3555
+ this.api.socket.send({ [`webrtc/${id}`]: { answer: {
3556
+ to: payload.uid,
3557
+ uid: session.uid,
3558
+ username: (_b = this.api.auth.user) == null ? void 0 : _b.login,
3559
+ answer: session.peers[payload.uid].connection.localDescription
3560
+ } } });
3561
+ handleTracks(session, payload.uid);
3562
+ } else if (event[key].answer && event[key].answer.to == session.uid) {
3563
+ (_d = (_c = session.peers[event[key].answer.uid]) == null ? void 0 : _c.connection) == null ? void 0 : _d.setRemoteDescription(new RTCSessionDescription(event[key].answer.answer));
3564
+ handleTracks(session, event[key].answer.uid);
3565
+ }
3566
+ }
3567
+ }, () => {
3568
+ var _a;
3569
+ return this.api.socket.send({ [`webrtc/${id}`]: { connected: { uid: session.uid, username: (_a = this.api.auth.user) == null ? void 0 : _a.login } } });
3570
+ });
3571
+ session.disconnect = () => {
3572
+ var _a;
3573
+ session.open = false;
3574
+ session.peers = {};
3575
+ this.api.socket.send({ [`webrtc/${id}`]: { disconnected: { uid: session.uid, username: (_a = this.api.auth.user) == null ? void 0 : _a.login } } });
3576
+ unsubscribe();
3577
+ };
3578
+ return session;
3579
+ }
3580
+ }
3581
+ const _Api = class _Api {
3582
+ /**
3583
+ * Connect to Datalynk & send requests
3584
+ *
3585
+ * @example
3586
+ * ```ts
3587
+ * const api = new Api('https://spoke.auxiliumgroup.com');
3588
+ * ```
3589
+ *
3590
+ * @param {string} origin API URL
3591
+ * @param {ApiOptions} options
3592
+ */
3593
+ constructor(origin, options = {}) {
3594
+ /** Current requests bundle */
3595
+ __publicField(this, "bundle", []);
3596
+ /** Bundle lifecycle tracking */
3597
+ __publicField(this, "bundleOngoing", false);
3598
+ /** LocalStorage key for persisting logins */
3599
+ __publicField(this, "localStorageKey", "datalynk-token");
3600
+ /** Pending requests cache */
3601
+ __publicField(this, "pending", {});
3602
+ /** Helpers */
3603
+ /** Authentication */
3604
+ __publicField(this, "auth");
3605
+ /** File */
3606
+ __publicField(this, "files");
3607
+ /** PDF */
3608
+ __publicField(this, "pdf");
3609
+ /** PWA setup & prompt */
3610
+ __publicField(this, "pwa");
3611
+ /** Socket */
3612
+ __publicField(this, "socket");
3613
+ /** Superuser */
3614
+ __publicField(this, "superuser");
3615
+ /** WebRTC */
3616
+ __publicField(this, "webrtc");
3617
+ /** Offline database */
3618
+ __publicField(this, "database");
3619
+ /** Options */
3620
+ __publicField(this, "options");
3621
+ /** Created slices */
3622
+ __publicField(this, "sliceCache", /* @__PURE__ */ new Map());
3623
+ /** API URL */
3624
+ __publicField(this, "url");
3625
+ /** Client library version */
3626
+ __publicField(this, "version", version);
3627
+ /** API Session token */
3628
+ __publicField(this, "token$", new BehaviorSubject(void 0));
3629
+ var _a, _b;
3630
+ this.origin = origin;
3631
+ this.url = `${new URL(origin).origin}/api/`;
3632
+ this.options = {
3633
+ manifest: {},
3634
+ name: typeof document != "undefined" ? document.title : "Datalynk",
3635
+ offline: [],
3636
+ origin: typeof location !== "undefined" ? location.host : "Unknown",
3637
+ saveSession: true,
3638
+ serviceWorker: "/service.worker.mjs",
3639
+ ...options,
3640
+ webrtc: {
3641
+ url: "scarborough.auxilium.world:3478",
3642
+ username: "auxilium-webrtc",
3643
+ password: "UU3qkD95Tg54eF",
3644
+ ...options.webrtc || {}
3645
+ }
3646
+ };
3647
+ if (this.options.saveSession) {
3648
+ if (typeof localStorage == "undefined") return;
3649
+ this.token = localStorage.getItem(this.localStorageKey) || null;
3650
+ this.token$.pipe(distinctUntilChanged()).subscribe((token) => {
3651
+ if (token) localStorage.setItem(this.localStorageKey, token);
3652
+ else localStorage.removeItem(this.localStorageKey);
3653
+ });
3654
+ }
3655
+ this.socket = new Socket(this, { url: options.socket });
3656
+ this.auth = new Auth(this);
3657
+ this.files = new Files(this);
3658
+ this.pdf = new Pdf(this);
3659
+ this.pwa = new PWA(this);
3660
+ this.superuser = new Superuser(this);
3661
+ this.webrtc = new WebRtc(this);
3662
+ if ((_a = this.options.offline) == null ? void 0 : _a.length) {
3663
+ this.pwa.setup();
3664
+ if (typeof indexedDB == "undefined") throw new Error("Cannot enable offline support, indexedDB is not available in this environment");
3665
+ this.database = new Database("datalynk", this.options.offline);
3666
+ (_b = this.options.offline) == null ? void 0 : _b.forEach((id) => this.slice(id));
3667
+ if (this.options.serviceWorker && typeof navigator["serviceWorker"] != "undefined") {
3668
+ (async () => {
3669
+ const init = () => {
3670
+ var _a2;
3671
+ (_a2 = navigator.serviceWorker.controller) == null ? void 0 : _a2.postMessage({ options: { ...this.options, url: this.url } });
3672
+ this.token$.subscribe((token) => {
3673
+ var _a3;
3674
+ return (_a3 = navigator.serviceWorker.controller) == null ? void 0 : _a3.postMessage({ token });
3675
+ });
3676
+ };
3677
+ await navigator.serviceWorker.getRegistration(this.options.serviceWorker).then((reg) => reg ?? navigator.serviceWorker.register(this.options.serviceWorker, { scope: "/", type: "module" }));
3678
+ navigator.serviceWorker.ready.then(() => {
3679
+ if (navigator.serviceWorker.controller) navigator.serviceWorker.ready.then(() => init());
3680
+ else navigator.serviceWorker.addEventListener("controllerchange", () => init(), { once: true });
3681
+ });
3682
+ })();
3683
+ }
3684
+ }
3685
+ }
3686
+ /** Get session info from JWT payload */
3687
+ get jwtPayload() {
3688
+ if (!this.token) return null;
3689
+ return decodeJwt(this.token);
3690
+ }
3691
+ /** Is token expired */
3692
+ get expired() {
3693
+ var _a;
3694
+ return (((_a = this.jwtPayload) == null ? void 0 : _a.exp) ?? Infinity) * 1e3 <= Date.now();
3695
+ }
3696
+ /** Logged in spoke */
3697
+ get spoke() {
3698
+ var _a;
3699
+ return (_a = this.jwtPayload) == null ? void 0 : _a.realm;
3700
+ }
3701
+ get token() {
3702
+ return this.token$.getValue();
3703
+ }
3704
+ set token(token) {
3705
+ this.token$.next(token);
3706
+ }
3707
+ _request(req, options = {}) {
3708
+ const token = options.token || this.token;
3709
+ return fetch(this.url, {
3710
+ method: "POST",
3711
+ headers: clean({
3712
+ Authorization: token ? `Bearer ${token}` : void 0,
3713
+ "Content-Type": "application/json",
3714
+ "X-Date-Return-Format": this.options.legacyDates ? void 0 : "ISO8601"
3715
+ }),
3716
+ body: JSON.stringify(_Api.translateTokens(req))
3717
+ }).then(async (resp) => {
3718
+ let data = JSONAttemptParse(await resp.text());
3719
+ if (!resp.ok || (data == null ? void 0 : data.error)) throw Object.assign(errorFromCode(resp.status, data.error), data);
3720
+ if (!options.raw) data = _Api.translateTokens(data);
3721
+ return data;
3722
+ });
3723
+ }
3724
+ /**
3725
+ * Get list of slices
3726
+ * @return {Promise<number[]>}
3727
+ */
3728
+ getSlices() {
3729
+ return this.request({ "$/tools/action_chain": [
3730
+ { "!/env/me": {} },
3731
+ { "!/slice/permissionsLite": {} },
3732
+ { "!/tools/column": { "col": "id", "rows": { "$_": "1:rows" } } }
3733
+ ] });
3734
+ }
3735
+ /**
3736
+ * Parses API request/response object for special Datalynk tokens & converts them to native JS objects
3737
+ *
3738
+ * @param obj An API request or response
3739
+ * @return {Object} Api request or response with translated tokens
3740
+ * @private
3741
+ */
3742
+ static translateTokens(obj) {
3743
+ let dot = (obj2, param) => param.split(".").reduce((acc, index) => acc[index], obj2);
3744
+ let queue = Object.keys(obj);
3745
+ queue.forEach((key) => {
3746
+ let val = dot(obj, key);
3747
+ if (val !== null && typeof val == "object") {
3748
+ Object.keys(val).forEach((index) => {
3749
+ if (index in Serializer.deserialize) {
3750
+ val = Serializer.deserialize[index](val[index]);
3751
+ } else if (index in Serializer.serialize) {
3752
+ val = Serializer.serialize[index](val[index]);
3753
+ } else if (val[index] == "Yes") {
3754
+ val[index] = true;
3755
+ } else if (val[index] == "No") {
3756
+ val[index] = false;
3757
+ } else {
3758
+ queue.push(`${key}.${index}`);
3759
+ }
3760
+ });
3761
+ }
3762
+ });
3763
+ return obj;
3764
+ }
3765
+ /**
3766
+ * Chain multiple requests to execute together
3767
+ * @param {Slice<any>} requests List of requests to chain
3768
+ * @return {Promise<any>} API Response
3769
+ */
3770
+ chain(...requests) {
3771
+ const arr = requests.length == 1 && Array.isArray(requests[0]) ? requests[0] : requests;
3772
+ return this.request({ "$/tools/action_chain": arr.map((r) => {
3773
+ if (!(r instanceof ApiCall)) return r;
3774
+ const req = r.raw;
3775
+ Object.keys(req).forEach((key) => {
3776
+ if (key.startsWith("$/")) {
3777
+ req[key.replace("$", "!")] = req[key];
3778
+ delete req[key];
3779
+ }
3780
+ });
3781
+ return req;
3782
+ }) });
3783
+ }
3784
+ /**
3785
+ * Organize multiple requests into a single mapped request
3786
+ * @param {{[p: string]: any}} request Map of requests
3787
+ * @return {Promise<any>} Map of API Responses
3788
+ */
3789
+ chainMap(request) {
3790
+ return this.request({ "$/tools/do": [
3791
+ ...Object.entries(request).flatMap(([key, r]) => {
3792
+ if (!(r instanceof ApiCall)) return [key, r];
3793
+ const req = r.raw;
3794
+ Object.keys(req).forEach((key2) => {
3795
+ if (key2.startsWith("$/")) {
3796
+ req[key2.replace("$", "!")] = req[key2];
3797
+ delete req[key2];
3798
+ }
3799
+ });
3800
+ return [key, req];
3801
+ }),
3802
+ "returnAllBoilerplate",
3803
+ { "$_": "*" }
3804
+ ] }, {});
3805
+ }
3806
+ /**
3807
+ * Exact same as `request` method, but logs the response in the console automatically
3808
+ *
3809
+ * @param {object | string} data Datalynk request as object or string
3810
+ * @param {ApiRequestOptions} options
3811
+ * @returns {Promise<any>} Datalynk response
3812
+ */
3813
+ debug(data, options = {}) {
3814
+ return this.request(data, options).then((data2) => {
3815
+ console.log(data2);
3816
+ return data2;
3817
+ }).catch((err) => {
3818
+ console.error(err);
3819
+ return err;
3820
+ });
3821
+ }
3822
+ /**
3823
+ * Send a request to Datalynk
3824
+ *
3825
+ * @example
3826
+ * ```ts
3827
+ * const response = await api.request('$/auth/current');
3828
+ * ```
3829
+ *
3830
+ * @param {object} data Request using Datalynk API syntax. Strings will be converted: '$/auth/current' -> {'$/auth/current': {}}
3831
+ * @param {ApiRequestOptions} options
3832
+ * @returns {Promise<any>} Datalynk response or error
3833
+ */
3834
+ request(data, options = {}) {
3835
+ data = typeof data == "string" ? { [data]: {} } : data;
3836
+ if (options.noOptimize) {
3837
+ return new Promise((res, rej) => {
3838
+ this._request(data, options).then((resp) => {
3839
+ (resp == null ? void 0 : resp.error) ? rej(resp) : res(resp);
3840
+ }).catch((err) => rej(err));
3841
+ });
3842
+ }
3843
+ let key = JSON.stringify(data);
3844
+ if (!this.pending[key]) {
3845
+ this.pending[key] = new Promise((res, rej) => this.bundle.push({ data, res, rej }));
3846
+ this.pending[key].catch().then(() => delete this.pending[key]);
3847
+ if (!this.bundleOngoing) {
3848
+ this.bundleOngoing = true;
3849
+ setTimeout(() => {
3850
+ let originalBundle = this.bundle;
3851
+ this.bundle = [];
3852
+ this.bundleOngoing = false;
3853
+ data = originalBundle.map((row) => row.data);
3854
+ this._request(data, options).then((resp) => {
3855
+ if (!(resp instanceof Array)) resp = [resp];
3856
+ resp.forEach((row, i) => (row == null ? void 0 : row.error) ? originalBundle[i].rej(row.error) : originalBundle[i].res(row));
3857
+ }).catch((err) => originalBundle.forEach((req) => req.rej(err)));
3858
+ }, this.options.bundleTime);
3859
+ }
3860
+ }
3861
+ return this.pending[key];
3862
+ }
3863
+ /**
3864
+ * Create a slice object using the API
3865
+ *
3866
+ * @example
3867
+ * ```ts
3868
+ * const contactsSlice = api.slice<Contacts>(12345);
3869
+ * const allContacts = await contactsSlice.select().exec().rows();
3870
+ * const unsubscribe = contactsSlice.sync().subscribe(rows => console.log(rows));
3871
+ * ```
3872
+ *
3873
+ * @param {number} id Slice ID the object will target
3874
+ * @returns {Slice<T = any>} Object for making requests & caching rows
3875
+ */
3876
+ slice(id) {
3877
+ if (!this.sliceCache.has(+id)) this.sliceCache.set(+id, new Slice(id, this));
3878
+ return this.sliceCache.get(+id);
3879
+ }
3880
+ };
3881
+ /** Client library version */
3882
+ __publicField(_Api, "version", version);
3883
+ let Api = _Api;
3884
+ exports2.Api = Api;
3885
+ exports2.ApiCall = ApiCall;
3886
+ exports2.Auth = Auth;
3887
+ exports2.Files = Files;
3888
+ exports2.LoginPrompt = LoginPrompt;
3889
+ exports2.PWA = PWA;
3890
+ exports2.Pdf = Pdf;
3891
+ exports2.Serializer = Serializer;
3892
+ exports2.Slice = Slice;
3893
+ exports2.Socket = Socket;
3894
+ exports2.Superuser = Superuser;
3895
+ exports2.getTheme = getTheme;
3896
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
3897
+ });