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