@go-avro/avro-js 0.1.14 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/auth/AuthManager.d.ts +28 -0
  2. package/dist/auth/AuthManager.js +119 -43
  3. package/dist/client/QueryClient.d.ts +56 -1
  4. package/dist/client/QueryClient.js +264 -80
  5. package/dist/client/cache.d.ts +24 -0
  6. package/dist/client/cache.js +51 -0
  7. package/dist/client/core/fetch.js +58 -49
  8. package/dist/client/core/policy.d.ts +17 -0
  9. package/dist/client/core/policy.js +35 -0
  10. package/dist/client/core/xhr.js +16 -14
  11. package/dist/client/hooks/bills.js +10 -14
  12. package/dist/client/hooks/catalog_items.js +18 -8
  13. package/dist/client/hooks/chats.js +2 -8
  14. package/dist/client/hooks/companies.js +11 -5
  15. package/dist/client/hooks/events.js +46 -35
  16. package/dist/client/hooks/groups.js +11 -26
  17. package/dist/client/hooks/jobs.js +3 -8
  18. package/dist/client/hooks/labels.js +11 -26
  19. package/dist/client/hooks/messages.js +3 -8
  20. package/dist/client/hooks/months.js +28 -22
  21. package/dist/client/hooks/payouts.js +3 -8
  22. package/dist/client/hooks/prepayments.js +28 -22
  23. package/dist/client/hooks/proposal.js +1 -0
  24. package/dist/client/hooks/routes.js +8 -6
  25. package/dist/client/hooks/sessions.js +11 -27
  26. package/dist/client/hooks/skills.js +6 -4
  27. package/dist/client/hooks/teams.js +6 -4
  28. package/dist/client/hooks/timecards.js +7 -7
  29. package/dist/client/hooks/waivers.js +6 -4
  30. package/dist/client/persist.js +21 -2
  31. package/dist/client/realtime.d.ts +12 -0
  32. package/dist/client/realtime.js +160 -46
  33. package/dist/types/api/Company.d.ts +2 -0
  34. package/dist/types/api/DelayEvent.d.ts +1 -1
  35. package/dist/types/api/LineItem.d.ts +4 -0
  36. package/dist/types/api/LineItem.js +8 -1
  37. package/dist/types/api/Task.d.ts +20 -0
  38. package/dist/types/api/Task.js +11 -1
  39. package/dist/types/api.d.ts +3 -3
  40. package/dist/version.d.ts +1 -1
  41. package/dist/version.js +1 -1
  42. package/package.json +7 -2
@@ -1,12 +1,50 @@
1
1
  import io from 'socket.io-client';
2
2
  import { useMutation, useQueryClient, } from '@tanstack/react-query';
3
3
  import { v4 as uuidv4 } from 'uuid';
4
+ import { isDefinitiveAuthFailure } from '../auth/AuthManager.js';
4
5
  import { fetchCensusFeatures } from '../census.js';
5
6
  import { LoginResponse, } from '../types/api.js';
6
7
  import { AuthState } from '../types/auth.js';
7
8
  import { StandardError } from '../types/error.js';
8
9
  import { ChangeApplier, fallbackInvalidate, patchMember, patchMemberLocation, patchTeamLocation, } from './realtime.js';
9
10
  import { QueryPersister } from './persist.js';
11
+ /** Keep the original status (401/403/404/0…) when surfacing a list-fetch failure. */
12
+ function fetchError(err, context) {
13
+ if (err instanceof StandardError)
14
+ return err;
15
+ const message = err instanceof Error ? err.message : String(err);
16
+ return new StandardError(0, `${context}: ${message}`);
17
+ }
18
+ /**
19
+ * Apply the list-endpoint filter contract client-side: non-empty
20
+ * `unknown_ids` = only these; else `known_ids` = exclude these; `query`
21
+ * substring-matches the given fields; then `offset`/`amt` paging.
22
+ */
23
+ function filterLocally(items, body, fields) {
24
+ let out = items;
25
+ if (body.unknown_ids && body.unknown_ids.length > 0) {
26
+ const wanted = new Set(body.unknown_ids);
27
+ out = out.filter((x) => x?.id && wanted.has(x.id));
28
+ }
29
+ else if (body.known_ids && body.known_ids.length > 0) {
30
+ const known = new Set(body.known_ids);
31
+ out = out.filter((x) => !(x?.id && known.has(x.id)));
32
+ }
33
+ const q = body.query?.trim().toLowerCase();
34
+ if (q) {
35
+ out = out.filter((x) => fields(x).some((f) => typeof f === 'string' && f.toLowerCase().includes(q)));
36
+ }
37
+ const offset = body.offset ?? 0;
38
+ return body.amt !== undefined ? out.slice(offset, offset + body.amt) : out.slice(offset);
39
+ }
40
+ /** Translate a legacy camelCase parent filter to the snake_case the backend reads. */
41
+ function withWireParent(body, legacy, wire) {
42
+ const { [legacy]: legacyValue, ...rest } = body;
43
+ return { ...rest, [wire]: rest[wire] ?? legacyValue ?? undefined };
44
+ }
45
+ const AUTH_RECHECK_MIN_MS = 2000;
46
+ const AUTH_RECHECK_MAX_MS = 60000;
47
+ const SOCKET_AUTH_RETRY_MS = 10000;
10
48
  export class AvroQueryClient {
11
49
  constructor(config) {
12
50
  this._authState = AuthState.UNKNOWN;
@@ -23,6 +61,11 @@ export class AvroQueryClient {
23
61
  this._restored = null;
24
62
  this._emailTracking = new Map();
25
63
  this._emailListenersInit = false;
64
+ this._authCheck = null;
65
+ this._authRecheckTimer = null;
66
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
67
+ this._socketAuthRetried = false;
68
+ this._socketRetryTimer = null;
26
69
  this.config = {
27
70
  baseUrl: config.baseUrl,
28
71
  authManager: config.authManager,
@@ -39,27 +82,8 @@ export class AvroQueryClient {
39
82
  transports: ['websocket'],
40
83
  });
41
84
  this.socket.on('connect', () => this.registerDevice());
42
- config.authManager.isAuthenticated().then((isAuth) => {
43
- this.setAuthState(isAuth);
44
- if (!this.socket.connected && isAuth === AuthState.AUTHENTICATED) {
45
- Promise.all([this.getCompanyId(), this.config.authManager.accessToken()])
46
- .then(([id, token]) => {
47
- this.companyId = id;
48
- this.socket.auth = this.socketAuth(token);
49
- this.ensureSocketConnected();
50
- })
51
- .catch((err) => {
52
- console.error('Not logged in:', err);
53
- });
54
- }
55
- else {
56
- // Not authenticated – still cache the companyId for later.
57
- this.getCompanyId().then((id) => {
58
- this.companyId = id;
59
- });
60
- }
61
- });
62
85
  this.socket.on('connect', () => {
86
+ this._socketAuthRetried = false;
63
87
  this.setAuthState(AuthState.AUTHENTICATED);
64
88
  console.log(`Socket connected with ID: ${this.socket?.id}`);
65
89
  });
@@ -67,7 +91,8 @@ export class AvroQueryClient {
67
91
  console.log(`Socket disconnected: ${reason}`);
68
92
  });
69
93
  this.socket.on('connect_error', (err) => {
70
- console.error(`Socket connection error: ${err.message}`);
94
+ console.error(`Socket connection error: ${err?.message}`);
95
+ this.handleSocketConnectError();
71
96
  });
72
97
  this.config.authManager.onTokenRefreshed((newAccessToken) => {
73
98
  if (this.socket && newAccessToken) {
@@ -79,6 +104,133 @@ export class AvroQueryClient {
79
104
  config.authManager.onTokenRefreshFailed(() => {
80
105
  void this.forceLogout();
81
106
  });
107
+ // Cache the stored companyId even before auth resolves.
108
+ this.getCompanyId().then((id) => {
109
+ this.companyId ?? (this.companyId = id);
110
+ });
111
+ void this.recheckAuth();
112
+ // Browsers: re-check as soon as the network comes back.
113
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
114
+ window.addEventListener('online', () => {
115
+ if (this._authState === AuthState.UNKNOWN)
116
+ void this.recheckAuth();
117
+ });
118
+ }
119
+ }
120
+ /**
121
+ * Re-validate the stored session (deduplicated). Call it when the app
122
+ * returns to the foreground or regains connectivity; the SDK also calls
123
+ * it on a backoff timer and after the next successful request while the
124
+ * state is UNKNOWN (e.g. after an offline cold start). A network error
125
+ * or 5xx never downgrades the state to UNAUTHENTICATED: only a
126
+ * definitive auth failure does.
127
+ */
128
+ recheckAuth() {
129
+ if (this._authCheck)
130
+ return this._authCheck;
131
+ if (this._authRecheckTimer) {
132
+ clearTimeout(this._authRecheckTimer);
133
+ this._authRecheckTimer = null;
134
+ }
135
+ const check = this.config.authManager
136
+ .isAuthenticated()
137
+ .catch((err) => {
138
+ console.error('Auth check failed:', err);
139
+ return AuthState.UNKNOWN;
140
+ })
141
+ .then(async (state) => {
142
+ if (state === AuthState.AUTHENTICATED) {
143
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
144
+ this.setAuthState(state);
145
+ if (!this.socket.connected) {
146
+ try {
147
+ const [id, token] = await Promise.all([
148
+ this.getCompanyId(),
149
+ this.config.authManager.accessToken(),
150
+ ]);
151
+ this.companyId = id;
152
+ this.socket.auth = this.socketAuth(token);
153
+ this.ensureSocketConnected();
154
+ }
155
+ catch (err) {
156
+ console.error('Not logged in:', err);
157
+ }
158
+ }
159
+ }
160
+ else if (state === AuthState.UNAUTHENTICATED) {
161
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
162
+ this.setAuthState(state);
163
+ }
164
+ else {
165
+ // Couldn't reach the server. Keep a known state (an
166
+ // AUTHENTICATED session stays usable offline) and retry.
167
+ if (this._authState === AuthState.UNKNOWN)
168
+ this.setAuthState(state);
169
+ this.scheduleAuthRecheck();
170
+ }
171
+ return state;
172
+ })
173
+ .finally(() => {
174
+ this._authCheck = null;
175
+ });
176
+ this._authCheck = check;
177
+ return check;
178
+ }
179
+ scheduleAuthRecheck() {
180
+ if (this._authRecheckTimer)
181
+ return;
182
+ const delay = this._authRecheckDelay;
183
+ this._authRecheckDelay = Math.min(delay * 2, AUTH_RECHECK_MAX_MS);
184
+ this._authRecheckTimer = setTimeout(() => {
185
+ this._authRecheckTimer = null;
186
+ if (this._authState === AuthState.UNKNOWN)
187
+ void this.recheckAuth();
188
+ }, delay);
189
+ }
190
+ /** Called by the transports after any 2xx: the server is reachable again. */
191
+ _noteRequestSucceeded() {
192
+ if (this._authState === AuthState.UNKNOWN && !this._authCheck) {
193
+ void this.recheckAuth();
194
+ }
195
+ }
196
+ /**
197
+ * The server refuses the socket handshake when the access token has
198
+ * expired; socket.io then stops reconnecting (`active` is false).
199
+ * Refresh the token once (shared with any in-flight refresh) and
200
+ * reconnect with it. A definitive refresh failure logs out via
201
+ * onTokenRefreshFailed; a transient one retries after a delay.
202
+ */
203
+ handleSocketConnectError() {
204
+ if (this.socket.active)
205
+ return; // transport error: socket.io retries itself
206
+ if (this._authState !== AuthState.AUTHENTICATED)
207
+ return;
208
+ if (this._socketAuthRetried)
209
+ return; // refreshed already and still refused
210
+ this._socketAuthRetried = true;
211
+ this.config.authManager
212
+ .refreshTokens()
213
+ .then((tokens) => {
214
+ // onTokenRefreshed already reconnects; make sure regardless.
215
+ if (tokens?.access_token) {
216
+ this.socket.auth = this.socketAuth(tokens.access_token);
217
+ this.ensureSocketConnected();
218
+ }
219
+ })
220
+ .catch((err) => {
221
+ if (isDefinitiveAuthFailure(err))
222
+ return; // forceLogout runs
223
+ console.error('Socket token refresh failed; retrying later:', err);
224
+ if (this._socketRetryTimer)
225
+ return;
226
+ this._socketRetryTimer = setTimeout(() => {
227
+ this._socketRetryTimer = null;
228
+ this._socketAuthRetried = false;
229
+ if (this._authState === AuthState.AUTHENTICATED) {
230
+ this.ensureSocketConnected();
231
+ }
232
+ }, SOCKET_AUTH_RETRY_MS);
233
+ });
82
234
  }
83
235
  /** Handshake payload: the token plus, when known, this install's identity. */
84
236
  socketAuth(token) {
@@ -177,6 +329,7 @@ export class AvroQueryClient {
177
329
  path: `/company/${this.companyId}/users`,
178
330
  data: JSON.stringify({ user_ids: userIds }),
179
331
  headers: { 'Content-Type': 'application/json' },
332
+ idempotent: true,
180
333
  })
181
334
  .then((members) => {
182
335
  if (!Array.isArray(members)) {
@@ -287,8 +440,8 @@ export class AvroQueryClient {
287
440
  // Reporting must never become a second failure.
288
441
  }
289
442
  }
290
- post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, }) {
291
- return this._xhr('POST', path, data, cancelToken, headers, false, maxRetries ?? this.config.maxRetries, progressUpdateCallback);
443
+ post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, }) {
444
+ return this._xhr('POST', path, data, cancelToken, headers, idempotent ?? false, maxRetries ?? this.config.maxRetries, progressUpdateCallback);
292
445
  }
293
446
  put({ path, data, cancelToken, headers, progressUpdateCallback, }) {
294
447
  return this._xhr('PUT', path, data, cancelToken, headers, true, this.config.maxRetries, progressUpdateCallback);
@@ -296,13 +449,20 @@ export class AvroQueryClient {
296
449
  delete({ path, cancelToken, headers, progressUpdateCallback, }) {
297
450
  return this._xhr('DELETE', path, null, cancelToken, headers, false, this.config.maxRetries, progressUpdateCallback);
298
451
  }
299
- loginSuccess(tokens) {
452
+ /**
453
+ * Persist freshly issued tokens, then flip to AUTHENTICATED and connect
454
+ * the socket. Tokens are stored first so that anything reacting to the
455
+ * auth-state change (queries enabled on AUTHENTICATED) finds them.
456
+ */
457
+ async loginSuccess(tokens) {
458
+ await this.config.authManager.setTokens(tokens);
459
+ this._socketAuthRetried = false;
460
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
300
461
  this.setAuthState(AuthState.AUTHENTICATED);
301
462
  this.socket.auth = this.socketAuth(tokens.access_token);
302
463
  if (!this.socket.connected) {
303
464
  this.ensureSocketConnected();
304
465
  }
305
- return this.config.authManager.setTokens(tokens);
306
466
  }
307
467
  useLogin() {
308
468
  const queryClient = this.getQueryClient();
@@ -554,12 +714,25 @@ export class AvroQueryClient {
554
714
  * server that no longer recognizes our identity.
555
715
  */
556
716
  async forceLogout() {
717
+ // Stop the socket first, including one that is mid-reconnect
718
+ // (`active` but not `connected`), so it can't come back with the
719
+ // old token.
720
+ if (this.socket && (this.socket.connected || this.socket.active)) {
721
+ this.socket.disconnect();
722
+ }
723
+ this.socket.auth = {};
724
+ if (this._socketRetryTimer) {
725
+ clearTimeout(this._socketRetryTimer);
726
+ this._socketRetryTimer = null;
727
+ }
728
+ if (this._authRecheckTimer) {
729
+ clearTimeout(this._authRecheckTimer);
730
+ this._authRecheckTimer = null;
731
+ }
732
+ this._socketAuthRetried = false;
557
733
  await this.clearCache();
558
734
  await this._persister?.clear();
559
735
  this.setAuthState(AuthState.UNAUTHENTICATED);
560
- if (this.socket && this.socket.connected) {
561
- this.socket.disconnect();
562
- }
563
736
  this.peekQueryClient()?.removeQueries();
564
737
  }
565
738
  useLogout() {
@@ -593,7 +766,7 @@ export class AvroQueryClient {
593
766
  return this._fetch('POST', `/company/${companyIdToUse}/jobs`, JSON.stringify(body), cancelToken, {
594
767
  ...headers,
595
768
  'Content-Type': 'application/json',
596
- })
769
+ }, true)
597
770
  .then((response) => {
598
771
  if (!response || !Array.isArray(response)) {
599
772
  throw new StandardError(400, 'Invalid jobs response');
@@ -602,7 +775,7 @@ export class AvroQueryClient {
602
775
  })
603
776
  .catch((err) => {
604
777
  console.error('Failed to fetch jobs:', err);
605
- throw new StandardError(500, `Failed to fetch jobs: ${err.message ?? err}`);
778
+ throw fetchError(err, 'Failed to fetch jobs');
606
779
  });
607
780
  }
608
781
  async autocompleteAddress({ address, size = 10, include_census = true, }, cancelToken, headers = {}) {
@@ -632,12 +805,15 @@ export class AvroQueryClient {
632
805
  }
633
806
  const features = pelias.value?.features ?? [];
634
807
  const knownLabels = new Set(features.map((feature) => feature.properties.label.toLowerCase()));
808
+ // Census only answers with exact geocodes of a complete address, so
809
+ // its matches lead; Pelias can fill the list with same-named streets
810
+ // elsewhere and bury the address the user actually typed.
635
811
  return {
636
812
  ...pelias.value,
637
813
  type: 'FeatureCollection',
638
814
  features: [
639
- ...features,
640
815
  ...census.filter((feature) => !knownLabels.has(feature.properties.label.toLowerCase())),
816
+ ...features,
641
817
  ],
642
818
  };
643
819
  }
@@ -657,23 +833,25 @@ export class AvroQueryClient {
657
833
  maxRetries: 0,
658
834
  });
659
835
  }
836
+ /**
837
+ * The caller's chats. The backend only exposes `GET /chat` (every chat
838
+ * the user belongs to, unpaged), so the id/query/paging filters are
839
+ * applied client-side.
840
+ */
660
841
  fetchChats(body = {}, cancelToken, headers = {}) {
661
- if (!this.companyId || this.companyId.trim() === '') {
662
- throw new StandardError(400, 'Company ID is required');
663
- }
664
- return this._fetch('POST', `/company/${this.companyId}/chats`, JSON.stringify(body), cancelToken, {
665
- ...headers,
666
- 'Content-Type': 'application/json',
667
- })
842
+ return this._fetch('GET', '/chat', null, cancelToken, headers, true)
668
843
  .then((response) => {
669
844
  if (!response || !Array.isArray(response)) {
670
845
  throw new StandardError(400, 'Invalid chats response');
671
846
  }
672
- return response;
847
+ const scoped = this.companyId
848
+ ? response.filter((c) => !c?.company_id || c.company_id === this.companyId)
849
+ : response;
850
+ return filterLocally(scoped, body, (c) => [c?.name]);
673
851
  })
674
852
  .catch((err) => {
675
853
  console.error('Failed to fetch chats:', err);
676
- throw new StandardError(500, 'Failed to fetch chats');
854
+ throw fetchError(err, 'Failed to fetch chats');
677
855
  });
678
856
  }
679
857
  fetchMessages(chatId, body = {}, cancelToken, headers = {}) {
@@ -683,7 +861,7 @@ export class AvroQueryClient {
683
861
  return this._fetch('POST', `/chat/${chatId}/messages`, JSON.stringify(body), cancelToken, {
684
862
  ...headers,
685
863
  'Content-Type': 'application/json',
686
- })
864
+ }, true)
687
865
  .then((response) => {
688
866
  if (!response || !Array.isArray(response)) {
689
867
  throw new StandardError(400, 'Invalid messages response');
@@ -692,17 +870,17 @@ export class AvroQueryClient {
692
870
  })
693
871
  .catch((err) => {
694
872
  console.error('Failed to fetch messages:', err);
695
- throw new StandardError(500, 'Failed to fetch messages');
873
+ throw fetchError(err, 'Failed to fetch messages');
696
874
  });
697
875
  }
698
876
  async fetchPrepayments(body = {}, cancelToken, headers = {}) {
699
877
  if (!this.companyId || this.companyId.trim() === '') {
700
878
  throw new StandardError(400, 'Company ID is required');
701
879
  }
702
- return this._fetch('POST', `/company/${this.companyId}/prepayments`, JSON.stringify(body), cancelToken, {
880
+ return this._fetch('POST', `/company/${this.companyId}/prepayments`, JSON.stringify(withWireParent(body, 'taskId', 'task_id')), cancelToken, {
703
881
  ...headers,
704
882
  'Content-Type': 'application/json',
705
- })
883
+ }, true)
706
884
  .then((response) => {
707
885
  if (!response || !Array.isArray(response)) {
708
886
  throw new StandardError(400, 'Invalid prepayments response');
@@ -711,7 +889,7 @@ export class AvroQueryClient {
711
889
  })
712
890
  .catch((err) => {
713
891
  console.error('Failed to fetch prepayments:', err);
714
- throw new StandardError(500, 'Failed to fetch prepayments');
892
+ throw fetchError(err, 'Failed to fetch prepayments');
715
893
  });
716
894
  }
717
895
  async fetchWaivers(body = {}, cancelToken, headers = {}) {
@@ -721,7 +899,7 @@ export class AvroQueryClient {
721
899
  return this._fetch('POST', `/company/${this.companyId}/waivers`, JSON.stringify(body), cancelToken, {
722
900
  ...headers,
723
901
  'Content-Type': 'application/json',
724
- })
902
+ }, true)
725
903
  .then((response) => {
726
904
  if (!response || !Array.isArray(response)) {
727
905
  throw new StandardError(400, 'Invalid waivers response');
@@ -730,7 +908,7 @@ export class AvroQueryClient {
730
908
  })
731
909
  .catch((err) => {
732
910
  console.error('Failed to fetch waivers:', err);
733
- throw new StandardError(500, 'Failed to fetch waivers');
911
+ throw fetchError(err, 'Failed to fetch waivers');
734
912
  });
735
913
  }
736
914
  async fetchEvents(body = {}, cancelToken, headers = {}) {
@@ -740,7 +918,7 @@ export class AvroQueryClient {
740
918
  return this._fetch('POST', `/company/${this.companyId}/events`, JSON.stringify(body), cancelToken, {
741
919
  ...headers,
742
920
  'Content-Type': 'application/json',
743
- })
921
+ }, true)
744
922
  .then((response) => {
745
923
  if (!response || !Array.isArray(response)) {
746
924
  throw new StandardError(400, 'Invalid events response');
@@ -749,17 +927,17 @@ export class AvroQueryClient {
749
927
  })
750
928
  .catch((err) => {
751
929
  console.error('Failed to fetch events:', err);
752
- throw new StandardError(500, 'Failed to fetch events');
930
+ throw fetchError(err, 'Failed to fetch events');
753
931
  });
754
932
  }
755
933
  fetchMonths(body = {}, cancelToken, headers = {}) {
756
934
  if (!this.companyId || this.companyId.trim() === '') {
757
935
  throw new StandardError(400, 'Company ID is required');
758
936
  }
759
- return this._fetch('POST', `/company/${this.companyId}/months`, JSON.stringify(body), cancelToken, {
937
+ return this._fetch('POST', `/company/${this.companyId}/months`, JSON.stringify(withWireParent(body, 'jobId', 'job_id')), cancelToken, {
760
938
  ...headers,
761
939
  'Content-Type': 'application/json',
762
- })
940
+ }, true)
763
941
  .then((response) => {
764
942
  if (!response || !Array.isArray(response)) {
765
943
  throw new StandardError(400, 'Invalid months response');
@@ -768,7 +946,7 @@ export class AvroQueryClient {
768
946
  })
769
947
  .catch((err) => {
770
948
  console.error('Failed to fetch months:', err);
771
- throw new StandardError(500, 'Failed to fetch months');
949
+ throw fetchError(err, 'Failed to fetch months');
772
950
  });
773
951
  }
774
952
  fetchBills(body = {}, cancelToken, headers = {}) {
@@ -778,7 +956,7 @@ export class AvroQueryClient {
778
956
  return this._fetch('POST', `/company/${this.companyId}/bills`, JSON.stringify(body), cancelToken, {
779
957
  ...headers,
780
958
  'Content-Type': 'application/json',
781
- })
959
+ }, true)
782
960
  .then((response) => {
783
961
  if (!response || !Array.isArray(response)) {
784
962
  throw new StandardError(400, 'Invalid bills response');
@@ -787,7 +965,7 @@ export class AvroQueryClient {
787
965
  })
788
966
  .catch((err) => {
789
967
  console.error('Failed to fetch bills:', err);
790
- throw new StandardError(500, 'Failed to fetch bills');
968
+ throw fetchError(err, 'Failed to fetch bills');
791
969
  });
792
970
  }
793
971
  fetchPayouts(body = {}, cancelToken, headers = {}) {
@@ -797,7 +975,7 @@ export class AvroQueryClient {
797
975
  return this._fetch('POST', `/company/${this.companyId}/payouts`, JSON.stringify(body), cancelToken, {
798
976
  ...headers,
799
977
  'Content-Type': 'application/json',
800
- })
978
+ }, true)
801
979
  .then((response) => {
802
980
  if (!response || !Array.isArray(response)) {
803
981
  throw new StandardError(400, 'Invalid payouts response');
@@ -806,7 +984,7 @@ export class AvroQueryClient {
806
984
  })
807
985
  .catch((err) => {
808
986
  console.error('Failed to fetch payouts:', err);
809
- throw new StandardError(500, 'Failed to fetch payouts');
987
+ throw fetchError(err, 'Failed to fetch payouts');
810
988
  });
811
989
  }
812
990
  fetchRoutes(body = {}, cancelToken, headers = {}) {
@@ -816,7 +994,7 @@ export class AvroQueryClient {
816
994
  return this._fetch('POST', `/company/${this.companyId}/routes`, JSON.stringify(body), cancelToken, {
817
995
  ...headers,
818
996
  'Content-Type': 'application/json',
819
- })
997
+ }, true)
820
998
  .then((response) => {
821
999
  if (!response || !Array.isArray(response)) {
822
1000
  throw new StandardError(400, 'Invalid routes response');
@@ -825,7 +1003,7 @@ export class AvroQueryClient {
825
1003
  })
826
1004
  .catch((err) => {
827
1005
  console.error('Failed to fetch routes:', err);
828
- throw new StandardError(500, 'Failed to fetch routes');
1006
+ throw fetchError(err, 'Failed to fetch routes');
829
1007
  });
830
1008
  }
831
1009
  fetchTeams(body = {}, cancelToken, headers = {}) {
@@ -835,7 +1013,7 @@ export class AvroQueryClient {
835
1013
  return this._fetch('POST', `/company/${this.companyId}/teams`, JSON.stringify(body), cancelToken, {
836
1014
  ...headers,
837
1015
  'Content-Type': 'application/json',
838
- })
1016
+ }, true)
839
1017
  .then((response) => {
840
1018
  if (!response || !Array.isArray(response)) {
841
1019
  throw new StandardError(400, 'Invalid teams response');
@@ -844,45 +1022,51 @@ export class AvroQueryClient {
844
1022
  })
845
1023
  .catch((err) => {
846
1024
  console.error('Failed to fetch teams:', err);
847
- throw new StandardError(500, 'Failed to fetch teams');
1025
+ throw fetchError(err, 'Failed to fetch teams');
848
1026
  });
849
1027
  }
1028
+ /**
1029
+ * Company labels. There is no list endpoint for them: they are embedded
1030
+ * in `GET /company/<id>`, so the id/query/paging filters are applied
1031
+ * client-side.
1032
+ */
850
1033
  fetchLabels(body = {}, cancelToken, headers = {}) {
851
1034
  if (!this.companyId || this.companyId.trim() === '') {
852
1035
  throw new StandardError(400, 'Company ID is required');
853
1036
  }
854
- return this._fetch('POST', `/company/${this.companyId}/labels`, JSON.stringify(body), cancelToken, {
855
- ...headers,
856
- 'Content-Type': 'application/json',
857
- })
858
- .then((response) => {
859
- if (!response || !Array.isArray(response)) {
1037
+ return this._fetch('GET', `/company/${this.companyId}`, null, cancelToken, headers, true)
1038
+ .then((company) => {
1039
+ const items = company?.labels;
1040
+ if (!Array.isArray(items)) {
860
1041
  throw new StandardError(400, 'Invalid labels response');
861
1042
  }
862
- return response;
1043
+ return filterLocally(items, body, (x) => [x?.name]);
863
1044
  })
864
1045
  .catch((err) => {
865
1046
  console.error('Failed to fetch labels:', err);
866
- throw new StandardError(500, 'Failed to fetch labels');
1047
+ throw fetchError(err, 'Failed to fetch labels');
867
1048
  });
868
1049
  }
1050
+ /**
1051
+ * Company groups. There is no list endpoint for them: they are embedded
1052
+ * in `GET /company/<id>`, so the id/query/paging filters are applied
1053
+ * client-side.
1054
+ */
869
1055
  fetchGroups(body = {}, cancelToken, headers = {}) {
870
1056
  if (!this.companyId || this.companyId.trim() === '') {
871
1057
  throw new StandardError(400, 'Company ID is required');
872
1058
  }
873
- return this._fetch('POST', `/company/${this.companyId}/groups`, JSON.stringify(body), cancelToken, {
874
- ...headers,
875
- 'Content-Type': 'application/json',
876
- })
877
- .then((response) => {
878
- if (!response || !Array.isArray(response)) {
1059
+ return this._fetch('GET', `/company/${this.companyId}`, null, cancelToken, headers, true)
1060
+ .then((company) => {
1061
+ const items = company?.groups;
1062
+ if (!Array.isArray(items)) {
879
1063
  throw new StandardError(400, 'Invalid groups response');
880
1064
  }
881
- return response;
1065
+ return filterLocally(items, body, (x) => [x?.name]);
882
1066
  })
883
1067
  .catch((err) => {
884
1068
  console.error('Failed to fetch groups:', err);
885
- throw new StandardError(500, 'Failed to fetch groups');
1069
+ throw fetchError(err, 'Failed to fetch groups');
886
1070
  });
887
1071
  }
888
1072
  fetchSkills(body = {}, cancelToken, headers = {}) {
@@ -892,7 +1076,7 @@ export class AvroQueryClient {
892
1076
  return this._fetch('POST', `/company/${this.companyId}/skills`, JSON.stringify(body), cancelToken, {
893
1077
  ...headers,
894
1078
  'Content-Type': 'application/json',
895
- })
1079
+ }, true)
896
1080
  .then((response) => {
897
1081
  if (!response || !Array.isArray(response)) {
898
1082
  throw new StandardError(400, 'Invalid skills response');
@@ -901,7 +1085,7 @@ export class AvroQueryClient {
901
1085
  })
902
1086
  .catch((err) => {
903
1087
  console.error('Failed to fetch skills:', err);
904
- throw new StandardError(500, 'Failed to fetch skills');
1088
+ throw fetchError(err, 'Failed to fetch skills');
905
1089
  });
906
1090
  }
907
1091
  fetchSessions(body = {}, cancelToken, headers = {}) {
@@ -912,7 +1096,7 @@ export class AvroQueryClient {
912
1096
  return this._fetch('POST', `/company/${this.companyId}/sessions?amount=${amount}`, JSON.stringify({ ...body, amt: amount }), cancelToken, {
913
1097
  ...headers,
914
1098
  'Content-Type': 'application/json',
915
- })
1099
+ }, true)
916
1100
  .then((response) => {
917
1101
  if (!response || !Array.isArray(response)) {
918
1102
  throw new StandardError(400, 'Invalid sessions response');
@@ -921,7 +1105,7 @@ export class AvroQueryClient {
921
1105
  })
922
1106
  .catch((err) => {
923
1107
  console.error('Failed to fetch sessions:', err);
924
- throw new StandardError(500, 'Failed to fetch sessions');
1108
+ throw fetchError(err, 'Failed to fetch sessions');
925
1109
  });
926
1110
  }
927
1111
  _initEmailListeners() {
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Small cache helpers shared by the hooks: namespace snapshots for
3
+ * optimistic-update rollback, detail seeding from list fetches, and
4
+ * optimistic-row cleanup.
5
+ */
6
+ import { QueryClient, QueryKey } from '@tanstack/react-query';
7
+ export type NsSnapshot = Array<[QueryKey, unknown]>;
8
+ /**
9
+ * Snapshot every cached query under `ns` (lists and details). A plain
10
+ * `getQueryData([ns])` only reads the exact key `[ns]`, which no hook
11
+ * uses, so rollbacks built on it were no-ops.
12
+ */
13
+ export declare function snapshotNs(qc: QueryClient, ns: string): NsSnapshot;
14
+ /** Restore a snapshot taken with `snapshotNs`. */
15
+ export declare function restoreNs(qc: QueryClient, snapshot: NsSnapshot | undefined): void;
16
+ /**
17
+ * Seed `[ns, id]` detail entries from a fetched list. Call from inside a
18
+ * `queryFn` (never during render).
19
+ */
20
+ export declare function seedDetails<T extends {
21
+ id?: string;
22
+ }>(qc: QueryClient | null, ns: string, items: T[]): T[];
23
+ /** Remove an optimistic row (by its temporary id) from every list in `ns`. */
24
+ export declare function removeOptimisticRow(qc: QueryClient, ns: string, tempId: string): void;