@ztimson/momentum 0.47.0 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,40 +1,49 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- var st = Object.defineProperty;
5
- var it = (r, t, e) => t in r ? st(r, t, { enumerable: true, configurable: true, writable: true, value: e }) : r[t] = e;
6
- var c = (r, t, e) => it(r, typeof t != "symbol" ? t + "" : t, e);
7
- function ot(r, t = false) {
8
- if (r == null) throw new Error("Cannot clean a NULL value");
9
- return Array.isArray(r) ? r = r.filter((e) => e != null) : Object.entries(r).forEach(([e, n]) => {
10
- (t && n === void 0 || !t && n == null) && delete r[e];
11
- }), r;
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) => 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;
12
17
  }
13
- function O(r, t) {
14
- const e = typeof r, n = typeof t;
15
- return e != "object" || r == null || n != "object" || t == null ? e == "function" && n == "function" ? r.toString() == t.toString() : r === t : Object.keys(r).length != Object.keys(t).length ? false : Object.keys(r).every((i) => O(r[i], t[i]));
18
+ function isEqual(a, b) {
19
+ const ta = typeof a, tb = typeof b;
20
+ if (ta != "object" || a == null || (tb != "object" || b == null))
21
+ return ta == "function" && tb == "function" ? a.toString() == b.toString() : a === b;
22
+ const keys = Object.keys(a);
23
+ if (keys.length != Object.keys(b).length) return false;
24
+ return Object.keys(a).every((key) => isEqual(a[key], b[key]));
16
25
  }
17
- function I(r) {
26
+ function JSONAttemptParse(json) {
18
27
  try {
19
- return JSON.parse(r);
28
+ return JSON.parse(json);
20
29
  } catch {
21
- return r;
30
+ return json;
22
31
  }
23
32
  }
24
- function Ot(r, t) {
25
- let e = [];
26
- return JSON.stringify(r, (n, s) => {
27
- if (typeof s == "object" && s !== null) {
28
- if (e.includes(s)) return;
29
- e.push(s);
33
+ function JSONSanitize(obj, space) {
34
+ let cache = [];
35
+ return JSON.stringify(obj, (key, value) => {
36
+ if (typeof value === "object" && value !== null) {
37
+ if (cache.includes(value)) return;
38
+ cache.push(value);
30
39
  }
31
- return s;
32
- }, t);
40
+ return value;
41
+ }, space);
33
42
  }
34
- function m(r) {
35
- return Array.isArray(r) ? r : [r];
43
+ function makeArray(value) {
44
+ return Array.isArray(value) ? value : [value];
36
45
  }
37
- class S extends Array {
46
+ class ASet extends Array {
38
47
  /** Number of elements in set */
39
48
  get size() {
40
49
  return this.length;
@@ -43,118 +52,144 @@ class S extends Array {
43
52
  * Array to create set from, duplicate values will be removed
44
53
  * @param {T[]} elements Elements which will be added to set
45
54
  */
46
- constructor(t = []) {
47
- super(), t != null && t.forEach && t.forEach((e) => this.add(e));
55
+ constructor(elements = []) {
56
+ super();
57
+ if (!!(elements == null ? void 0 : elements["forEach"]))
58
+ elements.forEach((el) => this.add(el));
48
59
  }
49
60
  /**
50
61
  * Add elements to set if unique
51
62
  * @param items
52
63
  */
53
- add(...t) {
54
- t.filter((e) => !this.has(e)).forEach((e) => this.push(e));
64
+ add(...items) {
65
+ items.filter((el) => !this.has(el)).forEach((el) => this.push(el));
66
+ return this;
55
67
  }
56
68
  /**
57
69
  * Delete elements from set
58
70
  * @param items Elements that will be deleted
59
71
  */
60
- delete(...t) {
61
- t.forEach((e) => {
62
- const n = this.indexOf(e);
63
- n != -1 && this.slice(n, 1);
72
+ delete(...items) {
73
+ items.forEach((el) => {
74
+ const index = this.indexOf(el);
75
+ if (index != -1) this.splice(index, 1);
64
76
  });
77
+ return this;
65
78
  }
66
79
  /**
67
80
  * Create list of elements this set has which the comparison set does not
68
81
  * @param {ASet<T>} set Set to compare against
69
82
  * @return {ASet<T>} Different elements
70
83
  */
71
- difference(t) {
72
- return new S(this.filter((e) => !t.has(e)));
84
+ difference(set) {
85
+ return new ASet(this.filter((el) => !set.has(el)));
73
86
  }
74
87
  /**
75
88
  * Check if set includes element
76
89
  * @param {T} el Element to look for
77
90
  * @return {boolean} True if element was found, false otherwise
78
91
  */
79
- has(t) {
80
- return this.indexOf(t) != -1;
92
+ has(el) {
93
+ return this.indexOf(el) != -1;
94
+ }
95
+ /**
96
+ * Find index number of element, or -1 if it doesn't exist. Matches by equality not reference
97
+ *
98
+ * @param {T} search Element to find
99
+ * @param {number} fromIndex Starting index position
100
+ * @return {number} Element index number or -1 if missing
101
+ */
102
+ indexOf(search, fromIndex) {
103
+ return super.findIndex((el) => isEqual(el, search), fromIndex);
81
104
  }
82
105
  /**
83
106
  * Create list of elements this set has in common with the comparison set
84
107
  * @param {ASet<T>} set Set to compare against
85
108
  * @return {boolean} Set of common elements
86
109
  */
87
- intersection(t) {
88
- return new S(this.filter((e) => t.has(e)));
110
+ intersection(set) {
111
+ return new ASet(this.filter((el) => set.has(el)));
89
112
  }
90
113
  /**
91
114
  * Check if this set has no elements in common with the comparison set
92
115
  * @param {ASet<T>} set Set to compare against
93
116
  * @return {boolean} True if nothing in common, false otherwise
94
117
  */
95
- isDisjointFrom(t) {
96
- return this.intersection(t).size == 0;
118
+ isDisjointFrom(set) {
119
+ return this.intersection(set).size == 0;
97
120
  }
98
121
  /**
99
122
  * Check if all elements in this set are included in the comparison set
100
123
  * @param {ASet<T>} set Set to compare against
101
124
  * @return {boolean} True if all elements are included, false otherwise
102
125
  */
103
- isSubsetOf(t) {
104
- return this.findIndex((e) => !t.has(e)) == -1;
126
+ isSubsetOf(set) {
127
+ return this.findIndex((el) => !set.has(el)) == -1;
105
128
  }
106
129
  /**
107
130
  * Check if all elements from comparison set are included in this set
108
131
  * @param {ASet<T>} set Set to compare against
109
132
  * @return {boolean} True if all elements are included, false otherwise
110
133
  */
111
- isSuperset(t) {
112
- return t.findIndex((e) => !this.has(e)) == -1;
134
+ isSuperset(set) {
135
+ return set.findIndex((el) => !this.has(el)) == -1;
113
136
  }
114
137
  /**
115
138
  * Create list of elements that are only in one set but not both (XOR)
116
139
  * @param {ASet<T>} set Set to compare against
117
140
  * @return {ASet<T>} New set of unique elements
118
141
  */
119
- symmetricDifference(t) {
120
- return new S([...this.difference(t), ...t.difference(this)]);
142
+ symmetricDifference(set) {
143
+ return new ASet([...this.difference(set), ...set.difference(this)]);
121
144
  }
122
145
  /**
123
146
  * Create joined list of elements included in this & the comparison set
124
147
  * @param {ASet<T>} set Set join
125
148
  * @return {ASet<T>} New set of both previous sets combined
126
149
  */
127
- union(t) {
128
- return new S([...this, ...t]);
150
+ union(set) {
151
+ return new ASet([...this, ...set]);
129
152
  }
130
153
  }
131
- class Tt {
154
+ class Cache {
132
155
  /**
133
156
  * Create new cache
134
157
  *
135
158
  * @param {keyof T} key Default property to use as primary key
136
159
  * @param options
137
160
  */
138
- constructor(t, e = {}) {
139
- c(this, "store", {});
140
- c(this, "complete", false);
141
- c(this, "values", this.all());
142
- if (this.key = t, this.options = e, e.storageKey && !e.storage && (e.storage = localStorage), e.storageKey && e.storage) {
143
- const n = e.storage.getItem(e.storageKey);
144
- if (n)
161
+ constructor(key, options = {}) {
162
+ __publicField2(this, "store", {});
163
+ __publicField2(this, "complete", false);
164
+ __publicField2(this, "values", this.all());
165
+ this.key = key;
166
+ this.options = options;
167
+ if (options.storageKey && !options.storage && typeof Storage !== "undefined")
168
+ options.storage = localStorage;
169
+ if (options.storageKey && options.storage) {
170
+ const stored = options.storage.getItem(options.storageKey);
171
+ if (stored) {
145
172
  try {
146
- Object.assign(this.store, JSON.parse(n));
173
+ Object.assign(this.store, JSON.parse(stored));
147
174
  } catch {
148
175
  }
176
+ }
149
177
  }
150
178
  return new Proxy(this, {
151
- get: (n, s) => s in n ? n[s] : n.store[s],
152
- set: (n, s, i) => (s in n ? n[s] = i : n.store[s] = i, true)
179
+ get: (target, prop) => {
180
+ if (prop in target) return target[prop];
181
+ return target.store[prop];
182
+ },
183
+ set: (target, prop, value) => {
184
+ if (prop in target) target[prop] = value;
185
+ else target.store[prop] = value;
186
+ return true;
187
+ }
153
188
  });
154
189
  }
155
- getKey(t) {
190
+ getKey(value) {
156
191
  if (!this.key) throw new Error("No key defined");
157
- return t[this.key];
192
+ return value[this.key];
158
193
  }
159
194
  /**
160
195
  * Get all cached items
@@ -171,9 +206,10 @@ class Tt {
171
206
  * @param {number | undefined} ttl Override default expiry
172
207
  * @return {this}
173
208
  */
174
- add(t, e = this.ttl) {
175
- const n = this.getKey(t);
176
- return this.set(n, t, e), this;
209
+ add(value, ttl = this.ttl) {
210
+ const key = this.getKey(value);
211
+ this.set(key, value, ttl);
212
+ return this;
177
213
  }
178
214
  /**
179
215
  * Add several rows to the cache
@@ -182,8 +218,10 @@ class Tt {
182
218
  * @param complete Mark cache as complete & reliable, defaults to true
183
219
  * @return {this}
184
220
  */
185
- addAll(t, e = true) {
186
- return t.forEach((n) => this.add(n)), this.complete = e, this;
221
+ addAll(rows, complete = true) {
222
+ rows.forEach((r) => this.add(r));
223
+ this.complete = complete;
224
+ return this;
187
225
  }
188
226
  /**
189
227
  * Remove all keys from cache
@@ -196,8 +234,10 @@ class Tt {
196
234
  *
197
235
  * @param {K} key Item's primary key
198
236
  */
199
- delete(t) {
200
- delete this.store[t], this.options.storageKey && this.options.storage && this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
237
+ delete(key) {
238
+ delete this.store[key];
239
+ if (this.options.storageKey && this.options.storage)
240
+ this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
201
241
  }
202
242
  /**
203
243
  * Return cache as an array of key-value pairs
@@ -211,8 +251,8 @@ class Tt {
211
251
  * @param {K} key Key to lookup
212
252
  * @return {T} Cached item
213
253
  */
214
- get(t) {
215
- return this.store[t];
254
+ get(key) {
255
+ return this.store[key];
216
256
  }
217
257
  /**
218
258
  * Get a list of cached keys
@@ -238,326 +278,389 @@ class Tt {
238
278
  * @param {number | undefined} ttl Override default expiry in seconds
239
279
  * @return {this}
240
280
  */
241
- set(t, e, n = this.options.ttl) {
242
- return this.store[t] = e, this.options.storageKey && this.options.storage && this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store)), n && setTimeout(() => {
243
- this.complete = false, this.delete(t);
244
- }, n * 1e3), this;
281
+ set(key, value, ttl = this.options.ttl) {
282
+ this.store[key] = value;
283
+ if (this.options.storageKey && this.options.storage)
284
+ this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
285
+ if (ttl) setTimeout(() => {
286
+ this.complete = false;
287
+ this.delete(key);
288
+ }, ttl * 1e3);
289
+ return this;
245
290
  }
246
291
  }
247
- class x extends Promise {
248
- constructor(e) {
249
- super((n, s) => e(
250
- (i) => n(i),
251
- (i) => s(i),
252
- (i) => this.progress = i
292
+ class PromiseProgress extends Promise {
293
+ constructor(executor) {
294
+ super((resolve, reject) => executor(
295
+ (value) => resolve(value),
296
+ (reason) => reject(reason),
297
+ (progress) => this.progress = progress
253
298
  ));
254
- c(this, "listeners", []);
255
- c(this, "_progress", 0);
299
+ __publicField2(this, "listeners", []);
300
+ __publicField2(this, "_progress", 0);
256
301
  }
257
302
  get progress() {
258
303
  return this._progress;
259
304
  }
260
- set progress(e) {
261
- e != this._progress && (this._progress = e, this.listeners.forEach((n) => n(e)));
305
+ set progress(p) {
306
+ if (p == this._progress) return;
307
+ this._progress = p;
308
+ this.listeners.forEach((l) => l(p));
262
309
  }
263
- static from(e) {
264
- return e instanceof x ? e : new x((n, s) => e.then((...i) => n(...i)).catch((...i) => s(...i)));
310
+ static from(promise) {
311
+ if (promise instanceof PromiseProgress) return promise;
312
+ return new PromiseProgress((res, rej) => promise.then((...args) => res(...args)).catch((...args) => rej(...args)));
265
313
  }
266
- from(e) {
267
- const n = x.from(e);
268
- return this.onProgress((s) => n.progress = s), n;
314
+ from(promise) {
315
+ const newPromise = PromiseProgress.from(promise);
316
+ this.onProgress((p) => newPromise.progress = p);
317
+ return newPromise;
269
318
  }
270
- onProgress(e) {
271
- return this.listeners.push(e), this;
319
+ onProgress(callback) {
320
+ this.listeners.push(callback);
321
+ return this;
272
322
  }
273
- then(e, n) {
274
- const s = super.then(e, n);
275
- return this.from(s);
323
+ then(res, rej) {
324
+ const resp = super.then(res, rej);
325
+ return this.from(resp);
276
326
  }
277
- catch(e) {
278
- return this.from(super.catch(e));
327
+ catch(rej) {
328
+ return this.from(super.catch(rej));
279
329
  }
280
- finally(e) {
281
- return this.from(super.finally(e));
330
+ finally(res) {
331
+ return this.from(super.finally(res));
282
332
  }
283
333
  }
284
- function Dt(r, t) {
285
- r instanceof Blob || (r = new Blob(m(r)));
286
- const e = URL.createObjectURL(r);
287
- lt(e, t), URL.revokeObjectURL(e);
334
+ function downloadFile(blob, name) {
335
+ if (!(blob instanceof Blob)) blob = new Blob(makeArray(blob));
336
+ const url = URL.createObjectURL(blob);
337
+ downloadUrl(url, name);
338
+ URL.revokeObjectURL(url);
288
339
  }
289
- function lt(r, t) {
290
- const e = document.createElement("a");
291
- e.href = r, e.download = t || r.split("/").pop(), document.body.appendChild(e), e.click(), document.body.removeChild(e);
340
+ function downloadUrl(href, name) {
341
+ const a = document.createElement("a");
342
+ a.href = href;
343
+ a.download = name || href.split("/").pop();
344
+ document.body.appendChild(a);
345
+ a.click();
346
+ document.body.removeChild(a);
292
347
  }
293
- function Mt(r = {}) {
294
- return new Promise((t) => {
295
- const e = document.createElement("input");
296
- e.type = "file", e.accept = r.accept || "*", e.style.display = "none", e.multiple = !!r.multiple, e.onblur = e.onchange = async () => {
297
- t(Array.from(e.files)), e.remove();
298
- }, document.body.appendChild(e), e.click();
348
+ function fileBrowser(options = {}) {
349
+ return new Promise((res) => {
350
+ const input = document.createElement("input");
351
+ input.type = "file";
352
+ input.accept = options.accept || "*";
353
+ input.style.display = "none";
354
+ input.multiple = !!options.multiple;
355
+ input.onblur = input.onchange = async () => {
356
+ res(Array.from(input.files));
357
+ input.remove();
358
+ };
359
+ document.body.appendChild(input);
360
+ input.click();
299
361
  });
300
362
  }
301
- function kt(r, t = /* @__PURE__ */ new Date()) {
302
- (typeof t == "number" || typeof t == "string") && (t = new Date(t));
303
- const e = `${t.getFullYear()}-${(t.getMonth() + 1).toString().padStart(2, "0")}-${t.getDate().toString().padStart(2, "0")}_${t.getHours().toString().padStart(2, "0")}-${t.getMinutes().toString().padStart(2, "0")}-${t.getSeconds().toString().padStart(2, "0")}`;
304
- return e;
363
+ function timestampFilename(name, date = /* @__PURE__ */ new Date()) {
364
+ if (typeof date == "number" || typeof date == "string") date = new Date(date);
365
+ const timestamp = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}_${date.getHours().toString().padStart(2, "0")}-${date.getMinutes().toString().padStart(2, "0")}-${date.getSeconds().toString().padStart(2, "0")}`;
366
+ return timestamp;
305
367
  }
306
- function Pt(r) {
307
- return new x((t, e, n) => {
308
- const s = new XMLHttpRequest(), i = new FormData();
309
- r.files.forEach((o) => i.append("file", o)), s.withCredentials = !!r.withCredentials, s.upload.addEventListener("progress", (o) => o.lengthComputable ? n(o.loaded / o.total) : null), s.addEventListener("loadend", () => t(I(s.responseText))), s.addEventListener("error", () => e(I(s.responseText))), s.addEventListener("timeout", () => e({ error: "Request timed out" })), s.open("POST", r.url), Object.entries(r.headers || {}).forEach(([o, a]) => s.setRequestHeader(o, a)), s.send(i);
368
+ function uploadWithProgress(options) {
369
+ return new PromiseProgress((res, rej, prog) => {
370
+ const xhr = new XMLHttpRequest();
371
+ const formData2 = new FormData();
372
+ options.files.forEach((f) => formData2.append("file", f));
373
+ xhr.withCredentials = !!options.withCredentials;
374
+ xhr.upload.addEventListener("progress", (event) => event.lengthComputable ? prog(event.loaded / event.total) : null);
375
+ xhr.addEventListener("loadend", () => res(JSONAttemptParse(xhr.responseText)));
376
+ xhr.addEventListener("error", () => rej(JSONAttemptParse(xhr.responseText)));
377
+ xhr.addEventListener("timeout", () => rej({ error: "Request timed out" }));
378
+ xhr.open("POST", options.url);
379
+ Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
380
+ xhr.send(formData2);
310
381
  });
311
382
  }
312
- class K {
383
+ class TypedEmitter {
313
384
  constructor() {
314
- c(this, "listeners", {});
315
- }
316
- static emit(t, ...e) {
317
- (this.listeners["*"] || []).forEach((n) => n(t, ...e)), (this.listeners[t.toString()] || []).forEach((n) => n(...e));
385
+ __publicField2(this, "listeners", {});
318
386
  }
319
- static off(t, e) {
320
- const n = t.toString();
321
- this.listeners[n] = (this.listeners[n] || []).filter((s) => s === e);
387
+ static emit(event, ...args) {
388
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
389
+ (this.listeners[event.toString()] || []).forEach((l) => l(...args));
322
390
  }
323
- static on(t, e) {
324
- var s;
325
- const n = t.toString();
326
- return this.listeners[n] || (this.listeners[n] = []), (s = this.listeners[n]) == null || s.push(e), () => this.off(t, e);
391
+ static off(event, listener) {
392
+ const e = event.toString();
393
+ this.listeners[e] = (this.listeners[e] || []).filter((l) => l === listener);
327
394
  }
328
- static once(t, e) {
329
- return new Promise((n) => {
330
- const s = this.on(t, (...i) => {
331
- n(i.length == 1 ? i[0] : i), e && e(...i), s();
395
+ static on(event, listener) {
396
+ var _a;
397
+ const e = event.toString();
398
+ if (!this.listeners[e]) this.listeners[e] = [];
399
+ (_a = this.listeners[e]) == null ? void 0 : _a.push(listener);
400
+ return () => this.off(event, listener);
401
+ }
402
+ static once(event, listener) {
403
+ return new Promise((res) => {
404
+ const unsubscribe = this.on(event, (...args) => {
405
+ res(args.length == 1 ? args[0] : args);
406
+ if (listener) listener(...args);
407
+ unsubscribe();
332
408
  });
333
409
  });
334
410
  }
335
- emit(t, ...e) {
336
- (this.listeners["*"] || []).forEach((n) => n(t, ...e)), (this.listeners[t] || []).forEach((n) => n(...e));
337
- }
338
- off(t, e) {
339
- this.listeners[t] = (this.listeners[t] || []).filter((n) => n === e);
411
+ emit(event, ...args) {
412
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
413
+ (this.listeners[event] || []).forEach((l) => l(...args));
340
414
  }
341
- on(t, e) {
342
- var n;
343
- return this.listeners[t] || (this.listeners[t] = []), (n = this.listeners[t]) == null || n.push(e), () => this.off(t, e);
415
+ off(event, listener) {
416
+ this.listeners[event] = (this.listeners[event] || []).filter((l) => l === listener);
344
417
  }
345
- once(t, e) {
346
- return new Promise((n) => {
347
- const s = this.on(t, (...i) => {
348
- n(i.length == 1 ? i[0] : i), e && e(...i), s();
418
+ on(event, listener) {
419
+ var _a;
420
+ if (!this.listeners[event]) this.listeners[event] = [];
421
+ (_a = this.listeners[event]) == null ? void 0 : _a.push(listener);
422
+ return () => this.off(event, listener);
423
+ }
424
+ once(event, listener) {
425
+ return new Promise((res) => {
426
+ const unsubscribe = this.on(event, (...args) => {
427
+ res(args.length == 1 ? args[0] : args);
428
+ if (listener) listener(...args);
429
+ unsubscribe();
349
430
  });
350
431
  });
351
432
  }
352
433
  }
353
- c(K, "listeners", {});
354
- class g extends Error {
355
- constructor(e, n) {
356
- super(e);
357
- c(this, "_code");
358
- n != null && (this._code = n);
434
+ __publicField2(TypedEmitter, "listeners", {});
435
+ class CustomError extends Error {
436
+ constructor(message, code) {
437
+ super(message);
438
+ __publicField2(this, "_code");
439
+ if (code != null) this._code = code;
359
440
  }
360
441
  get code() {
361
442
  return this._code || this.constructor.code;
362
443
  }
363
- set code(e) {
364
- this._code = e;
444
+ set code(c) {
445
+ this._code = c;
365
446
  }
366
- static from(e) {
367
- const n = Number(e.statusCode) ?? Number(e.code), s = new this(e.message || e.toString());
368
- return Object.assign(s, {
369
- stack: e.stack,
370
- ...e,
371
- code: n ?? void 0
447
+ static from(err) {
448
+ const code = Number(err.statusCode) ?? Number(err.code);
449
+ const newErr = new this(err.message || err.toString());
450
+ return Object.assign(newErr, {
451
+ stack: err.stack,
452
+ ...err,
453
+ code: code ?? void 0
372
454
  });
373
455
  }
374
- static instanceof(e) {
375
- return e.constructor.code != null;
456
+ static instanceof(err) {
457
+ return err.constructor.code != void 0;
376
458
  }
377
459
  toString() {
378
460
  return this.message || super.toString();
379
461
  }
380
462
  }
381
- c(g, "code", 500);
382
- class W extends g {
383
- constructor(t = "Bad Request") {
384
- super(t);
463
+ __publicField2(CustomError, "code", 500);
464
+ class BadRequestError extends CustomError {
465
+ constructor(message = "Bad Request") {
466
+ super(message);
385
467
  }
386
- static instanceof(t) {
387
- return t.constructor.code == this.code;
468
+ static instanceof(err) {
469
+ return err.constructor.code == this.code;
388
470
  }
389
471
  }
390
- c(W, "code", 400);
391
- class v extends g {
392
- constructor(t = "Unauthorized") {
393
- super(t);
472
+ __publicField2(BadRequestError, "code", 400);
473
+ class UnauthorizedError extends CustomError {
474
+ constructor(message = "Unauthorized") {
475
+ super(message);
394
476
  }
395
- static instanceof(t) {
396
- return t.constructor.code == this.code;
477
+ static instanceof(err) {
478
+ return err.constructor.code == this.code;
397
479
  }
398
480
  }
399
- c(v, "code", 401);
400
- class J extends g {
401
- constructor(t = "Payment Required") {
402
- super(t);
481
+ __publicField2(UnauthorizedError, "code", 401);
482
+ class PaymentRequiredError extends CustomError {
483
+ constructor(message = "Payment Required") {
484
+ super(message);
403
485
  }
404
- static instanceof(t) {
405
- return t.constructor.code == this.code;
486
+ static instanceof(err) {
487
+ return err.constructor.code == this.code;
406
488
  }
407
489
  }
408
- c(J, "code", 402);
409
- class z extends g {
410
- constructor(t = "Forbidden") {
411
- super(t);
490
+ __publicField2(PaymentRequiredError, "code", 402);
491
+ class ForbiddenError extends CustomError {
492
+ constructor(message = "Forbidden") {
493
+ super(message);
412
494
  }
413
- static instanceof(t) {
414
- return t.constructor.code == this.code;
495
+ static instanceof(err) {
496
+ return err.constructor.code == this.code;
415
497
  }
416
498
  }
417
- c(z, "code", 403);
418
- class Z extends g {
419
- constructor(t = "Not Found") {
420
- super(t);
499
+ __publicField2(ForbiddenError, "code", 403);
500
+ class NotFoundError extends CustomError {
501
+ constructor(message = "Not Found") {
502
+ super(message);
421
503
  }
422
- static instanceof(t) {
423
- return t.constructor.code == this.code;
504
+ static instanceof(err) {
505
+ return err.constructor.code == this.code;
424
506
  }
425
507
  }
426
- c(Z, "code", 404);
427
- class V extends g {
428
- constructor(t = "Method Not Allowed") {
429
- super(t);
508
+ __publicField2(NotFoundError, "code", 404);
509
+ class MethodNotAllowedError extends CustomError {
510
+ constructor(message = "Method Not Allowed") {
511
+ super(message);
430
512
  }
431
- static instanceof(t) {
432
- return t.constructor.code == this.code;
513
+ static instanceof(err) {
514
+ return err.constructor.code == this.code;
433
515
  }
434
516
  }
435
- c(V, "code", 405);
436
- class X extends g {
437
- constructor(t = "Not Acceptable") {
438
- super(t);
517
+ __publicField2(MethodNotAllowedError, "code", 405);
518
+ class NotAcceptableError extends CustomError {
519
+ constructor(message = "Not Acceptable") {
520
+ super(message);
439
521
  }
440
- static instanceof(t) {
441
- return t.constructor.code == this.code;
522
+ static instanceof(err) {
523
+ return err.constructor.code == this.code;
442
524
  }
443
525
  }
444
- c(X, "code", 406);
445
- class Q extends g {
446
- constructor(t = "Internal Server Error") {
447
- super(t);
526
+ __publicField2(NotAcceptableError, "code", 406);
527
+ class InternalServerError extends CustomError {
528
+ constructor(message = "Internal Server Error") {
529
+ super(message);
448
530
  }
449
- static instanceof(t) {
450
- return t.constructor.code == this.code;
531
+ static instanceof(err) {
532
+ return err.constructor.code == this.code;
451
533
  }
452
534
  }
453
- c(Q, "code", 500);
454
- class _ extends g {
455
- constructor(t = "Not Implemented") {
456
- super(t);
535
+ __publicField2(InternalServerError, "code", 500);
536
+ class NotImplementedError extends CustomError {
537
+ constructor(message = "Not Implemented") {
538
+ super(message);
457
539
  }
458
- static instanceof(t) {
459
- return t.constructor.code == this.code;
540
+ static instanceof(err) {
541
+ return err.constructor.code == this.code;
460
542
  }
461
543
  }
462
- c(_, "code", 501);
463
- class tt extends g {
464
- constructor(t = "Bad Gateway") {
465
- super(t);
544
+ __publicField2(NotImplementedError, "code", 501);
545
+ class BadGatewayError extends CustomError {
546
+ constructor(message = "Bad Gateway") {
547
+ super(message);
466
548
  }
467
- static instanceof(t) {
468
- return t.constructor.code == this.code;
549
+ static instanceof(err) {
550
+ return err.constructor.code == this.code;
469
551
  }
470
552
  }
471
- c(tt, "code", 502);
472
- class et extends g {
473
- constructor(t = "Service Unavailable") {
474
- super(t);
553
+ __publicField2(BadGatewayError, "code", 502);
554
+ class ServiceUnavailableError extends CustomError {
555
+ constructor(message = "Service Unavailable") {
556
+ super(message);
475
557
  }
476
- static instanceof(t) {
477
- return t.constructor.code == this.code;
558
+ static instanceof(err) {
559
+ return err.constructor.code == this.code;
478
560
  }
479
561
  }
480
- c(et, "code", 503);
481
- class rt extends g {
482
- constructor(t = "Gateway Timeout") {
483
- super(t);
562
+ __publicField2(ServiceUnavailableError, "code", 503);
563
+ class GatewayTimeoutError extends CustomError {
564
+ constructor(message = "Gateway Timeout") {
565
+ super(message);
484
566
  }
485
- static instanceof(t) {
486
- return t.constructor.code == this.code;
567
+ static instanceof(err) {
568
+ return err.constructor.code == this.code;
487
569
  }
488
570
  }
489
- c(rt, "code", 504);
490
- const E = class E2 {
491
- constructor(t = {}) {
492
- c(this, "interceptors", {});
493
- c(this, "headers", {});
494
- c(this, "url");
495
- this.url = t.url ?? null, this.headers = t.headers || {}, t.interceptors && t.interceptors.forEach((e) => E2.addInterceptor(e));
496
- }
497
- static addInterceptor(t) {
498
- const e = Object.keys(E2.interceptors).length.toString();
499
- return E2.interceptors[e] = t, () => {
500
- E2.interceptors[e] = null;
571
+ __publicField2(GatewayTimeoutError, "code", 504);
572
+ const _Http = class _Http2 {
573
+ constructor(defaults = {}) {
574
+ __publicField2(this, "interceptors", {});
575
+ __publicField2(this, "headers", {});
576
+ __publicField2(this, "url");
577
+ this.url = defaults.url ?? null;
578
+ this.headers = defaults.headers || {};
579
+ if (defaults.interceptors) {
580
+ defaults.interceptors.forEach((i) => _Http2.addInterceptor(i));
581
+ }
582
+ }
583
+ static addInterceptor(fn) {
584
+ const key = Object.keys(_Http2.interceptors).length.toString();
585
+ _Http2.interceptors[key] = fn;
586
+ return () => {
587
+ _Http2.interceptors[key] = null;
501
588
  };
502
589
  }
503
- addInterceptor(t) {
504
- const e = Object.keys(this.interceptors).length.toString();
505
- return this.interceptors[e] = t, () => {
506
- this.interceptors[e] = null;
590
+ addInterceptor(fn) {
591
+ const key = Object.keys(this.interceptors).length.toString();
592
+ this.interceptors[key] = fn;
593
+ return () => {
594
+ this.interceptors[key] = null;
507
595
  };
508
596
  }
509
- request(t = {}) {
510
- var s;
511
- if (!this.url && !t.url) throw new Error("URL needs to be set");
512
- let e = ((s = t.url) != null && s.startsWith("http") ? t.url : (this.url || "") + (t.url || "")).replace(/([^:]\/)\/+/g, "$1");
513
- if (t.fragment && (e.includes("#") ? e.replace(/#.*(\?|\n)/g, (i, o) => `#${t.fragment}${o}`) : e += "#" + t.fragment), t.query) {
514
- const i = Array.isArray(t.query) ? t.query : Object.keys(t.query).map((o) => ({ key: o, value: t.query[o] }));
515
- e += (e.includes("?") ? "&" : "?") + i.map((o) => `${o.key}=${o.value}`).join("&");
597
+ request(opts = {}) {
598
+ var _a;
599
+ if (!this.url && !opts.url) throw new Error("URL needs to be set");
600
+ let url = (((_a = opts.url) == null ? void 0 : _a.startsWith("http")) ? opts.url : (this.url || "") + (opts.url || "")).replace(/([^:]\/)\/+/g, "$1");
601
+ if (opts.fragment) url.includes("#") ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : url += "#" + opts.fragment;
602
+ if (opts.query) {
603
+ const q = Array.isArray(opts.query) ? opts.query : Object.keys(opts.query).map((k) => ({ key: k, value: opts.query[k] }));
604
+ url += (url.includes("?") ? "&" : "?") + q.map((q2) => `${q2.key}=${q2.value}`).join("&");
516
605
  }
517
- const n = ot({
518
- "Content-Type": t.body ? t.body instanceof FormData ? "multipart/form-data" : "application/json" : void 0,
519
- ...E2.headers,
606
+ const headers = clean({
607
+ "Content-Type": !opts.body ? void 0 : opts.body instanceof FormData ? "multipart/form-data" : "application/json",
608
+ ..._Http2.headers,
520
609
  ...this.headers,
521
- ...t.headers
610
+ ...opts.headers
522
611
  });
523
- return typeof t.body == "object" && t.body != null && n["Content-Type"] == "application/json" && (t.body = JSON.stringify(t.body)), new x((i, o, a) => {
612
+ if (typeof opts.body == "object" && opts.body != null && headers["Content-Type"] == "application/json")
613
+ opts.body = JSON.stringify(opts.body);
614
+ return new PromiseProgress((res, rej, prog) => {
524
615
  try {
525
- fetch(e, {
526
- headers: n,
527
- method: t.method || (t.body ? "POST" : "GET"),
528
- body: t.body
529
- }).then(async (u) => {
530
- var G, U;
531
- for (let l of [...Object.values(E2.interceptors), ...Object.values(this.interceptors)])
532
- await new Promise((C) => l(u, () => C()));
533
- const $ = u.headers.get("Content-Length"), j = $ ? parseInt($, 10) : 0;
534
- let P = 0;
535
- const T = (G = u.body) == null ? void 0 : G.getReader(), nt = new ReadableStream({
536
- start(l) {
537
- function C() {
538
- T == null || T.read().then((A) => {
539
- if (A.done) return l.close();
540
- P += A.value.byteLength, a(P / j), l.enqueue(A.value), C();
541
- }).catch((A) => l.error(A));
616
+ fetch(url, {
617
+ headers,
618
+ method: opts.method || (opts.body ? "POST" : "GET"),
619
+ body: opts.body
620
+ }).then(async (resp) => {
621
+ var _a2, _b;
622
+ for (let fn of [...Object.values(_Http2.interceptors), ...Object.values(this.interceptors)]) {
623
+ await new Promise((res2) => fn(resp, () => res2()));
624
+ }
625
+ const contentLength = resp.headers.get("Content-Length");
626
+ const total = contentLength ? parseInt(contentLength, 10) : 0;
627
+ let loaded = 0;
628
+ const reader = (_a2 = resp.body) == null ? void 0 : _a2.getReader();
629
+ const stream = new ReadableStream({
630
+ start(controller) {
631
+ function push() {
632
+ reader == null ? void 0 : reader.read().then((event) => {
633
+ if (event.done) return controller.close();
634
+ loaded += event.value.byteLength;
635
+ prog(loaded / total);
636
+ controller.enqueue(event.value);
637
+ push();
638
+ }).catch((error) => controller.error(error));
542
639
  }
543
- C();
640
+ push();
544
641
  }
545
642
  });
546
- if (u.data = new Response(nt), t.decode == null || t.decode) {
547
- const l = (U = u.headers.get("Content-Type")) == null ? void 0 : U.toLowerCase();
548
- l != null && l.includes("form") ? u.data = await u.data.formData() : l != null && l.includes("json") ? u.data = await u.data.json() : l != null && l.includes("text") ? u.data = await u.data.text() : l != null && l.includes("application") && (u.data = await u.data.blob());
643
+ resp.data = new Response(stream);
644
+ if (opts.decode == null || opts.decode) {
645
+ const content = (_b = resp.headers.get("Content-Type")) == null ? void 0 : _b.toLowerCase();
646
+ if (content == null ? void 0 : content.includes("form")) resp.data = await resp.data.formData();
647
+ else if (content == null ? void 0 : content.includes("json")) resp.data = await resp.data.json();
648
+ else if (content == null ? void 0 : content.includes("text")) resp.data = await resp.data.text();
649
+ else if (content == null ? void 0 : content.includes("application")) resp.data = await resp.data.blob();
549
650
  }
550
- u.ok ? i(u) : o(u);
551
- }).catch((u) => o(u));
552
- } catch (u) {
553
- o(u);
651
+ if (resp.ok) res(resp);
652
+ else rej(resp);
653
+ }).catch((err) => rej(err));
654
+ } catch (err) {
655
+ rej(err);
554
656
  }
555
657
  });
556
658
  }
557
659
  };
558
- c(E, "interceptors", {}), c(E, "headers", {});
559
- let F = E;
560
- const R = {
660
+ __publicField2(_Http, "interceptors", {});
661
+ __publicField2(_Http, "headers", {});
662
+ let Http = _Http;
663
+ const CliEffects = {
561
664
  CLEAR: "\x1B[0m",
562
665
  BRIGHT: "\x1B[1m",
563
666
  DIM: "\x1B[2m",
@@ -565,7 +668,8 @@ const R = {
565
668
  BLINK: "\x1B[5m",
566
669
  REVERSE: "\x1B[7m",
567
670
  HIDDEN: "\x1B[8m"
568
- }, L = {
671
+ };
672
+ const CliForeground = {
569
673
  BLACK: "\x1B[30m",
570
674
  RED: "\x1B[31m",
571
675
  GREEN: "\x1B[32m",
@@ -583,80 +687,138 @@ const R = {
583
687
  LIGHT_CYAN: "\x1B[96m",
584
688
  WHITE: "\x1B[97m"
585
689
  };
586
- var ft = /* @__PURE__ */ ((r) => (r[r.ERROR = 0] = "ERROR", r[r.WARN = 1] = "WARN", r[r.INFO = 2] = "INFO", r[r.LOG = 3] = "LOG", r[r.DEBUG = 4] = "DEBUG", r))(ft || {});
587
- const w = class w2 extends K {
588
- constructor(t) {
589
- super(), this.namespace = t;
590
- }
591
- pad(t, e, n, s = false) {
592
- const i = t.toString(), o = e - i.length;
593
- if (o <= 0) return i;
594
- const a = Array(~~(o / n.length)).fill(n).join("");
595
- return s ? i + a : a + i;
596
- }
597
- format(...t) {
598
- const e = /* @__PURE__ */ new Date();
599
- return `${`${e.getFullYear()}-${e.getMonth() + 1}-${e.getDate()} ${this.pad(e.getHours().toString(), 2, "0")}:${this.pad(e.getMinutes().toString(), 2, "0")}:${this.pad(e.getSeconds().toString(), 2, "0")}.${this.pad(e.getMilliseconds().toString(), 3, "0", true)}`}${this.namespace ? ` [${this.namespace}]` : ""} ${t.join(" ")}`;
600
- }
601
- debug(...t) {
602
- if (w2.LOG_LEVEL < 4) return;
603
- const e = this.format(...t);
604
- w2.emit(4, e), console.debug(L.LIGHT_GREY + e + R.CLEAR);
605
- }
606
- log(...t) {
607
- if (w2.LOG_LEVEL < 3) return;
608
- const e = this.format(...t);
609
- w2.emit(3, e), console.log(R.CLEAR + e);
610
- }
611
- info(...t) {
612
- if (w2.LOG_LEVEL < 2) return;
613
- const e = this.format(...t);
614
- w2.emit(2, e), console.info(L.BLUE + e + R.CLEAR);
615
- }
616
- warn(...t) {
617
- if (w2.LOG_LEVEL < 1) return;
618
- const e = this.format(...t);
619
- w2.emit(1, e), console.warn(L.YELLOW + e + R.CLEAR);
620
- }
621
- error(...t) {
622
- if (w2.LOG_LEVEL < 0) return;
623
- const e = this.format(...t);
624
- w2.emit(0, e), console.error(L.RED + e + R.CLEAR);
690
+ var LOG_LEVEL = /* @__PURE__ */ ((LOG_LEVEL2) => {
691
+ LOG_LEVEL2[LOG_LEVEL2["ERROR"] = 0] = "ERROR";
692
+ LOG_LEVEL2[LOG_LEVEL2["WARN"] = 1] = "WARN";
693
+ LOG_LEVEL2[LOG_LEVEL2["INFO"] = 2] = "INFO";
694
+ LOG_LEVEL2[LOG_LEVEL2["LOG"] = 3] = "LOG";
695
+ LOG_LEVEL2[LOG_LEVEL2["DEBUG"] = 4] = "DEBUG";
696
+ return LOG_LEVEL2;
697
+ })(LOG_LEVEL || {});
698
+ const _Logger = class _Logger2 extends TypedEmitter {
699
+ constructor(namespace) {
700
+ super();
701
+ this.namespace = namespace;
702
+ }
703
+ format(...text) {
704
+ const now = /* @__PURE__ */ new Date();
705
+ 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")}`;
706
+ return `${timestamp}${this.namespace ? ` [${this.namespace}]` : ""} ${text.map((t) => typeof t == "string" ? t : JSONSanitize(t, 2)).join(" ")}`;
707
+ }
708
+ debug(...args) {
709
+ if (_Logger2.LOG_LEVEL < 4) return;
710
+ const str = this.format(...args);
711
+ _Logger2.emit(4, str);
712
+ console.debug(CliForeground.LIGHT_GREY + str + CliEffects.CLEAR);
713
+ }
714
+ log(...args) {
715
+ if (_Logger2.LOG_LEVEL < 3) return;
716
+ const str = this.format(...args);
717
+ _Logger2.emit(3, str);
718
+ console.log(CliEffects.CLEAR + str);
719
+ }
720
+ info(...args) {
721
+ if (_Logger2.LOG_LEVEL < 2) return;
722
+ const str = this.format(...args);
723
+ _Logger2.emit(2, str);
724
+ console.info(CliForeground.BLUE + str + CliEffects.CLEAR);
725
+ }
726
+ warn(...args) {
727
+ if (_Logger2.LOG_LEVEL < 1) return;
728
+ const str = this.format(...args);
729
+ _Logger2.emit(1, str);
730
+ console.warn(CliForeground.YELLOW + str + CliEffects.CLEAR);
731
+ }
732
+ error(...args) {
733
+ if (_Logger2.LOG_LEVEL < 0) return;
734
+ const str = this.format(...args);
735
+ _Logger2.emit(0, str);
736
+ console.error(CliForeground.RED + str + CliEffects.CLEAR);
625
737
  }
626
738
  };
627
- c(w, "LOG_LEVEL", 4);
628
- function ee(r, ...t) {
629
- const e = [];
630
- for (let n = 0; n < r.length || n < t.length; n++)
631
- r[n] && e.push(r[n]), t[n] && e.push(t[n]);
632
- return new y(e.join(""));
739
+ __publicField2(_Logger, "LOG_LEVEL", 4);
740
+ function PE(str, ...args) {
741
+ const combined = [];
742
+ for (let i = 0; i < str.length || i < args.length; i++) {
743
+ if (str[i]) combined.push(str[i]);
744
+ if (args[i]) combined.push(args[i]);
745
+ }
746
+ return new PathEvent(combined.join(""));
747
+ }
748
+ function PES(str, ...args) {
749
+ let combined = [];
750
+ for (let i = 0; i < str.length || i < args.length; i++) {
751
+ if (str[i]) combined.push(str[i]);
752
+ if (args[i]) combined.push(args[i]);
753
+ }
754
+ const [paths, methods] = combined.join("").split(":");
755
+ return PathEvent.toString(paths, methods == null ? void 0 : methods.split(""));
633
756
  }
634
- function mt(r, ...t) {
635
- let e = [];
636
- for (let i = 0; i < r.length || i < t.length; i++)
637
- r[i] && e.push(r[i]), t[i] && e.push(t[i]);
638
- const [n, s] = e.join("").split(":");
639
- return y.toString(n, s == null ? void 0 : s.split(""));
757
+ class PathError extends Error {
640
758
  }
641
- class y {
642
- constructor(t) {
643
- c(this, "module");
644
- c(this, "fullPath");
645
- c(this, "path");
646
- c(this, "name");
647
- c(this, "methods");
648
- c(this, "all");
649
- c(this, "none");
650
- c(this, "create");
651
- c(this, "read");
652
- c(this, "update");
653
- c(this, "delete");
654
- var o;
655
- if (typeof t == "object") return Object.assign(this, t);
656
- let [e, n, s] = t.split(":");
657
- s || (s = n || "*"), (e == "*" || !e && s == "*") && (e = "", s = "*");
658
- let i = e.split("/").filter((a) => !!a);
659
- this.module = ((o = i.splice(0, 1)[0]) == null ? void 0 : o.toLowerCase()) || "", this.fullPath = e, this.path = i.join("/"), this.name = i.pop() || "", this.methods = s.split(""), this.all = s == null ? void 0 : s.includes("*"), this.none = s == null ? void 0 : s.includes("n"), this.create = !(s != null && s.includes("n")) && ((s == null ? void 0 : s.includes("*")) || (s == null ? void 0 : s.includes("w")) || (s == null ? void 0 : s.includes("c"))), this.read = !(s != null && s.includes("n")) && ((s == null ? void 0 : s.includes("*")) || (s == null ? void 0 : s.includes("r"))), this.update = !(s != null && s.includes("n")) && ((s == null ? void 0 : s.includes("*")) || (s == null ? void 0 : s.includes("w")) || (s == null ? void 0 : s.includes("u"))), this.delete = !(s != null && s.includes("n")) && ((s == null ? void 0 : s.includes("*")) || (s == null ? void 0 : s.includes("w")) || (s == null ? void 0 : s.includes("d")));
759
+ class PathEvent {
760
+ constructor(Event) {
761
+ __publicField2(this, "module");
762
+ __publicField2(this, "fullPath");
763
+ __publicField2(this, "path");
764
+ __publicField2(this, "name");
765
+ __publicField2(this, "methods");
766
+ var _a;
767
+ if (typeof Event == "object") return Object.assign(this, Event);
768
+ let [p, scope, method] = Event.split(":");
769
+ if (!method) method = scope || "*";
770
+ if (p == "*" || !p && method == "*") {
771
+ p = "";
772
+ method = "*";
773
+ }
774
+ let temp = p.split("/").filter((p2) => !!p2);
775
+ this.module = ((_a = temp.splice(0, 1)[0]) == null ? void 0 : _a.toLowerCase()) || "";
776
+ this.fullPath = p;
777
+ this.path = temp.join("/");
778
+ this.name = temp.pop() || "";
779
+ this.methods = new ASet(method.split(""));
780
+ }
781
+ /** All/Wildcard specified */
782
+ get all() {
783
+ return this.methods.has("*");
784
+ }
785
+ set all(v) {
786
+ v ? new ASet(["*"]) : this.methods.delete("*");
787
+ }
788
+ /** None specified */
789
+ get none() {
790
+ return this.methods.has("n");
791
+ }
792
+ set none(v) {
793
+ v ? this.methods = new ASet(["n"]) : this.methods.delete("n");
794
+ }
795
+ /** Create method specified */
796
+ get create() {
797
+ return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("c"));
798
+ }
799
+ set create(v) {
800
+ v ? this.methods.delete("n").add("c") : this.methods.delete("c");
801
+ }
802
+ /** Read method specified */
803
+ get read() {
804
+ return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("r"));
805
+ }
806
+ set read(v) {
807
+ v ? this.methods.delete("n").add("r") : this.methods.delete("r");
808
+ }
809
+ /** Update method specified */
810
+ get update() {
811
+ return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("u"));
812
+ }
813
+ set update(v) {
814
+ v ? this.methods.delete("n").add("u") : this.methods.delete("u");
815
+ }
816
+ /** Delete method specified */
817
+ get delete() {
818
+ return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("d"));
819
+ }
820
+ set delete(v) {
821
+ v ? this.methods.delete("n").add("d") : this.methods.delete("d");
660
822
  }
661
823
  /**
662
824
  * Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are
@@ -665,13 +827,35 @@ class y {
665
827
  * @param {string | PathEvent} paths Events as strings or pre-parsed
666
828
  * @return {PathEvent} Final combined permission
667
829
  */
668
- static combine(t) {
669
- let e = false;
670
- const n = t.map((s) => new y(s)).toSorted((s, i) => {
671
- const o = s.fullPath.length, a = i.fullPath.length;
672
- return o < a ? 1 : o > a ? -1 : 0;
673
- }).reduce((s, i) => (i.none && (e = true), s ? (e || (i.all && (s.all = true), (i.all || i.create) && (s.create = true), (i.all || i.read) && (s.read = true), (i.all || i.update) && (s.update = true), (i.all || i.delete) && (s.delete = true), s.methods = [...s.methods, ...i.methods]), s) : i), null);
674
- return n.all && (n.methods = ["*"]), n.none && (n.methods = ["n"]), n.methods = new S(n.methods), n.raw = mt`${n.fullPath}:${n.methods}`, n;
830
+ static combine(...paths) {
831
+ let hitNone = false;
832
+ const combined = paths.map((p) => new PathEvent(p)).toSorted((p1, p2) => {
833
+ const l1 = p1.fullPath.length, l2 = p2.fullPath.length;
834
+ return l1 < l2 ? 1 : l1 > l2 ? -1 : 0;
835
+ }).reduce((acc, p) => {
836
+ if (p.none) hitNone = true;
837
+ if (!acc) return p;
838
+ if (hitNone) return acc;
839
+ acc.methods = [...acc.methods, ...p.methods];
840
+ return acc;
841
+ }, null);
842
+ combined.methods = new ASet(combined.methods);
843
+ return combined;
844
+ }
845
+ /**
846
+ * Filter a set of paths based on the target
847
+ *
848
+ * @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
849
+ * @param filter {...PathEvent} Must container one of
850
+ * @return {boolean} Whether there is any overlap
851
+ */
852
+ static filter(target, ...filter) {
853
+ const parsedTarget = makeArray(target).map((pe) => new PathEvent(pe));
854
+ const parsedFind = makeArray(filter).map((pe) => new PathEvent(pe));
855
+ return parsedTarget.filter((t) => {
856
+ if (!t.fullPath && t.all) return true;
857
+ return !!parsedFind.find((f) => t.fullPath.startsWith(f.fullPath) && (f.all || t.all || t.methods.intersection(f.methods).length));
858
+ });
675
859
  }
676
860
  /**
677
861
  * Squash 2 sets of paths & return true if any overlap is found
@@ -680,14 +864,15 @@ class y {
680
864
  * @param has Target must have at least one of these path
681
865
  * @return {boolean} Whether there is any overlap
682
866
  */
683
- static has(t, ...e) {
684
- const n = m(e).map((i) => new y(i)), s = m(t).map((i) => new y(i));
685
- return !!n.find((i) => {
686
- if (!i.fullPath && i.all) return true;
687
- const o = s.filter((u) => i.fullPath.startsWith(u.fullPath));
688
- if (!o.length) return false;
689
- const a = y.combine(o);
690
- return !a.none && (a.all || new S(a.methods).intersection(new S(i.methods)).length);
867
+ static has(target, ...has) {
868
+ const parsedRequired = makeArray(has).map((pe) => new PathEvent(pe));
869
+ const parsedTarget = makeArray(target).map((pe) => new PathEvent(pe));
870
+ return !!parsedRequired.find((r) => {
871
+ if (!r.fullPath && r.all) return true;
872
+ const filtered = parsedTarget.filter((p) => r.fullPath.startsWith(p.fullPath));
873
+ if (!filtered.length) return false;
874
+ const combined = PathEvent.combine(...filtered);
875
+ return !combined.none && (combined.all || r.all) || combined.methods.intersection(r.methods).length;
691
876
  });
692
877
  }
693
878
  /**
@@ -697,8 +882,8 @@ class y {
697
882
  * @param has Target must have all these paths
698
883
  * @return {boolean} Whether there is any overlap
699
884
  */
700
- static hasAll(t, ...e) {
701
- return e.filter((n) => y.has(t, n)).length == e.length;
885
+ static hasAll(target, ...has) {
886
+ return has.filter((h) => PathEvent.has(target, h)).length == has.length;
702
887
  }
703
888
  /**
704
889
  * Same as `has` but raises an error if there is no overlap
@@ -706,8 +891,8 @@ class y {
706
891
  * @param {string | string[]} target Array of Events as strings or pre-parsed
707
892
  * @param has Target must have at least one of these path
708
893
  */
709
- static hasFatal(t, ...e) {
710
- if (!y.has(t, ...e)) throw new Error(`Requires one of: ${m(e).join(", ")}`);
894
+ static hasFatal(target, ...has) {
895
+ if (!PathEvent.has(target, ...has)) throw new PathError(`Requires one of: ${makeArray(has).join(", ")}`);
711
896
  }
712
897
  /**
713
898
  * Same as `hasAll` but raises an error if the target is missing any paths
@@ -715,8 +900,8 @@ class y {
715
900
  * @param {string | string[]} target Array of Events as strings or pre-parsed
716
901
  * @param has Target must have all these paths
717
902
  */
718
- static hasAllFatal(t, ...e) {
719
- if (!y.hasAll(t, ...e)) throw new Error(`Requires all: ${m(e).join(", ")}`);
903
+ static hasAllFatal(target, ...has) {
904
+ if (!PathEvent.hasAll(target, ...has)) throw new PathError(`Requires all: ${makeArray(has).join(", ")}`);
720
905
  }
721
906
  /**
722
907
  * Create event string from its components
@@ -725,9 +910,20 @@ class y {
725
910
  * @param {Method} methods Event method
726
911
  * @return {string} String representation of Event
727
912
  */
728
- static toString(t, e) {
729
- let n = m(t).filter((s) => s != null).join("/");
730
- return e != null && e.length && (n += `:${m(e).map((s) => s.toLowerCase()).join("")}`), n == null ? void 0 : n.trim().replaceAll(/\/{2,}/g, "/").replaceAll(/(^\/|\/$)/g, "");
913
+ static toString(path, methods) {
914
+ let p = makeArray(path).filter((p2) => p2 != null).join("/");
915
+ p = p == null ? void 0 : p.trim().replaceAll(/\/{2,}/g, "/").replaceAll(/(^\/|\/$)/g, "");
916
+ if (methods == null ? void 0 : methods.length) p += `:${makeArray(methods).map((m) => m.toLowerCase()).join("")}`;
917
+ return p;
918
+ }
919
+ /**
920
+ * Filter a set of paths based on this event
921
+ *
922
+ * @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
923
+ * @return {boolean} Whether there is any overlap
924
+ */
925
+ filter(target) {
926
+ return PathEvent.filter(target, this);
731
927
  }
732
928
  /**
733
929
  * Create event string from its components
@@ -735,38 +931,41 @@ class y {
735
931
  * @return {string} String representation of Event
736
932
  */
737
933
  toString() {
738
- return y.toString(this.fullPath, this.methods);
934
+ return PathEvent.toString(this.fullPath, this.methods);
739
935
  }
740
936
  }
741
- class re {
937
+ class PathEventEmitter {
742
938
  constructor() {
743
- c(this, "listeners", []);
939
+ __publicField2(this, "listeners", []);
744
940
  }
745
- emit(t, ...e) {
746
- const n = new y(t);
747
- this.listeners.filter((s) => y.has(s[0], t)).forEach(async (s) => s[1](n, ...e));
941
+ emit(event, ...args) {
942
+ const parsed = new PathEvent(event);
943
+ this.listeners.filter((l) => PathEvent.has(l[0], event)).forEach(async (l) => l[1](parsed, ...args));
748
944
  }
749
- off(t) {
750
- this.listeners = this.listeners.filter((e) => e[1] != t);
945
+ off(listener) {
946
+ this.listeners = this.listeners.filter((l) => l[1] != listener);
751
947
  }
752
- on(t, e) {
753
- return m(t).forEach((n) => this.listeners.push([new y(n), e])), () => this.off(e);
948
+ on(event, listener) {
949
+ makeArray(event).forEach((e) => this.listeners.push([new PathEvent(e), listener]));
950
+ return () => this.off(listener);
754
951
  }
755
- once(t, e) {
756
- return new Promise((n) => {
757
- const s = this.on(t, (i, ...o) => {
758
- n(o.length < 2 ? o[0] : o), e && e(i, ...o), s();
952
+ once(event, listener) {
953
+ return new Promise((res) => {
954
+ const unsubscribe = this.on(event, (event2, ...args) => {
955
+ res(args.length < 2 ? args[0] : args);
956
+ if (listener) listener(event2, ...args);
957
+ unsubscribe();
759
958
  });
760
959
  });
761
960
  }
762
- relayEvents(t) {
763
- t.on("*", (e, ...n) => this.emit(e, ...n));
961
+ relayEvents(emitter) {
962
+ emitter.on("*", (event, ...args) => this.emit(event, ...args));
764
963
  }
765
964
  }
766
- class Api extends F {
965
+ class Api extends Http {
767
966
  constructor(url = location.origin, opts = {}) {
768
967
  super({ ...(opts == null ? void 0 : opts.http) || {}, url });
769
- __publicField(this, "emitter", new re());
968
+ __publicField(this, "emitter", new PathEventEmitter());
770
969
  __publicField(this, "pending", {});
771
970
  __publicField(this, "storageKey");
772
971
  __publicField(this, "host");
@@ -796,27 +995,27 @@ class Api extends F {
796
995
  if (token) localStorage.setItem(this.storageKey, token);
797
996
  else localStorage.removeItem(this.storageKey);
798
997
  }
799
- this.emit(mt`api/token:${token ? "u" : "d"}`, token);
998
+ this.emit(PES`api/token:${token ? "u" : "d"}`, token);
800
999
  }
801
1000
  healthcheck() {
802
1001
  return this.request({ url: "/api/healthcheck" }).then((resp) => {
803
- this.emit(mt`api/healthcheck:r`, resp);
1002
+ this.emit(PES`api/healthcheck:r`, resp);
804
1003
  return resp;
805
1004
  });
806
1005
  }
807
1006
  request(options) {
808
- const key = Ot(options);
1007
+ const key = JSONSanitize(options);
809
1008
  const method = options.method == "GET" ? "r" : options.method == "POST" ? "c" : options.method == "DELETE" ? "d" : "u";
810
1009
  if (this.pending[key] != null) return this.pending[key];
811
1010
  this.pending[key] = super.request(options).then((response) => {
812
- this.emit(mt`api/response:${method}`, { request: options, response });
1011
+ this.emit(PES`api/response:${method}`, { request: options, response });
813
1012
  return response.data;
814
1013
  }).catch((err) => {
815
1014
  const e = (err == null ? void 0 : err.data) || err;
816
- this.emit(mt`api/error:${method}`, { request: options, error: e });
1015
+ this.emit(PES`api/error:${method}`, { request: options, error: e });
817
1016
  throw e;
818
1017
  }).finally(() => delete this.pending[key]);
819
- this.emit(mt`api/request:${method}`, { request: options, response: this.pending[key] });
1018
+ this.emit(PES`api/request:${method}`, { request: options, response: this.pending[key] });
820
1019
  return this.pending[key];
821
1020
  }
822
1021
  }
@@ -830,59 +1029,60 @@ var ActionType = /* @__PURE__ */ ((ActionType2) => {
830
1029
  ActionType2[ActionType2["PUT"] = 6] = "PUT";
831
1030
  return ActionType2;
832
1031
  })(ActionType || {});
833
- class Actions extends re {
1032
+ class Actions extends PathEventEmitter {
834
1033
  constructor(api) {
835
1034
  super();
836
1035
  __publicField(this, "api");
837
- __publicField(this, "cache", new Tt("_id"));
1036
+ __publicField(this, "cache", new Cache("_id"));
838
1037
  this.api = typeof api == "string" ? new Api(api) : api;
839
1038
  }
840
- all() {
841
- return this.api.request({ url: `/api/` + mt`actions` }).then((resp) => {
1039
+ async all(reload) {
1040
+ if (!reload && this.cache.complete) return this.cache.all();
1041
+ return this.api.request({ url: `/api/` + PES`actions` }).then((resp) => {
842
1042
  this.cache.addAll(resp);
843
- this.emit(mt`actions:r`, resp || []);
1043
+ this.emit(PES`actions:r`, resp || []);
844
1044
  return resp;
845
1045
  });
846
1046
  }
847
1047
  delete(id) {
848
1048
  if (!id) throw new Error("Cannot delete action, missing ID");
849
- return this.api.request({ url: `/api/` + mt`actions/${id}`, method: "DELETE" }).then(() => {
1049
+ return this.api.request({ url: `/api/` + PES`actions/${id}`, method: "DELETE" }).then(() => {
850
1050
  this.cache.delete(id);
851
- this.emit(mt`actions/${id}:d`, id);
1051
+ this.emit(PES`actions/${id}:d`, id);
852
1052
  });
853
1053
  }
854
1054
  read(id, reload = false) {
855
1055
  if (!id) throw new Error("Cannot read action, missing ID");
856
1056
  const cached = this.cache.get(id);
857
1057
  if (!reload && cached) return Promise.resolve(cached);
858
- return this.api.request({ url: `/api/` + mt`actions/${id}` }).then((action) => {
1058
+ return this.api.request({ url: `/api/` + PES`actions/${id}` }).then((action) => {
859
1059
  if (action) this.cache.add(action);
860
- this.emit(mt`actions/${id}:r`, action);
1060
+ this.emit(PES`actions/${id}:r`, action);
861
1061
  return action;
862
1062
  });
863
1063
  }
864
1064
  run(path, opts = {}) {
865
1065
  if (!path) throw new Error("Cannot run action, missing path");
866
- return this.api.request({ url: `/api/` + mt`actions/run/${path}`, ...opts });
1066
+ return this.api.request({ url: `/api/` + PES`actions/run/${path}`, ...opts });
867
1067
  }
868
1068
  runById(action, opts = {}) {
869
1069
  const id = typeof action == "string" ? action : action == null ? void 0 : action._id;
870
1070
  if (!id) throw new Error("Cannot run action, missing ID");
871
- return this.api.request({ url: "/api/" + mt`actions/run-by-id/${id}`, method: "POST", ...opts });
1071
+ return this.api.request({ url: "/api/" + PES`actions/run-by-id/${id}`, method: "POST", ...opts });
872
1072
  }
873
1073
  update(action) {
874
1074
  return this.api.request({
875
- url: `/api/` + mt`actions/${action._id}`,
1075
+ url: `/api/` + PES`actions/${action._id}`,
876
1076
  method: "POST",
877
1077
  body: action
878
1078
  }).then((action2) => {
879
1079
  if (action2) this.cache.add(action2);
880
- this.emit(mt`actions/${action2._id}:u`, action2);
1080
+ this.emit(PES`actions/${action2._id}:u`, action2);
881
1081
  return action2;
882
1082
  });
883
1083
  }
884
1084
  }
885
- class Ai extends re {
1085
+ class Ai extends PathEventEmitter {
886
1086
  constructor(api) {
887
1087
  super();
888
1088
  __publicField(this, "api");
@@ -890,19 +1090,19 @@ class Ai extends re {
890
1090
  }
891
1091
  ask(question, context) {
892
1092
  if (!question) throw new Error("Cannot ask AI, missing question");
893
- return this.api.request({ url: `/api/` + mt`ai`, method: "POST", body: {
1093
+ return this.api.request({ url: `/api/` + PES`ai`, method: "POST", body: {
894
1094
  question,
895
1095
  context
896
1096
  } }).then((response) => {
897
- this.emit(mt`ai:c`, { question, context, response });
1097
+ this.emit(PES`ai:c`, { question, context, response });
898
1098
  return response;
899
1099
  });
900
1100
  }
901
1101
  clear() {
902
- return this.api.request({ url: "/api/" + mt`ai`, method: "DELETE" }).then(() => this.emit(mt`ai:d`, this.api.token));
1102
+ return this.api.request({ url: "/api/" + PES`ai`, method: "DELETE" }).then(() => this.emit(PES`ai:d`, this.api.token));
903
1103
  }
904
1104
  }
905
- class Analytics extends re {
1105
+ class Analytics extends PathEventEmitter {
906
1106
  constructor(api) {
907
1107
  super();
908
1108
  __publicField(this, "api");
@@ -910,19 +1110,27 @@ class Analytics extends re {
910
1110
  }
911
1111
  ipTrace(ip) {
912
1112
  if (!ip) throw new Error("Cannot trace, missing IP");
913
- return this.api.request({ url: `/api/` + mt`analytics/trace/${ip}` }).then((resp) => {
914
- this.emit(mt`analytics/trace/${ip}:r`, resp);
1113
+ return this.api.request({ url: `/api/` + PES`analytics/trace/${ip}` }).then((resp) => {
1114
+ this.emit(PES`analytics/trace/${ip}:r`, resp);
915
1115
  return resp;
916
1116
  });
917
1117
  }
918
1118
  }
919
- class Auth extends re {
1119
+ class Auth extends PathEventEmitter {
920
1120
  constructor(api, opts = {}) {
921
1121
  super();
922
1122
  __publicField(this, "api");
1123
+ __publicField(this, "_permissions", []);
923
1124
  __publicField(this, "_user");
1125
+ // Permission helpers
1126
+ __publicField(this, "filter", (...events) => PathEvent.filter(this.permissions, ...events));
1127
+ __publicField(this, "has", (...events) => PathEvent.has(this.permissions, ...events));
1128
+ __publicField(this, "hasAll", (...events) => PathEvent.hasAll(this.permissions, ...events));
1129
+ __publicField(this, "hasFatal", (...events) => PathEvent.hasFatal(this.permissions, ...events));
1130
+ __publicField(this, "hasAllFatal", (...events) => PathEvent.hasAllFatal(this.permissions, ...events));
924
1131
  __publicField(this, "enableTotp", this.resetTotp);
925
1132
  this.opts = opts;
1133
+ window.PathEvent = PathEvent;
926
1134
  this.api = typeof api == "string" ? new Api(api) : api;
927
1135
  this.opts = {
928
1136
  loginUrl: this.api.url + "/ui/#/login",
@@ -935,7 +1143,7 @@ class Auth extends re {
935
1143
  "/api/auth/totp"
936
1144
  ];
937
1145
  if (resp.status == 401 && !blacklist.find((url) => resp.url.includes(url)))
938
- this.emit(mt`auth/session-expired:d`, this.api.token);
1146
+ this.emit(PES`auth/session-expired:d`, this.api.token);
939
1147
  next();
940
1148
  });
941
1149
  if (this.api.token) this.session(this.api.token, true);
@@ -946,13 +1154,20 @@ class Auth extends re {
946
1154
  else this.user = null;
947
1155
  });
948
1156
  }
1157
+ get permissions() {
1158
+ return this._permissions;
1159
+ }
1160
+ set permissions(perms) {
1161
+ this._permissions = perms;
1162
+ this.emit(PES`auth/permissions:u`, this._permissions);
1163
+ }
949
1164
  get user() {
950
1165
  return this._user;
951
1166
  }
952
1167
  set user(user) {
953
- if (!O(this.user, user)) {
1168
+ if (!isEqual(this.user, user)) {
954
1169
  this._user = user ? user : null;
955
- this.emit(mt`auth/user:u`, this._user);
1170
+ this.emit(PES`auth/user:u`, this._user);
956
1171
  }
957
1172
  }
958
1173
  knownHost(host = location.origin) {
@@ -973,7 +1188,7 @@ class Auth extends re {
973
1188
  }).then(async (resp) => {
974
1189
  this.api.token = (resp == null ? void 0 : resp.token) || null;
975
1190
  const user = await this.once("auth/user");
976
- this.emit(mt`auth/login/${username}:u`, user);
1191
+ this.emit(PES`auth/login/${username}:u`, user);
977
1192
  return user;
978
1193
  });
979
1194
  }
@@ -994,7 +1209,7 @@ class Auth extends re {
994
1209
  });
995
1210
  }
996
1211
  logout() {
997
- this.emit(mt`auth/logout:d`, this.user);
1212
+ this.emit(PES`auth/logout:d`, this.user);
998
1213
  this.api.token = null;
999
1214
  this.user = null;
1000
1215
  }
@@ -1003,7 +1218,7 @@ class Auth extends re {
1003
1218
  if (!u.username || !u.password) throw new Error("Cannot register user, missing username or password");
1004
1219
  const user = await this.api.request({ url: "/api/auth/register", body: { ...u } });
1005
1220
  if ((_a = user == null ? void 0 : user.image) == null ? void 0 : _a.startsWith("/")) user.image = `${this.api.url}${user.image}?token=${this.api.token}`;
1006
- this.emit(mt`auth/register:c`, user);
1221
+ this.emit(PES`auth/register:c`, user);
1007
1222
  return user;
1008
1223
  }
1009
1224
  reset(emailOrPass, token) {
@@ -1016,7 +1231,7 @@ class Auth extends re {
1016
1231
  password: token ? emailOrPass : void 0
1017
1232
  }
1018
1233
  }).then(() => {
1019
- this.emit(mt`auth/reset:${token ? "u" : "c"}`, token || emailOrPass);
1234
+ this.emit(PES`auth/reset:${token ? "u" : "c"}`, token || emailOrPass);
1020
1235
  });
1021
1236
  }
1022
1237
  async session(token, set = false) {
@@ -1025,12 +1240,13 @@ class Auth extends re {
1025
1240
  url: "/api/auth/session",
1026
1241
  headers: token ? { "Authorization": `Bearer ${token}` } : void 0
1027
1242
  });
1028
- this.emit(mt`auth/session:r`, session);
1243
+ this.emit(PES`auth/session:r`, session);
1029
1244
  if (set) {
1030
1245
  this.api.token = token;
1031
1246
  if (session == null ? void 0 : session.user) session.user.image = `${this.api.url}${session.user.image}?token=${this.api.token}`;
1032
1247
  this.user = (session == null ? void 0 : session.user) || null;
1033
- if (session) this.emit(mt`auth/login:c`, session.user);
1248
+ this.permissions = (session == null ? void 0 : session.permissions) || [];
1249
+ if (session) this.emit(PES`auth/login:c`, session.user);
1034
1250
  }
1035
1251
  return session;
1036
1252
  }
@@ -1040,7 +1256,7 @@ class Auth extends re {
1040
1256
  url: "/api/auth/password",
1041
1257
  body: { username, password, oldPassword }
1042
1258
  }).then((resp) => {
1043
- this.emit(mt`auth/reset:u`, resp == null ? void 0 : resp.token);
1259
+ this.emit(PES`auth/reset:u`, resp == null ? void 0 : resp.token);
1044
1260
  if (resp == null ? void 0 : resp.token) this.api.token = resp.token;
1045
1261
  });
1046
1262
  }
@@ -1052,22 +1268,32 @@ class Auth extends re {
1052
1268
  return this.api.request({ url: `/api/auth/totp/${username}`, method: "POST" });
1053
1269
  }
1054
1270
  setupTotp(username, method = "app", totp) {
1055
- return this.api.request({ url: `/api/auth/totp/${username}`, body: ot({
1271
+ return this.api.request({ url: `/api/auth/totp/${username}`, body: clean({
1056
1272
  method,
1057
1273
  totp
1058
1274
  }) });
1059
1275
  }
1060
1276
  }
1061
- class Client extends re {
1062
- constructor(settings) {
1277
+ class Client extends PathEventEmitter {
1278
+ constructor(api, settings) {
1063
1279
  super();
1280
+ __publicField(this, "_notifications", false);
1064
1281
  __publicField(this, "_platform");
1065
1282
  __publicField(this, "_pwa");
1283
+ this.api = api;
1066
1284
  this.settings = settings;
1285
+ this.pushSubscription.then((resp) => this.notifications = !!resp);
1067
1286
  }
1068
1287
  get mobile() {
1069
1288
  return ["android", "ios"].includes(this.platform);
1070
1289
  }
1290
+ get notifications() {
1291
+ return this._notifications;
1292
+ }
1293
+ set notifications(enabled) {
1294
+ this._notifications = enabled;
1295
+ this.emit(PES`client/notifications:${enabled ? "c" : "d"}`, enabled);
1296
+ }
1071
1297
  get platform() {
1072
1298
  if (!this._platform) {
1073
1299
  const userAgent = navigator.userAgent || navigator.vendor;
@@ -1080,6 +1306,10 @@ class Client extends re {
1080
1306
  }
1081
1307
  return this._platform;
1082
1308
  }
1309
+ get pushSubscription() {
1310
+ if (!navigator.serviceWorker.controller) return Promise.resolve(null);
1311
+ return navigator.serviceWorker.ready.then((sw) => sw.pushManager.getSubscription());
1312
+ }
1083
1313
  get pwa() {
1084
1314
  if (this._pwa == null)
1085
1315
  this._pwa = window.matchMedia("(display-mode: standalone)").matches || (navigator == null ? void 0 : navigator.standalone) || document.referrer.includes("android-app://");
@@ -1161,7 +1391,7 @@ class Client extends re {
1161
1391
  if (!dismissed && !this.pwa && this.mobile) this.pwaPrompt();
1162
1392
  }, 500);
1163
1393
  }
1164
- this.emit(mt`client/inject:c`, this.platform);
1394
+ this.emit(PES`client/inject:c`, this.platform);
1165
1395
  }
1166
1396
  pwaPrompt(platform) {
1167
1397
  const url = this.settings.api.url;
@@ -1278,16 +1508,34 @@ class Client extends re {
1278
1508
  setTimeout(() => {
1279
1509
  prompt.remove();
1280
1510
  backdrop.remove();
1281
- this.emit(mt`client/pwa:d`, platform);
1511
+ this.emit(PES`client/pwa:d`, platform);
1282
1512
  }, 500);
1283
1513
  };
1284
1514
  prompt.append(close);
1285
1515
  backdrop.append(prompt);
1286
1516
  document.body.append(backdrop);
1287
- this.emit(mt`client/pwa:c`, platform);
1517
+ this.emit(PES`client/pwa:c`, platform);
1518
+ }
1519
+ async enableNotifications() {
1520
+ const granted = await Notification.requestPermission();
1521
+ if (!granted) return null;
1522
+ const sw = await navigator.serviceWorker.ready;
1523
+ const subscription = (await sw.pushManager.subscribe({
1524
+ userVisibleOnly: true,
1525
+ applicationServerKey: this.settings.cache["push_public_key"]
1526
+ })).toJSON();
1527
+ return this.api.request({ url: "/api/notifications", body: subscription }).then(() => this.notifications = true);
1528
+ }
1529
+ async disableNotifications() {
1530
+ var _a;
1531
+ const subscription = await this.pushSubscription;
1532
+ subscription == null ? void 0 : subscription.unsubscribe();
1533
+ return this.api.request({ url: "/api/notifications", method: "DELETE", body: {
1534
+ p256dh: (_a = subscription == null ? void 0 : subscription.toJSON().keys) == null ? void 0 : _a["p256dh"]
1535
+ } }).then(() => this.notifications = false);
1288
1536
  }
1289
1537
  }
1290
- class Data extends re {
1538
+ class Data extends PathEventEmitter {
1291
1539
  constructor(api) {
1292
1540
  super();
1293
1541
  __publicField(this, "api");
@@ -1296,25 +1544,25 @@ class Data extends re {
1296
1544
  create(collection, document2) {
1297
1545
  if (!collection || !document2) throw new Error("Cannot create document, missing collection or document");
1298
1546
  return this.api.request({
1299
- url: `/api/` + mt`data/${collection}`,
1547
+ url: `/api/` + PES`data/${collection}`,
1300
1548
  method: "POST",
1301
1549
  body: document2
1302
1550
  }).then((resp) => {
1303
- this.emit(mt`data/${collection}:c`, resp);
1551
+ this.emit(PES`data/${collection}:c`, resp);
1304
1552
  return resp;
1305
1553
  });
1306
1554
  }
1307
1555
  delete(collection, id) {
1308
1556
  if (!collection || !id) throw new Error("Cannot delete document, missing collection or ID");
1309
1557
  return this.api.request({
1310
- url: `/api/` + mt`data/${collection}/${id}`,
1558
+ url: `/api/` + PES`data/${collection}/${id}`,
1311
1559
  method: "DELETE"
1312
- }).then(() => this.emit(mt`data/${collection}/${id}:d`, id));
1560
+ }).then(() => this.emit(PES`data/${collection}/${id}:d`, id));
1313
1561
  }
1314
1562
  read(collection, id) {
1315
1563
  if (!collection) throw new Error("Cannot read documents, missing collection");
1316
- return this.api.request({ url: `/api/` + mt`data/${collection}/${id}` }).then((resp) => {
1317
- this.emit(mt`data/${collection}/${id}:r`, collection, resp);
1564
+ return this.api.request({ url: `/api/` + PES`data/${collection}/${id}` }).then((resp) => {
1565
+ this.emit(PES`data/${collection}/${id}:r`, collection, resp);
1318
1566
  return resp;
1319
1567
  });
1320
1568
  }
@@ -1322,42 +1570,42 @@ class Data extends re {
1322
1570
  if (!collection || !document2) throw new Error("Cannot update document, missing collection or document");
1323
1571
  if (!document2._id) return this.create(collection, document2);
1324
1572
  return this.api.request({
1325
- url: `/api/` + mt`data/${collection}/${document2._id}`,
1573
+ url: `/api/` + PES`data/${collection}/${document2._id}`,
1326
1574
  method: append ? "PATCH" : "PUT",
1327
1575
  body: document2
1328
1576
  }).then((resp) => {
1329
- this.emit(mt`data/${collection}/${document2._id}:u`, resp);
1577
+ this.emit(PES`data/${collection}/${document2._id}:u`, resp);
1330
1578
  return resp;
1331
1579
  });
1332
1580
  }
1333
1581
  raw(collection, query) {
1334
1582
  if (!collection || !query) throw new Error("Cannot execute raw query, missing collection or query");
1335
1583
  const mode = query.operand.startsWith("find") ? "r" : query.operand == "insert" ? "c" : query.operand.startsWith("delete") ? "d" : "u";
1336
- return this.api.request({ url: `/api/` + mt`data/${collection}` + "?raw", body: query }).then((resp) => {
1337
- this.emit(mt`data/${collection}:${mode}`, resp);
1584
+ return this.api.request({ url: `/api/` + PES`data/${collection}` + "?raw", body: query }).then((resp) => {
1585
+ this.emit(PES`data/${collection}:${mode}`, resp);
1338
1586
  return resp;
1339
1587
  });
1340
1588
  }
1341
1589
  // Schema ==========================================================================================================
1342
1590
  deleteSchema(path) {
1343
1591
  if (!path) throw new Error("Cannot delete schema, missing collection path");
1344
- return this.api.request({ url: `/api/` + mt`schema/${path}`, method: "DELETE" }).then(() => this.emit(mt`schema/${path}:d`, path));
1592
+ return this.api.request({ url: `/api/` + PES`schema/${path}`, method: "DELETE" }).then(() => this.emit(PES`schema/${path}:d`, path));
1345
1593
  }
1346
1594
  readSchema(pathOrTree) {
1347
- return this.api.request({ url: "/api/" + mt`schema/${typeof pathOrTree == "string" ? pathOrTree : ""}` + (pathOrTree === true ? `?tree=${pathOrTree}` : "") }).then((resp) => {
1348
- this.emit(mt`schema/${typeof pathOrTree == "string" ? pathOrTree : ""}:r`, resp);
1595
+ return this.api.request({ url: "/api/" + PES`schema/${typeof pathOrTree == "string" ? pathOrTree : ""}` + (pathOrTree === true ? `?tree=${pathOrTree}` : "") }).then((resp) => {
1596
+ this.emit(PES`schema/${typeof pathOrTree == "string" ? pathOrTree : ""}:r`, resp);
1349
1597
  return resp;
1350
1598
  });
1351
1599
  }
1352
1600
  updateSchema(schema) {
1353
1601
  if (!schema.path) throw new Error("Cannot update schema, missing collection path");
1354
- return this.api.request({ url: "/api/" + mt`schema/${schema.path}`, body: schema }).then((resp) => {
1355
- this.emit(mt`schema/${schema.path}:${schema._id ? "u" : "c"}`, resp);
1602
+ return this.api.request({ url: "/api/" + PES`schema/${schema.path}`, body: schema }).then((resp) => {
1603
+ this.emit(PES`schema/${schema.path}:${schema._id ? "u" : "c"}`, resp);
1356
1604
  return resp;
1357
1605
  });
1358
1606
  }
1359
1607
  }
1360
- class Email extends re {
1608
+ class Email extends PathEventEmitter {
1361
1609
  constructor(api) {
1362
1610
  super();
1363
1611
  __publicField(this, "api");
@@ -1366,73 +1614,73 @@ class Email extends re {
1366
1614
  send(email) {
1367
1615
  var _a;
1368
1616
  if (!email.to && !email.bcc || !email.body) throw new Error("Cannot send email, missing address or body");
1369
- return this.api.request({ url: "/api/" + mt`email/${(_a = email.body) == null ? void 0 : _a.template}`, body: email }).then((response) => {
1617
+ return this.api.request({ url: "/api/" + PES`email/${(_a = email.body) == null ? void 0 : _a.template}`, body: email }).then((response) => {
1370
1618
  var _a2;
1371
- this.emit(mt`email/${(_a2 = email.body) == null ? void 0 : _a2.template}:c`, { email, response });
1619
+ this.emit(PES`email/${(_a2 = email.body) == null ? void 0 : _a2.template}:c`, { email, response });
1372
1620
  return response;
1373
1621
  });
1374
1622
  }
1375
1623
  }
1376
- class Groups extends re {
1624
+ class Groups extends PathEventEmitter {
1377
1625
  constructor(api) {
1378
1626
  super();
1379
1627
  __publicField(this, "api");
1380
- __publicField(this, "cache", new Tt("name"));
1628
+ __publicField(this, "cache", new Cache("name"));
1381
1629
  this.api = typeof api == "string" ? new Api(api) : api;
1382
1630
  }
1383
1631
  async all(reload) {
1384
1632
  if (!reload && this.cache.complete) return this.cache.all();
1385
- return this.api.request({ url: `/api/` + mt`groups` }).then((resp) => {
1633
+ return this.api.request({ url: `/api/` + PES`groups` }).then((resp) => {
1386
1634
  this.cache.addAll(resp);
1387
- this.emit(mt`groups:r`, resp || []);
1635
+ this.emit(PES`groups:r`, resp || []);
1388
1636
  return resp;
1389
1637
  });
1390
1638
  }
1391
1639
  delete(name) {
1392
1640
  if (!name) throw new Error("Cannot delete group, missing name");
1393
1641
  return this.api.request({
1394
- url: `/api/` + mt`groups/${name}`,
1642
+ url: `/api/` + PES`groups/${name}`,
1395
1643
  method: "DELETE"
1396
1644
  }).then(() => {
1397
1645
  this.cache.delete(name);
1398
- this.emit(mt`groups/${name}:d`);
1646
+ this.emit(PES`groups/${name}:d`);
1399
1647
  });
1400
1648
  }
1401
1649
  create(group) {
1402
1650
  if (!group.name) throw new Error("Cannot create group, missing name");
1403
1651
  return this.api.request({
1404
- url: `/api/` + mt`groups/${group.name}`,
1652
+ url: `/api/` + PES`groups/${group.name}`,
1405
1653
  method: "POST",
1406
1654
  body: group
1407
1655
  }).then((resp) => {
1408
1656
  this.cache.add(resp);
1409
- this.emit(mt`groups/${group.name}:c`, resp);
1657
+ this.emit(PES`groups/${group.name}:c`, resp);
1410
1658
  return resp;
1411
1659
  });
1412
1660
  }
1413
1661
  async read(name, reload) {
1414
1662
  if (!name) throw new Error("Cannot read group, missing name");
1415
1663
  if (!reload && this.cache.get(name)) return this.cache.get(name);
1416
- return this.api.request({ url: `/api/` + mt`groups/${name}` }).then((resp) => {
1664
+ return this.api.request({ url: `/api/` + PES`groups/${name}` }).then((resp) => {
1417
1665
  this.cache.add(resp);
1418
- this.emit(mt`groups/${name}:r`, resp);
1666
+ this.emit(PES`groups/${name}:r`, resp);
1419
1667
  return resp;
1420
1668
  });
1421
1669
  }
1422
1670
  update(group) {
1423
1671
  if (!group.name) throw new Error("Cannot update group, missing name");
1424
1672
  return this.api.request({
1425
- url: `/api/` + mt`groups/${group.name}`,
1673
+ url: `/api/` + PES`groups/${group.name}`,
1426
1674
  method: "PATCH",
1427
1675
  body: group
1428
1676
  }).then((resp) => {
1429
1677
  this.cache.add(resp);
1430
- this.emit(mt`groups/${group.name}:u`, resp);
1678
+ this.emit(PES`groups/${group.name}:u`, resp);
1431
1679
  return resp;
1432
1680
  });
1433
1681
  }
1434
1682
  }
1435
- class Logger extends re {
1683
+ class Logger extends PathEventEmitter {
1436
1684
  constructor(api, channel, logLevel) {
1437
1685
  super();
1438
1686
  __publicField(this, "api");
@@ -1447,7 +1695,7 @@ class Logger extends re {
1447
1695
  if (channel.toLowerCase() == "server") throw new Error('"Server" namespace is reserved');
1448
1696
  this.api = typeof api == "string" ? new Api(api) : api;
1449
1697
  if (logLevel != null && logLevel && logLevel != "NONE") {
1450
- if (ft[logLevel] >= 0) {
1698
+ if (LOG_LEVEL[logLevel] >= 0) {
1451
1699
  console.error = (...args) => {
1452
1700
  this.console.error(...args);
1453
1701
  this.error(...args);
@@ -1462,25 +1710,25 @@ ${log}`;
1462
1710
  ((_c = event.reason) == null ? void 0 : _c.code) == null || ((_d = event.reason) == null ? void 0 : _d.code) >= 500 ? this.error(log) : this.warn(log);
1463
1711
  });
1464
1712
  }
1465
- if (ft[logLevel] >= 1) {
1713
+ if (LOG_LEVEL[logLevel] >= 1) {
1466
1714
  console.warn = (...args) => {
1467
1715
  this.console.warn(...args);
1468
1716
  this.warn(...args);
1469
1717
  };
1470
1718
  }
1471
- if (ft[logLevel] >= 2) {
1719
+ if (LOG_LEVEL[logLevel] >= 2) {
1472
1720
  console.info = (...args) => {
1473
1721
  this.console.info(...args);
1474
1722
  this.info(...args);
1475
1723
  };
1476
1724
  }
1477
- if (ft[logLevel] >= 3) {
1725
+ if (LOG_LEVEL[logLevel] >= 3) {
1478
1726
  console.log = (...args) => {
1479
1727
  this.console.log(...args);
1480
1728
  this.log(...args);
1481
1729
  };
1482
1730
  }
1483
- if (ft[logLevel] >= 4) {
1731
+ if (LOG_LEVEL[logLevel] >= 4) {
1484
1732
  console.debug = (...args) => {
1485
1733
  this.console.debug(...args);
1486
1734
  this.debug(...args);
@@ -1503,39 +1751,39 @@ ${log}`;
1503
1751
  }
1504
1752
  create(log, channel = this.channel) {
1505
1753
  if (channel.toLowerCase() == "server") throw new Error('"Server" namespace is reserved');
1506
- return this.api.request({ url: `/api/` + mt`logs/${channel}`, body: log }).then(() => this.emit(mt`logs/${channel}:c`, log)).catch(() => {
1754
+ return this.api.request({ url: `/api/` + PES`logs/${channel}`, body: log }).then(() => this.emit(PES`logs/${channel}:c`, log)).catch(() => {
1507
1755
  });
1508
1756
  }
1509
1757
  channels() {
1510
- return this.api.request({ url: "/api/" + mt`logs/channels` });
1758
+ return this.api.request({ url: "/api/" + PES`logs/channels` });
1511
1759
  }
1512
1760
  delete(channel = this.channel) {
1513
- return this.api.request({ url: `/api/` + mt`logs/${channel}`, method: "DELETE" }).then(() => this.emit(mt`logs/${channel}:d`));
1761
+ return this.api.request({ url: `/api/` + PES`logs/${channel}`, method: "DELETE" }).then(() => this.emit(PES`logs/${channel}:d`));
1514
1762
  }
1515
1763
  read(channel = this.channel) {
1516
- return this.api.request({ url: `/api/` + mt`logs/${channel}` }).then((logs) => {
1517
- this.emit(mt`logs/${channel}:r`, logs);
1764
+ return this.api.request({ url: `/api/` + PES`logs/${channel}` }).then((logs) => {
1765
+ this.emit(PES`logs/${channel}:r`, logs);
1518
1766
  return logs;
1519
1767
  });
1520
1768
  }
1521
1769
  // Console =========================================================================================================
1522
1770
  debug(log, channel = this.channel) {
1523
- return this.create(this.buildLog(ft.DEBUG, log), channel);
1771
+ return this.create(this.buildLog(LOG_LEVEL.DEBUG, log), channel);
1524
1772
  }
1525
1773
  log(log, channel = this.channel) {
1526
- return this.create(this.buildLog(ft.LOG, log), channel);
1774
+ return this.create(this.buildLog(LOG_LEVEL.LOG, log), channel);
1527
1775
  }
1528
1776
  info(log, channel = this.channel) {
1529
- return this.create(this.buildLog(ft.INFO, log), channel);
1777
+ return this.create(this.buildLog(LOG_LEVEL.INFO, log), channel);
1530
1778
  }
1531
1779
  warn(log, channel = this.channel) {
1532
- return this.create(this.buildLog(ft.WARN, log), channel);
1780
+ return this.create(this.buildLog(LOG_LEVEL.WARN, log), channel);
1533
1781
  }
1534
1782
  error(log, channel = this.channel) {
1535
- return this.create(this.buildLog(ft.ERROR, log), channel);
1783
+ return this.create(this.buildLog(LOG_LEVEL.ERROR, log), channel);
1536
1784
  }
1537
1785
  }
1538
- class Payments extends re {
1786
+ class Payments extends PathEventEmitter {
1539
1787
  constructor(api, secret) {
1540
1788
  super();
1541
1789
  __publicField(this, "api");
@@ -1558,7 +1806,7 @@ class Payments extends re {
1558
1806
  amount,
1559
1807
  custom
1560
1808
  } });
1561
- this.emit(mt`payments:c`, request.data.clientSecret);
1809
+ this.emit(PES`payments:c`, request.data.clientSecret);
1562
1810
  return request.data.clientSecret;
1563
1811
  }
1564
1812
  async createForm(element, amount, custom) {
@@ -1572,28 +1820,28 @@ class Payments extends re {
1572
1820
  });
1573
1821
  }
1574
1822
  async history(username) {
1575
- const history = await this.api.request({ url: `/api/` + mt`payments/${username}` });
1576
- this.emit(mt`payments/${username}:r`, history);
1823
+ const history = await this.api.request({ url: `/api/` + PES`payments/${username}` });
1824
+ this.emit(PES`payments/${username}:r`, history);
1577
1825
  return history;
1578
1826
  }
1579
1827
  }
1580
- class Pdf extends re {
1828
+ class Pdf extends PathEventEmitter {
1581
1829
  constructor(api) {
1582
1830
  super();
1583
1831
  __publicField(this, "api");
1584
1832
  this.api = typeof api == "string" ? new Api(api) : api;
1585
1833
  }
1586
1834
  createPdf(body, options) {
1587
- return this.api.request({ url: `/api/` + mt`pdf`, body: { ...body, options }, decode: false }).then(async (resp) => {
1835
+ return this.api.request({ url: `/api/` + PES`pdf`, body: { ...body, options }, decode: false }).then(async (resp) => {
1588
1836
  const blob = await resp.blob();
1589
1837
  if (options == null ? void 0 : options.download) {
1590
- let filename = (options == null ? void 0 : options.filename) || kt();
1838
+ let filename = (options == null ? void 0 : options.filename) || timestampFilename();
1591
1839
  if (!filename.endsWith(".pdf")) filename += ".pdf";
1592
1840
  const url = URL.createObjectURL(blob);
1593
- lt(url, filename);
1841
+ downloadUrl(url, filename);
1594
1842
  URL.revokeObjectURL(url);
1595
1843
  }
1596
- this.emit(mt`pdf:c`, blob);
1844
+ this.emit(PES`pdf:c`, blob);
1597
1845
  return blob;
1598
1846
  });
1599
1847
  }
@@ -1660,7 +1908,7 @@ const _Socket = class _Socket {
1660
1908
  };
1661
1909
  __publicField(_Socket, "pollingSpeed", 3e4);
1662
1910
  let Socket = _Socket;
1663
- class Storage extends re {
1911
+ let Storage$1 = class Storage2 extends PathEventEmitter {
1664
1912
  constructor(api) {
1665
1913
  super();
1666
1914
  __publicField(this, "api");
@@ -1668,119 +1916,119 @@ class Storage extends re {
1668
1916
  }
1669
1917
  copy(source, destination) {
1670
1918
  if (!source || !destination) throw new Error("Cannot copy file or folder, missing source or destination");
1671
- return this.api.request({ url: "/api/" + mt`storage/${destination}`, body: { from: source } }).then((response) => {
1672
- this.emit(mt`storage/${destination}:c`, response);
1919
+ return this.api.request({ url: "/api/" + PES`storage/${destination}`, body: { from: source } }).then((response) => {
1920
+ this.emit(PES`storage/${destination}:c`, response);
1673
1921
  return response;
1674
1922
  });
1675
1923
  }
1676
1924
  delete(path) {
1677
1925
  if (!path) throw new Error("Cannot delete file or folder, missing path");
1678
- return this.api.request({ url: "/api/" + mt`storage/${path}`, method: "DELETE" }).then(() => {
1679
- this.emit(mt`storage/${path}:d`, path);
1926
+ return this.api.request({ url: "/api/" + PES`storage/${path}`, method: "DELETE" }).then(() => {
1927
+ this.emit(PES`storage/${path}:d`, path);
1680
1928
  });
1681
1929
  }
1682
1930
  download(path, opts = {}) {
1683
1931
  if (!path) throw new Error("Cannot download file, missing path");
1684
- return this.api.request({ ...opts, url: "/api/" + mt`storage/${path}`, decode: false }).then(async (response) => {
1932
+ return this.api.request({ ...opts, url: "/api/" + PES`storage/${path}`, decode: false }).then(async (response) => {
1685
1933
  const blob = await response.blob();
1686
1934
  const name = opts.downloadAs || path.split("/").pop();
1687
- this.emit(mt`storage/${path}:r`, blob);
1688
- Dt(blob, name);
1935
+ this.emit(PES`storage/${path}:r`, blob);
1936
+ downloadFile(blob, name);
1689
1937
  return response;
1690
1938
  });
1691
1939
  }
1692
1940
  list(path) {
1693
1941
  if (!path) path = "/";
1694
- return this.api.request({ url: "/api/" + mt`storage/${path}` + "?list" }).then((resp) => {
1695
- this.emit(mt`storage/${path}:r`, resp);
1942
+ return this.api.request({ url: "/api/" + PES`storage/${path}` + "?list" }).then((resp) => {
1943
+ this.emit(PES`storage/${path}:r`, resp);
1696
1944
  return resp;
1697
1945
  });
1698
1946
  }
1699
1947
  open(path, target = "_blank") {
1700
1948
  if (!path) throw new Error("Cannot download file, missing path");
1701
- const link = `${this.api.url}/api/` + mt`storage/${path}` + (this.api.token ? `?token=${this.api.token}` : "");
1949
+ const link = `${this.api.url}/api/` + PES`storage/${path}` + (this.api.token ? `?token=${this.api.token}` : "");
1702
1950
  if (!target) return link;
1703
- this.emit(mt`storage/${path}:r`, path);
1951
+ this.emit(PES`storage/${path}:r`, path);
1704
1952
  return window.open(link, target);
1705
1953
  }
1706
1954
  mkdir(path) {
1707
1955
  if (!path) throw new Error("Cannot make directory, missing path");
1708
- return this.api.request({ url: "/api/" + mt`storage/${path}`, body: { directory: true } }).then((resp) => {
1709
- this.emit(mt`storage/${path}:c`, resp);
1956
+ return this.api.request({ url: "/api/" + PES`storage/${path}`, body: { directory: true } }).then((resp) => {
1957
+ this.emit(PES`storage/${path}:c`, resp);
1710
1958
  return resp;
1711
1959
  });
1712
1960
  }
1713
1961
  move(source, destination) {
1714
1962
  if (!source || !destination) throw new Error("Cannot move file or folder, missing source or destination");
1715
1963
  if (source == destination) return this.list(destination);
1716
- return this.api.request({ url: "/api/" + mt`storage/${source}`, method: "PATCH", body: { move: destination } }).then((response) => {
1717
- this.emit(mt`storage/${source}:u`, response);
1964
+ return this.api.request({ url: "/api/" + PES`storage/${source}`, method: "PATCH", body: { move: destination } }).then((response) => {
1965
+ this.emit(PES`storage/${source}:u`, response);
1718
1966
  return response;
1719
1967
  });
1720
1968
  }
1721
1969
  upload(files, opts) {
1722
- return new x(async (res, rej, prog) => {
1723
- if (!files) files = await Mt(typeof opts == "object" ? opts : void 0);
1970
+ return new PromiseProgress(async (res, rej, prog) => {
1971
+ if (!files) files = await fileBrowser(typeof opts == "object" ? opts : void 0);
1724
1972
  if (!files || Array.isArray(files) && !files.length) return [];
1725
1973
  const path = (opts && typeof opts == "object" ? opts == null ? void 0 : opts.path : opts) || "/";
1726
- return Pt({
1727
- url: `${this.api.url}/api/` + mt`storage/${path}`,
1728
- files: m(files),
1974
+ return uploadWithProgress({
1975
+ url: `${this.api.url}/api/` + PES`storage/${path}`,
1976
+ files: makeArray(files),
1729
1977
  headers: this.api.headers
1730
1978
  }).onProgress((p) => {
1731
1979
  prog(p);
1732
1980
  }).then((resp) => {
1733
- this.emit(mt`storage/${path}:c`, resp);
1981
+ this.emit(PES`storage/${path}:c`, resp);
1734
1982
  res(resp);
1735
1983
  }).catch((err) => rej(err));
1736
1984
  });
1737
1985
  }
1738
- }
1739
- class Users extends re {
1986
+ };
1987
+ class Users extends PathEventEmitter {
1740
1988
  constructor(api) {
1741
1989
  super();
1742
1990
  __publicField(this, "api");
1743
- __publicField(this, "cache", new Tt("username"));
1991
+ __publicField(this, "cache", new Cache("username"));
1744
1992
  this.api = typeof api == "string" ? new Api(api) : api;
1745
1993
  }
1746
1994
  async all(reload) {
1747
1995
  if (!reload && this.cache.complete) return this.cache.all();
1748
- return this.api.request({ url: "/api/" + mt`users` }).then((resp) => {
1996
+ return this.api.request({ url: "/api/" + PES`users` }).then((resp) => {
1749
1997
  resp == null ? void 0 : resp.forEach((r) => {
1750
1998
  r.image = this.api.url + r.image + `?token=${this.api.token}`;
1751
1999
  return r;
1752
2000
  });
1753
2001
  this.cache.addAll(resp);
1754
- this.emit(mt`users:r`, resp || []);
2002
+ this.emit(PES`users:r`, resp || []);
1755
2003
  return resp;
1756
2004
  });
1757
2005
  }
1758
2006
  delete(username) {
1759
2007
  if (!username) throw new Error("Cannot delete user, missing username");
1760
2008
  return this.api.request({
1761
- url: "/api/" + mt`users/${username}`,
2009
+ url: "/api/" + PES`users/${username}`,
1762
2010
  method: "DELETE"
1763
2011
  }).then(() => {
1764
2012
  this.cache.delete(username);
1765
- this.emit(mt`users/${username}:d`, username);
2013
+ this.emit(PES`users/${username}:d`, username);
1766
2014
  });
1767
2015
  }
1768
2016
  async read(username, reload) {
1769
2017
  if (!username) throw new Error("Cannot read user, missing username");
1770
2018
  if (!reload && this.cache.get(username)) return this.cache.get(username);
1771
- return this.api.request({ url: "/api/" + mt`users/${username}` }).then((resp) => {
2019
+ return this.api.request({ url: "/api/" + PES`users/${username}` }).then((resp) => {
1772
2020
  if (resp) {
1773
2021
  resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
1774
2022
  this.cache.add(resp);
1775
2023
  }
1776
- this.emit(mt`users/${username}:r`, resp);
2024
+ this.emit(PES`users/${username}:r`, resp);
1777
2025
  return resp;
1778
2026
  });
1779
2027
  }
1780
2028
  update(user) {
1781
2029
  if (!user.username) throw new Error("Cannot update user, missing username");
1782
2030
  return this.api.request({
1783
- url: `/api/` + mt`users/${user.username}`,
2031
+ url: `/api/` + PES`users/${user.username}`,
1784
2032
  method: "PATCH",
1785
2033
  body: user
1786
2034
  }).then((resp) => {
@@ -1788,64 +2036,64 @@ class Users extends re {
1788
2036
  resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
1789
2037
  this.cache.add(resp);
1790
2038
  }
1791
- this.emit(mt`users/${user.username}:${resp._id ? "u" : "c"}`, resp);
2039
+ this.emit(PES`users/${user.username}:${resp._id ? "u" : "c"}`, resp);
1792
2040
  return resp;
1793
2041
  });
1794
2042
  }
1795
2043
  uploadImage(username, file) {
1796
2044
  if (!username || !file) throw new Error("Cannot update user image, missing username or file");
1797
- return Pt({
1798
- url: this.api.url + `/api/` + mt`users/${username}/image`,
2045
+ return uploadWithProgress({
2046
+ url: this.api.url + `/api/` + PES`users/${username}/image`,
1799
2047
  files: [file],
1800
2048
  headers: this.api.headers
1801
2049
  });
1802
2050
  }
1803
2051
  }
1804
- class Settings extends re {
2052
+ class Settings extends PathEventEmitter {
1805
2053
  constructor(api) {
1806
2054
  super();
1807
2055
  __publicField(this, "api");
1808
2056
  __publicField(this, "cache");
1809
2057
  this.api = typeof api == "string" ? new Api(api) : api;
1810
- this.cache = new Tt("key", { storageKey: `momentum:settings:${this.api.host}` });
2058
+ this.cache = new Cache("key", { storageKey: `momentum:settings:${this.api.host}` });
1811
2059
  this.api.on("api/token", () => this.all(false, true));
1812
2060
  }
1813
2061
  async all(detailed, reload) {
1814
2062
  if (!reload && !detailed && this.cache.complete) return this.cache;
1815
- return this.api.request({ url: `/api/` + mt`settings` + (detailed ? "?detailed" : "") }).then((resp) => {
2063
+ return this.api.request({ url: `/api/` + PES`settings` + (detailed ? "?detailed" : "") }).then((resp) => {
1816
2064
  this.cache.clear();
1817
2065
  if (resp) Object.keys(resp).forEach((key) => this.cache.set(key, detailed ? resp[key].value : resp[key]));
1818
2066
  this.cache.complete = true;
1819
- this.emit(mt`settings:r`, resp || []);
2067
+ this.emit(PES`settings:r`, resp || []);
1820
2068
  return resp;
1821
2069
  });
1822
2070
  }
1823
2071
  delete(key) {
1824
2072
  if (!key) throw new Error("Cannot delete setting, missing key");
1825
- return this.api.request({ url: `/api/` + mt`settings/${key}`, method: "DELETE" }).then(() => {
2073
+ return this.api.request({ url: `/api/` + PES`settings/${key}`, method: "DELETE" }).then(() => {
1826
2074
  this.cache.delete(key);
1827
- this.emit(mt`settings/${key}:d`, key);
2075
+ this.emit(PES`settings/${key}:d`, key);
1828
2076
  });
1829
2077
  }
1830
2078
  read(key, reload = false) {
1831
2079
  if (!key) throw new Error("Cannot read setting, missing key");
1832
2080
  if (!reload && this.cache.get(key)) return this.cache.get(key);
1833
- return this.api.request({ url: `/api/` + mt`settings/${key}` }).then((variable) => {
2081
+ return this.api.request({ url: `/api/` + PES`settings/${key}` }).then((variable) => {
1834
2082
  if (variable) this.cache.set(variable.key, variable.value);
1835
- this.emit(mt`settings/${key}:r`, variable);
2083
+ this.emit(PES`settings/${key}:r`, variable);
1836
2084
  return variable;
1837
2085
  });
1838
2086
  }
1839
2087
  update(variable) {
1840
2088
  if (!variable.key) throw new Error("Cannot update setting, missing key");
1841
- return this.api.request({ url: `/api/` + mt`settings/${variable.key}`, body: variable }).then((variable2) => {
2089
+ return this.api.request({ url: `/api/` + PES`settings/${variable.key}`, body: variable }).then((variable2) => {
1842
2090
  if (variable2) this.cache.set(variable2.key, variable2.value);
1843
- this.emit(`/api/` + mt`settings/${variable2.key}:${variable2._id ? "u" : "c"}`, variable2);
2091
+ this.emit(`/api/` + PES`settings/${variable2.key}:${variable2._id ? "u" : "c"}`, variable2);
1844
2092
  return variable2;
1845
2093
  });
1846
2094
  }
1847
2095
  }
1848
- class Static extends re {
2096
+ class Static extends PathEventEmitter {
1849
2097
  constructor(api) {
1850
2098
  super();
1851
2099
  __publicField(this, "api");
@@ -1853,27 +2101,27 @@ class Static extends re {
1853
2101
  }
1854
2102
  delete(path) {
1855
2103
  if (!path) throw new Error("Cannot delete static asset, missing path");
1856
- return this.api.request({ url: `/api/` + mt`static/${path}`, method: "DELETE" }).then(() => {
1857
- this.emit(mt`static/${path}:d`, path);
2104
+ return this.api.request({ url: `/api/` + PES`static/${path}`, method: "DELETE" }).then(() => {
2105
+ this.emit(PES`static/${path}:d`, path);
1858
2106
  });
1859
2107
  }
1860
2108
  upload(files, path = "/") {
1861
2109
  if (!files) throw new Error("Cannot upload static assets, missing file");
1862
- return new x(async (res, rej, prog) => {
1863
- return Pt({
1864
- url: this.api.url + "/api/" + mt`static/${path}`,
1865
- files: m(files),
2110
+ return new PromiseProgress(async (res, rej, prog) => {
2111
+ return uploadWithProgress({
2112
+ url: this.api.url + "/api/" + PES`static/${path}`,
2113
+ files: makeArray(files),
1866
2114
  headers: this.api.headers
1867
2115
  }).onProgress((p) => {
1868
2116
  prog(p);
1869
2117
  }).then((resp) => {
1870
- this.emit(mt`static/${path}:c`, resp);
2118
+ this.emit(PES`static/${path}:c`, resp);
1871
2119
  res(resp);
1872
2120
  }).catch((err) => rej(err));
1873
2121
  });
1874
2122
  }
1875
2123
  }
1876
- class Momentum extends re {
2124
+ class Momentum extends PathEventEmitter {
1877
2125
  constructor(url, opts) {
1878
2126
  super();
1879
2127
  __publicField(this, "api");
@@ -1907,8 +2155,8 @@ class Momentum extends re {
1907
2155
  this.settings = new Settings(this.api);
1908
2156
  if (opts == null ? void 0 : opts.socket) this.socket = new Socket(this.api);
1909
2157
  this.static = new Static(this.api);
1910
- this.storage = new Storage(this.api);
1911
- this.client = new Client(this.settings);
2158
+ this.storage = new Storage$1(this.api);
2159
+ this.client = new Client(this.api, this.settings);
1912
2160
  this.users = new Users(this.api);
1913
2161
  this.relayEvents(this.actions);
1914
2162
  this.relayEvents(this.ai);
@@ -1931,6 +2179,9 @@ class Momentum extends re {
1931
2179
  const cached = this.users.cache.get(this.auth.user.username);
1932
2180
  if (cached) this.auth.user = cached;
1933
2181
  });
2182
+ if (!(opts == null ? void 0 : opts.disableWorker) && "serviceWorker" in navigator) {
2183
+ navigator.serviceWorker.register("/momentum-worker.js");
2184
+ }
1934
2185
  }
1935
2186
  }
1936
2187
  export {
@@ -1946,15 +2197,15 @@ export {
1946
2197
  Groups,
1947
2198
  Logger,
1948
2199
  Momentum,
1949
- ee as PE,
1950
- mt as PES,
1951
- y as PathEvent,
1952
- re as PathEventEmitter,
2200
+ PE,
2201
+ PES,
2202
+ PathEvent,
2203
+ PathEventEmitter,
1953
2204
  Payments,
1954
2205
  Pdf,
1955
2206
  Settings,
1956
2207
  Socket,
1957
2208
  Static,
1958
- Storage,
2209
+ Storage$1 as Storage,
1959
2210
  Users
1960
2211
  };