@go-avro/avro-js 0.1.15 → 1.6.1-rc1

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 (51) hide show
  1. package/dist/auth/AuthManager.d.ts +32 -0
  2. package/dist/auth/AuthManager.js +138 -43
  3. package/dist/client/QueryClient.d.ts +68 -2
  4. package/dist/client/QueryClient.js +310 -96
  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 +56 -47
  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 +21 -24
  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 +21 -31
  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 +21 -1
  32. package/dist/client/realtime.js +183 -51
  33. package/dist/types/api/Bill.js +2 -1
  34. package/dist/types/api/Company.d.ts +2 -0
  35. package/dist/types/api/Email.d.ts +3 -9
  36. package/dist/types/api/EmailNotification.d.ts +1 -1
  37. package/dist/types/api/Job.js +8 -4
  38. package/dist/types/api/LineItem.d.ts +4 -0
  39. package/dist/types/api/LineItem.js +10 -2
  40. package/dist/types/api/Prepayment.js +2 -1
  41. package/dist/types/api/Route.js +2 -1
  42. package/dist/types/api/RouteJob.js +2 -1
  43. package/dist/types/api/Session.js +2 -1
  44. package/dist/types/api/Task.d.ts +27 -2
  45. package/dist/types/api/Task.js +44 -8
  46. package/dist/types/api/_Event.js +2 -1
  47. package/dist/types/api/assignData.d.ts +9 -0
  48. package/dist/types/api/assignData.js +17 -0
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/package.json +7 -2
@@ -1,20 +1,52 @@
1
1
  import { AuthState, Tokens } from '../types/auth.js';
2
2
  import { Cache, CacheData } from '../types/cache.js';
3
+ /**
4
+ * True when a refresh error means the session is over (no/invalid refresh
5
+ * token), as opposed to the server being unreachable or failing (0 / 5xx).
6
+ */
7
+ export declare function isDefinitiveAuthFailure(err: unknown): boolean;
3
8
  export declare class AuthManager {
4
9
  private storages;
5
10
  private baseUrl;
6
11
  private tokenRefreshedCallbacks;
7
12
  private tokenRefreshFailedCallbacks;
13
+ private refreshing;
14
+ /** Bumped on every login and logout; see refreshTokens. */
15
+ private generation;
8
16
  constructor({ baseUrl, storage }: {
9
17
  baseUrl: string;
10
18
  storage: Cache | Cache[];
11
19
  });
20
+ /**
21
+ * Validate the stored session against the server.
22
+ *
23
+ * - AUTHENTICATED: the server accepted our (possibly refreshed) token.
24
+ * - UNAUTHENTICATED: no stored tokens, or the server definitively
25
+ * rejected both the access and the refresh token.
26
+ * - UNKNOWN: the server couldn't be asked (offline, timeout, 5xx). The
27
+ * stored tokens are kept; the caller should re-check later.
28
+ */
12
29
  isAuthenticated(): Promise<AuthState>;
30
+ /** POST /validate: 2xx → AUTHENTICATED, 401/422 → UNAUTHENTICATED, else UNKNOWN. */
31
+ private validate;
32
+ /**
33
+ * Exchange a stored refresh token for new tokens. Throws a
34
+ * StandardError(410) when no storage holds a usable refresh token (a
35
+ * definitive failure), or the transient error (status 0 / 5xx) when
36
+ * the server couldn't be reached.
37
+ */
13
38
  fetchNewTokens(): Promise<Tokens>;
14
39
  accessToken(): Promise<string | undefined>;
15
40
  onTokenRefreshed(callback: (accessToken: string) => void): void;
16
41
  onTokenRefreshFailed(callback: () => void): void;
42
+ /**
43
+ * Refresh tokens, deduplicated: concurrent callers (parallel 401s, the
44
+ * socket, a re-check) share one /refresh round-trip. A definitive
45
+ * failure notifies `onTokenRefreshFailed` listeners (→ logout).
46
+ */
17
47
  refreshTokens(): Promise<Tokens>;
48
+ /** Start a new session: in-flight refreshes of the old one are void. */
49
+ private newSession;
18
50
  setTokens(tokens: Tokens): Promise<void>;
19
51
  setCache(data: Partial<CacheData> | Object): Promise<void>;
20
52
  getCache(key?: keyof CacheData | string): Promise<CacheData[keyof CacheData] | Object | string | null>;
@@ -1,9 +1,20 @@
1
1
  import { AuthState } from '../types/auth.js';
2
2
  import { StandardError } from '../types/error.js';
3
+ /**
4
+ * True when a refresh error means the session is over (no/invalid refresh
5
+ * token), as opposed to the server being unreachable or failing (0 / 5xx).
6
+ */
7
+ export function isDefinitiveAuthFailure(err) {
8
+ const status = err?.status;
9
+ return status === 401 || status === 410 || status === 422;
10
+ }
3
11
  export class AuthManager {
4
12
  constructor({ baseUrl, storage }) {
5
13
  this.tokenRefreshedCallbacks = [];
6
14
  this.tokenRefreshFailedCallbacks = [];
15
+ this.refreshing = null;
16
+ /** Bumped on every login and logout; see refreshTokens. */
17
+ this.generation = 0;
7
18
  this.storages = Array.isArray(storage) ? storage : [storage];
8
19
  if (this.storages.length === 0) {
9
20
  throw new Error('At least one token storage must be provided');
@@ -18,49 +29,82 @@ export class AuthManager {
18
29
  });
19
30
  this.baseUrl = baseUrl;
20
31
  }
32
+ /**
33
+ * Validate the stored session against the server.
34
+ *
35
+ * - AUTHENTICATED: the server accepted our (possibly refreshed) token.
36
+ * - UNAUTHENTICATED: no stored tokens, or the server definitively
37
+ * rejected both the access and the refresh token.
38
+ * - UNKNOWN: the server couldn't be asked (offline, timeout, 5xx). The
39
+ * stored tokens are kept; the caller should re-check later.
40
+ */
21
41
  async isAuthenticated() {
22
42
  if (!this.storages.length) {
23
43
  throw new Error('No token storages initialized');
24
44
  }
45
+ let inconclusive = false;
25
46
  for (const storage of this.storages) {
26
47
  const cache = await storage.get();
27
- if (cache && typeof cache !== 'string' && cache.access_token) {
28
- try {
29
- const response = await fetch(`${this.baseUrl}/validate`, {
30
- method: 'POST',
31
- headers: {
32
- 'Content-Type': 'application/json',
33
- Authorization: `Bearer ${cache.access_token}`,
34
- },
35
- });
36
- if (response.ok) {
37
- return AuthState.AUTHENTICATED;
38
- }
39
- else {
40
- // Attempt token refresh if validation fails
41
- const newTokens = await this.refreshTokens();
42
- if (newTokens && newTokens.access_token) {
43
- const retryResponse = await fetch(`${this.baseUrl}/validate`, {
44
- method: 'POST',
45
- headers: {
46
- 'Content-Type': 'application/json',
47
- Authorization: `Bearer ${newTokens.access_token}`,
48
- },
49
- });
50
- return retryResponse.ok
51
- ? AuthState.AUTHENTICATED
52
- : AuthState.UNAUTHENTICATED;
53
- }
54
- }
55
- }
56
- catch (error) {
57
- console.error('Error validating access token:', error);
58
- }
48
+ if (!cache || typeof cache === 'string' || !cache.access_token)
49
+ continue;
50
+ const verdict = await this.validate(cache.access_token);
51
+ if (verdict === AuthState.AUTHENTICATED)
52
+ return verdict;
53
+ if (verdict === AuthState.UNKNOWN) {
54
+ inconclusive = true;
55
+ continue;
59
56
  }
57
+ // Access token rejected: try the refresh token.
58
+ let newTokens;
59
+ try {
60
+ newTokens = await this.refreshTokens();
61
+ }
62
+ catch (err) {
63
+ if (isDefinitiveAuthFailure(err))
64
+ return AuthState.UNAUTHENTICATED;
65
+ inconclusive = true;
66
+ continue;
67
+ }
68
+ if (!newTokens?.access_token)
69
+ return AuthState.UNAUTHENTICATED;
70
+ const retry = await this.validate(newTokens.access_token);
71
+ // A fresh token we can't verify right now is still our best bet.
72
+ return retry === AuthState.UNKNOWN ? AuthState.AUTHENTICATED : retry;
60
73
  }
74
+ if (inconclusive)
75
+ return AuthState.UNKNOWN;
61
76
  return AuthState.UNAUTHENTICATED;
62
77
  }
78
+ /** POST /validate: 2xx → AUTHENTICATED, 401/422 → UNAUTHENTICATED, else UNKNOWN. */
79
+ async validate(accessToken) {
80
+ try {
81
+ const response = await fetch(`${this.baseUrl}/validate`, {
82
+ method: 'POST',
83
+ headers: {
84
+ 'Content-Type': 'application/json',
85
+ Authorization: `Bearer ${accessToken}`,
86
+ },
87
+ });
88
+ if (response.ok)
89
+ return AuthState.AUTHENTICATED;
90
+ if (response.status === 401 || response.status === 422) {
91
+ return AuthState.UNAUTHENTICATED;
92
+ }
93
+ return AuthState.UNKNOWN;
94
+ }
95
+ catch (error) {
96
+ console.error('Error validating access token:', error);
97
+ return AuthState.UNKNOWN;
98
+ }
99
+ }
100
+ /**
101
+ * Exchange a stored refresh token for new tokens. Throws a
102
+ * StandardError(410) when no storage holds a usable refresh token (a
103
+ * definitive failure), or the transient error (status 0 / 5xx) when
104
+ * the server couldn't be reached.
105
+ */
63
106
  async fetchNewTokens() {
107
+ let transient = null;
64
108
  for (const storage of this.storages) {
65
109
  const cache = await storage.get();
66
110
  if (!cache || typeof cache === 'string' || !cache.refresh_token)
@@ -79,13 +123,19 @@ export class AuthManager {
79
123
  return newTokens;
80
124
  }
81
125
  if (response.status === 401 || response.status === 422) {
82
- storage.clear();
126
+ await storage.clear();
127
+ }
128
+ else {
129
+ transient = new StandardError(response.status, `Token refresh failed (${response.status})`);
83
130
  }
84
131
  }
85
- catch {
86
- console.error('Error refreshing tokens from storage:', storage);
132
+ catch (err) {
133
+ console.error('Error refreshing tokens from storage:', err);
134
+ transient = new StandardError(0, 'Token refresh failed: network error');
87
135
  }
88
136
  }
137
+ if (transient)
138
+ throw transient;
89
139
  throw new StandardError(410, 'Failed to refresh tokens from all storages');
90
140
  }
91
141
  async accessToken() {
@@ -106,16 +156,60 @@ export class AuthManager {
106
156
  onTokenRefreshFailed(callback) {
107
157
  this.tokenRefreshFailedCallbacks.push(callback);
108
158
  }
109
- async refreshTokens() {
110
- const newToken = await this.fetchNewTokens();
111
- await Promise.all(this.storages.map((s) => s.set(newToken)));
112
- this.tokenRefreshedCallbacks.forEach((cb) => {
113
- if (newToken?.access_token)
114
- cb(newToken.access_token);
115
- });
116
- return newToken;
159
+ /**
160
+ * Refresh tokens, deduplicated: concurrent callers (parallel 401s, the
161
+ * socket, a re-check) share one /refresh round-trip. A definitive
162
+ * failure notifies `onTokenRefreshFailed` listeners (→ logout).
163
+ */
164
+ refreshTokens() {
165
+ if (this.refreshing)
166
+ return this.refreshing;
167
+ const generation = this.generation;
168
+ this.refreshing = (async () => {
169
+ try {
170
+ const newToken = await this.fetchNewTokens();
171
+ // A logout or a new login while this was in flight: these
172
+ // tokens belong to the old session, so never store them.
173
+ // Not an auth status: that would log out the new session.
174
+ if (generation !== this.generation) {
175
+ throw new StandardError(0, 'Session changed during token refresh');
176
+ }
177
+ await Promise.all(this.storages.map((s) => s.set(newToken)));
178
+ this.tokenRefreshedCallbacks.forEach((cb) => {
179
+ if (newToken?.access_token)
180
+ cb(newToken.access_token);
181
+ });
182
+ return newToken;
183
+ }
184
+ catch (err) {
185
+ // Only the current session's failure means "log out".
186
+ if (isDefinitiveAuthFailure(err) && generation === this.generation) {
187
+ this.tokenRefreshFailedCallbacks.forEach((cb) => {
188
+ try {
189
+ cb();
190
+ }
191
+ catch (cbErr) {
192
+ console.error('tokenRefreshFailed callback threw:', cbErr);
193
+ }
194
+ });
195
+ }
196
+ throw err;
197
+ }
198
+ finally {
199
+ // A newer session may already have its own refresh running.
200
+ if (generation === this.generation)
201
+ this.refreshing = null;
202
+ }
203
+ })();
204
+ return this.refreshing;
205
+ }
206
+ /** Start a new session: in-flight refreshes of the old one are void. */
207
+ newSession() {
208
+ this.generation++;
209
+ this.refreshing = null;
117
210
  }
118
211
  async setTokens(tokens) {
212
+ this.newSession();
119
213
  await Promise.all(this.storages.map((s) => s.set(tokens)));
120
214
  }
121
215
  async setCache(data) {
@@ -133,6 +227,7 @@ export class AuthManager {
133
227
  return null;
134
228
  }
135
229
  async clearCache() {
230
+ this.newSession();
136
231
  await Promise.all(this.storages.map((s) => s.clear()));
137
232
  }
138
233
  async getCompanyId() {
@@ -290,10 +290,12 @@ declare module './QueryClient.js' {
290
290
  pay_in_cash?: boolean;
291
291
  }>>;
292
292
  useCreateMessage(chatId: string): ReturnType<typeof useMutation<{
293
+ msg?: string;
293
294
  id: string;
294
295
  }, StandardError, {
295
296
  content: string;
296
297
  time_sent?: number;
298
+ id?: string;
297
299
  }>>;
298
300
  useCreateProposal(): ReturnType<typeof useMutation<{
299
301
  id: string;
@@ -721,10 +723,37 @@ export declare class AvroQueryClient {
721
723
  private _persister;
722
724
  private _presencePending;
723
725
  private _presenceTimer;
726
+ /** Chat rooms to (re)join on every connect; socket rooms don't survive reconnects. */
727
+ private _joinedChats;
724
728
  private _restored;
725
729
  private _emailTracking;
726
730
  private _emailListenersInit;
731
+ private _authCheck;
732
+ private _authRecheckTimer;
733
+ private _authRecheckDelay;
734
+ private _socketAuthRetried;
735
+ private _socketRetryTimer;
727
736
  constructor(config: AvroQueryClientConfig);
737
+ /**
738
+ * Re-validate the stored session (deduplicated). Call it when the app
739
+ * returns to the foreground or regains connectivity; the SDK also calls
740
+ * it on a backoff timer and after the next successful request while the
741
+ * state is UNKNOWN (e.g. after an offline cold start). A network error
742
+ * or 5xx never downgrades the state to UNAUTHENTICATED: only a
743
+ * definitive auth failure does.
744
+ */
745
+ recheckAuth(): Promise<AuthState>;
746
+ private scheduleAuthRecheck;
747
+ /** Called by the transports after any 2xx: the server is reachable again. */
748
+ _noteRequestSucceeded(): void;
749
+ /**
750
+ * The server refuses the socket handshake when the access token has
751
+ * expired; socket.io then stops reconnecting (`active` is false).
752
+ * Refresh the token once (shared with any in-flight refresh) and
753
+ * reconnect with it. A definitive refresh failure logs out via
754
+ * onTokenRefreshFailed; a transient one retries after a delay.
755
+ */
756
+ private handleSocketConnectError;
728
757
  /** Handshake payload: the token plus, when known, this install's identity. */
729
758
  private socketAuth;
730
759
  /** The install identity sent with sockets and location pings, if any. */
@@ -734,6 +763,13 @@ export declare class AvroQueryClient {
734
763
  /** Tell the server which install this live socket belongs to. */
735
764
  private registerDevice;
736
765
  emit(eventName: string, data: unknown): void;
766
+ /**
767
+ * Join a chat's socket room so `new_message` and presence events for it
768
+ * arrive. The room is rejoined after reconnects until `leaveChat`.
769
+ */
770
+ joinChat(chatId: string): void;
771
+ /** Leave a chat's socket room joined with `joinChat`. */
772
+ leaveChat(chatId: string): void;
737
773
  on<T>(eventName: string, callback: (data: T) => void): void;
738
774
  off(eventName: string, callback?: Function): void;
739
775
  /** Wire the socket to the cache (called once from the provider). */
@@ -757,13 +793,19 @@ export declare class AvroQueryClient {
757
793
  * Fire-and-forget: never throws, so it is safe inside error handlers.
758
794
  */
759
795
  reportClientError(report: ClientErrorReport): Promise<void>;
760
- post<T>({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, }: {
796
+ post<T>({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, }: {
761
797
  path: string;
762
798
  data?: any;
763
799
  cancelToken?: CancelToken;
764
800
  headers?: Record<string, string>;
765
801
  progressUpdateCallback?: (loaded: number, total: number) => void;
766
802
  maxRetries?: number;
803
+ /**
804
+ * Mark a read-only POST (list/search endpoints) as safe to retry on
805
+ * network errors / 5xx. Defaults to false: a POST that may have
806
+ * reached the server is never replayed.
807
+ */
808
+ idempotent?: boolean;
767
809
  }): Promise<T>;
768
810
  put<T>({ path, data, cancelToken, headers, progressUpdateCallback, }: {
769
811
  path: string;
@@ -778,6 +820,11 @@ export declare class AvroQueryClient {
778
820
  headers?: Record<string, string>;
779
821
  progressUpdateCallback?: (loaded: number, total: number) => void;
780
822
  }): Promise<T>;
823
+ /**
824
+ * Persist freshly issued tokens, then flip to AUTHENTICATED and connect
825
+ * the socket. Tokens are stored first so that anything reacting to the
826
+ * auth-state change (queries enabled on AUTHENTICATED) finds them.
827
+ */
781
828
  loginSuccess(tokens: Tokens): Promise<void>;
782
829
  useLogin(): ReturnType<typeof useMutation<LoginResponse, StandardError, {
783
830
  username: string;
@@ -860,6 +907,11 @@ export declare class AvroQueryClient {
860
907
  focus_point_latitude?: number;
861
908
  focus_point_longitude?: number;
862
909
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<AddressFeatureCollection>;
910
+ /**
911
+ * The caller's chats. The backend only exposes `GET /chat` (every chat
912
+ * the user belongs to, unpaged), so the id/query/paging filters are
913
+ * applied client-side.
914
+ */
863
915
  fetchChats(body?: {
864
916
  amt?: number;
865
917
  known_ids?: string[];
@@ -883,6 +935,8 @@ export declare class AvroQueryClient {
883
935
  unbilled?: boolean;
884
936
  billed?: boolean;
885
937
  paid?: boolean;
938
+ task_id?: string | null;
939
+ /** @deprecated ignored by the backend; use `task_id`. */
886
940
  taskId?: string | null;
887
941
  sort_by?: 'date' | 'amount' | 'name';
888
942
  direction?: 'asc' | 'desc';
@@ -917,6 +971,8 @@ export declare class AvroQueryClient {
917
971
  unbilled?: boolean;
918
972
  billed?: boolean;
919
973
  paid?: boolean;
974
+ job_id?: string | null;
975
+ /** @deprecated ignored by the backend; use `job_id`. */
920
976
  jobId?: string | null;
921
977
  sort_by?: 'date' | 'amount' | 'name';
922
978
  direction?: 'asc' | 'desc';
@@ -966,6 +1022,11 @@ export declare class AvroQueryClient {
966
1022
  query?: string;
967
1023
  offset?: number;
968
1024
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1025
+ /**
1026
+ * Company labels. There is no list endpoint for them: they are embedded
1027
+ * in `GET /company/<id>`, so the id/query/paging filters are applied
1028
+ * client-side.
1029
+ */
969
1030
  fetchLabels(body?: {
970
1031
  amt?: number;
971
1032
  known_ids?: string[];
@@ -973,6 +1034,11 @@ export declare class AvroQueryClient {
973
1034
  query?: string;
974
1035
  offset?: number;
975
1036
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1037
+ /**
1038
+ * Company groups. There is no list endpoint for them: they are embedded
1039
+ * in `GET /company/<id>`, so the id/query/paging filters are applied
1040
+ * client-side.
1041
+ */
976
1042
  fetchGroups(body?: {
977
1043
  amt?: number;
978
1044
  known_ids?: string[];
@@ -995,7 +1061,7 @@ export declare class AvroQueryClient {
995
1061
  unknown_ids?: string[];
996
1062
  active?: boolean;
997
1063
  user_id?: string;
998
- }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1064
+ }, cancelToken?: CancelToken, headers?: Record<string, string>, companyId?: string | undefined): Promise<any>;
999
1065
  private _initEmailListeners;
1000
1066
  trackEmail(options?: TrackEmailOptions): string;
1001
1067
  sendEmail(emailId: string, formData: FormData, progressUpdateCallback?: (loaded: number, total: number) => void): Promise<void>;