@ztimson/momentum 0.27.4 → 0.28.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1901 @@
1
+ (function(global, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.utils = {}));
3
+ })(this, function(exports2) {
4
+ "use strict";var __defProp = Object.defineProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+
8
+ var Y = Object.defineProperty;
9
+ var v = (n, e, t) => e in n ? Y(n, e, { enumerable: true, configurable: true, writable: true, value: t }) : n[e] = t;
10
+ var a = (n, e, t) => (v(n, typeof e != "symbol" ? e + "" : e, t), t);
11
+ function F(n, e = false) {
12
+ if (n == null)
13
+ throw new Error("Cannot clean a NULL value");
14
+ return Array.isArray(n) ? n = n.filter((t) => t != null) : Object.entries(n).forEach(([t, r]) => {
15
+ (e && r === void 0 || !e && r == null) && delete n[t];
16
+ }), n;
17
+ }
18
+ function b(n, e) {
19
+ const t = typeof n, r = typeof e;
20
+ return t != "object" || n == null || r != "object" || e == null ? t == "function" && r == "function" ? n.toString() == e.toString() : n === e : Object.keys(n).length != Object.keys(e).length ? false : Object.keys(n).every((s) => b(n[s], e[s]));
21
+ }
22
+ class E extends Promise {
23
+ constructor(t) {
24
+ super((r, o) => t(
25
+ (s) => r(s),
26
+ (s) => o(s),
27
+ (s) => this.progress = s
28
+ ));
29
+ a(this, "listeners", []);
30
+ a(this, "_progress", 0);
31
+ }
32
+ get progress() {
33
+ return this._progress;
34
+ }
35
+ set progress(t) {
36
+ t != this._progress && (this._progress = t, this.listeners.forEach((r) => r(t)));
37
+ }
38
+ static from(t) {
39
+ return t instanceof E ? t : new E((r, o) => t.then((...s) => r(...s)).catch((...s) => o(...s)));
40
+ }
41
+ from(t) {
42
+ const r = E.from(t);
43
+ return this.onProgress((o) => r.progress = o), r;
44
+ }
45
+ onProgress(t) {
46
+ return this.listeners.push(t), this;
47
+ }
48
+ then(t, r) {
49
+ const o = super.then(t, r);
50
+ return this.from(o);
51
+ }
52
+ catch(t) {
53
+ return this.from(super.catch(t));
54
+ }
55
+ finally(t) {
56
+ return this.from(super.finally(t));
57
+ }
58
+ }
59
+ function V(n, e) {
60
+ const t = document.createElement("a");
61
+ t.href = n, t.download = e, document.body.appendChild(t), t.click(), document.body.removeChild(t);
62
+ }
63
+ function wt(n, e) {
64
+ const t = URL.createObjectURL(n);
65
+ V(t, e), URL.revokeObjectURL(t);
66
+ }
67
+ function xt(n = {}) {
68
+ return new Promise((e) => {
69
+ const t = document.createElement("input");
70
+ t.type = "file", t.accept = n.accept || "*", t.style.display = "none", t.multiple = !!n.multiple, t.onblur = t.onchange = async () => {
71
+ e(Array.from(t.files)), t.remove();
72
+ }, document.body.appendChild(t), t.click();
73
+ });
74
+ }
75
+ function At(n) {
76
+ return new E((e, t, r) => {
77
+ const o = new XMLHttpRequest(), s = new FormData();
78
+ n.files.forEach((i) => s.append("file", i)), o.withCredentials = !!n.withCredentials, o.upload.addEventListener("progress", (i) => i.lengthComputable ? r(i.loaded / i.total) : null), o.upload.addEventListener("load", (i) => e(i)), o.upload.addEventListener("error", (i) => t(i)), o.open("POST", n.url), Object.entries(n.headers || {}).forEach(([i, y]) => o.setRequestHeader(i, y)), o.send(s);
79
+ });
80
+ }
81
+ class P {
82
+ constructor() {
83
+ a(this, "listeners", {});
84
+ }
85
+ static emit(e, ...t) {
86
+ (this.listeners["*"] || []).forEach((r) => r(e, ...t)), (this.listeners[e.toString()] || []).forEach((r) => r(...t));
87
+ }
88
+ static off(e, t) {
89
+ const r = e.toString();
90
+ this.listeners[r] = (this.listeners[r] || []).filter((o) => o === t);
91
+ }
92
+ static on(e, t) {
93
+ var o;
94
+ const r = e.toString();
95
+ return this.listeners[r] || (this.listeners[r] = []), (o = this.listeners[r]) == null || o.push(t), () => this.off(e, t);
96
+ }
97
+ static once(e, t) {
98
+ return new Promise((r) => {
99
+ const o = this.on(e, (...s) => {
100
+ r(s.length == 1 ? s[0] : s), t && t(...s), o();
101
+ });
102
+ });
103
+ }
104
+ emit(e, ...t) {
105
+ (this.listeners["*"] || []).forEach((r) => r(e, ...t)), (this.listeners[e] || []).forEach((r) => r(...t));
106
+ }
107
+ off(e, t) {
108
+ this.listeners[e] = (this.listeners[e] || []).filter((r) => r === t);
109
+ }
110
+ on(e, t) {
111
+ var r;
112
+ return this.listeners[e] || (this.listeners[e] = []), (r = this.listeners[e]) == null || r.push(t), () => this.off(e, t);
113
+ }
114
+ once(e, t) {
115
+ return new Promise((r) => {
116
+ const o = this.on(e, (...s) => {
117
+ r(s.length == 1 ? s[0] : s), t && t(...s), o();
118
+ });
119
+ });
120
+ }
121
+ }
122
+ a(P, "listeners", {});
123
+ class w extends Error {
124
+ constructor(t, r) {
125
+ super(t);
126
+ a(this, "_code");
127
+ r != null && (this._code = r);
128
+ }
129
+ get code() {
130
+ return this._code || this.constructor.code;
131
+ }
132
+ set code(t) {
133
+ this._code = t;
134
+ }
135
+ static from(t) {
136
+ const r = Number(t.statusCode) ?? Number(t.code), o = new this(t.message || t.toString());
137
+ return Object.assign(o, {
138
+ stack: t.stack,
139
+ ...t,
140
+ code: r ?? void 0
141
+ });
142
+ }
143
+ static instanceof(t) {
144
+ return t.constructor.code != null;
145
+ }
146
+ toString() {
147
+ return this.message || super.toString();
148
+ }
149
+ }
150
+ a(w, "code", 500);
151
+ class Z extends w {
152
+ constructor(e = "Bad Request") {
153
+ super(e);
154
+ }
155
+ static instanceof(e) {
156
+ return e.constructor.code == this.code;
157
+ }
158
+ }
159
+ a(Z, "code", 400);
160
+ class X extends w {
161
+ constructor(e = "Unauthorized") {
162
+ super(e);
163
+ }
164
+ static instanceof(e) {
165
+ return e.constructor.code == this.code;
166
+ }
167
+ }
168
+ a(X, "code", 401);
169
+ class Q extends w {
170
+ constructor(e = "Forbidden") {
171
+ super(e);
172
+ }
173
+ static instanceof(e) {
174
+ return e.constructor.code == this.code;
175
+ }
176
+ }
177
+ a(Q, "code", 403);
178
+ class _ extends w {
179
+ constructor(e = "Not Found") {
180
+ super(e);
181
+ }
182
+ static instanceof(e) {
183
+ return e.constructor.code == this.code;
184
+ }
185
+ }
186
+ a(_, "code", 404);
187
+ class tt extends w {
188
+ constructor(e = "Internal Server Error") {
189
+ super(e);
190
+ }
191
+ static instanceof(e) {
192
+ return e.constructor.code == this.code;
193
+ }
194
+ }
195
+ a(tt, "code", 500);
196
+ const g = class g2 {
197
+ constructor(e = {}) {
198
+ a(this, "interceptors", {});
199
+ a(this, "headers", {});
200
+ a(this, "url");
201
+ this.url = e.url ?? null, this.headers = e.headers || {}, e.interceptors && e.interceptors.forEach((t) => g2.addInterceptor(t));
202
+ }
203
+ static addInterceptor(e) {
204
+ const t = Object.keys(g2.interceptors).length.toString();
205
+ return g2.interceptors[t] = e, () => {
206
+ g2.interceptors[t] = null;
207
+ };
208
+ }
209
+ addInterceptor(e) {
210
+ const t = Object.keys(this.interceptors).length.toString();
211
+ return this.interceptors[t] = e, () => {
212
+ this.interceptors[t] = null;
213
+ };
214
+ }
215
+ request(e = {}) {
216
+ var o;
217
+ if (!this.url && !e.url)
218
+ throw new Error("URL needs to be set");
219
+ let t = ((o = e.url) != null && o.startsWith("http") ? e.url : (this.url || "") + (e.url || "")).replace(/([^:]\/)\/+/g, "$1");
220
+ if (e.fragment && (t.includes("#") ? t.replace(/#.*(\?|\n)/g, (s, i) => `#${e.fragment}${i}`) : t += "#" + e.fragment), e.query) {
221
+ const s = Array.isArray(e.query) ? e.query : Object.keys(e.query).map((i) => ({ key: i, value: e.query[i] }));
222
+ t += (t.includes("?") ? "&" : "?") + s.map((i) => `${i.key}=${i.value}`).join("&");
223
+ }
224
+ const r = F({
225
+ "Content-Type": e.body ? e.body instanceof FormData ? "multipart/form-data" : "application/json" : void 0,
226
+ ...g2.headers,
227
+ ...this.headers,
228
+ ...e.headers
229
+ });
230
+ return typeof e.body == "object" && e.body != null && r["Content-Type"] == "application/json" && (e.body = JSON.stringify(e.body)), new E((s, i, y) => {
231
+ fetch(t, {
232
+ headers: r,
233
+ method: e.method || (e.body ? "POST" : "GET"),
234
+ body: e.body
235
+ }).then(async (c) => {
236
+ var k, G;
237
+ for (let u of [...Object.values(g2.interceptors), ...Object.values(this.interceptors)])
238
+ await new Promise((L) => u(c, () => L()));
239
+ const R = c.headers.get("Content-Length"), N = R ? parseInt(R, 10) : 0;
240
+ let j = 0;
241
+ const I = (k = c.body) == null ? void 0 : k.getReader(), H = new ReadableStream({
242
+ start(u) {
243
+ function L() {
244
+ I == null || I.read().then((x) => {
245
+ if (x.done)
246
+ return u.close();
247
+ j += x.value.byteLength, y(j / N), u.enqueue(x.value), L();
248
+ }).catch((x) => u.error(x));
249
+ }
250
+ L();
251
+ }
252
+ });
253
+ if (c.data = new Response(H), e.decode == null || e.decode) {
254
+ const u = (G = c.headers.get("Content-Type")) == null ? void 0 : G.toLowerCase();
255
+ u != null && u.includes("form") ? c.data = await c.data.formData() : u != null && u.includes("json") ? c.data = await c.data.json() : u != null && u.includes("text") ? c.data = await c.data.text() : u != null && u.includes("application") && (c.data = await c.data.blob());
256
+ }
257
+ c.ok ? s(c) : i(c);
258
+ });
259
+ });
260
+ }
261
+ };
262
+ a(g, "interceptors", {}), a(g, "headers", {});
263
+ let M = g;
264
+ const A = {
265
+ CLEAR: "\x1B[0m",
266
+ BRIGHT: "\x1B[1m",
267
+ DIM: "\x1B[2m",
268
+ UNDERSCORE: "\x1B[4m",
269
+ BLINK: "\x1B[5m",
270
+ REVERSE: "\x1B[7m",
271
+ HIDDEN: "\x1B[8m"
272
+ }, O = {
273
+ BLACK: "\x1B[30m",
274
+ RED: "\x1B[31m",
275
+ GREEN: "\x1B[32m",
276
+ YELLOW: "\x1B[33m",
277
+ BLUE: "\x1B[34m",
278
+ MAGENTA: "\x1B[35m",
279
+ CYAN: "\x1B[36m",
280
+ LIGHT_GREY: "\x1B[37m",
281
+ GREY: "\x1B[90m",
282
+ LIGHT_RED: "\x1B[91m",
283
+ LIGHT_GREEN: "\x1B[92m",
284
+ LIGHT_YELLOW: "\x1B[93m",
285
+ LIGHT_BLUE: "\x1B[94m",
286
+ LIGHT_MAGENTA: "\x1B[95m",
287
+ LIGHT_CYAN: "\x1B[96m",
288
+ WHITE: "\x1B[97m"
289
+ };
290
+ var et = /* @__PURE__ */ ((n) => (n[n.ERROR = 0] = "ERROR", n[n.WARN = 1] = "WARN", n[n.INFO = 2] = "INFO", n[n.LOG = 3] = "LOG", n[n.DEBUG = 4] = "DEBUG", n))(et || {});
291
+ const p = class p2 extends P {
292
+ constructor(e) {
293
+ super(), this.namespace = e;
294
+ }
295
+ pad(e, t, r, o = false) {
296
+ const s = e.toString(), i = t - s.length;
297
+ if (i <= 0)
298
+ return s;
299
+ const y = Array(~~(i / r.length)).fill(r).join("");
300
+ return o ? s + y : y + s;
301
+ }
302
+ format(...e) {
303
+ const t = /* @__PURE__ */ new Date();
304
+ return `${`${t.getFullYear()}-${t.getMonth() + 1}-${t.getDate()} ${this.pad(t.getHours().toString(), 2, "0")}:${this.pad(t.getMinutes().toString(), 2, "0")}:${this.pad(t.getSeconds().toString(), 2, "0")}.${this.pad(t.getMilliseconds().toString(), 3, "0", true)}`}${this.namespace ? ` [${this.namespace}]` : ""} ${e.join(" ")}`;
305
+ }
306
+ debug(...e) {
307
+ if (p2.LOG_LEVEL < 4)
308
+ return;
309
+ const t = this.format(...e);
310
+ p2.emit(4, t), console.debug(O.LIGHT_GREY + t + A.CLEAR);
311
+ }
312
+ log(...e) {
313
+ if (p2.LOG_LEVEL < 3)
314
+ return;
315
+ const t = this.format(...e);
316
+ p2.emit(3, t), console.log(A.CLEAR + t);
317
+ }
318
+ info(...e) {
319
+ if (p2.LOG_LEVEL < 2)
320
+ return;
321
+ const t = this.format(...e);
322
+ p2.emit(2, t), console.info(O.BLUE + t + A.CLEAR);
323
+ }
324
+ warn(...e) {
325
+ if (p2.LOG_LEVEL < 1)
326
+ return;
327
+ const t = this.format(...e);
328
+ p2.emit(1, t), console.warn(O.YELLOW + t + A.CLEAR);
329
+ }
330
+ error(...e) {
331
+ if (p2.LOG_LEVEL < 0)
332
+ return;
333
+ const t = this.format(...e);
334
+ p2.emit(0, t), console.error(O.RED + t + A.CLEAR);
335
+ }
336
+ };
337
+ a(p, "LOG_LEVEL", 4);
338
+ class Api extends M {
339
+ constructor(url = location.origin, opts = {}) {
340
+ opts.url = url;
341
+ super(opts);
342
+ __publicField(this, "emitter", new P());
343
+ __publicField(this, "_token", null);
344
+ __publicField(this, "emit", this.emitter.emit.bind(this.emitter));
345
+ __publicField(this, "off", this.emitter.off.bind(this.emitter));
346
+ __publicField(this, "on", this.emitter.on.bind(this.emitter));
347
+ __publicField(this, "once", this.emitter.once.bind(this.emitter));
348
+ this.url = url;
349
+ this.opts = opts;
350
+ }
351
+ get token() {
352
+ return this._token;
353
+ }
354
+ set token(token) {
355
+ if (token == this._token) return;
356
+ this._token = token;
357
+ this.headers["Authorization"] = token ? `Bearer ${token}` : void 0;
358
+ this.emit("TOKEN", token);
359
+ }
360
+ healthcheck() {
361
+ return this.request({ url: "/api/healthcheck" });
362
+ }
363
+ request(options) {
364
+ const req = super.request(options).then((resp) => {
365
+ this.emit("RESPONSE", resp, options);
366
+ return resp.data;
367
+ }).catch((err) => {
368
+ const e = (err == null ? void 0 : err.data) || err;
369
+ this.emit("REJECTED", e, options);
370
+ throw e;
371
+ });
372
+ this.emit("REQUEST", req, options);
373
+ return req;
374
+ }
375
+ }
376
+ var extendStatics = function(d, b2) {
377
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b3) {
378
+ d2.__proto__ = b3;
379
+ } || function(d2, b3) {
380
+ for (var p2 in b3) if (Object.prototype.hasOwnProperty.call(b3, p2)) d2[p2] = b3[p2];
381
+ };
382
+ return extendStatics(d, b2);
383
+ };
384
+ function __extends(d, b2) {
385
+ if (typeof b2 !== "function" && b2 !== null)
386
+ throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
387
+ extendStatics(d, b2);
388
+ function __() {
389
+ this.constructor = d;
390
+ }
391
+ d.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
392
+ }
393
+ function __values(o) {
394
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
395
+ if (m) return m.call(o);
396
+ if (o && typeof o.length === "number") return {
397
+ next: function() {
398
+ if (o && i >= o.length) o = void 0;
399
+ return { value: o && o[i++], done: !o };
400
+ }
401
+ };
402
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
403
+ }
404
+ function __read(o, n) {
405
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
406
+ if (!m) return o;
407
+ var i = m.call(o), r, ar = [], e;
408
+ try {
409
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
410
+ } catch (error) {
411
+ e = { error };
412
+ } finally {
413
+ try {
414
+ if (r && !r.done && (m = i["return"])) m.call(i);
415
+ } finally {
416
+ if (e) throw e.error;
417
+ }
418
+ }
419
+ return ar;
420
+ }
421
+ function __spreadArray(to, from, pack) {
422
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
423
+ if (ar || !(i in from)) {
424
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
425
+ ar[i] = from[i];
426
+ }
427
+ }
428
+ return to.concat(ar || Array.prototype.slice.call(from));
429
+ }
430
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
431
+ var e = new Error(message);
432
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
433
+ };
434
+ function isFunction(value) {
435
+ return typeof value === "function";
436
+ }
437
+ function createErrorClass(createImpl) {
438
+ var _super = function(instance) {
439
+ Error.call(instance);
440
+ instance.stack = new Error().stack;
441
+ };
442
+ var ctorFunc = createImpl(_super);
443
+ ctorFunc.prototype = Object.create(Error.prototype);
444
+ ctorFunc.prototype.constructor = ctorFunc;
445
+ return ctorFunc;
446
+ }
447
+ var UnsubscriptionError = createErrorClass(function(_super) {
448
+ return function UnsubscriptionErrorImpl(errors) {
449
+ _super(this);
450
+ this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
451
+ return i + 1 + ") " + err.toString();
452
+ }).join("\n ") : "";
453
+ this.name = "UnsubscriptionError";
454
+ this.errors = errors;
455
+ };
456
+ });
457
+ function arrRemove(arr, item) {
458
+ if (arr) {
459
+ var index = arr.indexOf(item);
460
+ 0 <= index && arr.splice(index, 1);
461
+ }
462
+ }
463
+ var Subscription = function() {
464
+ function Subscription2(initialTeardown) {
465
+ this.initialTeardown = initialTeardown;
466
+ this.closed = false;
467
+ this._parentage = null;
468
+ this._finalizers = null;
469
+ }
470
+ Subscription2.prototype.unsubscribe = function() {
471
+ var e_1, _a, e_2, _b;
472
+ var errors;
473
+ if (!this.closed) {
474
+ this.closed = true;
475
+ var _parentage = this._parentage;
476
+ if (_parentage) {
477
+ this._parentage = null;
478
+ if (Array.isArray(_parentage)) {
479
+ try {
480
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
481
+ var parent_1 = _parentage_1_1.value;
482
+ parent_1.remove(this);
483
+ }
484
+ } catch (e_1_1) {
485
+ e_1 = { error: e_1_1 };
486
+ } finally {
487
+ try {
488
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
489
+ } finally {
490
+ if (e_1) throw e_1.error;
491
+ }
492
+ }
493
+ } else {
494
+ _parentage.remove(this);
495
+ }
496
+ }
497
+ var initialFinalizer = this.initialTeardown;
498
+ if (isFunction(initialFinalizer)) {
499
+ try {
500
+ initialFinalizer();
501
+ } catch (e) {
502
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
503
+ }
504
+ }
505
+ var _finalizers = this._finalizers;
506
+ if (_finalizers) {
507
+ this._finalizers = null;
508
+ try {
509
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
510
+ var finalizer = _finalizers_1_1.value;
511
+ try {
512
+ execFinalizer(finalizer);
513
+ } catch (err) {
514
+ errors = errors !== null && errors !== void 0 ? errors : [];
515
+ if (err instanceof UnsubscriptionError) {
516
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
517
+ } else {
518
+ errors.push(err);
519
+ }
520
+ }
521
+ }
522
+ } catch (e_2_1) {
523
+ e_2 = { error: e_2_1 };
524
+ } finally {
525
+ try {
526
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
527
+ } finally {
528
+ if (e_2) throw e_2.error;
529
+ }
530
+ }
531
+ }
532
+ if (errors) {
533
+ throw new UnsubscriptionError(errors);
534
+ }
535
+ }
536
+ };
537
+ Subscription2.prototype.add = function(teardown) {
538
+ var _a;
539
+ if (teardown && teardown !== this) {
540
+ if (this.closed) {
541
+ execFinalizer(teardown);
542
+ } else {
543
+ if (teardown instanceof Subscription2) {
544
+ if (teardown.closed || teardown._hasParent(this)) {
545
+ return;
546
+ }
547
+ teardown._addParent(this);
548
+ }
549
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
550
+ }
551
+ }
552
+ };
553
+ Subscription2.prototype._hasParent = function(parent) {
554
+ var _parentage = this._parentage;
555
+ return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
556
+ };
557
+ Subscription2.prototype._addParent = function(parent) {
558
+ var _parentage = this._parentage;
559
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
560
+ };
561
+ Subscription2.prototype._removeParent = function(parent) {
562
+ var _parentage = this._parentage;
563
+ if (_parentage === parent) {
564
+ this._parentage = null;
565
+ } else if (Array.isArray(_parentage)) {
566
+ arrRemove(_parentage, parent);
567
+ }
568
+ };
569
+ Subscription2.prototype.remove = function(teardown) {
570
+ var _finalizers = this._finalizers;
571
+ _finalizers && arrRemove(_finalizers, teardown);
572
+ if (teardown instanceof Subscription2) {
573
+ teardown._removeParent(this);
574
+ }
575
+ };
576
+ Subscription2.EMPTY = function() {
577
+ var empty = new Subscription2();
578
+ empty.closed = true;
579
+ return empty;
580
+ }();
581
+ return Subscription2;
582
+ }();
583
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
584
+ function isSubscription(value) {
585
+ return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
586
+ }
587
+ function execFinalizer(finalizer) {
588
+ if (isFunction(finalizer)) {
589
+ finalizer();
590
+ } else {
591
+ finalizer.unsubscribe();
592
+ }
593
+ }
594
+ var config = {
595
+ onUnhandledError: null,
596
+ onStoppedNotification: null,
597
+ Promise: void 0,
598
+ useDeprecatedSynchronousErrorHandling: false,
599
+ useDeprecatedNextContext: false
600
+ };
601
+ var timeoutProvider = {
602
+ setTimeout: function(handler, timeout) {
603
+ var args = [];
604
+ for (var _i = 2; _i < arguments.length; _i++) {
605
+ args[_i - 2] = arguments[_i];
606
+ }
607
+ return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
608
+ },
609
+ clearTimeout: function(handle) {
610
+ var delegate = timeoutProvider.delegate;
611
+ return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
612
+ },
613
+ delegate: void 0
614
+ };
615
+ function reportUnhandledError(err) {
616
+ timeoutProvider.setTimeout(function() {
617
+ {
618
+ throw err;
619
+ }
620
+ });
621
+ }
622
+ function noop() {
623
+ }
624
+ function errorContext(cb) {
625
+ {
626
+ cb();
627
+ }
628
+ }
629
+ var Subscriber = function(_super) {
630
+ __extends(Subscriber2, _super);
631
+ function Subscriber2(destination) {
632
+ var _this = _super.call(this) || this;
633
+ _this.isStopped = false;
634
+ if (destination) {
635
+ _this.destination = destination;
636
+ if (isSubscription(destination)) {
637
+ destination.add(_this);
638
+ }
639
+ } else {
640
+ _this.destination = EMPTY_OBSERVER;
641
+ }
642
+ return _this;
643
+ }
644
+ Subscriber2.create = function(next, error, complete) {
645
+ return new SafeSubscriber(next, error, complete);
646
+ };
647
+ Subscriber2.prototype.next = function(value) {
648
+ if (this.isStopped) ;
649
+ else {
650
+ this._next(value);
651
+ }
652
+ };
653
+ Subscriber2.prototype.error = function(err) {
654
+ if (this.isStopped) ;
655
+ else {
656
+ this.isStopped = true;
657
+ this._error(err);
658
+ }
659
+ };
660
+ Subscriber2.prototype.complete = function() {
661
+ if (this.isStopped) ;
662
+ else {
663
+ this.isStopped = true;
664
+ this._complete();
665
+ }
666
+ };
667
+ Subscriber2.prototype.unsubscribe = function() {
668
+ if (!this.closed) {
669
+ this.isStopped = true;
670
+ _super.prototype.unsubscribe.call(this);
671
+ this.destination = null;
672
+ }
673
+ };
674
+ Subscriber2.prototype._next = function(value) {
675
+ this.destination.next(value);
676
+ };
677
+ Subscriber2.prototype._error = function(err) {
678
+ try {
679
+ this.destination.error(err);
680
+ } finally {
681
+ this.unsubscribe();
682
+ }
683
+ };
684
+ Subscriber2.prototype._complete = function() {
685
+ try {
686
+ this.destination.complete();
687
+ } finally {
688
+ this.unsubscribe();
689
+ }
690
+ };
691
+ return Subscriber2;
692
+ }(Subscription);
693
+ var _bind = Function.prototype.bind;
694
+ function bind(fn, thisArg) {
695
+ return _bind.call(fn, thisArg);
696
+ }
697
+ var ConsumerObserver = function() {
698
+ function ConsumerObserver2(partialObserver) {
699
+ this.partialObserver = partialObserver;
700
+ }
701
+ ConsumerObserver2.prototype.next = function(value) {
702
+ var partialObserver = this.partialObserver;
703
+ if (partialObserver.next) {
704
+ try {
705
+ partialObserver.next(value);
706
+ } catch (error) {
707
+ handleUnhandledError(error);
708
+ }
709
+ }
710
+ };
711
+ ConsumerObserver2.prototype.error = function(err) {
712
+ var partialObserver = this.partialObserver;
713
+ if (partialObserver.error) {
714
+ try {
715
+ partialObserver.error(err);
716
+ } catch (error) {
717
+ handleUnhandledError(error);
718
+ }
719
+ } else {
720
+ handleUnhandledError(err);
721
+ }
722
+ };
723
+ ConsumerObserver2.prototype.complete = function() {
724
+ var partialObserver = this.partialObserver;
725
+ if (partialObserver.complete) {
726
+ try {
727
+ partialObserver.complete();
728
+ } catch (error) {
729
+ handleUnhandledError(error);
730
+ }
731
+ }
732
+ };
733
+ return ConsumerObserver2;
734
+ }();
735
+ var SafeSubscriber = function(_super) {
736
+ __extends(SafeSubscriber2, _super);
737
+ function SafeSubscriber2(observerOrNext, error, complete) {
738
+ var _this = _super.call(this) || this;
739
+ var partialObserver;
740
+ if (isFunction(observerOrNext) || !observerOrNext) {
741
+ partialObserver = {
742
+ next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0,
743
+ error: error !== null && error !== void 0 ? error : void 0,
744
+ complete: complete !== null && complete !== void 0 ? complete : void 0
745
+ };
746
+ } else {
747
+ var context_1;
748
+ if (_this && config.useDeprecatedNextContext) {
749
+ context_1 = Object.create(observerOrNext);
750
+ context_1.unsubscribe = function() {
751
+ return _this.unsubscribe();
752
+ };
753
+ partialObserver = {
754
+ next: observerOrNext.next && bind(observerOrNext.next, context_1),
755
+ error: observerOrNext.error && bind(observerOrNext.error, context_1),
756
+ complete: observerOrNext.complete && bind(observerOrNext.complete, context_1)
757
+ };
758
+ } else {
759
+ partialObserver = observerOrNext;
760
+ }
761
+ }
762
+ _this.destination = new ConsumerObserver(partialObserver);
763
+ return _this;
764
+ }
765
+ return SafeSubscriber2;
766
+ }(Subscriber);
767
+ function handleUnhandledError(error) {
768
+ {
769
+ reportUnhandledError(error);
770
+ }
771
+ }
772
+ function defaultErrorHandler(err) {
773
+ throw err;
774
+ }
775
+ var EMPTY_OBSERVER = {
776
+ closed: true,
777
+ next: noop,
778
+ error: defaultErrorHandler,
779
+ complete: noop
780
+ };
781
+ var observable = function() {
782
+ return typeof Symbol === "function" && Symbol.observable || "@@observable";
783
+ }();
784
+ function identity(x) {
785
+ return x;
786
+ }
787
+ function pipeFromArray(fns) {
788
+ if (fns.length === 0) {
789
+ return identity;
790
+ }
791
+ if (fns.length === 1) {
792
+ return fns[0];
793
+ }
794
+ return function piped(input) {
795
+ return fns.reduce(function(prev, fn) {
796
+ return fn(prev);
797
+ }, input);
798
+ };
799
+ }
800
+ var Observable = function() {
801
+ function Observable2(subscribe) {
802
+ if (subscribe) {
803
+ this._subscribe = subscribe;
804
+ }
805
+ }
806
+ Observable2.prototype.lift = function(operator) {
807
+ var observable2 = new Observable2();
808
+ observable2.source = this;
809
+ observable2.operator = operator;
810
+ return observable2;
811
+ };
812
+ Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
813
+ var _this = this;
814
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
815
+ errorContext(function() {
816
+ var _a = _this, operator = _a.operator, source = _a.source;
817
+ subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
818
+ });
819
+ return subscriber;
820
+ };
821
+ Observable2.prototype._trySubscribe = function(sink) {
822
+ try {
823
+ return this._subscribe(sink);
824
+ } catch (err) {
825
+ sink.error(err);
826
+ }
827
+ };
828
+ Observable2.prototype.forEach = function(next, promiseCtor) {
829
+ var _this = this;
830
+ promiseCtor = getPromiseCtor(promiseCtor);
831
+ return new promiseCtor(function(resolve, reject) {
832
+ var subscriber = new SafeSubscriber({
833
+ next: function(value) {
834
+ try {
835
+ next(value);
836
+ } catch (err) {
837
+ reject(err);
838
+ subscriber.unsubscribe();
839
+ }
840
+ },
841
+ error: reject,
842
+ complete: resolve
843
+ });
844
+ _this.subscribe(subscriber);
845
+ });
846
+ };
847
+ Observable2.prototype._subscribe = function(subscriber) {
848
+ var _a;
849
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
850
+ };
851
+ Observable2.prototype[observable] = function() {
852
+ return this;
853
+ };
854
+ Observable2.prototype.pipe = function() {
855
+ var operations = [];
856
+ for (var _i = 0; _i < arguments.length; _i++) {
857
+ operations[_i] = arguments[_i];
858
+ }
859
+ return pipeFromArray(operations)(this);
860
+ };
861
+ Observable2.prototype.toPromise = function(promiseCtor) {
862
+ var _this = this;
863
+ promiseCtor = getPromiseCtor(promiseCtor);
864
+ return new promiseCtor(function(resolve, reject) {
865
+ var value;
866
+ _this.subscribe(function(x) {
867
+ return value = x;
868
+ }, function(err) {
869
+ return reject(err);
870
+ }, function() {
871
+ return resolve(value);
872
+ });
873
+ });
874
+ };
875
+ Observable2.create = function(subscribe) {
876
+ return new Observable2(subscribe);
877
+ };
878
+ return Observable2;
879
+ }();
880
+ function getPromiseCtor(promiseCtor) {
881
+ var _a;
882
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
883
+ }
884
+ function isObserver(value) {
885
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
886
+ }
887
+ function isSubscriber(value) {
888
+ return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
889
+ }
890
+ var ObjectUnsubscribedError = createErrorClass(function(_super) {
891
+ return function ObjectUnsubscribedErrorImpl() {
892
+ _super(this);
893
+ this.name = "ObjectUnsubscribedError";
894
+ this.message = "object unsubscribed";
895
+ };
896
+ });
897
+ var Subject = function(_super) {
898
+ __extends(Subject2, _super);
899
+ function Subject2() {
900
+ var _this = _super.call(this) || this;
901
+ _this.closed = false;
902
+ _this.currentObservers = null;
903
+ _this.observers = [];
904
+ _this.isStopped = false;
905
+ _this.hasError = false;
906
+ _this.thrownError = null;
907
+ return _this;
908
+ }
909
+ Subject2.prototype.lift = function(operator) {
910
+ var subject = new AnonymousSubject(this, this);
911
+ subject.operator = operator;
912
+ return subject;
913
+ };
914
+ Subject2.prototype._throwIfClosed = function() {
915
+ if (this.closed) {
916
+ throw new ObjectUnsubscribedError();
917
+ }
918
+ };
919
+ Subject2.prototype.next = function(value) {
920
+ var _this = this;
921
+ errorContext(function() {
922
+ var e_1, _a;
923
+ _this._throwIfClosed();
924
+ if (!_this.isStopped) {
925
+ if (!_this.currentObservers) {
926
+ _this.currentObservers = Array.from(_this.observers);
927
+ }
928
+ try {
929
+ for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
930
+ var observer = _c.value;
931
+ observer.next(value);
932
+ }
933
+ } catch (e_1_1) {
934
+ e_1 = { error: e_1_1 };
935
+ } finally {
936
+ try {
937
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
938
+ } finally {
939
+ if (e_1) throw e_1.error;
940
+ }
941
+ }
942
+ }
943
+ });
944
+ };
945
+ Subject2.prototype.error = function(err) {
946
+ var _this = this;
947
+ errorContext(function() {
948
+ _this._throwIfClosed();
949
+ if (!_this.isStopped) {
950
+ _this.hasError = _this.isStopped = true;
951
+ _this.thrownError = err;
952
+ var observers = _this.observers;
953
+ while (observers.length) {
954
+ observers.shift().error(err);
955
+ }
956
+ }
957
+ });
958
+ };
959
+ Subject2.prototype.complete = function() {
960
+ var _this = this;
961
+ errorContext(function() {
962
+ _this._throwIfClosed();
963
+ if (!_this.isStopped) {
964
+ _this.isStopped = true;
965
+ var observers = _this.observers;
966
+ while (observers.length) {
967
+ observers.shift().complete();
968
+ }
969
+ }
970
+ });
971
+ };
972
+ Subject2.prototype.unsubscribe = function() {
973
+ this.isStopped = this.closed = true;
974
+ this.observers = this.currentObservers = null;
975
+ };
976
+ Object.defineProperty(Subject2.prototype, "observed", {
977
+ get: function() {
978
+ var _a;
979
+ return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
980
+ },
981
+ enumerable: false,
982
+ configurable: true
983
+ });
984
+ Subject2.prototype._trySubscribe = function(subscriber) {
985
+ this._throwIfClosed();
986
+ return _super.prototype._trySubscribe.call(this, subscriber);
987
+ };
988
+ Subject2.prototype._subscribe = function(subscriber) {
989
+ this._throwIfClosed();
990
+ this._checkFinalizedStatuses(subscriber);
991
+ return this._innerSubscribe(subscriber);
992
+ };
993
+ Subject2.prototype._innerSubscribe = function(subscriber) {
994
+ var _this = this;
995
+ var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
996
+ if (hasError || isStopped) {
997
+ return EMPTY_SUBSCRIPTION;
998
+ }
999
+ this.currentObservers = null;
1000
+ observers.push(subscriber);
1001
+ return new Subscription(function() {
1002
+ _this.currentObservers = null;
1003
+ arrRemove(observers, subscriber);
1004
+ });
1005
+ };
1006
+ Subject2.prototype._checkFinalizedStatuses = function(subscriber) {
1007
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
1008
+ if (hasError) {
1009
+ subscriber.error(thrownError);
1010
+ } else if (isStopped) {
1011
+ subscriber.complete();
1012
+ }
1013
+ };
1014
+ Subject2.prototype.asObservable = function() {
1015
+ var observable2 = new Observable();
1016
+ observable2.source = this;
1017
+ return observable2;
1018
+ };
1019
+ Subject2.create = function(destination, source) {
1020
+ return new AnonymousSubject(destination, source);
1021
+ };
1022
+ return Subject2;
1023
+ }(Observable);
1024
+ var AnonymousSubject = function(_super) {
1025
+ __extends(AnonymousSubject2, _super);
1026
+ function AnonymousSubject2(destination, source) {
1027
+ var _this = _super.call(this) || this;
1028
+ _this.destination = destination;
1029
+ _this.source = source;
1030
+ return _this;
1031
+ }
1032
+ AnonymousSubject2.prototype.next = function(value) {
1033
+ var _a, _b;
1034
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
1035
+ };
1036
+ AnonymousSubject2.prototype.error = function(err) {
1037
+ var _a, _b;
1038
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1039
+ };
1040
+ AnonymousSubject2.prototype.complete = function() {
1041
+ var _a, _b;
1042
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
1043
+ };
1044
+ AnonymousSubject2.prototype._subscribe = function(subscriber) {
1045
+ var _a, _b;
1046
+ return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
1047
+ };
1048
+ return AnonymousSubject2;
1049
+ }(Subject);
1050
+ var BehaviorSubject = function(_super) {
1051
+ __extends(BehaviorSubject2, _super);
1052
+ function BehaviorSubject2(_value) {
1053
+ var _this = _super.call(this) || this;
1054
+ _this._value = _value;
1055
+ return _this;
1056
+ }
1057
+ Object.defineProperty(BehaviorSubject2.prototype, "value", {
1058
+ get: function() {
1059
+ return this.getValue();
1060
+ },
1061
+ enumerable: false,
1062
+ configurable: true
1063
+ });
1064
+ BehaviorSubject2.prototype._subscribe = function(subscriber) {
1065
+ var subscription = _super.prototype._subscribe.call(this, subscriber);
1066
+ !subscription.closed && subscriber.next(this._value);
1067
+ return subscription;
1068
+ };
1069
+ BehaviorSubject2.prototype.getValue = function() {
1070
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
1071
+ if (hasError) {
1072
+ throw thrownError;
1073
+ }
1074
+ this._throwIfClosed();
1075
+ return _value;
1076
+ };
1077
+ BehaviorSubject2.prototype.next = function(value) {
1078
+ _super.prototype.next.call(this, this._value = value);
1079
+ };
1080
+ return BehaviorSubject2;
1081
+ }(Subject);
1082
+ var ActionType = /* @__PURE__ */ ((ActionType2) => {
1083
+ ActionType2[ActionType2["CRON"] = 0] = "CRON";
1084
+ ActionType2[ActionType2["EVENT"] = 1] = "EVENT";
1085
+ ActionType2[ActionType2["DELETE"] = 2] = "DELETE";
1086
+ ActionType2[ActionType2["GET"] = 3] = "GET";
1087
+ ActionType2[ActionType2["PATCH"] = 4] = "PATCH";
1088
+ ActionType2[ActionType2["POST"] = 5] = "POST";
1089
+ ActionType2[ActionType2["PUT"] = 6] = "PUT";
1090
+ return ActionType2;
1091
+ })(ActionType || {});
1092
+ class Actions extends P {
1093
+ constructor(api) {
1094
+ super();
1095
+ __publicField(this, "api");
1096
+ __publicField(this, "$cache", new BehaviorSubject([]));
1097
+ this.api = typeof api == "string" ? new Api(api) : api;
1098
+ }
1099
+ get cache() {
1100
+ return this.$cache.value;
1101
+ }
1102
+ set cache(val) {
1103
+ this.$cache.next(val);
1104
+ }
1105
+ delete(id) {
1106
+ return this.api.request({ url: `/api/actions/${id}`, method: "DELETE" }).then(() => {
1107
+ this.cache = this.cache.filter((a2) => a2._id != id);
1108
+ this.emit("DELETE", id);
1109
+ });
1110
+ }
1111
+ list() {
1112
+ return this.api.request({ url: `/api/actions` }).then((resp) => {
1113
+ if (resp) this.cache = resp;
1114
+ this.emit("LIST", resp || []);
1115
+ return resp;
1116
+ });
1117
+ }
1118
+ read(id, reload = false) {
1119
+ const cached = this.cache.find((a2) => a2._id == id);
1120
+ if (!reload && cached) return Promise.resolve(cached);
1121
+ return this.api.request({ url: `/api/actions/${id}` }).then((action) => {
1122
+ if (action) this.cache = this.cache.filter((a2) => a2._id != id).concat([action]);
1123
+ this.emit("READ", action);
1124
+ return action;
1125
+ });
1126
+ }
1127
+ run(path, opts = {}) {
1128
+ return this.api.request({ url: (`/api/actions/run/` + path).replaceAll("//", "/"), ...opts });
1129
+ }
1130
+ runById(action, opts = {}) {
1131
+ const id = typeof action == "string" ? action : action._id;
1132
+ return this.api.request({ url: "/api/actions/run-by-id/" + id, method: "POST", ...opts });
1133
+ }
1134
+ update(action) {
1135
+ return this.api.request({
1136
+ url: `/api/actions${action._id ? `/${action._id}` : ""}`,
1137
+ method: "POST",
1138
+ body: action
1139
+ }).then((action2) => {
1140
+ if (action2) this.cache = this.cache.filter((a2) => a2._id != (action2 == null ? void 0 : action2._id)).concat([action2]);
1141
+ this.emit("UPDATE", action2);
1142
+ return action2;
1143
+ });
1144
+ }
1145
+ }
1146
+ class Totp {
1147
+ constructor(api) {
1148
+ __publicField(this, "enable", this.reset);
1149
+ this.api = api;
1150
+ }
1151
+ disable(username) {
1152
+ return this.api.request({ url: `/api/auth/totp/${username}`, method: "DELETE" });
1153
+ }
1154
+ reset(username) {
1155
+ return this.api.request({ url: `/api/auth/totp/${username}`, method: "POST" });
1156
+ }
1157
+ setup(username, method = "app", totp) {
1158
+ return this.api.request({ url: `/api/auth/totp/${username}`, body: F({
1159
+ method,
1160
+ totp
1161
+ }) });
1162
+ }
1163
+ }
1164
+ class Auth extends P {
1165
+ constructor(api, opts) {
1166
+ var _a;
1167
+ super();
1168
+ __publicField(this, "api");
1169
+ __publicField(this, "storageKey");
1170
+ __publicField(this, "totp");
1171
+ __publicField(this, "$user", new BehaviorSubject(void 0));
1172
+ this.opts = opts;
1173
+ this.api = typeof api == "string" ? new Api(api) : api;
1174
+ this.totp = new Totp(this.api);
1175
+ if (!((_a = this.opts) == null ? void 0 : _a.loginUi)) this.opts = { ...this.opts, loginUi: this.api.url + "/ui/login" };
1176
+ this.storageKey = `momentum:${new URL(this.api.url).host}`;
1177
+ this.api.addInterceptor((resp, next) => {
1178
+ const blacklist = [
1179
+ "/api/auth/login",
1180
+ "/api/auth/password",
1181
+ "/api/auth/totp"
1182
+ ];
1183
+ if (resp.status == 401 && !blacklist.find((url) => resp.url.includes(url)))
1184
+ this.emit("SESSION_EXPIRED");
1185
+ next();
1186
+ });
1187
+ this.api.on("TOKEN", (token) => {
1188
+ var _a2;
1189
+ if ((_a2 = this.opts) == null ? void 0 : _a2.persist) {
1190
+ if (token) localStorage.setItem(this.storageKey, token);
1191
+ else localStorage.removeItem(this.storageKey);
1192
+ }
1193
+ if (token) this.session(token, true).catch(() => {
1194
+ });
1195
+ else this.user = null;
1196
+ });
1197
+ if (opts == null ? void 0 : opts.persist) {
1198
+ const token = localStorage.getItem(this.storageKey);
1199
+ if (token) this.api.token = token;
1200
+ else this.user = null;
1201
+ } else {
1202
+ this.user = null;
1203
+ }
1204
+ }
1205
+ get user() {
1206
+ return this.$user.value;
1207
+ }
1208
+ set user(user) {
1209
+ if (!b(this.user, user)) {
1210
+ const u = user ? user : null;
1211
+ this.$user.next(u);
1212
+ this.emit("USER", u);
1213
+ }
1214
+ }
1215
+ knownHost(host = location.origin) {
1216
+ if (host.startsWith("/")) return Promise.resolve();
1217
+ return this.api.request({ url: `/api/auth/known-host?host=${encodeURI(new URL(host).origin)}` }).then(() => {
1218
+ });
1219
+ }
1220
+ login(username, password, totp) {
1221
+ return this.api.request({
1222
+ url: "/api/auth/login",
1223
+ headers: { Authorization: void 0 },
1224
+ method: "POST",
1225
+ body: {
1226
+ username: username.trim(),
1227
+ password: password.trim(),
1228
+ totp
1229
+ }
1230
+ }).then(async (resp) => {
1231
+ this.api.token = (resp == null ? void 0 : resp.token) || null;
1232
+ return await this.once("USER");
1233
+ });
1234
+ }
1235
+ loginRedirect(host = location.origin) {
1236
+ return new Promise((res, rej) => {
1237
+ var _a;
1238
+ const win = window.open(encodeURI(`${(_a = this.opts) == null ? void 0 : _a.loginUi}?redirect=postmessage&host=${host}`), "_blank");
1239
+ if (!win) return rej("Unable to open login");
1240
+ win.addEventListener("message", (event) => {
1241
+ var _a2;
1242
+ if (!((_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.token)) return rej("Unknown response from login");
1243
+ this.api.token = event.data.token;
1244
+ res(event.data.token);
1245
+ win.close();
1246
+ });
1247
+ });
1248
+ }
1249
+ logout() {
1250
+ this.api.token = null;
1251
+ this.user = null;
1252
+ this.emit("LOGOUT");
1253
+ }
1254
+ async register(u) {
1255
+ var _a;
1256
+ const user = await this.api.request({ url: "/api/auth/register", body: { ...u } });
1257
+ if ((_a = user == null ? void 0 : user.image) == null ? void 0 : _a.startsWith("/")) user.image = `${this.api.url}${user.image}?token=${this.api.token}`;
1258
+ this.emit("REGISTER", user);
1259
+ return user;
1260
+ }
1261
+ reset(emailOrPass, token) {
1262
+ return this.api.request({
1263
+ url: "/api/auth/reset",
1264
+ headers: { "Authorization": token ? `Bearer ${token}` : void 0 },
1265
+ body: {
1266
+ email: token ? void 0 : emailOrPass,
1267
+ password: token ? emailOrPass : void 0
1268
+ }
1269
+ }).then(() => {
1270
+ });
1271
+ }
1272
+ async session(token, set = false) {
1273
+ if (!token) token = this.api.token;
1274
+ const session = await this.api.request({
1275
+ url: "/api/auth/session",
1276
+ headers: token ? { "Authorization": `Bearer ${token}` } : void 0
1277
+ });
1278
+ if (set) {
1279
+ this.api.token = token;
1280
+ if (session == null ? void 0 : session.user) session.user.image = `${this.api.url}${session.user.image}?token=${this.api.token}`;
1281
+ this.user = (session == null ? void 0 : session.user) || null;
1282
+ if (session) this.emit("LOGIN", session.user);
1283
+ }
1284
+ return session;
1285
+ }
1286
+ async updatePassword(username, password, oldPassword) {
1287
+ return this.api.request({
1288
+ url: "/api/auth/password",
1289
+ body: { username, password, oldPassword }
1290
+ }).then((resp) => {
1291
+ if (resp == null ? void 0 : resp.token) this.api.token = resp.token;
1292
+ });
1293
+ }
1294
+ }
1295
+ class Data extends P {
1296
+ constructor(api) {
1297
+ super();
1298
+ __publicField(this, "api");
1299
+ this.api = typeof api == "string" ? new Api(api) : api;
1300
+ }
1301
+ delete(collection, document2) {
1302
+ return this.api.request({
1303
+ url: `/api/data/${collection}/${document2}`,
1304
+ method: "DELETE"
1305
+ }).then(() => this.emit("DELETE", collection, document2));
1306
+ }
1307
+ get(collection, document2) {
1308
+ return this.api.request({ url: `/api/data/${collection}${document2 ? `/${document2}` : ""}` }).then((resp) => {
1309
+ this.emit("GET", collection, resp);
1310
+ return resp;
1311
+ });
1312
+ }
1313
+ raw(collection, operand, query, options) {
1314
+ return this.api.request({
1315
+ url: `/api/data/${collection}`,
1316
+ body: {
1317
+ operand,
1318
+ query,
1319
+ options
1320
+ }
1321
+ }).then((resp) => {
1322
+ this.emit("RAW", collection, resp);
1323
+ return resp;
1324
+ });
1325
+ }
1326
+ set(collection, document2, append = false) {
1327
+ return this.api.request({
1328
+ url: `/api/data/${collection}/${document2._id || ""}`,
1329
+ method: append ? "PATCH" : "POST",
1330
+ body: document2
1331
+ }).then((resp) => {
1332
+ this.emit("SET", collection, resp);
1333
+ return resp;
1334
+ });
1335
+ }
1336
+ }
1337
+ class Email extends P {
1338
+ constructor(api) {
1339
+ super();
1340
+ __publicField(this, "api");
1341
+ this.api = typeof api == "string" ? new Api(api) : api;
1342
+ }
1343
+ send(email) {
1344
+ let url = "/api/email";
1345
+ if (typeof email.body == "object") url += `/${email.body.template}`;
1346
+ return this.api.request({ url, body: email }).then((resp) => {
1347
+ this.emit("SENT", email);
1348
+ return resp;
1349
+ });
1350
+ }
1351
+ }
1352
+ class Groups extends P {
1353
+ constructor(api) {
1354
+ super();
1355
+ __publicField(this, "api");
1356
+ this.api = typeof api == "string" ? new Api(api) : api;
1357
+ }
1358
+ create(group) {
1359
+ return this.api.request({
1360
+ url: `/api/groups/${group.name}`,
1361
+ method: "POST",
1362
+ body: group
1363
+ }).then((resp) => {
1364
+ this.emit("CREATE", resp);
1365
+ return resp;
1366
+ });
1367
+ }
1368
+ list() {
1369
+ return this.api.request({ url: `/api/groups` }).then((resp) => {
1370
+ this.emit("LIST", resp || []);
1371
+ return resp;
1372
+ });
1373
+ }
1374
+ read(name) {
1375
+ return this.api.request({ url: `/api/groups/${name}` }).then((resp) => {
1376
+ this.emit("READ", resp);
1377
+ return resp;
1378
+ });
1379
+ }
1380
+ update(group) {
1381
+ return this.api.request({
1382
+ url: `/api/groups/${group.name}`,
1383
+ method: "PATCH",
1384
+ body: group
1385
+ }).then((resp) => {
1386
+ this.emit("UPDATE", resp);
1387
+ return resp;
1388
+ });
1389
+ }
1390
+ delete(name) {
1391
+ return this.api.request({
1392
+ url: `/api/groups/${name}`,
1393
+ method: "DELETE"
1394
+ }).then(() => this.emit("DELETE", name));
1395
+ }
1396
+ }
1397
+ class Logger {
1398
+ constructor(api, logLevel) {
1399
+ __publicField(this, "api");
1400
+ this.api = typeof api == "string" ? new Api(api) : api;
1401
+ if (logLevel != null && logLevel != "NONE") {
1402
+ window.addEventListener("error", (event) => this.error(event.error.stack));
1403
+ window.addEventListener("unhandledrejection", async (event) => this.error(event.reason.stack));
1404
+ }
1405
+ }
1406
+ buildLog(level, log) {
1407
+ return {
1408
+ time: (/* @__PURE__ */ new Date()).getTime(),
1409
+ level,
1410
+ log,
1411
+ ctx: {
1412
+ cores: navigator.hardwareConcurrency,
1413
+ mem: navigator == null ? void 0 : navigator.deviceMemory,
1414
+ res: [window.innerWidth, window.innerHeight],
1415
+ url: location.href
1416
+ }
1417
+ };
1418
+ }
1419
+ clearClientLogs() {
1420
+ return this.api.request({ url: `/api/logs/client`, method: "DELETE" });
1421
+ }
1422
+ clearServerLogs() {
1423
+ return this.api.request({ url: `/api/logs/server`, method: "DELETE" });
1424
+ }
1425
+ clientLogs(length, page) {
1426
+ const query = [length ? `length=${length}` : void 0, page ? `page=${page}` : void 0].filter((v2) => !!v2).join("&");
1427
+ return this.api.request({ url: `/api/logs/client${query ? `?${query}` : ""}` }).then((resp) => resp);
1428
+ }
1429
+ serverLogs(length, page) {
1430
+ const query = [length ? `length=${length}` : void 0, page ? `page=${page}` : void 0].filter((v2) => !!v2).join("&");
1431
+ return this.api.request({ url: `/api/logs/server${query ? `?${query}` : ""}` }).then((resp) => resp);
1432
+ }
1433
+ debug(...logs) {
1434
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(et.DEBUG, logs) }).then(() => {
1435
+ }).catch(() => {
1436
+ });
1437
+ }
1438
+ log(...logs) {
1439
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(et.LOG, logs) }).then(() => {
1440
+ }).catch(() => {
1441
+ });
1442
+ }
1443
+ info(...logs) {
1444
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(et.INFO, logs) }).then(() => {
1445
+ }).catch(() => {
1446
+ });
1447
+ }
1448
+ warn(...logs) {
1449
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(et.WARN, logs) }).then(() => {
1450
+ }).catch(() => {
1451
+ });
1452
+ }
1453
+ error(...logs) {
1454
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(et.ERROR, logs) }).then(() => {
1455
+ }).catch(() => {
1456
+ });
1457
+ }
1458
+ }
1459
+ class Payments extends P {
1460
+ constructor(api, secret) {
1461
+ super();
1462
+ __publicField(this, "api");
1463
+ __publicField(this, "stripe");
1464
+ this.api = typeof api == "string" ? new Api(api) : api;
1465
+ const setup = (retry = 1) => {
1466
+ try {
1467
+ if (!Stripe) throw new Error("Stripe not added");
1468
+ this.stripe = Stripe(secret);
1469
+ } catch (err) {
1470
+ if (retry > 0) setTimeout(() => setup(retry--), 250);
1471
+ else console.warn("Stripe failed, did you add the library & setup your API key?", err);
1472
+ }
1473
+ };
1474
+ setup();
1475
+ }
1476
+ async charge(amount, custom = {}) {
1477
+ this.emit("CHECKOUT", amount, custom);
1478
+ const request = await this.api.request({ url: "/api/payments", body: {
1479
+ amount,
1480
+ custom
1481
+ } });
1482
+ return request.data.clientSecret;
1483
+ }
1484
+ async createForm(element, amount, custom) {
1485
+ const token = await this.charge(amount, custom);
1486
+ const form = this.stripe.elements({ clientSecret: token });
1487
+ form.create("payment").mount(element);
1488
+ return () => this.stripe.confirmPayment({
1489
+ elements: form,
1490
+ redirect: "if_required",
1491
+ confirmParams: { return_url: location.origin }
1492
+ });
1493
+ }
1494
+ async history(username) {
1495
+ const history = await this.api.request({ url: `/api/payments${username ? `/${username}` : ""}` });
1496
+ this.emit("LIST", username || null, history);
1497
+ return history;
1498
+ }
1499
+ }
1500
+ class Pdf extends P {
1501
+ constructor(api) {
1502
+ super();
1503
+ __publicField(this, "api");
1504
+ this.api = typeof api == "string" ? new Api(api) : api;
1505
+ }
1506
+ async handleResponse(resp, fileName) {
1507
+ const blob = await resp.blob();
1508
+ if (fileName) {
1509
+ const url = URL.createObjectURL(blob);
1510
+ V(url, fileName.endsWith(".pdf") ? fileName : fileName + ".pdf");
1511
+ URL.revokeObjectURL(url);
1512
+ }
1513
+ this.emit("CREATE", blob);
1514
+ return blob;
1515
+ }
1516
+ fromHtml(content, opts = {}) {
1517
+ return this.api.request({ url: `/api/pdf`, body: { html: content } }).then((resp) => this.handleResponse(resp, opts.download ? opts.fileName || (/* @__PURE__ */ new Date()).toISOString() : void 0));
1518
+ }
1519
+ fromTemplate(template, data, opts = {}) {
1520
+ return this.api.request({ url: `/api/pdf${template}`, body: data }).then((resp) => this.handleResponse(resp, opts.download ? opts.fileName || (/* @__PURE__ */ new Date()).toISOString() : void 0));
1521
+ }
1522
+ fromUrl(url, opts = {}) {
1523
+ return this.api.request({ url: `/api/pdf?url=${url}` }).then((resp) => this.handleResponse(resp, opts.download ? opts.fileName || (/* @__PURE__ */ new Date()).toISOString() : void 0));
1524
+ }
1525
+ }
1526
+ const _Socket = class _Socket {
1527
+ constructor(api) {
1528
+ __publicField(this, "api");
1529
+ __publicField(this, "url");
1530
+ __publicField(this, "connection");
1531
+ __publicField(this, "open", false);
1532
+ this.api = typeof api == "string" ? new Api(api) : api;
1533
+ this.url = this.api.url.replace("http", "ws");
1534
+ this.api.on("TOKEN", () => this.connect());
1535
+ this.connect();
1536
+ }
1537
+ close() {
1538
+ console.debug("Disconnected from Momentum");
1539
+ this.open = false;
1540
+ this.connection.close();
1541
+ }
1542
+ connect(retry = 3) {
1543
+ var _a;
1544
+ if (((_a = this.connection) == null ? void 0 : _a.readyState) < 2) this.connection.close();
1545
+ this.connection = new WebSocket(this.url + (this.api.token ? `?token=${this.api.token}` : ""));
1546
+ const timeout = setTimeout(() => {
1547
+ if (this.open) return;
1548
+ this.connection.close();
1549
+ console.error(`Momentum connection timeout`);
1550
+ if (retry > 0) this.connect(retry - 1);
1551
+ }, _Socket.timeout);
1552
+ this.connection.onclose = () => this.open = false;
1553
+ this.connection.onmessage = this.handle;
1554
+ this.connection.onopen = () => {
1555
+ this.open = true;
1556
+ clearTimeout(timeout);
1557
+ console.debug("Connected to Momentum");
1558
+ };
1559
+ }
1560
+ handle(...args) {
1561
+ console.log(args);
1562
+ }
1563
+ send(channel, payload) {
1564
+ this.connection.send(JSON.stringify({
1565
+ token: this.api.token,
1566
+ channel,
1567
+ payload
1568
+ }));
1569
+ }
1570
+ };
1571
+ __publicField(_Socket, "timeout", 1e4);
1572
+ let Socket = _Socket;
1573
+ class Storage extends P {
1574
+ constructor(api) {
1575
+ super();
1576
+ __publicField(this, "api");
1577
+ this.api = typeof api == "string" ? new Api(api) : api;
1578
+ }
1579
+ delete(path) {
1580
+ const url = (path.startsWith("/api/storage/") ? path : "/api/storage/" + path).replaceAll("//", "/");
1581
+ return this.api.request({ url, method: "DELETE" }).then(() => {
1582
+ this.emit("DELETE", url);
1583
+ });
1584
+ }
1585
+ list(path) {
1586
+ const url = (path.startsWith("/api/storage/") ? path : "/api/storage/" + path).replaceAll("//", "/");
1587
+ return this.api.request({ url: url + "?list" }).then((resp) => {
1588
+ this.emit("LIST", path, resp);
1589
+ return resp;
1590
+ });
1591
+ }
1592
+ open(path, target = "_blank") {
1593
+ const p2 = (path.startsWith("/api/storage/") ? path : "/api/storage/" + path).replaceAll(/\/{2,}/g, "/");
1594
+ const link = `${this.api.url}${p2}${this.api.token ? `?token=${this.api.token}` : ""}`;
1595
+ if (!target) return link;
1596
+ this.emit("OPEN", path);
1597
+ return window.open(link, target);
1598
+ }
1599
+ mkdir(path) {
1600
+ const p2 = (path.startsWith("/api/storage/") ? path : "/api/storage/" + path).replaceAll(/\/{2,}/g, "/");
1601
+ return this.api.request({ url: p2 + "?directory", method: "POST" });
1602
+ }
1603
+ download(path, opts = {}) {
1604
+ const p2 = ("/api/storage/" + path).replaceAll("//", "/");
1605
+ return this.api.request({ ...opts, url: p2, decode: false }).then(async (response) => {
1606
+ const blob = await response.blob();
1607
+ const name = opts.downloadAs || new URL(path).pathname.split("/").pop();
1608
+ this.emit("DOWNLOAD", path, blob);
1609
+ wt(blob, name);
1610
+ return response;
1611
+ });
1612
+ }
1613
+ upload(files, opts = "") {
1614
+ return new E(async (res, rej, prog) => {
1615
+ if (!files) files = await xt();
1616
+ if (!files || Array.isArray(files) && !files.length) return [];
1617
+ const url = this.api.url + ("/api/storage/" + (typeof opts == "string" ? opts : opts == null ? void 0 : opts.path)).replaceAll("//", "/");
1618
+ return At({
1619
+ url,
1620
+ files: Array.isArray(files) ? files : [files],
1621
+ headers: this.api.headers
1622
+ }).onProgress((p2) => {
1623
+ prog(p2);
1624
+ }).then((resp) => {
1625
+ this.emit("UPLOAD", resp);
1626
+ res(resp);
1627
+ }).catch((err) => rej(err));
1628
+ });
1629
+ }
1630
+ }
1631
+ class UI {
1632
+ constructor(settings) {
1633
+ this.settings = settings;
1634
+ }
1635
+ async inject(reload = false) {
1636
+ if (!Object.keys(this.settings.cache).length || reload) await this.settings.list();
1637
+ window.document.body.classList.add(this.settings.cache.theme.darkMode ? "theme-dark" : "theme-light");
1638
+ window.document.body.classList.remove(this.settings.cache.theme.darkMode ? "theme-light" : "theme-dark");
1639
+ if (this.settings.cache.title)
1640
+ window.document.querySelectorAll(".momentum-title").forEach((el) => el.innerText = this.settings.cache.title);
1641
+ if (this.settings.cache.description)
1642
+ window.document.querySelectorAll(".momentum-description").forEach((el) => el.innerText = this.settings.cache.description);
1643
+ if (this.settings.cache.version)
1644
+ window.document.querySelectorAll(".momentum-version").forEach((el) => el.innerText = this.settings.cache.version);
1645
+ if (this.settings.cache.logo) {
1646
+ window.document.querySelectorAll(".momentum-logo").forEach((el) => {
1647
+ el.src = this.settings.cache.logo;
1648
+ el.href = this.settings.cache.logo;
1649
+ });
1650
+ }
1651
+ if (this.settings.cache.theme) {
1652
+ let style = window.document.querySelector("#momentum-theme");
1653
+ if (!style) {
1654
+ style = window.document.createElement("style");
1655
+ style.id = "momentum-theme";
1656
+ window.document.head.append(style);
1657
+ }
1658
+ style.innerHTML = `
1659
+ :root {
1660
+ --theme-bg-primary: ${this.settings.cache.theme.background};
1661
+ --theme-bg-secondary: ${this.settings.cache.theme.darkMode ? "#2e2e2e" : "#ffffff"};
1662
+ --theme-primary: ${this.settings.cache.theme.primary};
1663
+ --theme-secondary: ${this.settings.cache.theme.secondary};
1664
+ --theme-text: ${this.settings.cache.theme.darkMode ? "#ffffff" : "#000000"};
1665
+ --theme-muted: ${this.settings.cache.theme.darkMode ? "#cccccc" : "#6c757d"};
1666
+ }`;
1667
+ }
1668
+ if (this.settings.cache.pwa) {
1669
+ const link = window.document.createElement("link");
1670
+ link.setAttribute("rel", "manifest");
1671
+ link.setAttribute("href", this.settings.api.url + "/manifest.json");
1672
+ window.document.head.append(link);
1673
+ }
1674
+ }
1675
+ }
1676
+ class Users extends P {
1677
+ constructor(api) {
1678
+ super();
1679
+ __publicField(this, "api");
1680
+ __publicField(this, "listed", false);
1681
+ __publicField(this, "$cache", new BehaviorSubject([]));
1682
+ this.api = typeof api == "string" ? new Api(api) : api;
1683
+ }
1684
+ get cache() {
1685
+ return this.$cache.value;
1686
+ }
1687
+ set cache(val) {
1688
+ this.$cache.next(val);
1689
+ }
1690
+ delete(username) {
1691
+ return this.api.request({
1692
+ url: `/api/users/${username}`,
1693
+ method: "DELETE"
1694
+ }).then(() => {
1695
+ this.cache = this.cache.filter((u) => u.username != username);
1696
+ this.emit("DELETE", username);
1697
+ });
1698
+ }
1699
+ list(reload = false) {
1700
+ if (!reload && this.listed) return Promise.resolve(this.cache);
1701
+ return this.api.request({ url: `/api/users` }).then((resp) => {
1702
+ resp == null ? void 0 : resp.map((r) => {
1703
+ r.image = this.api.url + r.image + `?token=${this.api.token}`;
1704
+ return r;
1705
+ });
1706
+ this.cache = resp || [];
1707
+ this.listed = true;
1708
+ this.emit("LIST", resp || []);
1709
+ return resp;
1710
+ });
1711
+ }
1712
+ read(username, reload = false) {
1713
+ if (!reload) {
1714
+ const cached = this.cache.find((u) => u.username == username);
1715
+ if (cached) return Promise.resolve(cached);
1716
+ }
1717
+ return this.api.request({ url: `/api/users/${username}` }).then((resp) => {
1718
+ if (resp) {
1719
+ resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
1720
+ this.cache = [...this.cache.filter((u) => u.username != username), resp];
1721
+ }
1722
+ this.emit("READ", resp);
1723
+ return resp;
1724
+ });
1725
+ }
1726
+ update(user) {
1727
+ return this.api.request({
1728
+ url: `/api/users/${user.username}`,
1729
+ method: "PATCH",
1730
+ body: user
1731
+ }).then((resp) => {
1732
+ if (resp) {
1733
+ resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
1734
+ this.cache = this.cache.filter((u) => u.username != user.username).concat([resp]);
1735
+ }
1736
+ this.emit(user._id ? "UPDATE" : "CREATE", resp);
1737
+ return resp;
1738
+ });
1739
+ }
1740
+ uploadImage(username, file) {
1741
+ return At({
1742
+ url: this.api.url + `/api/users/${username}/image`,
1743
+ files: [file],
1744
+ headers: this.api.headers
1745
+ }).then((resp) => {
1746
+ this.emit("UPLOAD_IMAGE", username, file);
1747
+ return resp;
1748
+ });
1749
+ }
1750
+ }
1751
+ class Settings extends P {
1752
+ constructor(api) {
1753
+ super();
1754
+ __publicField(this, "api");
1755
+ __publicField(this, "$cache", new BehaviorSubject({}));
1756
+ this.api = typeof api == "string" ? new Api(api) : api;
1757
+ }
1758
+ get cache() {
1759
+ return this.$cache.value;
1760
+ }
1761
+ set cache(val) {
1762
+ this.$cache.next(val);
1763
+ }
1764
+ list(detailed = false) {
1765
+ return this.api.request({ url: `/api/settings` + (detailed ? "?detailed" : "") }).then((resp) => {
1766
+ this.cache = !detailed ? resp : Object.values(resp).reduce((acc, v2) => ({ ...acc, [v2.key]: v2.value }), {});
1767
+ this.emit("LIST", resp || []);
1768
+ return resp;
1769
+ });
1770
+ }
1771
+ delete(key) {
1772
+ return this.api.request({ url: `/api/settings/${key}`, method: "DELETE" }).then(() => {
1773
+ this.cache = { ...this.cache, [key]: void 0 };
1774
+ this.emit("DELETE", key);
1775
+ });
1776
+ }
1777
+ read(key, reload = false) {
1778
+ if (!reload && this.cache[key]) return Promise.resolve(this.cache[key]);
1779
+ return this.api.request({ url: `/api/settings/${key}` }).then((variable) => {
1780
+ if (variable) this.cache = { ...this.cache, [variable.key]: variable };
1781
+ this.emit("READ", variable);
1782
+ return variable;
1783
+ });
1784
+ }
1785
+ update(variable) {
1786
+ return this.api.request({ url: `/api/settings/${variable.key}`, body: variable }).then((variable2) => {
1787
+ if (variable2) this.cache = { ...this.cache, [variable2.key]: variable2.value };
1788
+ this.emit("UPDATE", variable2);
1789
+ return variable2;
1790
+ });
1791
+ }
1792
+ }
1793
+ class Static extends P {
1794
+ constructor(api) {
1795
+ super();
1796
+ __publicField(this, "api");
1797
+ this.api = typeof api == "string" ? new Api(api) : api;
1798
+ }
1799
+ delete(path) {
1800
+ return this.api.request({ url: `/api/static/${path}`, method: "DELETE" }).then(() => {
1801
+ this.emit("DELETE", path);
1802
+ });
1803
+ }
1804
+ list(path) {
1805
+ const url = ("/api/static/" + path).replaceAll("//", "/");
1806
+ return this.api.request({ url }).then((resp) => {
1807
+ this.emit("LIST", path, resp || []);
1808
+ return resp;
1809
+ });
1810
+ }
1811
+ upload(files, path = "/") {
1812
+ const data = new FormData();
1813
+ (Array.isArray(files) ? files : [files]).forEach((f) => data.append("file", f));
1814
+ return this.api.request({ url: "/api/static" + path, body: data }).then((resp) => {
1815
+ this.emit("UPLOAD", resp || []);
1816
+ return resp;
1817
+ });
1818
+ }
1819
+ }
1820
+ class Momentum extends P {
1821
+ constructor(url, opts) {
1822
+ super();
1823
+ __publicField(this, "api");
1824
+ __publicField(this, "actions");
1825
+ __publicField(this, "auth");
1826
+ __publicField(this, "data");
1827
+ __publicField(this, "email");
1828
+ __publicField(this, "groups");
1829
+ __publicField(this, "logger");
1830
+ __publicField(this, "payments");
1831
+ __publicField(this, "pdf");
1832
+ __publicField(this, "settings");
1833
+ __publicField(this, "socket");
1834
+ __publicField(this, "static");
1835
+ __publicField(this, "storage");
1836
+ __publicField(this, "ui");
1837
+ __publicField(this, "users");
1838
+ this.api = new Api(url, opts == null ? void 0 : opts.api);
1839
+ this.actions = new Actions(this.api);
1840
+ this.auth = new Auth(this.api, {
1841
+ persist: (opts == null ? void 0 : opts.persist) ?? true,
1842
+ loginUi: opts == null ? void 0 : opts.loginUi
1843
+ });
1844
+ this.data = new Data(this.api);
1845
+ this.email = new Email(this.api);
1846
+ this.groups = new Groups(this.api);
1847
+ this.logger = new Logger(this.api, opts == null ? void 0 : opts.logLevel);
1848
+ if (opts == null ? void 0 : opts.stripeSecret) this.payments = new Payments(this.api, opts.stripeSecret);
1849
+ this.pdf = new Pdf(this.api);
1850
+ this.settings = new Settings(this.api);
1851
+ if (opts == null ? void 0 : opts.socket) this.socket = new Socket(this.api);
1852
+ this.static = new Static(this.api);
1853
+ this.storage = new Storage(this.api);
1854
+ this.ui = new UI(this.settings);
1855
+ this.users = new Users(this.api);
1856
+ this.api.on("*", (event, ...args) => this.emit(`API::${event}`, ...args));
1857
+ this.actions.on("*", (event, ...args) => this.emit(`ACTIONS::${event}`, ...args));
1858
+ this.auth.on("*", (event, ...args) => this.emit(`AUTH::${event}`, ...args));
1859
+ this.data.on("*", (event, ...args) => this.emit(`DATA::${event}`, ...args));
1860
+ this.email.on("*", (event, ...args) => this.emit(`EMAIL::${event}`, ...args));
1861
+ this.groups.on("*", (event, ...args) => this.emit(`GROUPS::${event}`, ...args));
1862
+ if (this.payments) this.payments.on("*", (event, ...args) => this.emit(`PAYMENT::${event}`, ...args));
1863
+ this.pdf.on("*", (event, ...args) => this.emit(`PDF::${event}`, ...args));
1864
+ this.settings.on("*", (event, ...args) => this.emit(`SETTINGS::${event}`, ...args));
1865
+ this.static.on("*", (event, ...args) => this.emit(`STATIC::${event}`, ...args));
1866
+ this.storage.on("*", (event, ...args) => this.emit(`STORAGE::${event}`, ...args));
1867
+ this.users.on("*", (event, ...args) => this.emit(`USERS::${event}`, ...args));
1868
+ this.users.on("*", (event, ...args) => {
1869
+ var _a;
1870
+ if (Array.isArray(args[0])) {
1871
+ const u = args[0].find((u2) => {
1872
+ var _a2;
1873
+ return u2._id == ((_a2 = this.auth.user) == null ? void 0 : _a2._id);
1874
+ });
1875
+ if (u) this.auth.user = u;
1876
+ } else if (args[0]._id == ((_a = this.auth.user) == null ? void 0 : _a._id)) {
1877
+ this.auth.user = args[0];
1878
+ }
1879
+ });
1880
+ }
1881
+ }
1882
+ exports2.ActionType = ActionType;
1883
+ exports2.Actions = Actions;
1884
+ exports2.Api = Api;
1885
+ exports2.Auth = Auth;
1886
+ exports2.Data = Data;
1887
+ exports2.Email = Email;
1888
+ exports2.Groups = Groups;
1889
+ exports2.Logger = Logger;
1890
+ exports2.Momentum = Momentum;
1891
+ exports2.Payments = Payments;
1892
+ exports2.Pdf = Pdf;
1893
+ exports2.Settings = Settings;
1894
+ exports2.Socket = Socket;
1895
+ exports2.Static = Static;
1896
+ exports2.Storage = Storage;
1897
+ exports2.Totp = Totp;
1898
+ exports2.UI = UI;
1899
+ exports2.Users = Users;
1900
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
1901
+ });