@ztimson/momentum 0.27.2 → 0.27.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/actions.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Api } from './api';
2
- import { RequestOptions, TypedEmitter, type TypedEvents } from '@ztimson/utils';
2
+ import { HttpRequestOptions, TypedEmitter, type TypedEvents } from '@ztimson/utils';
3
3
  import { BehaviorSubject } from 'rxjs';
4
4
  import { Meta } from './core';
5
5
  export type Action = Meta & {
@@ -45,8 +45,8 @@ export declare class Actions extends TypedEmitter<ActionEvents> {
45
45
  delete(id: string): Promise<void>;
46
46
  list(): Promise<Action[]>;
47
47
  read(id: string, reload?: boolean): Promise<Action | null>;
48
- run<T>(path: string, opts?: RequestOptions): Promise<T>;
49
- runById(action: string | Action, opts?: RequestOptions): Promise<ActionResponse>;
48
+ run<T>(path: string, opts?: HttpRequestOptions): import("@ztimson/utils").PromiseProgress<any>;
49
+ runById(action: string | Action, opts?: HttpRequestOptions): import("@ztimson/utils").PromiseProgress<any>;
50
50
  update(action: Action): Promise<Action>;
51
51
  }
52
52
  //# sourceMappingURL=actions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../src/actions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,cAAc,EAAE,YAAY,EAAE,KAAK,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAC9E,OAAO,EAAC,eAAe,EAAC,MAAM,MAAM,CAAC;AACrC,OAAO,EAAC,IAAI,EAAC,MAAM,QAAQ,CAAC;AAE5B,MAAM,MAAM,MAAM,GAAG,IAAI,GAAG;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE;QAAC,IAAI,EAAE,UAAU,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAC,CAAC;IAC3C,MAAM,CAA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OAAO,IAAA;IACP,MAAM,IAAA;IACN,KAAK,IAAA;CACL;AAED,MAAM,MAAM,YAAY,GAAG,WAAW,GAAG;IACxC,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,GAAG,CAAC;IACjC,MAAM,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,GAAG,CAAC;IAC5B,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,KAAK,GAAG,CAAC;IACrC,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,GAAG,CAAC;IAChC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,GAAG,CAAC;CAC5C,CAAA;AAED,qBAAa,OAAQ,SAAQ,YAAY,CAAC,YAAY,CAAC;IACtD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;IAE3B,MAAM,4BAAqC;IAC3C,IAAI,KAAK,aAAgC;IACzC,IAAI,KAAK,CAAC,GAAG,UAAA,EAA4B;gBAE7B,GAAG,EAAE,GAAG,GAAG,MAAM;IAK7B,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAOjC,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAQzB,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,UAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAUtD,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,kBAAuB;IAKlD,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,IAAI,GAAE,kBAAuB;IAM9D,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAWvC"}
package/dist/actions.js CHANGED
@@ -31,9 +31,10 @@ class Actions extends utils_1.TypedEmitter {
31
31
  }
32
32
  list() {
33
33
  return this.api.request({ url: `/api/actions` }).then(resp => {
34
- this.cache = resp;
35
- this.emit('LIST', resp);
36
- return resp;
34
+ if (resp.data)
35
+ this.cache = resp.data;
36
+ this.emit('LIST', resp.data || []);
37
+ return resp.data;
37
38
  });
38
39
  }
39
40
  read(id, reload = false) {
@@ -41,18 +42,20 @@ class Actions extends utils_1.TypedEmitter {
41
42
  if (!reload && cached)
42
43
  return Promise.resolve(cached);
43
44
  return this.api.request({ url: `/api/actions/${id}` }).then(action => {
44
- if (action)
45
- this.cache = this.cache.filter(a => a._id != id).concat([action]);
46
- this.emit('READ', action);
47
- return action;
45
+ if (action.data)
46
+ this.cache = this.cache.filter(a => a._id != id).concat([action.data]);
47
+ this.emit('READ', action.data);
48
+ return action.data;
48
49
  });
49
50
  }
50
51
  run(path, opts = {}) {
51
- return this.api.request({ url: (`/api/actions/run/` + path).replaceAll('//', '/'), ...opts });
52
+ return this.api.request({ url: (`/api/actions/run/` + path).replaceAll('//', '/'), ...opts })
53
+ .then(resp => resp.data);
52
54
  }
53
55
  runById(action, opts = {}) {
54
56
  const id = typeof action == 'string' ? action : action._id;
55
- return this.api.request({ url: '/api/actions/run-by-id/' + id, method: 'POST', ...opts });
57
+ return this.api.request({ url: '/api/actions/run-by-id/' + id, method: 'POST', ...opts })
58
+ .then(resp => resp.data);
56
59
  }
57
60
  update(action) {
58
61
  return this.api.request({
@@ -60,10 +63,10 @@ class Actions extends utils_1.TypedEmitter {
60
63
  method: 'POST',
61
64
  body: action
62
65
  }).then(action => {
63
- if (action)
64
- this.cache = this.cache.filter(a => a._id != action._id).concat([action]);
65
- this.emit('UPDATE', action);
66
- return action;
66
+ if (action.data)
67
+ this.cache = this.cache.filter(a => a._id != action.data?._id).concat([action.data]);
68
+ this.emit('UPDATE', action.data);
69
+ return action.data;
67
70
  });
68
71
  }
69
72
  }
package/dist/api.d.ts CHANGED
@@ -1,22 +1,22 @@
1
- import { type TypedEvents, type RequestOptions, XHR, type XhrOptions } from '@ztimson/utils';
1
+ import { DecodedResponse, Http, HttpDefaults, HttpRequestOptions, PromiseProgress, type TypedEvents } from '@ztimson/utils';
2
2
  export type ApiEvents = TypedEvents & {
3
- REQUEST: (request: Promise<any>, options: RequestOptions) => any;
4
- RESPONSE: (response: any, options: RequestOptions) => any;
5
- REJECTED: (response: Error, options: RequestOptions) => any;
3
+ REQUEST: (request: Promise<any>, options: HttpRequestOptions) => any;
4
+ RESPONSE: (response: any, options: HttpRequestOptions) => any;
5
+ REJECTED: (response: Error, options: HttpRequestOptions) => any;
6
6
  TOKEN: (token: string | null) => any;
7
7
  };
8
- export declare class Api extends XHR {
8
+ export declare class Api extends Http {
9
9
  readonly url: string;
10
- readonly opts: XhrOptions;
10
+ readonly opts: HttpDefaults;
11
11
  private emitter;
12
12
  private _token;
13
13
  get token(): string | null;
14
14
  set token(token: string | null);
15
- constructor(url?: string, opts?: XhrOptions);
15
+ constructor(url?: string, opts?: HttpDefaults);
16
16
  emit: <K extends string | symbol>(event: K, ...args: Parameters<ApiEvents[K]>) => void;
17
17
  off: <K extends string | symbol = string>(event: K, listener: ApiEvents[K]) => void;
18
18
  on: <K extends string | symbol = string>(event: K, listener: ApiEvents[K]) => () => void;
19
19
  once: <K extends string | symbol = string>(event: K, listener?: ApiEvents[K] | undefined) => Promise<any>;
20
- request<T>(options: RequestOptions): Promise<T>;
20
+ request<T>(options: HttpRequestOptions): PromiseProgress<DecodedResponse<T>>;
21
21
  }
22
22
  //# sourceMappingURL=api.d.ts.map
package/dist/api.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,GAAG,EACH,KAAK,UAAU,EACf,MAAM,gBAAgB,CAAC;AAExB,MAAM,MAAM,SAAS,GAAG,WAAW,GAAG;IACrC,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,cAAc,KAAK,GAAG,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BAAkB,KAAK,GAAG,CAAC;IAChE,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,KAAK,GAAG,CAAA;CACpC,CAAA;AAED,qBAAa,GAAI,SAAQ,IAAI;aAYA,GAAG,EAAE,MAAM;aAAoC,IAAI,EAAE,YAAY;IAX7F,OAAO,CAAC,OAAO,CAAiC;IAEhD,OAAO,CAAC,MAAM,CAAuB;IACrC,IAAI,KAAK,IAAI,MAAM,GAAG,IAAI,CAAwB;IAClD,IAAI,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,EAK7B;gBAE2B,GAAG,GAAE,MAAwB,EAAkB,IAAI,GAAE,YAAiB;IAKlG,IAAI,mFAAwC;IAC5C,GAAG,iFAAuC;IAC1C,EAAE,uFAAsC;IACxC,IAAI,sGAAwC;IAE5C,OAAO,CAAC,CAAC,EAAE,OAAO,EAAE,kBAAkB,GAAG,eAAe,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;CAa5E"}
package/dist/api.js CHANGED
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Api = void 0;
4
4
  const utils_1 = require("@ztimson/utils");
5
- class Api extends utils_1.XHR {
5
+ class Api extends utils_1.Http {
6
6
  url;
7
7
  opts;
8
8
  emitter = new utils_1.TypedEmitter();
@@ -26,12 +26,14 @@ class Api extends utils_1.XHR {
26
26
  on = this.emitter.on.bind(this.emitter);
27
27
  once = this.emitter.once.bind(this.emitter);
28
28
  request(options) {
29
- const req = super.request(options).then(resp => {
29
+ const req = super.request(options)
30
+ .then(resp => {
30
31
  this.emit('RESPONSE', resp, options);
31
32
  return resp;
32
33
  }).catch(err => {
33
- this.emit('REJECTED', err, options);
34
- throw err;
34
+ const e = err?.data || err;
35
+ this.emit('REJECTED', e, options);
36
+ throw e;
35
37
  });
36
38
  this.emit('REQUEST', req, options);
37
39
  return req;
package/dist/auth.d.ts CHANGED
@@ -16,10 +16,10 @@ export type AuthOptions = {
16
16
  export declare class Totp {
17
17
  private api;
18
18
  constructor(api: Api);
19
- disable(username: string): Promise<void>;
20
- enable: (username: string) => Promise<void>;
21
- reset(username: string): Promise<void>;
22
- setup(username: string, method?: string, totp?: string): Promise<void>;
19
+ disable(username: string): import("@ztimson/utils").PromiseProgress<import("@ztimson/utils").DecodedResponse<void>>;
20
+ enable: (username: string) => import("@ztimson/utils").PromiseProgress<import("@ztimson/utils").DecodedResponse<void>>;
21
+ reset(username: string): import("@ztimson/utils").PromiseProgress<import("@ztimson/utils").DecodedResponse<void>>;
22
+ setup(username: string, method?: string, totp?: string): import("@ztimson/utils").PromiseProgress<import("@ztimson/utils").DecodedResponse<void>>;
23
23
  }
24
24
  export declare class Auth extends TypedEmitter<AuthEvents> {
25
25
  private readonly opts?;
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,eAAe,EAAC,MAAM,MAAM,CAAC;AACrC,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAiB,YAAY,EAAE,KAAK,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAC9E,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,SAAS,CAAC;AAElC,MAAM,MAAM,UAAU,GAAG,WAAW,GAAG;IACtC,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,KAAK,GAAG,CAAC;IACjC,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;IAC3B,MAAM,EAAE,MAAM,GAAG,CAAC;IAClB,QAAQ,EAAE,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,KAAK,GAAG,CAAC;IACvC,eAAe,EAAE,MAAM,GAAG,CAAC;CAC3B,CAAA;AAED,MAAM,MAAM,WAAW,GAAG;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;C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I,CAAC;IACtD,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAY7B,OAAO,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,UAAQ,GAAG,OAAO,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,IAAI,CAAC;QAAC,WAAW,EAAE,MAAM,EAAE,CAAA;KAAC,GAAG,IAAI,CAAC;IAexG,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAQ7F"}
package/dist/auth.js CHANGED
@@ -82,19 +82,21 @@ class Auth extends utils_1.TypedEmitter {
82
82
  knownHost(host = location.origin) {
83
83
  if (host.startsWith('/'))
84
84
  return Promise.resolve();
85
- return this.api.request({ url: `/api/auth/known-host?host=${encodeURI(new URL(host).origin)}` });
85
+ return this.api.request({ url: `/api/auth/known-host?host=${encodeURI(new URL(host).origin)}` })
86
+ .then(() => { });
86
87
  }
87
88
  login(username, password, totp) {
88
89
  return this.api.request({
89
90
  url: '/api/auth/login',
90
91
  headers: { Authorization: undefined },
92
+ method: 'POST',
91
93
  body: {
92
94
  username: username.trim(),
93
95
  password: password.trim(),
94
96
  totp,
95
97
  }
96
98
  }).then(async (resp) => {
97
- this.api.token = resp.token;
99
+ this.api.token = resp.data?.token || null;
98
100
  return await this.once('USER');
99
101
  });
100
102
  }
@@ -118,8 +120,8 @@ class Auth extends utils_1.TypedEmitter {
118
120
  this.emit('LOGOUT');
119
121
  }
120
122
  async register(u) {
121
- const user = await this.api.request({ url: '/api/auth/register', body: { ...u } });
122
- if (user.image.startsWith('/'))
123
+ const user = (await this.api.request({ url: '/api/auth/register', body: { ...u } }))?.data;
124
+ if (user?.image?.startsWith('/'))
123
125
  user.image = `${this.api.url}${user.image}?token=${this.api.token}`;
124
126
  this.emit('REGISTER', user);
125
127
  return user;
@@ -132,32 +134,32 @@ class Auth extends utils_1.TypedEmitter {
132
134
  email: token ? undefined : emailOrPass,
133
135
  password: token ? emailOrPass : undefined,
134
136
  }
135
- });
137
+ }).then(() => { });
136
138
  }
137
139
  async session(token, set = false) {
138
140
  if (!token)
139
141
  token = this.api.token;
140
- const user = await this.api.request({
142
+ const session = (await this.api.request({
141
143
  url: '/api/auth/session',
142
144
  headers: token ? { 'Authorization': `Bearer ${token}` } : undefined
143
- });
145
+ }))?.data;
144
146
  if (set) {
145
147
  this.api.token = token;
146
- if (user?.user)
147
- user.user.image = `${this.api.url}${user.user.image}?token=${this.api.token}`;
148
- this.user = user?.user || null;
149
- if (user)
150
- this.emit('LOGIN', user.user);
148
+ if (session?.user)
149
+ session.user.image = `${this.api.url}${session.user.image}?token=${this.api.token}`;
150
+ this.user = session?.user || null;
151
+ if (session)
152
+ this.emit('LOGIN', session.user);
151
153
  }
152
- return user;
154
+ return session;
153
155
  }
154
156
  async updatePassword(username, password, oldPassword) {
155
157
  return this.api.request({
156
158
  url: '/api/auth/password',
157
159
  body: { username, password, oldPassword }
158
160
  }).then(resp => {
159
- if (resp?.token)
160
- this.api.token = resp.token;
161
+ if (resp?.data?.token)
162
+ this.api.token = resp.data.token;
161
163
  });
162
164
  }
163
165
  }
package/dist/data.js CHANGED
@@ -17,8 +17,8 @@ class Data extends utils_1.TypedEmitter {
17
17
  }
18
18
  get(collection, document) {
19
19
  return this.api.request({ url: `/api/data/${collection}${document ? `/${document}` : ''}` }).then(resp => {
20
- this.emit('GET', collection, resp);
21
- return resp;
20
+ this.emit('GET', collection, resp.data);
21
+ return resp.data;
22
22
  });
23
23
  }
24
24
  raw(collection, operand, query, options) {
@@ -30,8 +30,8 @@ class Data extends utils_1.TypedEmitter {
30
30
  options,
31
31
  }
32
32
  }).then(resp => {
33
- this.emit('RAW', collection, resp);
34
- return resp;
33
+ this.emit('RAW', collection, resp.data);
34
+ return resp.data;
35
35
  });
36
36
  }
37
37
  set(collection, document, append = false) {
@@ -40,8 +40,8 @@ class Data extends utils_1.TypedEmitter {
40
40
  method: append ? 'PATCH' : 'POST',
41
41
  body: document
42
42
  }).then(resp => {
43
- this.emit('SET', collection, document);
44
- return resp;
43
+ this.emit('SET', collection, resp.data);
44
+ return resp.data;
45
45
  });
46
46
  }
47
47
  }
package/dist/email.d.ts CHANGED
@@ -17,6 +17,6 @@ export type EmailEvents = TypedEvents & {
17
17
  export declare class Email extends TypedEmitter<EmailEvents> {
18
18
  private readonly api;
19
19
  constructor(api: Api | string);
20
- send(email: Mail): Promise<unknown>;
20
+ send(email: Mail): import("@ztimson/utils").PromiseProgress<any>;
21
21
  }
22
22
  //# sourceMappingURL=email.d.ts.map
package/dist/email.js CHANGED
@@ -15,7 +15,7 @@ class Email extends utils_1.TypedEmitter {
15
15
  url += `/${email.body.template}`;
16
16
  return this.api.request({ url, body: email }).then(resp => {
17
17
  this.emit('SENT', email);
18
- return resp;
18
+ return resp.data;
19
19
  });
20
20
  }
21
21
  }
package/dist/groups.d.ts CHANGED
@@ -12,7 +12,7 @@ export type Group = Meta & {
12
12
  export type GroupEvents = TypedEvents & {
13
13
  LIST: (users: Group[]) => any;
14
14
  CREATE: (user: Group) => any;
15
- READ: (user: Group) => any;
15
+ READ: (user: Group | null) => any;
16
16
  UPDATE: (user: Group) => any;
17
17
  DELETE: (name: string) => any;
18
18
  };
@@ -1 +1 @@
1
- {"version":3,"file":"groups.d.ts","sourceRoot":"","sources":["../src/groups.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,YAAY,EAAE,KAAK,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAC9D,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,QAAQ,CAAC;AAEjC,MAAM,MAAM,KAAK,GAAG,IAAI,GAAG;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,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C1B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC;CACZ,CAAA;AAED,MAAM,MAAM,WAAW,GAAG,WAAW,GAAG;IACvC,IAAI,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,GAAG,CAAC;IAC9B,MAAM,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,GAAG,CAAC;IAC7B,IAAI,EAAE,CAAC,IAAI,EAAE,KAAK,GAAG,IAAI,KAAK,GAAG,CAAC;IAClC,MAAM,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,GAAG,CAAC;IAC7B,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,GAAG,CAAC;CAC9B,CAAC;AAEF,qBAAa,MAAO,SAAQ,YAAY,CAAC,WAAW,CAAC;IACpD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;gBAEf,GAAG,EAAE,GAAG,GAAG,MAAM;IAK7B,MAAM,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;IAWpC,IAAI,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;IAOxB,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC;IAOlC,MAAM,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;IAWpC,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAMnC"}
package/dist/groups.js CHANGED
@@ -15,20 +15,20 @@ class Groups extends utils_1.TypedEmitter {
15
15
  method: 'POST',
16
16
  body: group
17
17
  }).then(resp => {
18
- this.emit('CREATE', resp);
19
- return resp;
18
+ this.emit('CREATE', resp.data);
19
+ return resp.data;
20
20
  });
21
21
  }
22
22
  list() {
23
23
  return this.api.request({ url: `/api/groups` }).then(resp => {
24
- this.emit('LIST', resp);
25
- return resp;
24
+ this.emit('LIST', resp.data || []);
25
+ return resp.data;
26
26
  });
27
27
  }
28
28
  read(name) {
29
29
  return this.api.request({ url: `/api/groups/${name}` }).then(resp => {
30
- this.emit('READ', resp);
31
- return resp;
30
+ this.emit('READ', resp.data);
31
+ return resp.data;
32
32
  });
33
33
  }
34
34
  update(group) {
@@ -37,8 +37,8 @@ class Groups extends utils_1.TypedEmitter {
37
37
  method: 'PATCH',
38
38
  body: group
39
39
  }).then(resp => {
40
- this.emit('UPDATE', resp);
41
- return resp;
40
+ this.emit('UPDATE', resp.data);
41
+ return resp.data;
42
42
  });
43
43
  }
44
44
  delete(name) {
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export * from './email';
7
7
  export * from './groups';
8
8
  export * from './logger';
9
9
  export * from './momentum';
10
+ export * from './payments';
10
11
  export * from './pdf';
11
12
  export * from './settings';
12
13
  export * from './sockets';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,OAAO,CAAC;AACtB,cAAc,QAAQ,CAAC;AACvB,cAAc,QAAQ,CAAC;AACvB,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC;AAC3B,cAAc,OAAO,CAAC;AACtB,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,OAAO,CAAC;AACtB,cAAc,QAAQ,CAAC;AACvB,cAAc,QAAQ,CAAC;AACvB,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,OAAO,CAAC;AACtB,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC"}
package/dist/index.js CHANGED
@@ -23,6 +23,7 @@ __exportStar(require("./email"), exports);
23
23
  __exportStar(require("./groups"), exports);
24
24
  __exportStar(require("./logger"), exports);
25
25
  __exportStar(require("./momentum"), exports);
26
+ __exportStar(require("./payments"), exports);
26
27
  __exportStar(require("./pdf"), exports);
27
28
  __exportStar(require("./settings"), exports);
28
29
  __exportStar(require("./sockets"), exports);
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var B=function(t,i=!1){if(t==null)throw new Error("Cannot clean a NULL value");return Array.isArray(t)?t=t.filter((e)=>e!=null):Object.entries(t).forEach(([e,n])=>{(i&&n===void 0||!i&&n==null)&&delete t[e]}),t};var Q=function(t,i){const e=typeof t,n=typeof i;return e!="object"||t==null||n!="object"||i==null?e=="function"&&n=="function"?t.toString()==i.toString():t===i:Object.keys(t).length!=Object.keys(i).length?!1:Object.keys(t).every((s)=>Q(t[s],i[s]))};var x=function(t,i){const e=document.createElement("a");e.href=t,e.download=i,document.body.appendChild(e),e.click(),document.body.removeChild(e)};var St=Object.defineProperty,Mt=(t,i,e)=>(i in t)?St(t,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[i]=e,r=(t,i,e)=>(Mt(t,typeof i!="symbol"?i+"":i,e),e);class a{constructor(){r(this,"listeners",{})}static emit(t,...i){(this.listeners["*"]||[]).forEach((e)=>e(t,...i)),(this.listeners[t.toString()]||[]).forEach((e)=>e(...i))}static off(t,i){const e=t.toString();this.listeners[e]=(this.listeners[e]||[]).filter((n)=>n===i)}static on(t,i){var e;const n=t.toString();return this.listeners[n]||(this.listeners[n]=[]),(e=this.listeners[n])==null||e.push(i),()=>this.off(t,i)}static once(t,i){return new Promise((e)=>{const n=this.on(t,(...s)=>{e(s.length==1?s[0]:s),i&&i(...s),n()})})}emit(t,...i){(this.listeners["*"]||[]).forEach((e)=>e(t,...i)),(this.listeners[t]||[]).forEach((e)=>e(...i))}off(t,i){this.listeners[t]=(this.listeners[t]||[]).filter((e)=>e===i)}on(t,i){var e;return this.listeners[t]||(this.listeners[t]=[]),(e=this.listeners[t])==null||e.push(i),()=>this.off(t,i)}once(t,i){return new Promise((e)=>{const n=this.on(t,(...s)=>{e(s.length==1?s[0]:s),i&&i(...s),n()})})}}r(a,"listeners",{});class w extends Error{constructor(t,i){super(t);r(this,"_code"),i!=null&&(this._code=i)}get code(){return this._code||this.constructor.code}set code(t){this._code=t}static from(t){const i=Number(t.statusCode)??Number(t.code),e=new this(t.message||t.toString());return Object.assign(e,{stack:t.stack,...t,code:i??void 0})}static instanceof(t){return t.constructor.code!=null}toString(){return this.message||super.toString()}}r(w,"code",500);class yt extends w{constructor(t="Bad Request"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(yt,"code",400);class mt extends w{constructor(t="Unauthorized"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(mt,"code",401);class ct extends w{constructor(t="Forbidden"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(ct,"code",403);class dt extends w{constructor(t="Not Found"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(dt,"code",404);class gt extends w{constructor(t="Internal Server Error"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(gt,"code",500);var U={CLEAR:"\x1B[0m",BRIGHT:"\x1B[1m",DIM:"\x1B[2m",UNDERSCORE:"\x1B[4m",BLINK:"\x1B[5m",REVERSE:"\x1B[7m",HIDDEN:"\x1B[8m"},k={BLACK:"\x1B[30m",RED:"\x1B[31m",GREEN:"\x1B[32m",YELLOW:"\x1B[33m",BLUE:"\x1B[34m",MAGENTA:"\x1B[35m",CYAN:"\x1B[36m",LIGHT_GREY:"\x1B[37m",GREY:"\x1B[90m",LIGHT_RED:"\x1B[91m",LIGHT_GREEN:"\x1B[92m",LIGHT_YELLOW:"\x1B[93m",LIGHT_BLUE:"\x1B[94m",LIGHT_MAGENTA:"\x1B[95m",LIGHT_CYAN:"\x1B[96m",WHITE:"\x1B[97m"};var P=((t)=>(t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG",t))(P||{}),kt=class t extends a{constructor(i){super(),this.namespace=i}pad(i,e,n,s=!1){const o=i.toString(),u=e-o.length;if(u<=0)return o;const h=Array(~~(u/n.length)).fill(n).join("");return s?o+h:h+o}format(...i){const e=new Date;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",!0)}`}${this.namespace?` [${this.namespace}]`:""} ${i.join(" ")}`}debug(...i){if(t.LOG_LEVEL<4)return;const e=this.format(...i);t.emit(4,e),console.debug(k.LIGHT_GREY+e+U.CLEAR)}log(...i){if(t.LOG_LEVEL<3)return;const e=this.format(...i);t.emit(3,e),console.log(U.CLEAR+e)}info(...i){if(t.LOG_LEVEL<2)return;const e=this.format(...i);t.emit(2,e),console.info(k.BLUE+e+U.CLEAR)}warn(...i){if(t.LOG_LEVEL<1)return;const e=this.format(...i);t.emit(1,e),console.warn(k.YELLOW+e+U.CLEAR)}error(...i){if(t.LOG_LEVEL<0)return;const e=this.format(...i);t.emit(0,e),console.error(k.RED+e+U.CLEAR)}};r(kt,"LOG_LEVEL",4);var xt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",Wt="0123456789",Ht="~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/",Ct=xt+Wt+Ht;class J extends Promise{constructor(t){super((i,e)=>t((n)=>i(n),(n)=>e(n),(n)=>this.progress=n));r(this,"listeners",[]),r(this,"_progress",0)}get progress(){return this._progress}set progress(t){t!=this._progress&&(this._progress=t,this.listeners.forEach((i)=>i(t)))}onProgress(t){return this.listeners.push(t),this}}var X=class t{constructor(i={}){r(this,"interceptors",{}),r(this,"headers",{}),this.opts=i,this.headers=i.headers||{},i.interceptors&&i.interceptors.forEach((e)=>t.addInterceptor(e))}static addInterceptor(i){const e=Object.keys(t.interceptors).length.toString();return t.interceptors[e]=i,()=>{t.interceptors[e]=null}}addInterceptor(i){const e=Object.keys(this.interceptors).length.toString();return this.interceptors[e]=i,()=>{this.interceptors[e]=null}}async request(i={}){var e,n;if(!this.opts.url&&!i.url)throw new Error("URL needs to be set");let s=((e=i.url)!=null&&e.startsWith("http")?i.url:(this.opts.url||"")+(i.url||"")).replace(/([^:]\/)\/+/g,"$1");if(i.fragment&&(s.includes("#")?s.replace(/#.*(\?|\n)/g,(u,h)=>`#${i.fragment}${h}`):s+="#"+i.fragment),i.query){const u=Array.isArray(i.query)?i.query:Object.keys(i.query).map((h)=>({key:h,value:i.query[h]}));s+=(s.includes("?")?"&":"?")+u.map((h)=>`${h.key}=${h.value}`).join("&")}const o=B({"Content-Type":i.body&&!(i.body instanceof FormData)?"application/json":void 0,...t.headers,...this.headers,...i.headers});return fetch(s,{headers:o,method:i.method||(i.body?"POST":"GET"),body:(n=o["Content-Type"])!=null&&n.startsWith("application/json")&&i.body?JSON.stringify(i.body):i.body}).then(async(u)=>{for(let l of[...Object.values(t.interceptors),...Object.values(this.interceptors)])await new Promise((m)=>l(u,()=>m()));const h=await(async()=>{var l,m;return!i.skipConverting&&((l=u.headers.get("Content-Type"))!=null&&l.startsWith("application/json"))?await u.json():!i.skipConverting&&((m=u.headers.get("Content-Type"))!=null&&m.startsWith("text/plain"))?await u.text():u})();if(u.ok)return h;throw Object.assign(new Error(typeof h=="string"?h:u.statusText),typeof h=="object"?h:{})})}};r(X,"interceptors",{}),r(X,"headers",{});var Et=X;class p extends Et{t;i;emitter=new a;_token=null;get token(){return this._token}set token(t){if(t==this._token)return;this._token=t,this.headers.Authorization=t?`Bearer ${t}`:void 0,this.emit("TOKEN",t)}constructor(t=location.origin,i={}){i.url=t;super(i);this.url=t;this.opts=i}emit=this.emitter.emit.bind(this.emitter);off=this.emitter.off.bind(this.emitter);on=this.emitter.on.bind(this.emitter);once=this.emitter.once.bind(this.emitter);request(t){const i=super.request(t).then((e)=>{return this.emit("RESPONSE",e,t),e}).catch((e)=>{throw this.emit("REJECTED",e,t),e});return this.emit("REQUEST",i,t),i}}function T(t,i){if(typeof i!=="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");C(t,i);function e(){this.constructor=t}t.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}function S(t){var i=typeof Symbol==="function"&&Symbol.iterator,e=i&&t[i],n=0;if(e)return e.call(t);if(t&&typeof t.length==="number")return{next:function(){if(t&&n>=t.length)t=void 0;return{value:t&&t[n++],done:!t}}};throw new TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")}function L(t,i){var e=typeof Symbol==="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),s,o=[],u;try{while((i===void 0||i-- >0)&&!(s=n.next()).done)o.push(s.value)}catch(h){u={error:h}}finally{try{if(s&&!s.done&&(e=n.return))e.call(n)}finally{if(u)throw u.error}}return o}function R(t,i,e){if(e||arguments.length===2){for(var n=0,s=i.length,o;n<s;n++)if(o||!(n in i)){if(!o)o=Array.prototype.slice.call(i,0,n);o[n]=i[n]}}return t.concat(o||Array.prototype.slice.call(i))}var C=function(t,i){return C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var s in n)if(Object.prototype.hasOwnProperty.call(n,s))e[s]=n[s]},C(t,i)};function y(t){return typeof t==="function"}function W(t){var i=function(n){Error.call(n),n.stack=new Error().stack},e=t(i);return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}var H=W(function(t){return function i(e){t(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map(function(n,s){return s+1+") "+n.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=e}});function M(t,i){if(t){var e=t.indexOf(i);0<=e&&t.splice(e,1)}}function F(t){return t instanceof $||t&&"closed"in t&&y(t.remove)&&y(t.add)&&y(t.unsubscribe)}var Tt=function(t){if(y(t))t();else t.unsubscribe()},$=function(){function t(i){this.initialTeardown=i,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var i,e,n,s,o;if(!this.closed){this.closed=!0;var u=this._parentage;if(u)if(this._parentage=null,Array.isArray(u))try{for(var h=S(u),l=h.next();!l.done;l=h.next()){var m=l.value;m.remove(this)}}catch(f){i={error:f}}finally{try{if(l&&!l.done&&(e=h.return))e.call(h)}finally{if(i)throw i.error}}else u.remove(this);var I=this.initialTeardown;if(y(I))try{I()}catch(f){o=f instanceof H?f.errors:[f]}var G=this._finalizers;if(G){this._finalizers=null;try{for(var A=S(G),g=A.next();!g.done;g=A.next()){var E=g.value;try{Tt(E)}catch(f){if(o=o!==null&&o!==void 0?o:[],f instanceof H)o=R(R([],L(o)),L(f.errors));else o.push(f)}}}catch(f){n={error:f}}finally{try{if(g&&!g.done&&(s=A.return))s.call(A)}finally{if(n)throw n.error}}}if(o)throw new H(o)}},t.prototype.add=function(i){var e;if(i&&i!==this)if(this.closed)Tt(i);else{if(i instanceof t){if(i.closed||i._hasParent(this))return;i._addParent(this)}(this._finalizers=(e=this._finalizers)!==null&&e!==void 0?e:[]).push(i)}},t.prototype._hasParent=function(i){var e=this._parentage;return e===i||Array.isArray(e)&&e.includes(i)},t.prototype._addParent=function(i){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(i),e):e?[e,i]:i},t.prototype._removeParent=function(i){var e=this._parentage;if(e===i)this._parentage=null;else if(Array.isArray(e))M(e,i)},t.prototype.remove=function(i){var e=this._finalizers;if(e&&M(e,i),i instanceof t)i._removeParent(this)},t.EMPTY=function(){var i=new t;return i.closed=!0,i}(),t}();var Z=$.EMPTY;var c={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var O={setTimeout:function(t,i){var e=[];for(var n=2;n<arguments.length;n++)e[n-2]=arguments[n];var s=O.delegate;if(s===null||s===void 0?void 0:s.setTimeout)return s.setTimeout.apply(s,R([t,i],L(e)));return setTimeout.apply(void 0,R([t,i],L(e)))},clearTimeout:function(t){var i=O.delegate;return((i===null||i===void 0?void 0:i.clearTimeout)||clearTimeout)(t)},delegate:void 0};function At(t){O.setTimeout(function(){var i=c.onUnhandledError;if(i)i(t);else throw t})}function Y(){}function Pt(t){return v("E",void 0,t)}function Dt(t){return v("N",t,void 0)}function v(t,i,e){return{kind:t,value:i,error:e}}var wt=function(){return v("C",void 0,void 0)}();function q(t){if(c.useDeprecatedSynchronousErrorHandling){var i=!D;if(i)D={errorThrown:!1,error:null};if(t(),i){var e=D,n=e.errorThrown,s=e.error;if(D=null,n)throw s}}else t()}function Lt(t){if(c.useDeprecatedSynchronousErrorHandling&&D)D.errorThrown=!0,D.error=t}var D=null;var j=function(t,i){return Ft.call(t,i)},K=function(t){if(c.useDeprecatedSynchronousErrorHandling)Lt(t);else At(t)},Nt=function(t){throw t},z=function(t,i){var e=c.onStoppedNotification;e&&O.setTimeout(function(){return e(t,i)})},b=function(t){T(i,t);function i(e){var n=t.call(this)||this;if(n.isStopped=!1,e){if(n.destination=e,F(e))e.add(n)}else n.destination=Vt;return n}return i.create=function(e,n,s){return new N(e,n,s)},i.prototype.next=function(e){if(this.isStopped)z(Dt(e),this);else this._next(e)},i.prototype.error=function(e){if(this.isStopped)z(Pt(e),this);else this.isStopped=!0,this._error(e)},i.prototype.complete=function(){if(this.isStopped)z(wt,this);else this.isStopped=!0,this._complete()},i.prototype.unsubscribe=function(){if(!this.closed)this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null},i.prototype._next=function(e){this.destination.next(e)},i.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},i.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},i}($);var Ft=Function.prototype.bind,Kt=function(){function t(i){this.partialObserver=i}return t.prototype.next=function(i){var e=this.partialObserver;if(e.next)try{e.next(i)}catch(n){K(n)}},t.prototype.error=function(i){var e=this.partialObserver;if(e.error)try{e.error(i)}catch(n){K(n)}else K(i)},t.prototype.complete=function(){var i=this.partialObserver;if(i.complete)try{i.complete()}catch(e){K(e)}},t}(),N=function(t){T(i,t);function i(e,n,s){var o=t.call(this)||this,u;if(y(e)||!e)u={next:e!==null&&e!==void 0?e:void 0,error:n!==null&&n!==void 0?n:void 0,complete:s!==null&&s!==void 0?s:void 0};else{var h;if(o&&c.useDeprecatedNextContext)h=Object.create(e),h.unsubscribe=function(){return o.unsubscribe()},u={next:e.next&&j(e.next,h),error:e.error&&j(e.error,h),complete:e.complete&&j(e.complete,h)};else u=e}return o.destination=new Kt(u),o}return i}(b);var Vt={closed:!0,next:Y,error:Nt,complete:Y};var Rt=function(){return typeof Symbol==="function"&&Symbol.observable||"@@observable"}();function $t(t){return t}function Ot(t){if(t.length===0)return $t;if(t.length===1)return t[0];return function i(e){return t.reduce(function(n,s){return s(n)},e)}}var qt=function(t){var i;return(i=t!==null&&t!==void 0?t:c.Promise)!==null&&i!==void 0?i:Promise},Xt=function(t){return t&&y(t.next)&&y(t.error)&&y(t.complete)},Bt=function(t){return t&&t instanceof b||Xt(t)&&F(t)},_=function(){function t(i){if(i)this._subscribe=i}return t.prototype.lift=function(i){var e=new t;return e.source=this,e.operator=i,e},t.prototype.subscribe=function(i,e,n){var s=this,o=Bt(i)?i:new N(i,e,n);return q(function(){var u=s,h=u.operator,l=u.source;o.add(h?h.call(o,l):l?s._subscribe(o):s._trySubscribe(o))}),o},t.prototype._trySubscribe=function(i){try{return this._subscribe(i)}catch(e){i.error(e)}},t.prototype.forEach=function(i,e){var n=this;return e=qt(e),new e(function(s,o){var u=new N({next:function(h){try{i(h)}catch(l){o(l),u.unsubscribe()}},error:o,complete:s});n.subscribe(u)})},t.prototype._subscribe=function(i){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(i)},t.prototype[Rt]=function(){return this},t.prototype.pipe=function(){var i=[];for(var e=0;e<arguments.length;e++)i[e]=arguments[e];return Ot(i)(this)},t.prototype.toPromise=function(i){var e=this;return i=qt(i),new i(function(n,s){var o;e.subscribe(function(u){return o=u},function(u){return s(u)},function(){return n(o)})})},t.create=function(i){return new t(i)},t}();var It=W(function(t){return function i(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var tt=function(t){T(i,t);function i(){var e=t.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return i.prototype.lift=function(e){var n=new Gt(this,this);return n.operator=e,n},i.prototype._throwIfClosed=function(){if(this.closed)throw new It},i.prototype.next=function(e){var n=this;q(function(){var s,o;if(n._throwIfClosed(),!n.isStopped){if(!n.currentObservers)n.currentObservers=Array.from(n.observers);try{for(var u=S(n.currentObservers),h=u.next();!h.done;h=u.next()){var l=h.value;l.next(e)}}catch(m){s={error:m}}finally{try{if(h&&!h.done&&(o=u.return))o.call(u)}finally{if(s)throw s.error}}}})},i.prototype.error=function(e){var n=this;q(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=e;var s=n.observers;while(s.length)s.shift().error(e)}})},i.prototype.complete=function(){var e=this;q(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;var n=e.observers;while(n.length)n.shift().complete()}})},i.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(i.prototype,"observed",{get:function(){var e;return((e=this.observers)===null||e===void 0?void 0:e.length)>0},enumerable:!1,configurable:!0}),i.prototype._trySubscribe=function(e){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,e)},i.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},i.prototype._innerSubscribe=function(e){var n=this,s=this,o=s.hasError,u=s.isStopped,h=s.observers;if(o||u)return Z;return this.currentObservers=null,h.push(e),new $(function(){n.currentObservers=null,M(h,e)})},i.prototype._checkFinalizedStatuses=function(e){var n=this,s=n.hasError,o=n.thrownError,u=n.isStopped;if(s)e.error(o);else if(u)e.complete()},i.prototype.asObservable=function(){var e=new _;return e.source=this,e},i.create=function(e,n){return new Gt(e,n)},i}(_);var Gt=function(t){T(i,t);function i(e,n){var s=t.call(this)||this;return s.destination=e,s.source=n,s}return i.prototype.next=function(e){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,e)},i.prototype.error=function(e){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.call(n,e)},i.prototype.complete=function(){var e,n;(n=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||n===void 0||n.call(e)},i.prototype._subscribe=function(e){var n,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(e))!==null&&s!==void 0?s:Z},i}(tt);var d=function(t){T(i,t);function i(e){var n=t.call(this)||this;return n._value=e,n}return Object.defineProperty(i.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),i.prototype._subscribe=function(e){var n=t.prototype._subscribe.call(this,e);return!n.closed&&e.next(this._value),n},i.prototype.getValue=function(){var e=this,n=e.hasError,s=e.thrownError,o=e._value;if(n)throw s;return this._throwIfClosed(),o},i.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},i}(tt);var Qt;((h)=>{h[h.CRON=0]="CRON";h[h.EVENT=1]="EVENT";h[h.DELETE=2]="DELETE";h[h.GET=3]="GET";h[h.PATCH=4]="PATCH";h[h.POST=5]="POST";h[h.PUT=6]="PUT"})(Qt||={});class it extends a{api;$cache=new d([]);get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){return this.api.request({url:`/api/actions/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter((i)=>i._id!=t),this.emit("DELETE",t)})}list(){return this.api.request({url:"/api/actions"}).then((t)=>{return this.cache=t,this.emit("LIST",t),t})}read(t,i=!1){const e=this.cache.find((n)=>n._id==t);if(!i&&e)return Promise.resolve(e);return this.api.request({url:`/api/actions/${t}`}).then((n)=>{if(n)this.cache=this.cache.filter((s)=>s._id!=t).concat([n]);return this.emit("READ",n),n})}run(t,i={}){return this.api.request({url:("/api/actions/run/"+t).replaceAll("//","/"),...i})}runById(t,i={}){const e=typeof t=="string"?t:t._id;return this.api.request({url:"/api/actions/run-by-id/"+e,method:"POST",...i})}update(t){return this.api.request({url:`/api/actions${t._id?`/${t._id}`:""}`,method:"POST",body:t}).then((i)=>{if(i)this.cache=this.cache.filter((e)=>e._id!=i._id).concat([i]);return this.emit("UPDATE",i),i})}}class Ut{t;constructor(t){this.api=t}disable(t){return this.api.request({url:`/api/auth/totp/${t}`,method:"DELETE"})}enable=this.reset;reset(t){return this.api.request({url:`/api/auth/totp/${t}`,method:"POST"})}setup(t,i="app",e){return this.api.request({url:`/api/auth/totp/${t}`,body:B({method:i,totp:e})})}}class et extends a{i;api;storageKey;totp;$user=new d(void 0);get user(){return this.$user.value}set user(t){if(!Q(this.user,t)){const i=t?t:null;this.$user.next(i),this.emit("USER",i)}}constructor(t,i){super();this.opts=i;if(this.api=typeof t=="string"?new p(t):t,this.totp=new Ut(this.api),!this.opts?.loginUi)this.opts={...this.opts,loginUi:this.api.url+"/ui/login"};if(this.storageKey=`momentum:${new URL(this.api.url).host}`,this.api.addInterceptor((e,n)=>{const s=["/api/auth/login","/api/auth/password","/api/auth/totp"];if(e.status==401&&!s.find((o)=>e.url.includes(o)))this.emit("SESSION_EXPIRED");n()}),this.api.on("TOKEN",(e)=>{if(this.opts?.persist)if(e)localStorage.setItem(this.storageKey,e);else localStorage.removeItem(this.storageKey);if(e)this.session(e,!0).catch(()=>{});else this.user=null}),i?.persist){const e=localStorage.getItem(this.storageKey);if(e)this.api.token=e;else this.user=null}else this.user=null}knownHost(t=location.origin){if(t.startsWith("/"))return Promise.resolve();return this.api.request({url:`/api/auth/known-host?host=${encodeURI(new URL(t).origin)}`})}login(t,i,e){return this.api.request({url:"/api/auth/login",headers:{Authorization:void 0},body:{username:t.trim(),password:i.trim(),totp:e}}).then(async(n)=>{return this.api.token=n.token,await this.once("USER")})}loginRedirect(t=location.origin){return new Promise((i,e)=>{const n=window.open(encodeURI(`${this.opts?.loginUi}?redirect=postmessage&host=${t}`),"_blank");if(!n)return e("Unable to open login");n.addEventListener("message",(s)=>{if(!s?.data?.token)return e("Unknown response from login");this.api.token=s.data.token,i(s.data.token),n.close()})})}logout(){this.api.token=null,this.user=null,this.emit("LOGOUT")}async register(t){const i=await this.api.request({url:"/api/auth/register",body:{...t}});if(i.image.startsWith("/"))i.image=`${this.api.url}${i.image}?token=${this.api.token}`;return this.emit("REGISTER",i),i}reset(t,i){return this.api.request({url:"/api/auth/reset",headers:{Authorization:i?`Bearer ${i}`:void 0},body:{email:i?void 0:t,password:i?t:void 0}})}async session(t,i=!1){if(!t)t=this.api.token;const e=await this.api.request({url:"/api/auth/session",headers:t?{Authorization:`Bearer ${t}`}:void 0});if(i){if(this.api.token=t,e?.user)e.user.image=`${this.api.url}${e.user.image}?token=${this.api.token}`;if(this.user=e?.user||null,e)this.emit("LOGIN",e.user)}return e}async updatePassword(t,i,e){return this.api.request({url:"/api/auth/password",body:{username:t,password:i,oldPassword:e}}).then((n)=>{if(n?.token)this.api.token=n.token})}}class nt extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t,i){return this.api.request({url:`/api/data/${t}/${i}`,method:"DELETE"}).then(()=>this.emit("DELETE",t,i))}get(t,i){return this.api.request({url:`/api/data/${t}${i?`/${i}`:""}`}).then((e)=>{return this.emit("GET",t,e),e})}raw(t,i,e,n){return this.api.request({url:`/api/data/${t}`,body:{operand:i,query:e,options:n}}).then((s)=>{return this.emit("RAW",t,s),s})}set(t,i,e=!1){return this.api.request({url:`/api/data/${t}/${i._id||""}`,method:e?"PATCH":"POST",body:i}).then((n)=>{return this.emit("SET",t,i),n})}}class st extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}send(t){let i="/api/email";if(typeof t.body=="object")i+=`/${t.body.template}`;return this.api.request({url:i,body:t}).then((e)=>{return this.emit("SENT",t),e})}}class ot extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}create(t){return this.api.request({url:`/api/groups/${t.name}`,method:"POST",body:t}).then((i)=>{return this.emit("CREATE",i),i})}list(){return this.api.request({url:"/api/groups"}).then((t)=>{return this.emit("LIST",t),t})}read(t){return this.api.request({url:`/api/groups/${t}`}).then((i)=>{return this.emit("READ",i),i})}update(t){return this.api.request({url:`/api/groups/${t.name}`,method:"PATCH",body:t}).then((i)=>{return this.emit("UPDATE",i),i})}delete(t){return this.api.request({url:`/api/groups/${t}`,method:"DELETE"}).then(()=>this.emit("DELETE",t))}}class ut{api;constructor(t,i){if(this.api=typeof t=="string"?new p(t):t,i!=null&&i!="NONE")window.addEventListener("error",(e)=>this.error(e.error.stack)),window.addEventListener("unhandledrejection",async(e)=>this.error(e.reason.stack))}buildLog(t,i){return{time:(new Date()).getTime(),level:t,log:i,ctx:{cores:navigator.hardwareConcurrency,mem:navigator?.deviceMemory,res:[window.innerWidth,window.innerHeight],url:location.href}}}clearClientLogs(){return this.api.request({url:"/api/logs/client",method:"DELETE"})}clearServerLogs(){return this.api.request({url:"/api/logs/server",method:"DELETE"})}clientLogs(t,i){const e=[t?`length=${t}`:void 0,i?`page=${i}`:void 0].filter((n)=>!!n).join("&");return this.api.request({url:`/api/logs/client${e?`?${e}`:""}`})}serverLogs(t,i){const e=[t?`length=${t}`:void 0,i?`page=${i}`:void 0].filter((n)=>!!n).join("&");return this.api.request({url:`/api/logs/server${e?`?${e}`:""}`})}debug(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.DEBUG,t)}).catch(()=>{})}log(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.LOG,t)}).catch(()=>{})}info(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.INFO,t)}).catch(()=>{})}warn(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.WARN,t)}).catch(()=>{})}error(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.ERROR,t)}).catch(()=>{})}}class ht extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}async handleResponse(t,i){const e=await t.blob();if(i){const n=URL.createObjectURL(e);x(n,i.endsWith(".pdf")?i:i+".pdf"),URL.revokeObjectURL(n)}return this.emit("CREATE",e),e}fromHtml(t,i={}){return this.api.request({url:"/api/pdf",body:{html:t}}).then((e)=>this.handleResponse(e,i.download?i.fileName||(new Date()).toISOString():void 0))}fromTemplate(t,i,e={}){return this.api.request({url:`/api/pdf${t}`,body:i}).then((n)=>this.handleResponse(n,e.download?e.fileName||(new Date()).toISOString():void 0))}fromUrl(t,i={}){return this.api.request({url:`/api/pdf?url=${t}`}).then((e)=>this.handleResponse(e,i.download?i.fileName||(new Date()).toISOString():void 0))}}class V{static timeout=1e4;api;url;connection;open=!1;constructor(t){if(this.api=typeof t=="string"?new p(t):t,this.url=this.api.url.replace("http","ws"),this.api.on("TOKEN",()=>this.connect()),!this.api.token)this.connect()}close(){console.debug("Disconnected from Momentum"),this.open=!1,this.connection.close()}connect(t=3){if(this.connection?.readyState<2)this.connection.close();this.connection=new WebSocket(this.url+(this.api.token?`?token=${this.api.token}`:""));const i=setTimeout(()=>{if(this.open)return;if(this.connection.close(),console.error("Momentum connection timeout"),t>0)this.connect(t-1)},V.timeout);this.connection.onclose=()=>this.open=!1,this.connection.onmessage=this.handle,this.connection.onopen=()=>{this.open=!0,clearTimeout(i),console.debug("Connected to Momentum")}}handle(...t){console.log(t)}send(t,i){this.connection.send(JSON.stringify({token:this.api.token,channel:t,payload:i}))}}class at extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:i,method:"DELETE"}).then(()=>{this.emit("DELETE",i)})}list(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:i+"?list"}).then((e)=>{return this.emit("LIST",t,e),e})}open(t,i="_blank"){const e=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/"),n=`${this.api.url}${e}${this.api.token?`?token=${this.api.token}`:""}`;if(!i)return n;return this.emit("OPEN",t),window.open(n,i)}mkdir(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/");return this.api.request({url:i+"?directory",method:"POST"})}download(t,i={}){return new J((e,n,s)=>{const o=("/api/storage/"+t).replaceAll("//","/");this.api.request({...i,url:o,skipConverting:!0}).then((u)=>{if(!u.ok)return n(u.statusText);const h=u.headers.get("Content-Length"),l=h?parseInt(h,10):0;let m=[],I=0;const G=u.body?.getReader(),A=(g)=>{if(g.done){s(1);const E=new Blob(m),f=i.downloadAs||new URL(u.url).pathname.split("/").pop(),ft=URL.createObjectURL(E);x(ft,f.includes(".")?f:f+".zip"),URL.revokeObjectURL(ft),this.emit("DOWNLOAD",t,E),e(E)}else{const E=g.value;m.push(E),I+=E.length,s(I/l),G.read().then(A)}};G?.read().then(A)})})}async upload(t,i=""){const e=()=>{return new Promise((o)=>{const u=document.createElement("input");u.type="file",u.accept=i?.accept||"*",u.style.display="none",u.multiple=!!i?.multiple,u.onblur=u.onchange=async()=>{o(Array.from(u.files)),u.remove()},document.body.appendChild(u),u.click()})};if(!t)t=await e();if(!t||Array.isArray(t)&&!t.length)return[];const n=new FormData,s=("/api/storage/"+(typeof i=="string"?i:i?.path)).replaceAll("//","/");return(Array.isArray(t)?t:[t]).forEach((o)=>n.append("file",o)),this.api.request({url:s,body:n}).then((o)=>{return this.emit("UPLOAD",o),o})}}class pt extends a{api;listed=!1;$cache=new d([]);get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){return this.api.request({url:`/api/users/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter((i)=>i.username!=t),this.emit("DELETE",t)})}list(t=!1){if(!t&&this.listed)return Promise.resolve(this.cache);return this.api.request({url:"/api/users"}).then((i)=>{return i.map((e)=>{return e.image=this.api.url+e.image+`?token=${this.api.token}`,e}),this.cache=i,this.listed=!0,this.emit("LIST",i),i})}read(t,i=!1){if(!i){const e=this.cache.find((n)=>n.username==t);if(e)return Promise.resolve(e)}return this.api.request({url:`/api/users/${t}`}).then((e)=>{if(e.image=this.api.url+e.image+`?token=${this.api.token}`,e)this.cache=[...this.cache.filter((n)=>n.username!=t),e];return this.emit("READ",e),e})}update(t){return this.api.request({url:`/api/users/${t.username}`,method:"PATCH",body:t}).then((i)=>{if(i.image=this.api.url+i.image+`?token=${this.api.token}`,i)this.cache=this.cache.filter((e)=>e.username!=t.username).concat([i]);return this.emit("UPDATE",i),i})}uploadImage(t,i){const e=new FormData;return e.append("file",i),this.api.request({url:`/api/users/${t}/image`,body:e}).then((n)=>{return this.emit("UPLOAD_IMAGE",i),n})}}class lt extends a{api;$cache=new d({});get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new p(t):t}list(t=!1){return this.api.request({url:"/api/settings"+(t?"?detailed":"")}).then((i)=>{return this.cache=!t?i:Object.values(i).reduce((e,n)=>({...e,[n.key]:n.value}),{}),this.emit("LIST",i),i})}delete(t){return this.api.request({url:`/api/settings/${t}`,method:"DELETE"}).then(()=>{this.cache={...this.cache,[t]:void 0},this.emit("DELETE",t)})}read(t,i=!1){if(!i&&this.cache[t])return Promise.resolve(this.cache[t]);return this.api.request({url:`/api/settings/${t}`}).then((e)=>{if(e)this.cache={...this.cache,[e.key]:e};return this.emit("READ",e),e})}update(t){return this.api.request({url:`/api/settings/${t.key}`,body:t}).then((i)=>{if(i)this.cache={...this.cache,[i.key]:i.value};return this.emit("UPDATE",i),i})}}class rt extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){return this.api.request({url:`/api/static/${t}`,method:"DELETE"}).then(()=>{this.emit("DELETE",t)})}list(t){const i=("/api/static/"+t).replaceAll("//","/");return this.api.request({url:i}).then((e)=>{return this.emit("LIST",t,e),e})}upload(t,i="/"){const e=new FormData;return(Array.isArray(t)?t:[t]).forEach((n)=>e.append("file",n)),this.api.request({url:"/api/static"+i,body:e}).then((n)=>{return this.emit("UPLOAD",n),n})}}class Jt extends a{api;actions;auth;data;email;groups;logger;pdf;settings;socket;static;storage;users;constructor(t,i){super();if(this.api=new p(t,i?.api),this.actions=new it(this.api),this.auth=new et(this.api,{persist:i?.persist??!0,loginUi:i?.loginUi}),this.data=new nt(this.api),this.email=new st(this.api),this.groups=new ot(this.api),this.logger=new ut(this.api,i?.logLevel),this.pdf=new ht(this.api),this.settings=new lt(this.api),this.static=new rt(this.api),this.storage=new at(this.api),this.users=new pt(this.api),i?.socket)this.socket=new V(this.api);this.api.on("*",(e,...n)=>this.emit(`API::${e}`,...n)),this.actions.on("*",(e,...n)=>this.emit(`ACTIONS::${e}`,...n)),this.auth.on("*",(e,...n)=>this.emit(`AUTH::${e}`,...n)),this.data.on("*",(e,...n)=>this.emit(`DATA::${e}`,...n)),this.email.on("*",(e,...n)=>this.emit(`EMAIL::${e}`,...n)),this.groups.on("*",(e,...n)=>this.emit(`GROUPS::${e}`,...n)),this.pdf.on("*",(e,...n)=>this.emit(`PDF::${e}`,...n)),this.settings.on("*",(e,...n)=>this.emit(`SETTINGS::${e}`,...n)),this.static.on("*",(e,...n)=>this.emit(`STATIC::${e}`,...n)),this.storage.on("*",(e,...n)=>this.emit(`STORAGE::${e}`,...n)),this.users.on("*",(e,...n)=>this.emit(`USERS::${e}`,...n)),this.users.on("*",(e,...n)=>{if(Array.isArray(n[0])){const s=n[0].find((o)=>o._id==this.auth.user?._id);if(s)this.auth.user=s}else if(n[0]._id==this.auth.user?._id)this.auth.user=n[0]})}}export{pt as Users,Ut as Totp,at as Storage,rt as Static,V as Socket,lt as Settings,ht as Pdf,Jt as Momentum,ut as Logger,ot as Groups,st as Email,nt as Data,et as Auth,p as Api,it as Actions,Qt as ActionType};
1
+ function B(t,i=!1){if(t==null)throw new Error("Cannot clean a NULL value");return Array.isArray(t)?t=t.filter((e)=>e!=null):Object.entries(t).forEach(([e,n])=>{(i&&n===void 0||!i&&n==null)&&delete t[e]}),t}function Z(t,i){const e=typeof t,n=typeof i;return e!="object"||t==null||n!="object"||i==null?e=="function"&&n=="function"?t.toString()==i.toString():t===i:Object.keys(t).length!=Object.keys(i).length?!1:Object.keys(t).every((s)=>Z(t[s],i[s]))}function v(t,i){const e=document.createElement("a");e.href=t,e.download=i,document.body.appendChild(e),e.click(),document.body.removeChild(e)}function ct(t,i){const e=URL.createObjectURL(t);v(e,i),URL.revokeObjectURL(e)}function Et(t={}){return new Promise((i)=>{const e=document.createElement("input");e.type="file",e.accept=t.accept||"*",e.style.display="none",e.multiple=!!t.multiple,e.onblur=e.onchange=async()=>{i(Array.from(e.files)),e.remove()},document.body.appendChild(e),e.click()})}function K(t){return new E((i,e,n)=>{const s=new XMLHttpRequest,a=new FormData;t.files.forEach((o)=>a.append("file",o)),s.withCredentials=!!t.withCredentials,s.upload.addEventListener("progress",(o)=>o.lengthComputable?n(o.loaded/o.total):null),s.upload.addEventListener("load",(o)=>i(o)),s.upload.addEventListener("error",(o)=>e(o)),s.open("POST",t.url),Object.entries(t.headers||{}).forEach(([o,p])=>s.setRequestHeader(o,p)),s.send(a)})}var Ft=Object.defineProperty,Kt=(t,i,e)=>(i in t)?Ft(t,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[i]=e,l=(t,i,e)=>(Kt(t,typeof i!="symbol"?i+"":i,e),e);class E extends Promise{constructor(t){super((i,e)=>t((n)=>i(n),(n)=>e(n),(n)=>this.progress=n));l(this,"listeners",[]),l(this,"_progress",0)}get progress(){return this._progress}set progress(t){t!=this._progress&&(this._progress=t,this.listeners.forEach((i)=>i(t)))}static from(t){return t instanceof E?t:new E((i,e)=>t.then((...n)=>i(...n)).catch((...n)=>e(...n)))}from(t){const i=E.from(t);return this.onProgress((e)=>i.progress=e),i}onProgress(t){return this.listeners.push(t),this}then(t,i){const e=super.then(t,i);return this.from(e)}catch(t){return this.from(super.catch(t))}finally(t){return this.from(super.finally(t))}}class u{constructor(){l(this,"listeners",{})}static emit(t,...i){(this.listeners["*"]||[]).forEach((e)=>e(t,...i)),(this.listeners[t.toString()]||[]).forEach((e)=>e(...i))}static off(t,i){const e=t.toString();this.listeners[e]=(this.listeners[e]||[]).filter((n)=>n===i)}static on(t,i){var e;const n=t.toString();return this.listeners[n]||(this.listeners[n]=[]),(e=this.listeners[n])==null||e.push(i),()=>this.off(t,i)}static once(t,i){return new Promise((e)=>{const n=this.on(t,(...s)=>{e(s.length==1?s[0]:s),i&&i(...s),n()})})}emit(t,...i){(this.listeners["*"]||[]).forEach((e)=>e(t,...i)),(this.listeners[t]||[]).forEach((e)=>e(...i))}off(t,i){this.listeners[t]=(this.listeners[t]||[]).filter((e)=>e===i)}on(t,i){var e;return this.listeners[t]||(this.listeners[t]=[]),(e=this.listeners[t])==null||e.push(i),()=>this.off(t,i)}once(t,i){return new Promise((e)=>{const n=this.on(t,(...s)=>{e(s.length==1?s[0]:s),i&&i(...s),n()})})}}l(u,"listeners",{});class A extends Error{constructor(t,i){super(t);l(this,"_code"),i!=null&&(this._code=i)}get code(){return this._code||this.constructor.code}set code(t){this._code=t}static from(t){const i=Number(t.statusCode)??Number(t.code),e=new this(t.message||t.toString());return Object.assign(e,{stack:t.stack,...t,code:i??void 0})}static instanceof(t){return t.constructor.code!=null}toString(){return this.message||super.toString()}}l(A,"code",500);class Tt extends A{constructor(t="Bad Request"){super(t)}static instanceof(t){return t.constructor.code==this.code}}l(Tt,"code",400);class At extends A{constructor(t="Unauthorized"){super(t)}static instanceof(t){return t.constructor.code==this.code}}l(At,"code",401);class wt extends A{constructor(t="Forbidden"){super(t)}static instanceof(t){return t.constructor.code==this.code}}l(wt,"code",403);class Pt extends A{constructor(t="Not Found"){super(t)}static instanceof(t){return t.constructor.code==this.code}}l(Pt,"code",404);class Dt extends A{constructor(t="Internal Server Error"){super(t)}static instanceof(t){return t.constructor.code==this.code}}l(Dt,"code",500);var X=class t{constructor(i={}){l(this,"interceptors",{}),l(this,"headers",{}),l(this,"url"),this.url=i.url??null,this.headers=i.headers||{},i.interceptors&&i.interceptors.forEach((e)=>t.addInterceptor(e))}static addInterceptor(i){const e=Object.keys(t.interceptors).length.toString();return t.interceptors[e]=i,()=>{t.interceptors[e]=null}}addInterceptor(i){const e=Object.keys(this.interceptors).length.toString();return this.interceptors[e]=i,()=>{this.interceptors[e]=null}}request(i={}){var e;if(!this.url&&!i.url)throw new Error("URL needs to be set");let n=((e=i.url)!=null&&e.startsWith("http")?i.url:(this.url||"")+(i.url||"")).replace(/([^:]\/)\/+/g,"$1");if(i.fragment&&(n.includes("#")?n.replace(/#.*(\?|\n)/g,(a,o)=>`#${i.fragment}${o}`):n+="#"+i.fragment),i.query){const a=Array.isArray(i.query)?i.query:Object.keys(i.query).map((o)=>({key:o,value:i.query[o]}));n+=(n.includes("?")?"&":"?")+a.map((o)=>`${o.key}=${o.value}`).join("&")}const s=B({"Content-Type":i.body?i.body instanceof FormData?"multipart/form-data":"application/json":void 0,...t.headers,...this.headers,...i.headers});return typeof i.body=="object"&&i.body!=null&&s["Content-Type"]=="application/json"&&(i.body=JSON.stringify(i.body)),new E((a,o,p)=>{fetch(n,{headers:s,method:i.method||(i.body?"POST":"GET"),body:i.body}).then(async(h)=>{var D,S;for(let y of[...Object.values(t.interceptors),...Object.values(this.interceptors)])await new Promise((W)=>y(h,()=>W()));const G=h.headers.get("Content-Length"),L=G?parseInt(G,10):0;let c=0;const k=(D=h.body)==null?void 0:D.getReader(),d=new ReadableStream({start(y){function W(){k==null||k.read().then((U)=>{if(U.done)return y.close();c+=U.value.byteLength,p(c/L),y.enqueue(U.value),W()}).catch((U)=>y.error(U))}W()}});if(h.data=new Response(d),i.decode==null||i.decode){const y=(S=h.headers.get("Content-Type"))==null?void 0:S.toLowerCase();y!=null&&y.includes("form")?h.data=await h.data.formData():y!=null&&y.includes("json")?h.data=await h.data.json():y!=null&&y.includes("text")?h.data=await h.data.text():y!=null&&y.includes("application")&&(h.data=await h.data.blob())}h.ok?a(h):o(h)})})}};l(X,"interceptors",{}),l(X,"headers",{});var Lt=X,H={CLEAR:"\x1B[0m",BRIGHT:"\x1B[1m",DIM:"\x1B[2m",UNDERSCORE:"\x1B[4m",BLINK:"\x1B[5m",REVERSE:"\x1B[7m",HIDDEN:"\x1B[8m"},F={BLACK:"\x1B[30m",RED:"\x1B[31m",GREEN:"\x1B[32m",YELLOW:"\x1B[33m",BLUE:"\x1B[34m",MAGENTA:"\x1B[35m",CYAN:"\x1B[36m",LIGHT_GREY:"\x1B[37m",GREY:"\x1B[90m",LIGHT_RED:"\x1B[91m",LIGHT_GREEN:"\x1B[92m",LIGHT_YELLOW:"\x1B[93m",LIGHT_BLUE:"\x1B[94m",LIGHT_MAGENTA:"\x1B[95m",LIGHT_CYAN:"\x1B[96m",WHITE:"\x1B[97m"};var w=((t)=>(t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG",t))(w||{}),Nt=class t extends u{constructor(i){super(),this.namespace=i}pad(i,e,n,s=!1){const a=i.toString(),o=e-a.length;if(o<=0)return a;const p=Array(~~(o/n.length)).fill(n).join("");return s?a+p:p+a}format(...i){const e=new Date;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",!0)}`}${this.namespace?` [${this.namespace}]`:""} ${i.join(" ")}`}debug(...i){if(t.LOG_LEVEL<4)return;const e=this.format(...i);t.emit(4,e),console.debug(F.LIGHT_GREY+e+H.CLEAR)}log(...i){if(t.LOG_LEVEL<3)return;const e=this.format(...i);t.emit(3,e),console.log(H.CLEAR+e)}info(...i){if(t.LOG_LEVEL<2)return;const e=this.format(...i);t.emit(2,e),console.info(F.BLUE+e+H.CLEAR)}warn(...i){if(t.LOG_LEVEL<1)return;const e=this.format(...i);t.emit(1,e),console.warn(F.YELLOW+e+H.CLEAR)}error(...i){if(t.LOG_LEVEL<0)return;const e=this.format(...i);t.emit(0,e),console.error(F.RED+e+H.CLEAR)}};l(Nt,"LOG_LEVEL",4);var Vt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",Ct="0123456789",Jt="~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/",bt=Vt+Ct+Jt;class r extends Lt{t;i;emitter=new u;_token=null;get token(){return this._token}set token(t){if(t==this._token)return;this._token=t,this.headers.Authorization=t?`Bearer ${t}`:void 0,this.emit("TOKEN",t)}constructor(t=location.origin,i={}){i.url=t;super(i);this.url=t;this.opts=i}emit=this.emitter.emit.bind(this.emitter);off=this.emitter.off.bind(this.emitter);on=this.emitter.on.bind(this.emitter);once=this.emitter.once.bind(this.emitter);request(t){const i=super.request(t).then((e)=>{return this.emit("RESPONSE",e,t),e}).catch((e)=>{const n=e?.data||e;throw this.emit("REJECTED",n,t),n});return this.emit("REQUEST",i,t),i}}function T(t,i){if(typeof i!=="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");j(t,i);function e(){this.constructor=t}t.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}function M(t){var i=typeof Symbol==="function"&&Symbol.iterator,e=i&&t[i],n=0;if(e)return e.call(t);if(t&&typeof t.length==="number")return{next:function(){if(t&&n>=t.length)t=void 0;return{value:t&&t[n++],done:!t}}};throw new TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")}function R(t,i){var e=typeof Symbol==="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),s,a=[],o;try{while((i===void 0||i-- >0)&&!(s=n.next()).done)a.push(s.value)}catch(p){o={error:p}}finally{try{if(s&&!s.done&&(e=n.return))e.call(n)}finally{if(o)throw o.error}}return a}function $(t,i,e){if(e||arguments.length===2){for(var n=0,s=i.length,a;n<s;n++)if(a||!(n in i)){if(!a)a=Array.prototype.slice.call(i,0,n);a[n]=i[n]}}return t.concat(a||Array.prototype.slice.call(i))}var j=function(t,i){return j=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var s in n)if(Object.prototype.hasOwnProperty.call(n,s))e[s]=n[s]},j(t,i)};function f(t){return typeof t==="function"}function N(t){var i=function(n){Error.call(n),n.stack=new Error().stack},e=t(i);return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}var V=N(function(t){return function i(e){t(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map(function(n,s){return s+1+") "+n.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=e}});function x(t,i){if(t){var e=t.indexOf(i);0<=e&&t.splice(e,1)}}function C(t){return t instanceof O||t&&"closed"in t&&f(t.remove)&&f(t.add)&&f(t.unsubscribe)}function Rt(t){if(f(t))t();else t.unsubscribe()}var O=function(){function t(i){this.initialTeardown=i,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var i,e,n,s,a;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var p=M(o),h=p.next();!h.done;h=p.next()){var D=h.value;D.remove(this)}}catch(d){i={error:d}}finally{try{if(h&&!h.done&&(e=p.return))e.call(p)}finally{if(i)throw i.error}}else o.remove(this);var S=this.initialTeardown;if(f(S))try{S()}catch(d){a=d instanceof V?d.errors:[d]}var G=this._finalizers;if(G){this._finalizers=null;try{for(var L=M(G),c=L.next();!c.done;c=L.next()){var k=c.value;try{Rt(k)}catch(d){if(a=a!==null&&a!==void 0?a:[],d instanceof V)a=$($([],R(a)),R(d.errors));else a.push(d)}}}catch(d){n={error:d}}finally{try{if(c&&!c.done&&(s=L.return))s.call(L)}finally{if(n)throw n.error}}}if(a)throw new V(a)}},t.prototype.add=function(i){var e;if(i&&i!==this)if(this.closed)Rt(i);else{if(i instanceof t){if(i.closed||i._hasParent(this))return;i._addParent(this)}(this._finalizers=(e=this._finalizers)!==null&&e!==void 0?e:[]).push(i)}},t.prototype._hasParent=function(i){var e=this._parentage;return e===i||Array.isArray(e)&&e.includes(i)},t.prototype._addParent=function(i){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(i),e):e?[e,i]:i},t.prototype._removeParent=function(i){var e=this._parentage;if(e===i)this._parentage=null;else if(Array.isArray(e))x(e,i)},t.prototype.remove=function(i){var e=this._finalizers;if(e&&x(e,i),i instanceof t)i._removeParent(this)},t.EMPTY=function(){var i=new t;return i.closed=!0,i}(),t}();var z=O.EMPTY;var m={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var q={setTimeout:function(t,i){var e=[];for(var n=2;n<arguments.length;n++)e[n-2]=arguments[n];var s=q.delegate;if(s===null||s===void 0?void 0:s.setTimeout)return s.setTimeout.apply(s,$([t,i],R(e)));return setTimeout.apply(void 0,$([t,i],R(e)))},clearTimeout:function(t){var i=q.delegate;return((i===null||i===void 0?void 0:i.clearTimeout)||clearTimeout)(t)},delegate:void 0};function $t(t){q.setTimeout(function(){var i=m.onUnhandledError;if(i)i(t);else throw t})}function b(){}function qt(t){return _("E",void 0,t)}function It(t){return _("N",t,void 0)}function _(t,i,e){return{kind:t,value:i,error:e}}var Ot=function(){return _("C",void 0,void 0)}();function I(t){if(m.useDeprecatedSynchronousErrorHandling){var i=!P;if(i)P={errorThrown:!1,error:null};if(t(),i){var e=P,n=e.errorThrown,s=e.error;if(P=null,n)throw s}}else t()}function St(t){if(m.useDeprecatedSynchronousErrorHandling&&P)P.errorThrown=!0,P.error=t}var P=null;function tt(t,i){return Yt.call(t,i)}function J(t){if(m.useDeprecatedSynchronousErrorHandling)St(t);else $t(t)}function Xt(t){throw t}function it(t,i){var e=m.onStoppedNotification;e&&q.setTimeout(function(){return e(t,i)})}var et=function(t){T(i,t);function i(e){var n=t.call(this)||this;if(n.isStopped=!1,e){if(n.destination=e,C(e))e.add(n)}else n.destination=Bt;return n}return i.create=function(e,n,s){return new Y(e,n,s)},i.prototype.next=function(e){if(this.isStopped)it(It(e),this);else this._next(e)},i.prototype.error=function(e){if(this.isStopped)it(qt(e),this);else this.isStopped=!0,this._error(e)},i.prototype.complete=function(){if(this.isStopped)it(Ot,this);else this.isStopped=!0,this._complete()},i.prototype.unsubscribe=function(){if(!this.closed)this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null},i.prototype._next=function(e){this.destination.next(e)},i.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},i.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},i}(O);var Yt=Function.prototype.bind,Qt=function(){function t(i){this.partialObserver=i}return t.prototype.next=function(i){var e=this.partialObserver;if(e.next)try{e.next(i)}catch(n){J(n)}},t.prototype.error=function(i){var e=this.partialObserver;if(e.error)try{e.error(i)}catch(n){J(n)}else J(i)},t.prototype.complete=function(){var i=this.partialObserver;if(i.complete)try{i.complete()}catch(e){J(e)}},t}(),Y=function(t){T(i,t);function i(e,n,s){var a=t.call(this)||this,o;if(f(e)||!e)o={next:e!==null&&e!==void 0?e:void 0,error:n!==null&&n!==void 0?n:void 0,complete:s!==null&&s!==void 0?s:void 0};else{var p;if(a&&m.useDeprecatedNextContext)p=Object.create(e),p.unsubscribe=function(){return a.unsubscribe()},o={next:e.next&&tt(e.next,p),error:e.error&&tt(e.error,p),complete:e.complete&&tt(e.complete,p)};else o=e}return a.destination=new Qt(o),a}return i}(et);var Bt={closed:!0,next:b,error:Xt,complete:b};var Gt=function(){return typeof Symbol==="function"&&Symbol.observable||"@@observable"}();function Ut(t){return t}function Ht(t){if(t.length===0)return Ut;if(t.length===1)return t[0];return function i(e){return t.reduce(function(n,s){return s(n)},e)}}function Mt(t){var i;return(i=t!==null&&t!==void 0?t:m.Promise)!==null&&i!==void 0?i:Promise}function Zt(t){return t&&f(t.next)&&f(t.error)&&f(t.complete)}function vt(t){return t&&t instanceof et||Zt(t)&&C(t)}var nt=function(){function t(i){if(i)this._subscribe=i}return t.prototype.lift=function(i){var e=new t;return e.source=this,e.operator=i,e},t.prototype.subscribe=function(i,e,n){var s=this,a=vt(i)?i:new Y(i,e,n);return I(function(){var o=s,p=o.operator,h=o.source;a.add(p?p.call(a,h):h?s._subscribe(a):s._trySubscribe(a))}),a},t.prototype._trySubscribe=function(i){try{return this._subscribe(i)}catch(e){i.error(e)}},t.prototype.forEach=function(i,e){var n=this;return e=Mt(e),new e(function(s,a){var o=new Y({next:function(p){try{i(p)}catch(h){a(h),o.unsubscribe()}},error:a,complete:s});n.subscribe(o)})},t.prototype._subscribe=function(i){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(i)},t.prototype[Gt]=function(){return this},t.prototype.pipe=function(){var i=[];for(var e=0;e<arguments.length;e++)i[e]=arguments[e];return Ht(i)(this)},t.prototype.toPromise=function(i){var e=this;return i=Mt(i),new i(function(n,s){var a;e.subscribe(function(o){return a=o},function(o){return s(o)},function(){return n(a)})})},t.create=function(i){return new t(i)},t}();var xt=N(function(t){return function i(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var st=function(t){T(i,t);function i(){var e=t.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return i.prototype.lift=function(e){var n=new kt(this,this);return n.operator=e,n},i.prototype._throwIfClosed=function(){if(this.closed)throw new xt},i.prototype.next=function(e){var n=this;I(function(){var s,a;if(n._throwIfClosed(),!n.isStopped){if(!n.currentObservers)n.currentObservers=Array.from(n.observers);try{for(var o=M(n.currentObservers),p=o.next();!p.done;p=o.next()){var h=p.value;h.next(e)}}catch(D){s={error:D}}finally{try{if(p&&!p.done&&(a=o.return))a.call(o)}finally{if(s)throw s.error}}}})},i.prototype.error=function(e){var n=this;I(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=e;var s=n.observers;while(s.length)s.shift().error(e)}})},i.prototype.complete=function(){var e=this;I(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;var n=e.observers;while(n.length)n.shift().complete()}})},i.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(i.prototype,"observed",{get:function(){var e;return((e=this.observers)===null||e===void 0?void 0:e.length)>0},enumerable:!1,configurable:!0}),i.prototype._trySubscribe=function(e){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,e)},i.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},i.prototype._innerSubscribe=function(e){var n=this,s=this,a=s.hasError,o=s.isStopped,p=s.observers;if(a||o)return z;return this.currentObservers=null,p.push(e),new O(function(){n.currentObservers=null,x(p,e)})},i.prototype._checkFinalizedStatuses=function(e){var n=this,s=n.hasError,a=n.thrownError,o=n.isStopped;if(s)e.error(a);else if(o)e.complete()},i.prototype.asObservable=function(){var e=new nt;return e.source=this,e},i.create=function(e,n){return new kt(e,n)},i}(nt);var kt=function(t){T(i,t);function i(e,n){var s=t.call(this)||this;return s.destination=e,s.source=n,s}return i.prototype.next=function(e){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,e)},i.prototype.error=function(e){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.call(n,e)},i.prototype.complete=function(){var e,n;(n=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||n===void 0||n.call(e)},i.prototype._subscribe=function(e){var n,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(e))!==null&&s!==void 0?s:z},i}(st);var g=function(t){T(i,t);function i(e){var n=t.call(this)||this;return n._value=e,n}return Object.defineProperty(i.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),i.prototype._subscribe=function(e){var n=t.prototype._subscribe.call(this,e);return!n.closed&&e.next(this._value),n},i.prototype.getValue=function(){var e=this,n=e.hasError,s=e.thrownError,a=e._value;if(n)throw s;return this._throwIfClosed(),a},i.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},i}(st);var jt;((p)=>{p[p.CRON=0]="CRON";p[p.EVENT=1]="EVENT";p[p.DELETE=2]="DELETE";p[p.GET=3]="GET";p[p.PATCH=4]="PATCH";p[p.POST=5]="POST";p[p.PUT=6]="PUT"})(jt||={});class at extends u{api;$cache=new g([]);get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new r(t):t}delete(t){return this.api.request({url:`/api/actions/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter((i)=>i._id!=t),this.emit("DELETE",t)})}list(){return this.api.request({url:"/api/actions"}).then((t)=>{if(t.data)this.cache=t.data;return this.emit("LIST",t.data||[]),t.data})}read(t,i=!1){const e=this.cache.find((n)=>n._id==t);if(!i&&e)return Promise.resolve(e);return this.api.request({url:`/api/actions/${t}`}).then((n)=>{if(n.data)this.cache=this.cache.filter((s)=>s._id!=t).concat([n.data]);return this.emit("READ",n.data),n.data})}run(t,i={}){return this.api.request({url:("/api/actions/run/"+t).replaceAll("//","/"),...i}).then((e)=>e.data)}runById(t,i={}){const e=typeof t=="string"?t:t._id;return this.api.request({url:"/api/actions/run-by-id/"+e,method:"POST",...i}).then((n)=>n.data)}update(t){return this.api.request({url:`/api/actions${t._id?`/${t._id}`:""}`,method:"POST",body:t}).then((i)=>{if(i.data)this.cache=this.cache.filter((e)=>e._id!=i.data?._id).concat([i.data]);return this.emit("UPDATE",i.data),i.data})}}class Wt{t;constructor(t){this.api=t}disable(t){return this.api.request({url:`/api/auth/totp/${t}`,method:"DELETE"})}enable=this.reset;reset(t){return this.api.request({url:`/api/auth/totp/${t}`,method:"POST"})}setup(t,i="app",e){return this.api.request({url:`/api/auth/totp/${t}`,body:B({method:i,totp:e})})}}class ot extends u{i;api;storageKey;totp;$user=new g(void 0);get user(){return this.$user.value}set user(t){if(!Z(this.user,t)){const i=t?t:null;this.$user.next(i),this.emit("USER",i)}}constructor(t,i){super();this.opts=i;if(this.api=typeof t=="string"?new r(t):t,this.totp=new Wt(this.api),!this.opts?.loginUi)this.opts={...this.opts,loginUi:this.api.url+"/ui/login"};if(this.storageKey=`momentum:${new URL(this.api.url).host}`,this.api.addInterceptor((e,n)=>{const s=["/api/auth/login","/api/auth/password","/api/auth/totp"];if(e.status==401&&!s.find((a)=>e.url.includes(a)))this.emit("SESSION_EXPIRED");n()}),this.api.on("TOKEN",(e)=>{if(this.opts?.persist)if(e)localStorage.setItem(this.storageKey,e);else localStorage.removeItem(this.storageKey);if(e)this.session(e,!0).catch(()=>{});else this.user=null}),i?.persist){const e=localStorage.getItem(this.storageKey);if(e)this.api.token=e;else this.user=null}else this.user=null}knownHost(t=location.origin){if(t.startsWith("/"))return Promise.resolve();return this.api.request({url:`/api/auth/known-host?host=${encodeURI(new URL(t).origin)}`}).then(()=>{})}login(t,i,e){return this.api.request({url:"/api/auth/login",headers:{Authorization:void 0},method:"POST",body:{username:t.trim(),password:i.trim(),totp:e}}).then(async(n)=>{return this.api.token=n.data?.token||null,await this.once("USER")})}loginRedirect(t=location.origin){return new Promise((i,e)=>{const n=window.open(encodeURI(`${this.opts?.loginUi}?redirect=postmessage&host=${t}`),"_blank");if(!n)return e("Unable to open login");n.addEventListener("message",(s)=>{if(!s?.data?.token)return e("Unknown response from login");this.api.token=s.data.token,i(s.data.token),n.close()})})}logout(){this.api.token=null,this.user=null,this.emit("LOGOUT")}async register(t){const i=(await this.api.request({url:"/api/auth/register",body:{...t}}))?.data;if(i?.image?.startsWith("/"))i.image=`${this.api.url}${i.image}?token=${this.api.token}`;return this.emit("REGISTER",i),i}reset(t,i){return this.api.request({url:"/api/auth/reset",headers:{Authorization:i?`Bearer ${i}`:void 0},body:{email:i?void 0:t,password:i?t:void 0}}).then(()=>{})}async session(t,i=!1){if(!t)t=this.api.token;const e=(await this.api.request({url:"/api/auth/session",headers:t?{Authorization:`Bearer ${t}`}:void 0}))?.data;if(i){if(this.api.token=t,e?.user)e.user.image=`${this.api.url}${e.user.image}?token=${this.api.token}`;if(this.user=e?.user||null,e)this.emit("LOGIN",e.user)}return e}async updatePassword(t,i,e){return this.api.request({url:"/api/auth/password",body:{username:t,password:i,oldPassword:e}}).then((n)=>{if(n?.data?.token)this.api.token=n.data.token})}}class pt extends u{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}delete(t,i){return this.api.request({url:`/api/data/${t}/${i}`,method:"DELETE"}).then(()=>this.emit("DELETE",t,i))}get(t,i){return this.api.request({url:`/api/data/${t}${i?`/${i}`:""}`}).then((e)=>{return this.emit("GET",t,e.data),e.data})}raw(t,i,e,n){return this.api.request({url:`/api/data/${t}`,body:{operand:i,query:e,options:n}}).then((s)=>{return this.emit("RAW",t,s.data),s.data})}set(t,i,e=!1){return this.api.request({url:`/api/data/${t}/${i._id||""}`,method:e?"PATCH":"POST",body:i}).then((n)=>{return this.emit("SET",t,n.data),n.data})}}class ht extends u{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}send(t){let i="/api/email";if(typeof t.body=="object")i+=`/${t.body.template}`;return this.api.request({url:i,body:t}).then((e)=>{return this.emit("SENT",t),e.data})}}class ut extends u{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}create(t){return this.api.request({url:`/api/groups/${t.name}`,method:"POST",body:t}).then((i)=>{return this.emit("CREATE",i.data),i.data})}list(){return this.api.request({url:"/api/groups"}).then((t)=>{return this.emit("LIST",t.data||[]),t.data})}read(t){return this.api.request({url:`/api/groups/${t}`}).then((i)=>{return this.emit("READ",i.data),i.data})}update(t){return this.api.request({url:`/api/groups/${t.name}`,method:"PATCH",body:t}).then((i)=>{return this.emit("UPDATE",i.data),i.data})}delete(t){return this.api.request({url:`/api/groups/${t}`,method:"DELETE"}).then(()=>this.emit("DELETE",t))}}class rt{api;constructor(t,i){if(this.api=typeof t=="string"?new r(t):t,i!=null&&i!="NONE")window.addEventListener("error",(e)=>this.error(e.error.stack)),window.addEventListener("unhandledrejection",async(e)=>this.error(e.reason.stack))}buildLog(t,i){return{time:new Date().getTime(),level:t,log:i,ctx:{cores:navigator.hardwareConcurrency,mem:navigator?.deviceMemory,res:[window.innerWidth,window.innerHeight],url:location.href}}}clearClientLogs(){return this.api.request({url:"/api/logs/client",method:"DELETE"})}clearServerLogs(){return this.api.request({url:"/api/logs/server",method:"DELETE"})}clientLogs(t,i){const e=[t?`length=${t}`:void 0,i?`page=${i}`:void 0].filter((n)=>!!n).join("&");return this.api.request({url:`/api/logs/client${e?`?${e}`:""}`}).then((n)=>n.data)}serverLogs(t,i){const e=[t?`length=${t}`:void 0,i?`page=${i}`:void 0].filter((n)=>!!n).join("&");return this.api.request({url:`/api/logs/server${e?`?${e}`:""}`}).then((n)=>n.data)}debug(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(w.DEBUG,t)}).then(()=>{}).catch(()=>{})}log(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(w.LOG,t)}).then(()=>{}).catch(()=>{})}info(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(w.INFO,t)}).then(()=>{}).catch(()=>{})}warn(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(w.WARN,t)}).then(()=>{}).catch(()=>{})}error(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(w.ERROR,t)}).then(()=>{}).catch(()=>{})}}class lt extends u{api;stripe;constructor(t,i){super();this.api=typeof t=="string"?new r(t):t;const e=(n=1)=>{try{if(!Stripe)throw new Error("Stripe not added");this.stripe=Stripe(i)}catch(s){if(n>0)setTimeout(()=>e(n--),250);else console.warn("Stripe failed, did you add the library & setup your API key?",s)}};e()}async charge(t,i={}){return this.emit("CHECKOUT",t,i),(await this.api.request({url:"/api/payments",body:{amount:t,custom:i}})).data.clientSecret}async createForm(t,i,e){const n=await this.charge(i,e),s=this.stripe.elements({clientSecret:n});return s.create("payment").mount(t),()=>this.stripe.confirmPayment({elements:s,redirect:"if_required",confirmParams:{return_url:location.origin}})}async history(t){const i=await this.api.request({url:`/api/payments${t?`/${t}`:""}`});return this.emit("LIST",t||null,i.data),i.data}}class yt extends u{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}async handleResponse(t,i){const e=await t.blob();if(i){const n=URL.createObjectURL(e);v(n,i.endsWith(".pdf")?i:i+".pdf"),URL.revokeObjectURL(n)}return this.emit("CREATE",e),e}fromHtml(t,i={}){return this.api.request({url:"/api/pdf",body:{html:t}}).then((e)=>this.handleResponse(e,i.download?i.fileName||new Date().toISOString():void 0))}fromTemplate(t,i,e={}){return this.api.request({url:`/api/pdf${t}`,body:i}).then((n)=>this.handleResponse(n,e.download?e.fileName||new Date().toISOString():void 0))}fromUrl(t,i={}){return this.api.request({url:`/api/pdf?url=${t}`}).then((e)=>this.handleResponse(e,i.download?i.fileName||new Date().toISOString():void 0))}}class Q{static timeout=1e4;api;url;connection;open=!1;constructor(t){if(this.api=typeof t=="string"?new r(t):t,this.url=this.api.url.replace("http","ws"),this.api.on("TOKEN",()=>this.connect()),!this.api.token)this.connect()}close(){console.debug("Disconnected from Momentum"),this.open=!1,this.connection.close()}connect(t=3){if(this.connection?.readyState<2)this.connection.close();this.connection=new WebSocket(this.url+(this.api.token?`?token=${this.api.token}`:""));const i=setTimeout(()=>{if(this.open)return;if(this.connection.close(),console.error("Momentum connection timeout"),t>0)this.connect(t-1)},Q.timeout);this.connection.onclose=()=>this.open=!1,this.connection.onmessage=this.handle,this.connection.onopen=()=>{this.open=!0,clearTimeout(i),console.debug("Connected to Momentum")}}handle(...t){console.log(t)}send(t,i){this.connection.send(JSON.stringify({token:this.api.token,channel:t,payload:i}))}}class dt extends u{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}delete(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:i,method:"DELETE"}).then(()=>{this.emit("DELETE",i)})}list(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:i+"?list"}).then((e)=>{return this.emit("LIST",t,e.data),e.data})}open(t,i="_blank"){const e=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/"),n=`${this.api.url}${e}${this.api.token?`?token=${this.api.token}`:""}`;if(!i)return n;return this.emit("OPEN",t),window.open(n,i)}mkdir(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/");return this.api.request({url:i+"?directory",method:"POST"}).then((e)=>e.data)}download(t,i={}){const e=("/api/storage/"+t).replaceAll("//","/");return this.api.request({...i,url:e,decode:!1}).then(async(n)=>{const s=await n.data.blob(),a=i.downloadAs||new URL(n.url).pathname.split("/").pop();return this.emit("DOWNLOAD",t,s),ct(s,a),n.data})}upload(t,i=""){return new E(async(e,n,s)=>{if(!t)t=await Et();if(!t||Array.isArray(t)&&!t.length)return[];const a=this.api.url+("/api/storage/"+(typeof i=="string"?i:i?.path)).replaceAll("//","/");return K({url:a,files:Array.isArray(t)?t:[t],headers:this.api.headers}).onProgress((o)=>{s(o)}).then((o)=>{this.emit("UPLOAD",o),e(o)}).catch((o)=>n(o))})}}class ft extends u{api;listed=!1;$cache=new g([]);get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new r(t):t}delete(t){return this.api.request({url:`/api/users/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter((i)=>i.username!=t),this.emit("DELETE",t)})}list(t=!1){if(!t&&this.listed)return Promise.resolve(this.cache);return this.api.request({url:"/api/users"}).then((i)=>{return i.data?.map((e)=>{return e.image=this.api.url+e.image+`?token=${this.api.token}`,e}),this.cache=i.data||[],this.listed=!0,this.emit("LIST",i.data||[]),i.data})}read(t,i=!1){if(!i){const e=this.cache.find((n)=>n.username==t);if(e)return Promise.resolve(e)}return this.api.request({url:`/api/users/${t}`}).then((e)=>{if(e.data)e.data.image=this.api.url+e.data.image+`?token=${this.api.token}`,this.cache=[...this.cache.filter((n)=>n.username!=t),e.data];return this.emit("READ",e.data),e.data})}update(t){return this.api.request({url:`/api/users/${t.username}`,method:"PATCH",body:t}).then((i)=>{if(i.data)i.data.image=this.api.url+i.data.image+`?token=${this.api.token}`,this.cache=this.cache.filter((e)=>e.username!=t.username).concat([i.data]);return this.emit(t._id?"UPDATE":"CREATE",i.data),i.data})}uploadImage(t,i){return K({url:this.api.url+`/api/users/${t}/image`,files:[i],headers:this.api.headers}).then((e)=>{return this.emit("UPLOAD_IMAGE",t,i),e})}}class mt extends u{api;$cache=new g({});get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new r(t):t}list(t=!1){return this.api.request({url:"/api/settings"+(t?"?detailed":"")}).then((i)=>{return this.cache=!t?i.data:Object.values(i.data||{}).reduce((e,n)=>({...e,[n.key]:n.value}),{}),this.emit("LIST",i.data||[]),i.data})}delete(t){return this.api.request({url:`/api/settings/${t}`,method:"DELETE"}).then(()=>{this.cache={...this.cache,[t]:void 0},this.emit("DELETE",t)})}read(t,i=!1){if(!i&&this.cache[t])return Promise.resolve(this.cache[t]);return this.api.request({url:`/api/settings/${t}`}).then((e)=>{if(e.data)this.cache={...this.cache,[e.data.key]:e};return this.emit("READ",e.data),e.data})}update(t){return this.api.request({url:`/api/settings/${t.key}`,body:t}).then((i)=>{if(i.data)this.cache={...this.cache,[i.data.key]:i.data.value};return this.emit("UPDATE",i.data),i.data})}}class gt extends u{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}delete(t){return this.api.request({url:`/api/static/${t}`,method:"DELETE"}).then(()=>{this.emit("DELETE",t)})}list(t){const i=("/api/static/"+t).replaceAll("//","/");return this.api.request({url:i}).then((e)=>{return this.emit("LIST",t,e.data||[]),e.data})}upload(t,i="/"){const e=new FormData;return(Array.isArray(t)?t:[t]).forEach((n)=>e.append("file",n)),this.api.request({url:"/api/static"+i,body:e}).then((n)=>{return this.emit("UPLOAD",n.data||[]),n.data})}}class zt extends u{api;actions;auth;data;email;groups;logger;payments;pdf;settings;socket;static;storage;users;constructor(t,i){super();if(this.api=new r(t,i?.api),this.actions=new at(this.api),this.auth=new ot(this.api,{persist:i?.persist??!0,loginUi:i?.loginUi}),this.data=new pt(this.api),this.email=new ht(this.api),this.groups=new ut(this.api),this.logger=new rt(this.api,i?.logLevel),i?.stripeSecret)this.payments=new lt(this.api,i.stripeSecret);if(this.pdf=new yt(this.api),this.settings=new mt(this.api),this.static=new gt(this.api),this.storage=new dt(this.api),this.users=new ft(this.api),i?.socket)this.socket=new Q(this.api);if(this.api.on("*",(e,...n)=>this.emit(`API::${e}`,...n)),this.actions.on("*",(e,...n)=>this.emit(`ACTIONS::${e}`,...n)),this.auth.on("*",(e,...n)=>this.emit(`AUTH::${e}`,...n)),this.data.on("*",(e,...n)=>this.emit(`DATA::${e}`,...n)),this.email.on("*",(e,...n)=>this.emit(`EMAIL::${e}`,...n)),this.groups.on("*",(e,...n)=>this.emit(`GROUPS::${e}`,...n)),this.payments)this.payments.on("*",(e,...n)=>this.emit(`PAYMENT::${e}`,...n));this.pdf.on("*",(e,...n)=>this.emit(`PDF::${e}`,...n)),this.settings.on("*",(e,...n)=>this.emit(`SETTINGS::${e}`,...n)),this.static.on("*",(e,...n)=>this.emit(`STATIC::${e}`,...n)),this.storage.on("*",(e,...n)=>this.emit(`STORAGE::${e}`,...n)),this.users.on("*",(e,...n)=>this.emit(`USERS::${e}`,...n)),this.users.on("*",(e,...n)=>{if(Array.isArray(n[0])){const s=n[0].find((a)=>a._id==this.auth.user?._id);if(s)this.auth.user=s}else if(n[0]._id==this.auth.user?._id)this.auth.user=n[0]})}}export{ft as Users,Wt as Totp,dt as Storage,gt as Static,Q as Socket,mt as Settings,yt as Pdf,lt as Payments,zt as Momentum,rt as Logger,ut as Groups,ht as Email,pt as Data,ot as Auth,r as Api,at as Actions,jt as ActionType};
package/dist/logger.d.ts CHANGED
@@ -42,14 +42,14 @@ export declare class Logger {
42
42
  private readonly api;
43
43
  constructor(api: Api | string, logLevel?: LogLevel | null);
44
44
  private buildLog;
45
- clearClientLogs(): Promise<ClientLog[]>;
46
- clearServerLogs(): Promise<ClientLog[]>;
45
+ clearClientLogs(): import("@ztimson/utils").PromiseProgress<import("@ztimson/utils").DecodedResponse<ClientLog[]>>;
46
+ clearServerLogs(): import("@ztimson/utils").PromiseProgress<import("@ztimson/utils").DecodedResponse<ClientLog[]>>;
47
47
  clientLogs(length?: number, page?: number): Promise<ClientLog[]>;
48
48
  serverLogs(length?: number, page?: number): Promise<Log<any>[]>;
49
- debug(...logs: any[]): Promise<unknown>;
50
- log(...logs: any[]): Promise<unknown>;
51
- info(...logs: any[]): Promise<unknown>;
52
- warn(...logs: any[]): Promise<unknown>;
53
- error(...logs: any[]): Promise<unknown>;
49
+ debug(...logs: any[]): import("@ztimson/utils").PromiseProgress<any>;
50
+ log(...logs: any[]): import("@ztimson/utils").PromiseProgress<any>;
51
+ info(...logs: any[]): import("@ztimson/utils").PromiseProgress<any>;
52
+ warn(...logs: any[]): import("@ztimson/utils").PromiseProgress<any>;
53
+ error(...logs: any[]): import("@ztimson/utils").PromiseProgress<any>;
54
54
  }
55
55
  //# sourceMappingURL=logger.d.ts.map
package/dist/logger.js CHANGED
@@ -34,26 +34,26 @@ class Logger {
34
34
  }
35
35
  clientLogs(length, page) {
36
36
  const query = [length ? `length=${length}` : undefined, page ? `page=${page}` : undefined,].filter(v => !!v).join('&');
37
- return this.api.request({ url: `/api/logs/client${query ? `?${query}` : ''}` });
37
+ return this.api.request({ url: `/api/logs/client${query ? `?${query}` : ''}` }).then(resp => resp.data);
38
38
  }
39
39
  serverLogs(length, page) {
40
40
  const query = [length ? `length=${length}` : undefined, page ? `page=${page}` : undefined,].filter(v => !!v).join('&');
41
- return this.api.request({ url: `/api/logs/server${query ? `?${query}` : ''}` });
41
+ return this.api.request({ url: `/api/logs/server${query ? `?${query}` : ''}` }).then(resp => resp.data);
42
42
  }
43
43
  debug(...logs) {
44
- return this.api.request({ url: `/api/logs/client`, body: this.buildLog(utils_1.LOG_LEVEL.DEBUG, logs) }).catch(() => { });
44
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(utils_1.LOG_LEVEL.DEBUG, logs) }).then(() => { }).catch(() => { });
45
45
  }
46
46
  log(...logs) {
47
- return this.api.request({ url: `/api/logs/client`, body: this.buildLog(utils_1.LOG_LEVEL.LOG, logs) }).catch(() => { });
47
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(utils_1.LOG_LEVEL.LOG, logs) }).then(() => { }).catch(() => { });
48
48
  }
49
49
  info(...logs) {
50
- return this.api.request({ url: `/api/logs/client`, body: this.buildLog(utils_1.LOG_LEVEL.INFO, logs) }).catch(() => { });
50
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(utils_1.LOG_LEVEL.INFO, logs) }).then(() => { }).catch(() => { });
51
51
  }
52
52
  warn(...logs) {
53
- return this.api.request({ url: `/api/logs/client`, body: this.buildLog(utils_1.LOG_LEVEL.WARN, logs) }).catch(() => { });
53
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(utils_1.LOG_LEVEL.WARN, logs) }).then(() => { }).catch(() => { });
54
54
  }
55
55
  error(...logs) {
56
- return this.api.request({ url: `/api/logs/client`, body: this.buildLog(utils_1.LOG_LEVEL.ERROR, logs) }).catch(() => { });
56
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(utils_1.LOG_LEVEL.ERROR, logs) }).then(() => { }).catch(() => { });
57
57
  }
58
58
  }
59
59
  exports.Logger = Logger;
@@ -4,8 +4,9 @@ import { Auth, type AuthEvents, AuthOptions } from './auth';
4
4
  import { Data, type DataEvents } from './data';
5
5
  import { Email, type EmailEvents } from './email';
6
6
  import { Groups } from './groups';
7
- import { TypedEmitter, type TypedEvents, type XhrOptions } from '@ztimson/utils';
7
+ import { TypedEmitter, type TypedEvents, type HttpRequestOptions } from '@ztimson/utils';
8
8
  import { Logger, LogLevel } from './logger';
9
+ import { Payments } from './payments';
9
10
  import { Pdf, type PdfEvents } from './pdf';
10
11
  import { Socket } from './sockets';
11
12
  import { Storage, type StorageEvents } from './storage';
@@ -16,7 +17,8 @@ export type MomentumEvents = TypedEvents & ApiEvents & AuthEvents & DataEvents &
16
17
  export type MomentumOptions = AuthOptions & {
17
18
  logLevel?: LogLevel;
18
19
  socket?: boolean;
19
- api?: XhrOptions;
20
+ stripeSecret?: string;
21
+ api?: HttpRequestOptions;
20
22
  };
21
23
  export declare class Momentum extends TypedEmitter<MomentumEvents> {
22
24
  api: Api;
@@ -26,6 +28,7 @@ export declare class Momentum extends TypedEmitter<MomentumEvents> {
26
28
  email: Email;
27
29
  groups: Groups;
28
30
  logger: Logger;
31
+ payments: Payments;
29
32
  pdf: Pdf;
30
33
  settings: Settings;
31
34
  socket?: Socket;
@@ -1 +1 @@
1
- {"version":3,"file":"momentum.d.ts","sourceRoot":"","sources":["../src/momentum.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,EAAC,MAAM,WAAW,CAAC;AAClC,OAAO,EAAC,GAAG,EAAE,KAAK,SAAS,EAAC,MAAM,OAAO,CAAC;AAC1C,OAAO,EAAC,IAAI,EAAE,KAAK,UAAU,EAAE,WAAW,EAAC,MAAM,QAAQ,CAAC;AAC1D,OAAO,EAAC,IAAI,EAAE,KAAK,UAAU,EAAC,MAAM,QAAQ,CAAC;AAC7C,OAAO,EAAC,KAAK,EAAE,KAAK,WAAW,EAAC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AS,GAAG,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG,SAAS,GAAG,YAAY,GAAG,aAAa,GAAG,aAAa,CAAC;AAExJ,MAAM,MAAM,eAAe,GAAG,WAAW,GAAG;IAC3C,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,GAAG,CAAC,EAAE,kBAAkB,CAAC;CACzB,CAAA;AAED,qBAAa,QAAS,SAAQ,YAAY,CAAC,cAAc,CAAC;IACzD,GAAG,EAAG,GAAG,CAAC;IACV,OAAO,EAAG,OAAO,CAAC;IAClB,IAAI,EAAG,IAAI,CAAC;IACZ,IAAI,EAAG,IAAI,CAAC;IACZ,KAAK,EAAG,KAAK,CAAC;IACd,MAAM,EAAG,MAAM,CAAC;IAChB,MAAM,EAAG,MAAM,CAAC;IAChB,QAAQ,EAAG,QAAQ,CAAC;IACpB,GAAG,EAAG,GAAG,CAAC;IACV,QAAQ,EAAG,QAAQ,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,EAAG,MAAM,CAAC;IAChB,OAAO,EAAG,OAAO,CAAC;IAClB,KAAK,EAAG,KAAK,CAAC;gBACF,GAAG,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,eAAe;CA0ChD"}
package/dist/momentum.js CHANGED
@@ -9,6 +9,7 @@ const email_1 = require("./email");
9
9
  const groups_1 = require("./groups");
10
10
  const utils_1 = require("@ztimson/utils");
11
11
  const logger_1 = require("./logger");
12
+ const payments_1 = require("./payments");
12
13
  const pdf_1 = require("./pdf");
13
14
  const sockets_1 = require("./sockets");
14
15
  const storage_1 = require("./storage");
@@ -23,6 +24,7 @@ class Momentum extends utils_1.TypedEmitter {
23
24
  email;
24
25
  groups;
25
26
  logger;
27
+ payments;
26
28
  pdf;
27
29
  settings;
28
30
  socket;
@@ -41,6 +43,8 @@ class Momentum extends utils_1.TypedEmitter {
41
43
  this.email = new email_1.Email(this.api);
42
44
  this.groups = new groups_1.Groups(this.api);
43
45
  this.logger = new logger_1.Logger(this.api, opts?.logLevel);
46
+ if (opts?.stripeSecret)
47
+ this.payments = new payments_1.Payments(this.api, opts.stripeSecret);
44
48
  this.pdf = new pdf_1.Pdf(this.api);
45
49
  this.settings = new settings_1.Settings(this.api);
46
50
  this.static = new static_1.Static(this.api);
@@ -54,6 +58,8 @@ class Momentum extends utils_1.TypedEmitter {
54
58
  this.data.on('*', (event, ...args) => this.emit(`DATA::${event}`, ...args));
55
59
  this.email.on('*', (event, ...args) => this.emit(`EMAIL::${event}`, ...args));
56
60
  this.groups.on('*', (event, ...args) => this.emit(`GROUPS::${event}`, ...args));
61
+ if (this.payments)
62
+ this.payments.on('*', (event, ...args) => this.emit(`PAYMENT::${event}`, ...args));
57
63
  this.pdf.on('*', (event, ...args) => this.emit(`PDF::${event}`, ...args));
58
64
  this.settings.on('*', (event, ...args) => this.emit(`SETTINGS::${event}`, ...args));
59
65
  this.static.on('*', (event, ...args) => this.emit(`STATIC::${event}`, ...args));
@@ -0,0 +1,15 @@
1
+ import { TypedEmitter, type TypedEvents } from '@ztimson/utils';
2
+ import { Api } from './api';
3
+ export type PaymentEvents = TypedEvents & {
4
+ 'CHECKOUT': (amount: number, custom: any) => any;
5
+ 'LIST': (username: string | null, history: any[]) => void;
6
+ };
7
+ export declare class Payments extends TypedEmitter<PaymentEvents> {
8
+ private readonly api;
9
+ stripe: any;
10
+ constructor(api: Api | string, secret: string);
11
+ private charge;
12
+ createForm(element: string, amount: number, custom?: any): Promise<() => Promise<any>>;
13
+ history(username?: string): Promise<any[] | null>;
14
+ }
15
+ //# sourceMappingURL=payments.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payments.d.ts","sourceRoot":"","sources":["../src/payments.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAE,KAAK,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAI1B,MAAM,MAAM,aAAa,GAAG,WAAW,GAAG;IACzC,UAAU,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,GAAG,CAAC;IACjD,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;CAC1D,CAAC;AAEF,qBAAa,QAAS,SAAQ,YAAY,CAAC,aAAa,CAAC;IACxD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;IAE3B,MAAM,EAAG,GAAG,CAAC;gBAED,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,MAAM,EAAE,MAAM;YAgB/B,MAAM;IASd,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC;IAWtF,OAAO,CAAC,QAAQ,CAAC,EAAE,MAAM;CAK/B"}
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Payments = void 0;
4
+ const utils_1 = require("@ztimson/utils");
5
+ const api_1 = require("./api");
6
+ class Payments extends utils_1.TypedEmitter {
7
+ api;
8
+ stripe;
9
+ constructor(api, secret) {
10
+ super();
11
+ this.api = typeof api == 'string' ? new api_1.Api(api) : api;
12
+ const setup = (retry = 1) => {
13
+ try {
14
+ if (!Stripe)
15
+ throw new Error('Stripe not added');
16
+ this.stripe = Stripe(secret);
17
+ }
18
+ catch (err) {
19
+ if (retry > 0)
20
+ setTimeout(() => setup(retry--), 250);
21
+ else
22
+ console.warn('Stripe failed, did you add the library & setup your API key?', err);
23
+ }
24
+ };
25
+ setup();
26
+ }
27
+ async charge(amount, custom = {}) {
28
+ this.emit('CHECKOUT', amount, custom);
29
+ const request = await this.api.request({ url: '/api/payments', body: {
30
+ amount,
31
+ custom,
32
+ } });
33
+ return request.data.clientSecret;
34
+ }
35
+ async createForm(element, amount, custom) {
36
+ const token = await this.charge(amount, custom);
37
+ const form = this.stripe.elements({ clientSecret: token });
38
+ form.create('payment').mount(element);
39
+ return () => this.stripe.confirmPayment({
40
+ elements: form,
41
+ redirect: "if_required",
42
+ confirmParams: { return_url: location.origin }
43
+ });
44
+ }
45
+ async history(username) {
46
+ const history = await this.api.request({ url: `/api/payments${username ? `/${username}` : ''}` });
47
+ this.emit('LIST', username || null, history.data);
48
+ return history.data;
49
+ }
50
+ }
51
+ exports.Payments = Payments;
package/dist/pdf.d.ts CHANGED
@@ -11,8 +11,8 @@ export declare class Pdf extends TypedEmitter<PdfEvents> {
11
11
  private readonly api;
12
12
  constructor(api: Api | string);
13
13
  private handleResponse;
14
- fromHtml(content: string, opts?: PdfOptions): Promise<Blob>;
15
- fromTemplate(template: string, data: object, opts?: PdfOptions): Promise<Blob>;
16
- fromUrl(url: string, opts?: PdfOptions): Promise<Blob>;
14
+ fromHtml(content: string, opts?: PdfOptions): import("@ztimson/utils").PromiseProgress<any>;
15
+ fromTemplate(template: string, data: object, opts?: PdfOptions): import("@ztimson/utils").PromiseProgress<any>;
16
+ fromUrl(url: string, opts?: PdfOptions): import("@ztimson/utils").PromiseProgress<any>;
17
17
  }
18
18
  //# sourceMappingURL=pdf.d.ts.map
package/dist/settings.js CHANGED
@@ -15,9 +15,9 @@ class Settings extends utils_1.TypedEmitter {
15
15
  }
16
16
  list(detailed = false) {
17
17
  return this.api.request({ url: `/api/settings` + (detailed ? '?detailed' : '') }).then(resp => {
18
- this.cache = !detailed ? resp : Object.values(resp).reduce((acc, v) => ({ ...acc, [v.key]: v.value }), {});
19
- this.emit('LIST', resp);
20
- return resp;
18
+ this.cache = !detailed ? resp.data : Object.values(resp.data || {}).reduce((acc, v) => ({ ...acc, [v.key]: v.value }), {});
19
+ this.emit('LIST', resp.data || []);
20
+ return resp.data;
21
21
  });
22
22
  }
23
23
  delete(key) {
@@ -30,18 +30,18 @@ class Settings extends utils_1.TypedEmitter {
30
30
  if (!reload && this.cache[key])
31
31
  return Promise.resolve(this.cache[key]);
32
32
  return this.api.request({ url: `/api/settings/${key}` }).then(variable => {
33
- if (variable)
34
- this.cache = { ...this.cache, [variable.key]: variable };
35
- this.emit('READ', variable);
36
- return variable;
33
+ if (variable.data)
34
+ this.cache = { ...this.cache, [variable.data.key]: variable };
35
+ this.emit('READ', variable.data);
36
+ return variable.data;
37
37
  });
38
38
  }
39
39
  update(variable) {
40
40
  return this.api.request({ url: `/api/settings/${variable.key}`, body: variable }).then(variable => {
41
- if (variable)
42
- this.cache = { ...this.cache, [variable.key]: variable.value };
43
- this.emit('UPDATE', variable);
44
- return variable;
41
+ if (variable.data)
42
+ this.cache = { ...this.cache, [variable.data.key]: variable.data.value };
43
+ this.emit('UPDATE', variable.data);
44
+ return variable.data;
45
45
  });
46
46
  }
47
47
  }
package/dist/static.js CHANGED
@@ -17,16 +17,16 @@ class Static extends utils_1.TypedEmitter {
17
17
  list(path) {
18
18
  const url = ('/api/static/' + path).replaceAll('//', '/');
19
19
  return this.api.request({ url }).then(resp => {
20
- this.emit('LIST', path, resp);
21
- return resp;
20
+ this.emit('LIST', path, resp.data || []);
21
+ return resp.data;
22
22
  });
23
23
  }
24
24
  upload(files, path = '/') {
25
25
  const data = new FormData();
26
26
  (Array.isArray(files) ? files : [files]).forEach(f => data.append('file', f));
27
27
  return this.api.request({ url: '/api/static' + path, body: data }).then(resp => {
28
- this.emit('UPLOAD', resp);
29
- return resp;
28
+ this.emit('UPLOAD', resp.data || []);
29
+ return resp.data;
30
30
  });
31
31
  }
32
32
  }
package/dist/storage.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Api } from './api';
2
2
  import { type Meta } from './core';
3
- import { PromiseProgress, type RequestOptions, TypedEmitter, type TypedEvents } from '@ztimson/utils';
3
+ import { PromiseProgress, TypedEmitter, type TypedEvents, HttpRequestOptions } from '@ztimson/utils';
4
4
  export type DirMeta = {
5
5
  children: (DirMeta | FileMeta)[];
6
6
  path: string;
@@ -29,13 +29,13 @@ export declare class Storage extends TypedEmitter<StorageEvents> {
29
29
  open(path: string, target: false): string;
30
30
  open(path: string, target?: '_blank' | '_self'): Window | null;
31
31
  mkdir(path: string): Promise<DirMeta>;
32
- download(path: string, opts?: RequestOptions & {
32
+ download(path: string, opts?: HttpRequestOptions & {
33
33
  'downloadAs'?: string;
34
34
  }): PromiseProgress<Blob>;
35
35
  upload(files?: File | File[] | null, opts?: string | {
36
36
  path?: string;
37
37
  accept?: string;
38
38
  multiple?: boolean;
39
- }): Promise<FileMeta[]>;
39
+ }): PromiseProgress<FileMeta[]>;
40
40
  }
41
41
  //# sourceMappingURL=storage.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,KAAK,IAAI,EAAC,MAAM,QAAQ,CAAC;AACjC,OAAO,EAAC,eAAe,EAAE,KAAK,cAAc,EAAE,YAAY,EAAY,KAAK,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAE9G,MAAM,MAAM,OAAO,GAAG;IACrB,QAAQ,EAAE,CAAC,OAAO,GAAG,QAAQ,CAAC,EAAE,CAAC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,WAAW,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACb,CAAA;AAED,MAAM,MAAM,QAAQ,GAAG,IAAI,GAAG;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACb,CAAA;AAED,MAAM,MAAM,aAAa,GAAG,WAAW,GAAG;IACzC,IAAI,EAAE,CAAC,IAAI,E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,MAAM;IAK7B,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAOnC,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,QAAQ,CAAC;IAQ/C,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,GAAG,MAAM;IACzC,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,IAAI;IAS9D,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAKrC,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,kBAAkB,GAAG;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAM,GAAG,eAAe,CAAC,IAAI,CAAC;IAWtG,MAAM,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,IAAI,EAAE,IAAI,GAAE,MAAM,GAAG;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAM,GAAG,eAAe,CAAC,QAAQ,EAAE,CAAC;CAkB3I"}
package/dist/storage.js CHANGED
@@ -18,8 +18,8 @@ class Storage extends utils_1.TypedEmitter {
18
18
  list(path) {
19
19
  const url = (path.startsWith('/api/storage/') ? path : '/api/storage/' + path).replaceAll('//', '/');
20
20
  return this.api.request({ url: url + '?list' }).then(resp => {
21
- this.emit('LIST', path, resp);
22
- return resp;
21
+ this.emit('LIST', path, resp.data);
22
+ return resp.data;
23
23
  });
24
24
  }
25
25
  open(path, target = '_blank') {
@@ -32,67 +32,35 @@ class Storage extends utils_1.TypedEmitter {
32
32
  }
33
33
  mkdir(path) {
34
34
  const p = (path.startsWith('/api/storage/') ? path : '/api/storage/' + path).replaceAll(/\/{2,}/g, '/');
35
- return this.api.request({ url: p + '?directory', method: 'POST' });
35
+ return this.api.request({ url: p + '?directory', method: 'POST' }).then(resp => resp.data);
36
36
  }
37
37
  download(path, opts = {}) {
38
- return new utils_1.PromiseProgress((res, rej, progress) => {
39
- const p = ('/api/storage/' + path).replaceAll('//', '/');
40
- this.api.request({ ...opts, url: p, skipConverting: true }).then((response) => {
41
- if (!response.ok)
42
- return rej(response.statusText);
43
- const contentLength = response.headers.get('Content-Length');
44
- const total = contentLength ? parseInt(contentLength, 10) : 0;
45
- let chunks = [], loaded = 0;
46
- const reader = response.body?.getReader();
47
- const process = (result) => {
48
- if (result.done) {
49
- progress(1);
50
- const blob = new Blob(chunks);
51
- const name = opts.downloadAs || new URL(response.url).pathname.split('/').pop();
52
- const url = URL.createObjectURL(blob);
53
- (0, utils_1.download)(url, name.includes('.') ? name : name + '.zip');
54
- URL.revokeObjectURL(url);
55
- this.emit('DOWNLOAD', path, blob);
56
- res(blob);
57
- }
58
- else {
59
- const chunk = result.value;
60
- chunks.push(chunk);
61
- loaded += chunk.length;
62
- progress(loaded / total);
63
- reader.read().then(process);
64
- }
65
- };
66
- reader?.read().then(process);
67
- });
38
+ const p = ('/api/storage/' + path).replaceAll('//', '/');
39
+ return this.api.request({ ...opts, url: p, decode: false }).then(async (response) => {
40
+ const blob = await response.data.blob();
41
+ const name = opts.downloadAs || new URL(response.url).pathname.split('/').pop();
42
+ this.emit('DOWNLOAD', path, blob);
43
+ (0, utils_1.downloadBlob)(blob, name);
44
+ return response.data;
68
45
  });
69
46
  }
70
- async upload(files, opts = '') {
71
- const fileBrowser = () => {
72
- return new Promise(res => {
73
- const input = document.createElement('input');
74
- input.type = 'file';
75
- input.accept = opts?.accept || '*';
76
- input.style.display = 'none';
77
- input.multiple = !!opts?.multiple;
78
- input.onblur = input.onchange = async () => {
79
- res(Array.from(input.files));
80
- input.remove();
81
- };
82
- document.body.appendChild(input);
83
- input.click();
84
- });
85
- };
86
- if (!files)
87
- files = await fileBrowser();
88
- if (!files || Array.isArray(files) && !files.length)
89
- return [];
90
- const data = new FormData();
91
- const p = ('/api/storage/' + (typeof opts == 'string' ? opts : opts?.path)).replaceAll('//', '/');
92
- (Array.isArray(files) ? files : [files]).forEach(f => data.append('file', f));
93
- return this.api.request({ url: p, body: data }).then(resp => {
94
- this.emit('UPLOAD', resp);
95
- return resp;
47
+ upload(files, opts = '') {
48
+ return new utils_1.PromiseProgress(async (res, rej, prog) => {
49
+ if (!files)
50
+ files = await (0, utils_1.fileBrowser)();
51
+ if (!files || Array.isArray(files) && !files.length)
52
+ return [];
53
+ const url = this.api.url + ('/api/storage/' + (typeof opts == 'string' ? opts : opts?.path)).replaceAll('//', '/');
54
+ return (0, utils_1.uploadWithProgress)({
55
+ url,
56
+ files: Array.isArray(files) ? files : [files],
57
+ headers: this.api.headers
58
+ }).onProgress(p => {
59
+ prog(p);
60
+ }).then(resp => {
61
+ this.emit('UPLOAD', resp);
62
+ res(resp);
63
+ }).catch(err => rej(err));
96
64
  });
97
65
  }
98
66
  }
package/dist/users.d.ts CHANGED
@@ -17,10 +17,11 @@ export type User = Meta & {
17
17
  };
18
18
  export type UserEvents = TypedEvents & {
19
19
  LIST: (users: User[]) => any;
20
- READ: (user: User) => any;
20
+ CREATE: (user: User) => any;
21
+ READ: (user: User | null) => any;
21
22
  UPDATE: (user: User) => any;
22
23
  DELETE: (username: string) => any;
23
- UPLOAD_IMAGE: (file: File) => any;
24
+ UPLOAD_IMAGE: (username: string, file: File) => any;
24
25
  };
25
26
  export declare class Users extends TypedEmitter<UserEvents> {
26
27
  private readonly api;
@@ -33,6 +34,6 @@ export declare class Users extends TypedEmitter<UserEvents> {
33
34
  list(reload?: boolean): Promise<User[]>;
34
35
  read(username: string, reload?: boolean): Promise<User>;
35
36
  update(user: User): Promise<User>;
36
- uploadImage(username: string, file: File): Promise<unknown>;
37
+ uploadImage(username: string, file: File): import("@ztimson/utils").PromiseProgress<any>;
37
38
  }
38
39
  //# sourceMappingURL=users.d.ts.map
@@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,OAAO,GAAG,OAAO,CAAC;CACzC,CAAA;AAED,MAAM,MAAM,UAAU,GAAG,WAAW,GAAG;IACtC,IAAI,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,GAAG,CAAC;IAC7B,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;IAC5B,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,KAAK,GAAG,CAAC;IACjC,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;IAC5B,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,GAAG,CAAC;IAClC,YAAY,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;CACpD,CAAC;AAEF,qBAAa,KAAM,SAAQ,YAAY,CAAC,UAAU,CAAC;IAClD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;IAC3B,OAAO,CAAC,MAAM,CAAS;IAEvB,MAAM,0BAAkC;IACxC,IAAI,KAAK,WAAgC;IACzC,IAAI,KAAK,CAAC,GAAG,QAAA,EAA4B;gBAE7B,GAAG,EAAE,GAAG,GAAG,MAAM;IAK7B,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUvC,IAAI,CAAC,MAAM,UAAM,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAcnC,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,UAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAenD,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAejC,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI;CAUxC"}
package/dist/users.js CHANGED
@@ -27,14 +27,14 @@ class Users extends utils_1.TypedEmitter {
27
27
  if (!reload && this.listed)
28
28
  return Promise.resolve(this.cache);
29
29
  return this.api.request({ url: `/api/users` }).then(resp => {
30
- resp.map(r => {
30
+ resp.data?.map(r => {
31
31
  r.image = this.api.url + r.image + `?token=${this.api.token}`;
32
32
  return r;
33
33
  });
34
- this.cache = resp;
34
+ this.cache = resp.data || [];
35
35
  this.listed = true;
36
- this.emit('LIST', resp);
37
- return resp;
36
+ this.emit('LIST', resp.data || []);
37
+ return resp.data;
38
38
  });
39
39
  }
40
40
  read(username, reload = false) {
@@ -44,11 +44,12 @@ class Users extends utils_1.TypedEmitter {
44
44
  return Promise.resolve(cached);
45
45
  }
46
46
  return this.api.request({ url: `/api/users/${username}` }).then(resp => {
47
- resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
48
- if (resp)
49
- this.cache = [...this.cache.filter(u => u.username != username), resp];
50
- this.emit('READ', resp);
51
- return resp;
47
+ if (resp.data) {
48
+ resp.data.image = this.api.url + resp.data.image + `?token=${this.api.token}`;
49
+ this.cache = [...this.cache.filter(u => u.username != username), resp.data];
50
+ }
51
+ this.emit('READ', resp.data);
52
+ return resp.data;
52
53
  });
53
54
  }
54
55
  update(user) {
@@ -57,18 +58,21 @@ class Users extends utils_1.TypedEmitter {
57
58
  method: 'PATCH',
58
59
  body: user
59
60
  }).then(resp => {
60
- resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
61
- if (resp)
62
- this.cache = this.cache.filter(u => u.username != user.username).concat([resp]);
63
- this.emit('UPDATE', resp);
64
- return resp;
61
+ if (resp.data) {
62
+ resp.data.image = this.api.url + resp.data.image + `?token=${this.api.token}`;
63
+ this.cache = this.cache.filter(u => u.username != user.username).concat([resp.data]);
64
+ }
65
+ this.emit(user._id ? 'UPDATE' : 'CREATE', resp.data);
66
+ return resp.data;
65
67
  });
66
68
  }
67
69
  uploadImage(username, file) {
68
- const data = new FormData();
69
- data.append('file', file);
70
- return this.api.request({ url: `/api/users/${username}/image`, body: data }).then(resp => {
71
- this.emit('UPLOAD_IMAGE', file);
70
+ return (0, utils_1.uploadWithProgress)({
71
+ url: this.api.url + `/api/users/${username}/image`,
72
+ files: [file],
73
+ headers: this.api.headers,
74
+ }).then(resp => {
75
+ this.emit('UPLOAD_IMAGE', username, file);
72
76
  return resp;
73
77
  });
74
78
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ztimson/momentum",
3
- "version": "0.27.2",
3
+ "version": "0.27.4",
4
4
  "description": "Client library for momentum",
5
5
  "keywords": [
6
6
  "Momentum"
@@ -26,7 +26,7 @@
26
26
  "watch": "tsc -w & bun build --watch --target browser --outfile dist/index.mjs --minify src/index.ts"
27
27
  },
28
28
  "dependencies": {
29
- "@ztimson/utils": "^0.12.3",
29
+ "@ztimson/utils": "^0.14.11",
30
30
  "rxjs": "^7.8.1"
31
31
  },
32
32
  "devDependencies": {