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