@go-avro/avro-js 0.0.2-beta.9 → 0.0.2-beta.90

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.
Files changed (46) hide show
  1. package/README.md +1 -0
  2. package/dist/auth/AuthManager.d.ts +4 -0
  3. package/dist/auth/AuthManager.js +18 -2
  4. package/dist/client/QueryClient.d.ts +349 -15
  5. package/dist/client/QueryClient.js +302 -195
  6. package/dist/client/core/fetch.d.ts +1 -0
  7. package/dist/client/core/fetch.js +62 -0
  8. package/dist/client/core/utils.d.ts +1 -0
  9. package/dist/client/core/utils.js +14 -0
  10. package/dist/client/core/xhr.d.ts +1 -0
  11. package/dist/client/core/xhr.js +84 -0
  12. package/dist/client/hooks/analytics.d.ts +1 -0
  13. package/dist/client/hooks/analytics.js +10 -0
  14. package/dist/client/hooks/avro.d.ts +1 -0
  15. package/dist/client/hooks/avro.js +9 -0
  16. package/dist/client/hooks/bills.d.ts +1 -0
  17. package/dist/client/hooks/bills.js +141 -0
  18. package/dist/client/hooks/chats.d.ts +1 -0
  19. package/dist/client/hooks/chats.js +37 -0
  20. package/dist/client/hooks/companies.d.ts +1 -0
  21. package/dist/client/hooks/companies.js +79 -0
  22. package/dist/client/hooks/events.d.ts +1 -0
  23. package/dist/client/hooks/events.js +307 -0
  24. package/dist/client/hooks/jobs.d.ts +1 -0
  25. package/dist/client/hooks/jobs.js +185 -0
  26. package/dist/client/hooks/messages.d.ts +1 -0
  27. package/dist/client/hooks/messages.js +30 -0
  28. package/dist/client/hooks/months.d.ts +1 -0
  29. package/dist/client/hooks/months.js +92 -0
  30. package/dist/client/hooks/plans.d.ts +1 -0
  31. package/dist/client/hooks/plans.js +9 -0
  32. package/dist/client/hooks/root.d.ts +1 -0
  33. package/dist/client/hooks/root.js +8 -0
  34. package/dist/client/hooks/routes.d.ts +1 -0
  35. package/dist/client/hooks/routes.js +123 -0
  36. package/dist/client/hooks/sessions.d.ts +1 -0
  37. package/dist/client/hooks/sessions.js +154 -0
  38. package/dist/client/hooks/teams.d.ts +1 -0
  39. package/dist/client/hooks/teams.js +117 -0
  40. package/dist/client/hooks/users.d.ts +1 -0
  41. package/dist/client/hooks/users.js +104 -0
  42. package/dist/index.d.ts +19 -0
  43. package/dist/index.js +19 -0
  44. package/dist/types/api.d.ts +118 -29
  45. package/dist/types/api.js +10 -1
  46. package/package.json +6 -1
@@ -1,6 +1,10 @@
1
+ import io from 'socket.io-client';
2
+ import { useMutation, useQueryClient } from '@tanstack/react-query';
3
+ import { LoginResponse } from '../types/api';
1
4
  import { StandardError } from '../types/error';
2
5
  export class AvroQueryClient {
3
6
  constructor(config) {
7
+ this._isAuthenticated = false;
4
8
  this.config = {
5
9
  baseUrl: config.baseUrl,
6
10
  authManager: config.authManager,
@@ -8,228 +12,248 @@ export class AvroQueryClient {
8
12
  retryStrategy: config.retryStrategy ?? 'fixed',
9
13
  timeout: config.timeout ?? 0,
10
14
  };
11
- }
12
- getDelay(strategy, attempt) {
13
- if (typeof strategy === 'function') {
14
- return strategy(attempt);
15
- }
16
- else if (strategy === 'fixed') {
17
- return 1000;
15
+ config.authManager.isAuthenticated().then(isAuth => {
16
+ this._isAuthenticated = isAuth;
17
+ });
18
+ this.socket = io(config.baseUrl, { autoConnect: false, transports: ["websocket"], });
19
+ if (!this.socket.connected) {
20
+ this.config.authManager.accessToken().then(token => {
21
+ console.log('Initializing socket connection with token...');
22
+ this.socket.auth = { token: token };
23
+ this.socket.connect();
24
+ });
18
25
  }
19
- else if (strategy === 'exponential') {
20
- return Math.pow(2, attempt) * 100;
26
+ this.socket.on('connect', () => {
27
+ this._isAuthenticated = true;
28
+ console.log(`Socket connected with ID: ${this.socket?.id}`);
29
+ });
30
+ this.socket.on('disconnect', (reason) => {
31
+ console.log(`Socket disconnected: ${reason}`);
32
+ });
33
+ this.socket.on('connect_error', (err) => {
34
+ console.error(`Socket connection error: ${err.message}`);
35
+ });
36
+ this.config.authManager.onTokenRefreshed((newAccessToken) => {
37
+ if (this.socket && newAccessToken) {
38
+ this._isAuthenticated = true;
39
+ console.log('Access token refreshed, updating socket auth...');
40
+ this.socket.auth = { token: newAccessToken };
41
+ this.socket.disconnect().connect();
42
+ }
43
+ });
44
+ config.authManager.onTokenRefreshFailed(() => {
45
+ this._isAuthenticated = false;
46
+ if (this.socket && this.socket.connected) {
47
+ this.socket.disconnect();
48
+ }
49
+ });
50
+ }
51
+ emit(eventName, data) {
52
+ if (!this.socket?.connected) {
53
+ console.error('Socket is not connected. Cannot emit event.');
54
+ return;
21
55
  }
22
- throw new Error(`Invalid retry strategy: ${strategy}`);
56
+ this.socket.emit(eventName, data);
23
57
  }
24
- _xhr(method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount = 0) {
25
- const checkCancelled = () => {
26
- if (cancelToken?.isCancelled()) {
27
- return new StandardError(0, 'Request cancelled');
28
- }
29
- return null;
30
- };
31
- return this.config.authManager.accessToken().then(token => {
32
- return new Promise((resolve, reject) => {
33
- const cancelErr = checkCancelled();
34
- if (cancelErr)
35
- return reject(cancelErr);
36
- const xhr = new XMLHttpRequest();
37
- const url = this.config.baseUrl + path;
38
- xhr.open(method, url, true);
39
- if (token) {
40
- xhr.setRequestHeader('Authorization', `Bearer ${token}`);
41
- }
42
- Object.entries(headers).forEach(([key, value]) => {
43
- xhr.setRequestHeader(key, value);
44
- });
45
- xhr.onload = () => {
46
- const cancelErr = checkCancelled();
47
- if (cancelErr)
48
- return reject(cancelErr);
49
- if (xhr.status === 401 && this.config.authManager.refreshTokens && retryCount === 0) {
50
- this.config.authManager
51
- .refreshTokens()
52
- .then(() => {
53
- this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
54
- })
55
- .catch(() => {
56
- reject(new StandardError(401, 'Unauthorized (refresh failed)'));
57
- });
58
- return;
59
- }
60
- if (xhr.status >= 200 && xhr.status < 300) {
61
- try {
62
- resolve(JSON.parse(xhr.responseText));
63
- }
64
- catch {
65
- resolve(xhr.responseText);
66
- }
67
- }
68
- else {
69
- if (retryCount < this.config.maxRetries) {
70
- const delay = this.getDelay(this.config.retryStrategy, retryCount);
71
- setTimeout(() => {
72
- this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
73
- }, delay);
74
- }
75
- else {
76
- let msg = xhr.statusText;
77
- try {
78
- const parsed = JSON.parse(xhr.responseText);
79
- msg = parsed.message || msg;
80
- }
81
- catch {
82
- console.warn('Failed to parse error response:', xhr.responseText);
83
- }
84
- reject(new StandardError(xhr.status, msg));
85
- }
86
- }
87
- };
88
- xhr.onerror = () => {
89
- if (retryCount < this.config.maxRetries) {
90
- const delay = this.getDelay(this.config.retryStrategy, retryCount);
91
- setTimeout(() => {
92
- this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
93
- }, delay);
94
- }
95
- else {
96
- reject(new StandardError(0, 'Network Error'));
58
+ on(eventName, callback) {
59
+ this.socket?.on(eventName, callback);
60
+ }
61
+ off(eventName, callback) {
62
+ this.socket?.off(eventName, callback);
63
+ }
64
+ get(path, cancelToken, headers = {}, progressUpdateCallback) {
65
+ return this._xhr('GET', path, null, cancelToken, headers, true, this.config.maxRetries, progressUpdateCallback);
66
+ }
67
+ post(path, data, cancelToken, headers = {}, progressUpdateCallback) {
68
+ return this._xhr('POST', path, data, cancelToken, headers, false, this.config.maxRetries, progressUpdateCallback);
69
+ }
70
+ put(path, data, cancelToken, headers = {}, progressUpdateCallback) {
71
+ return this._xhr('PUT', path, data, cancelToken, headers, true, this.config.maxRetries, progressUpdateCallback);
72
+ }
73
+ delete(path, cancelToken, headers = {}, progressUpdateCallback) {
74
+ return this._xhr('DELETE', path, null, cancelToken, headers, false, this.config.maxRetries, progressUpdateCallback);
75
+ }
76
+ useLogin() {
77
+ const queryClient = useQueryClient();
78
+ return useMutation({
79
+ mutationFn: async ({ username, password, code, cancelToken }) => {
80
+ const resp = await this.post('/login', JSON.stringify({ username, password, code }), cancelToken, { 'Content-Type': 'application/json' });
81
+ if (!resp || !('access_token' in resp)) {
82
+ if (resp.msg === "TOTP required") {
83
+ return LoginResponse.NEEDS_TOTP;
97
84
  }
98
- };
99
- if (this.config.timeout) {
100
- xhr.timeout = this.config.timeout;
101
- xhr.ontimeout = () => reject(new StandardError(0, 'Request timed out'));
85
+ throw new StandardError(401, 'Invalid login response');
102
86
  }
103
- xhr.send(body);
104
- });
87
+ this.socket.auth = { token: resp.access_token };
88
+ if (!this.socket.connected) {
89
+ this.socket.connect();
90
+ }
91
+ await this.config.authManager.setTokens({ access_token: resp.access_token, refresh_token: resp.refresh_token });
92
+ return LoginResponse.SUCCESS;
93
+ },
94
+ onSettled: () => {
95
+ queryClient.invalidateQueries();
96
+ },
97
+ onError: (err) => {
98
+ this.config.authManager.clearTokens();
99
+ throw new StandardError(401, err.message || 'Login failed');
100
+ }
105
101
  });
106
102
  }
107
- _fetch(method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount = 0) {
108
- const checkCancelled = () => {
109
- if (cancelToken?.isCancelled()) {
110
- return new StandardError(0, 'Request cancelled');
103
+ useRequestCode() {
104
+ const queryClient = useQueryClient();
105
+ return useMutation({
106
+ mutationFn: async ({ username, email, cancelToken }) => {
107
+ const resp = await this.post('/code', JSON.stringify({ username, email }), cancelToken, { 'Content-Type': 'application/json' });
108
+ return resp;
109
+ },
110
+ onSettled: () => {
111
+ queryClient.invalidateQueries();
112
+ },
113
+ onError: (err) => {
114
+ throw new StandardError(err.status, err.message || 'Request code failed');
111
115
  }
112
- return null;
113
- };
114
- return this.config.authManager.accessToken().then(token => {
115
- const cancelErr = checkCancelled();
116
- if (cancelErr)
117
- return Promise.reject(cancelErr);
118
- const url = this.config.baseUrl + path;
119
- const requestHeaders = {
120
- 'Content-Type': 'application/json',
121
- ...headers,
122
- };
123
- if (token) {
124
- requestHeaders['Authorization'] = `Bearer ${token}`;
116
+ });
117
+ }
118
+ useUpdatePassword() {
119
+ const queryClient = useQueryClient();
120
+ return useMutation({
121
+ mutationFn: async ({ username, email, code, newPassword, cancelToken }) => {
122
+ await this.post('/update-password', JSON.stringify({ username, email, code, password: newPassword }), cancelToken, { 'Content-Type': 'application/json' });
123
+ },
124
+ onSettled: () => {
125
+ queryClient.invalidateQueries();
126
+ },
127
+ onError: (err) => {
128
+ throw new StandardError(err.status, err.message || 'Update password failed');
125
129
  }
126
- const options = {
127
- method,
128
- headers: requestHeaders,
129
- body: body ? JSON.stringify(body) : null,
130
- };
131
- return fetch(url, options).then(response => {
132
- if (response.status === 401 && this.config.authManager.refreshTokens && retryCount === 0) {
133
- return this.config.authManager
134
- .refreshTokens()
135
- .then(() => this._fetch(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1))
136
- .catch(() => Promise.reject(new StandardError(401, 'Unauthorized (refresh failed)')));
137
- }
138
- if (!response.ok) {
139
- if (retryCount < this.config.maxRetries) {
140
- const delay = this.getDelay(this.config.retryStrategy, retryCount);
141
- return new Promise((resolve, reject) => {
142
- setTimeout(() => {
143
- this._fetch(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1)
144
- .then(resolve)
145
- .catch(reject);
146
- }, delay);
147
- });
148
- }
149
- else {
150
- return response.text().then(text => {
151
- let msg = response.statusText;
152
- try {
153
- const parsed = JSON.parse(text);
154
- msg = parsed.message || msg;
155
- }
156
- catch {
157
- console.warn('Failed to parse error response:', text);
158
- }
159
- throw new StandardError(response.status, msg);
160
- });
130
+ });
131
+ }
132
+ useGoogleLogin() {
133
+ const queryClient = useQueryClient();
134
+ return useMutation({
135
+ mutationFn: async ({ token, cancelToken }) => {
136
+ const resp = await this._xhr('POST', `/google/authorize?token=${token}`, {}, cancelToken, { 'Content-Type': 'application/json' });
137
+ if (!resp || !('access_token' in resp)) {
138
+ if (resp.msg === "TOTP required") {
139
+ return LoginResponse.NEEDS_TOTP;
161
140
  }
141
+ throw new StandardError(401, 'Invalid Google login response');
162
142
  }
163
- return response.json();
164
- });
143
+ this.socket.auth = { token: resp.access_token };
144
+ if (!this.socket.connected) {
145
+ this.socket.connect();
146
+ }
147
+ await this.config.authManager.setTokens({ access_token: resp.access_token, refresh_token: resp.refresh_token });
148
+ return LoginResponse.SUCCESS;
149
+ },
150
+ onSettled: () => {
151
+ queryClient.invalidateQueries();
152
+ },
153
+ onError: (err) => {
154
+ this.config.authManager.clearTokens();
155
+ throw new StandardError(err.status, err.message || 'Google Login failed');
156
+ }
165
157
  });
166
158
  }
167
- get(path, cancelToken, headers = {}) {
168
- return this._xhr('GET', path, null, cancelToken, headers, true);
159
+ setTokens(tokens) {
160
+ return this.config.authManager.setTokens(tokens);
169
161
  }
170
- post(path, data, cancelToken, headers = {}) {
171
- return this._xhr('POST', path, data, cancelToken, headers, false);
162
+ clearTokens() {
163
+ return this.config.authManager.clearTokens();
172
164
  }
173
- put(path, data, cancelToken, headers = {}) {
174
- return this._xhr('PUT', path, data, cancelToken, headers, true);
165
+ isAuthenticated() {
166
+ return this._isAuthenticated;
175
167
  }
176
- delete(path, cancelToken, headers = {}) {
177
- return this._xhr('DELETE', path, null, cancelToken, headers, false);
168
+ isAuthenticatedAsync() {
169
+ return this.config.authManager.isAuthenticated();
178
170
  }
179
- login(data, cancelToken) {
180
- return this._fetch('POST', '/login', data, cancelToken)
181
- .then(tokens => {
182
- if (!tokens || !tokens.access_token || !tokens.refresh_token) {
183
- throw new StandardError(401, 'Invalid login response');
171
+ useLogout() {
172
+ const queryClient = useQueryClient();
173
+ return useMutation({
174
+ mutationFn: async (cancelToken) => {
175
+ await this.post('/logout', null, cancelToken);
176
+ await this.config.authManager.clearTokens();
177
+ if (this.socket && this.socket.connected) {
178
+ this.socket.disconnect();
179
+ }
180
+ },
181
+ onSettled: () => {
182
+ this._isAuthenticated = false;
183
+ queryClient.invalidateQueries();
184
+ },
185
+ onError: (err) => {
186
+ this.config.authManager.clearTokens();
187
+ console.error('Logout failed:', err);
188
+ throw new StandardError(500, 'Logout failed');
189
+ }
190
+ });
191
+ }
192
+ fetchJobs(companyGuid, body = {}, cancelToken, headers = {}) {
193
+ if (!companyGuid || companyGuid.trim() === '') {
194
+ return Promise.reject(new StandardError(400, 'Company GUID is required'));
195
+ }
196
+ return this._fetch('POST', `/company/${companyGuid}/jobs`, JSON.stringify(body), cancelToken, {
197
+ ...headers,
198
+ 'Content-Type': 'application/json',
199
+ })
200
+ .then(response => {
201
+ if (!response || !Array.isArray(response)) {
202
+ throw new StandardError(400, 'Invalid jobs response');
184
203
  }
185
- return this.config.authManager.setTokens(tokens).then(() => true);
204
+ return response;
186
205
  })
187
206
  .catch(err => {
188
- console.error('Login failed:', err);
189
- throw new StandardError(401, 'Login failed');
207
+ console.error('Failed to fetch jobs:', err);
208
+ throw new StandardError(500, 'Failed to fetch jobs');
190
209
  });
191
210
  }
192
- logout(cancelToken) {
193
- return this._fetch('POST', '/logout', null, cancelToken)
194
- .then(() => this.config.authManager.clearTokens())
211
+ fetchChats(companyGuid, body = {}, cancelToken, headers = {}) {
212
+ if (!companyGuid || companyGuid.trim() === '') {
213
+ return Promise.reject(new StandardError(400, 'Company GUID is required'));
214
+ }
215
+ return this._fetch('POST', `/company/${companyGuid}/chats`, JSON.stringify(body), cancelToken, {
216
+ ...headers,
217
+ 'Content-Type': 'application/json',
218
+ })
219
+ .then(response => {
220
+ if (!response || !Array.isArray(response)) {
221
+ throw new StandardError(400, 'Invalid chats response');
222
+ }
223
+ return response;
224
+ })
195
225
  .catch(err => {
196
- console.error('Logout failed:', err);
197
- throw new StandardError(500, 'Logout failed');
226
+ console.error('Failed to fetch chats:', err);
227
+ throw new StandardError(500, 'Failed to fetch chats');
198
228
  });
199
229
  }
200
- fetchJobs(companyGuid, amt = 50, knownIds = [], unknownIds = [], keyword = '', offset = 0, cancelToken, headers = {}) {
201
- const body = {
202
- amt,
203
- known_ids: knownIds,
204
- unknown_ids: unknownIds,
205
- query: keyword,
206
- };
207
- if (!companyGuid) {
208
- return Promise.reject(new StandardError(400, 'Company GUID is required'));
230
+ fetchMessages(chatGuid, body = {}, cancelToken, headers = {}) {
231
+ if (!chatGuid || chatGuid.trim() === '') {
232
+ return Promise.reject(new StandardError(400, 'Chat GUID is required'));
209
233
  }
210
- return this._fetch('POST', `/company/${companyGuid}/jobs?amt=${amt}&offset=${offset}`, body, cancelToken, headers)
234
+ return this._fetch('POST', `/chat/${chatGuid}/messages`, JSON.stringify(body), cancelToken, {
235
+ ...headers,
236
+ 'Content-Type': 'application/json',
237
+ })
211
238
  .then(response => {
212
239
  if (!response || !Array.isArray(response)) {
213
- throw new StandardError(400, 'Invalid jobs response');
240
+ throw new StandardError(400, 'Invalid messages response');
214
241
  }
215
242
  return response;
216
243
  })
217
244
  .catch(err => {
218
- console.error('Failed to fetch jobs:', err);
219
- throw new StandardError(500, 'Failed to fetch jobs');
245
+ console.error('Failed to fetch messages:', err);
246
+ throw new StandardError(500, 'Failed to fetch messages');
220
247
  });
221
248
  }
222
- fetchEvents(companyGuid, amt = 50, known_ids = [], unknown_ids = [], keyword = '', unbilled = false, billed = false, paid = false, offset = 0, cancelToken, headers = {}) {
223
- const body = {
224
- amt,
225
- known_ids,
226
- unknown_ids,
227
- query: keyword,
228
- };
229
- if (!companyGuid) {
249
+ fetchEvents(companyGuid, body = {}, cancelToken, headers = {}) {
250
+ if (!companyGuid || companyGuid.trim() === '') {
230
251
  return Promise.reject(new StandardError(400, 'Company GUID is required'));
231
252
  }
232
- return this._fetch('POST', `/company/${companyGuid}/events?amt=${amt}&offset=${offset}&unbilled=${unbilled}&billed=${billed}&paid=${paid}`, body, cancelToken, headers)
253
+ return this._fetch('POST', `/company/${companyGuid}/events`, JSON.stringify(body), cancelToken, {
254
+ ...headers,
255
+ 'Content-Type': 'application/json',
256
+ })
233
257
  .then(response => {
234
258
  if (!response || !Array.isArray(response)) {
235
259
  throw new StandardError(400, 'Invalid events response');
@@ -241,17 +265,33 @@ export class AvroQueryClient {
241
265
  throw new StandardError(500, 'Failed to fetch events');
242
266
  });
243
267
  }
244
- fetchBills(companyGuid, amt = 50, known_ids = [], unknown_ids = [], keyword = '', offset = 0, cancelToken, headers = {}) {
245
- const body = {
246
- amt,
247
- known_ids,
248
- unknown_ids,
249
- query: keyword,
250
- };
251
- if (!companyGuid) {
268
+ fetchMonths(companyGuid, body = {}, cancelToken, headers = {}) {
269
+ if (!companyGuid || companyGuid.trim() === '') {
252
270
  return Promise.reject(new StandardError(400, 'Company GUID is required'));
253
271
  }
254
- return this._fetch('POST', `/company/${companyGuid}/bills?amt=${amt}&offset=${offset}`, body, cancelToken, headers)
272
+ return this._fetch('POST', `/company/${companyGuid}/months`, JSON.stringify(body), cancelToken, {
273
+ ...headers,
274
+ 'Content-Type': 'application/json',
275
+ })
276
+ .then(response => {
277
+ if (!response || !Array.isArray(response)) {
278
+ throw new StandardError(400, 'Invalid months response');
279
+ }
280
+ return response;
281
+ })
282
+ .catch(err => {
283
+ console.error('Failed to fetch months:', err);
284
+ throw new StandardError(500, 'Failed to fetch months');
285
+ });
286
+ }
287
+ fetchBills(companyGuid, body = {}, cancelToken, headers = {}) {
288
+ if (!companyGuid || companyGuid.trim() === '') {
289
+ return Promise.reject(new StandardError(400, 'Company GUID is required'));
290
+ }
291
+ return this._fetch('POST', `/company/${companyGuid}/bills`, JSON.stringify(body), cancelToken, {
292
+ ...headers,
293
+ 'Content-Type': 'application/json',
294
+ })
255
295
  .then(response => {
256
296
  if (!response || !Array.isArray(response)) {
257
297
  throw new StandardError(400, 'Invalid bills response');
@@ -263,4 +303,71 @@ export class AvroQueryClient {
263
303
  throw new StandardError(500, 'Failed to fetch bills');
264
304
  });
265
305
  }
306
+ fetchRoutes(companyGuid, body = {}, cancelToken, headers = {}) {
307
+ if (!companyGuid || companyGuid.trim() === '') {
308
+ return Promise.reject(new StandardError(400, 'Company GUID is required'));
309
+ }
310
+ return this._fetch('POST', `/company/${companyGuid}/routes`, JSON.stringify(body), cancelToken, {
311
+ ...headers,
312
+ 'Content-Type': 'application/json',
313
+ })
314
+ .then(response => {
315
+ if (!response || !Array.isArray(response)) {
316
+ throw new StandardError(400, 'Invalid routes response');
317
+ }
318
+ return response;
319
+ })
320
+ .catch(err => {
321
+ console.error('Failed to fetch routes:', err);
322
+ throw new StandardError(500, 'Failed to fetch routes');
323
+ });
324
+ }
325
+ fetchTeams(companyGuid, body = {}, cancelToken, headers = {}) {
326
+ if (!companyGuid || companyGuid.trim() === '') {
327
+ return Promise.reject(new StandardError(400, 'Company GUID is required'));
328
+ }
329
+ return this._fetch('POST', `/company/${companyGuid}/teams`, JSON.stringify(body), cancelToken, {
330
+ ...headers,
331
+ 'Content-Type': 'application/json',
332
+ })
333
+ .then(response => {
334
+ if (!response || !Array.isArray(response)) {
335
+ throw new StandardError(400, 'Invalid teams response');
336
+ }
337
+ return response;
338
+ })
339
+ .catch(err => {
340
+ console.error('Failed to fetch teams:', err);
341
+ throw new StandardError(500, 'Failed to fetch teams');
342
+ });
343
+ }
344
+ sendEmail(emailId, formData, progressUpdateCallback) {
345
+ try {
346
+ return this.post(`/email/${emailId}`, formData, undefined, {}, progressUpdateCallback);
347
+ }
348
+ catch (error) {
349
+ throw new StandardError(500, `Failed to send email: ${error}`);
350
+ }
351
+ }
352
+ createBill(companyGuid, data, cancelToken) {
353
+ if (!companyGuid) {
354
+ return Promise.reject(new StandardError(400, 'Company GUID is required'));
355
+ }
356
+ const body = {
357
+ events: data.line_items.filter(item => item.line_item_type === 'EVENT').map(item => item.id),
358
+ months: data.line_items.filter(item => item.line_item_type === 'SERVICE_MONTH').map(item => item.id),
359
+ line_items: data.line_items.filter(item => item.line_item_type === 'CUSTOM'),
360
+ manual_emails: data.custom_emails,
361
+ users: data.users,
362
+ due_date: data.due_date,
363
+ };
364
+ try {
365
+ return this._xhr('POST', `/company/${companyGuid}/bill`, JSON.stringify(body), cancelToken, {
366
+ 'Content-Type': 'application/json',
367
+ });
368
+ }
369
+ catch (error) {
370
+ throw new StandardError(500, `Failed to create bill: ${error}`);
371
+ }
372
+ }
266
373
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,62 @@
1
+ import { AvroQueryClient } from '../../client/QueryClient';
2
+ import { StandardError } from '../../types/error';
3
+ AvroQueryClient.prototype._fetch = async function (method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount = 0) {
4
+ const checkCancelled = () => {
5
+ try {
6
+ if (cancelToken?.isCancelled()) {
7
+ throw new StandardError(0, 'Request cancelled');
8
+ }
9
+ }
10
+ catch (error) {
11
+ throw new StandardError(0, `Error checking cancellation: ${error.message}`);
12
+ }
13
+ };
14
+ try {
15
+ checkCancelled();
16
+ const token = await this.config.authManager.accessToken();
17
+ checkCancelled();
18
+ const url = this.config.baseUrl + path;
19
+ const requestHeaders = {
20
+ Authorization: `Bearer ${token}`,
21
+ ...headers,
22
+ };
23
+ const options = {
24
+ method,
25
+ headers: requestHeaders,
26
+ body,
27
+ };
28
+ const response = await fetch(url, options);
29
+ if (response.ok) {
30
+ const text = await response.text();
31
+ if (!text) {
32
+ return undefined;
33
+ }
34
+ return JSON.parse(text);
35
+ }
36
+ if (response.status === 401 && this.config.authManager.refreshTokens && retryCount === 0) {
37
+ await this.config.authManager.refreshTokens();
38
+ return this._fetch(method, path, body, cancelToken, headers, isIdempotent, 1);
39
+ }
40
+ if (retryCount < this.config.maxRetries) {
41
+ const delay = this.getDelay(this.config.retryStrategy, retryCount);
42
+ await this.sleep(delay);
43
+ return this._fetch(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1);
44
+ }
45
+ let errorMessage = response.statusText;
46
+ try {
47
+ const parsedError = await response.json();
48
+ errorMessage = parsedError.message ?? parsedError.msg ?? errorMessage;
49
+ }
50
+ catch (e) {
51
+ console.error('Ignoring:', e);
52
+ }
53
+ throw new StandardError(response.status, errorMessage);
54
+ }
55
+ catch (error) {
56
+ if (error instanceof StandardError) {
57
+ throw error;
58
+ }
59
+ const message = error instanceof Error ? error.message : String(error);
60
+ throw new StandardError(0, `Request failed: ${message}`);
61
+ }
62
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ import { AvroQueryClient } from '../../client/QueryClient';
2
+ AvroQueryClient.prototype.getDelay = function (strategy, attempt) {
3
+ if (typeof strategy === 'function') {
4
+ return strategy(attempt);
5
+ }
6
+ else if (strategy === 'fixed') {
7
+ return 1000;
8
+ }
9
+ else if (strategy === 'exponential') {
10
+ return Math.pow(2, attempt) * 100;
11
+ }
12
+ throw new Error(`Invalid retry strategy: ${strategy}`);
13
+ };
14
+ AvroQueryClient.prototype.sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
@@ -0,0 +1 @@
1
+ export {};