@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,19 +1,47 @@
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;
8
14
  constructor({ baseUrl, storage }: {
9
15
  baseUrl: string;
10
16
  storage: Cache | Cache[];
11
17
  });
18
+ /**
19
+ * Validate the stored session against the server.
20
+ *
21
+ * - AUTHENTICATED: the server accepted our (possibly refreshed) token.
22
+ * - UNAUTHENTICATED: no stored tokens, or the server definitively
23
+ * rejected both the access and the refresh token.
24
+ * - UNKNOWN: the server couldn't be asked (offline, timeout, 5xx). The
25
+ * stored tokens are kept; the caller should re-check later.
26
+ */
12
27
  isAuthenticated(): Promise<AuthState>;
28
+ /** POST /validate: 2xx → AUTHENTICATED, 401/422 → UNAUTHENTICATED, else UNKNOWN. */
29
+ private validate;
30
+ /**
31
+ * Exchange a stored refresh token for new tokens. Throws a
32
+ * StandardError(410) when no storage holds a usable refresh token (a
33
+ * definitive failure), or the transient error (status 0 / 5xx) when
34
+ * the server couldn't be reached.
35
+ */
13
36
  fetchNewTokens(): Promise<Tokens>;
14
37
  accessToken(): Promise<string | undefined>;
15
38
  onTokenRefreshed(callback: (accessToken: string) => void): void;
16
39
  onTokenRefreshFailed(callback: () => void): void;
40
+ /**
41
+ * Refresh tokens, deduplicated: concurrent callers (parallel 401s, the
42
+ * socket, a re-check) share one /refresh round-trip. A definitive
43
+ * failure notifies `onTokenRefreshFailed` listeners (→ logout).
44
+ */
17
45
  refreshTokens(): Promise<Tokens>;
18
46
  setTokens(tokens: Tokens): Promise<void>;
19
47
  setCache(data: Partial<CacheData> | Object): Promise<void>;
@@ -1,9 +1,18 @@
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;
7
16
  this.storages = Array.isArray(storage) ? storage : [storage];
8
17
  if (this.storages.length === 0) {
9
18
  throw new Error('At least one token storage must be provided');
@@ -18,49 +27,82 @@ export class AuthManager {
18
27
  });
19
28
  this.baseUrl = baseUrl;
20
29
  }
30
+ /**
31
+ * Validate the stored session against the server.
32
+ *
33
+ * - AUTHENTICATED: the server accepted our (possibly refreshed) token.
34
+ * - UNAUTHENTICATED: no stored tokens, or the server definitively
35
+ * rejected both the access and the refresh token.
36
+ * - UNKNOWN: the server couldn't be asked (offline, timeout, 5xx). The
37
+ * stored tokens are kept; the caller should re-check later.
38
+ */
21
39
  async isAuthenticated() {
22
40
  if (!this.storages.length) {
23
41
  throw new Error('No token storages initialized');
24
42
  }
43
+ let inconclusive = false;
25
44
  for (const storage of this.storages) {
26
45
  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
- }
46
+ if (!cache || typeof cache === 'string' || !cache.access_token)
47
+ continue;
48
+ const verdict = await this.validate(cache.access_token);
49
+ if (verdict === AuthState.AUTHENTICATED)
50
+ return verdict;
51
+ if (verdict === AuthState.UNKNOWN) {
52
+ inconclusive = true;
53
+ continue;
59
54
  }
55
+ // Access token rejected: try the refresh token.
56
+ let newTokens;
57
+ try {
58
+ newTokens = await this.refreshTokens();
59
+ }
60
+ catch (err) {
61
+ if (isDefinitiveAuthFailure(err))
62
+ return AuthState.UNAUTHENTICATED;
63
+ inconclusive = true;
64
+ continue;
65
+ }
66
+ if (!newTokens?.access_token)
67
+ return AuthState.UNAUTHENTICATED;
68
+ const retry = await this.validate(newTokens.access_token);
69
+ // A fresh token we can't verify right now is still our best bet.
70
+ return retry === AuthState.UNKNOWN ? AuthState.AUTHENTICATED : retry;
60
71
  }
72
+ if (inconclusive)
73
+ return AuthState.UNKNOWN;
61
74
  return AuthState.UNAUTHENTICATED;
62
75
  }
76
+ /** POST /validate: 2xx → AUTHENTICATED, 401/422 → UNAUTHENTICATED, else UNKNOWN. */
77
+ async validate(accessToken) {
78
+ try {
79
+ const response = await fetch(`${this.baseUrl}/validate`, {
80
+ method: 'POST',
81
+ headers: {
82
+ 'Content-Type': 'application/json',
83
+ Authorization: `Bearer ${accessToken}`,
84
+ },
85
+ });
86
+ if (response.ok)
87
+ return AuthState.AUTHENTICATED;
88
+ if (response.status === 401 || response.status === 422) {
89
+ return AuthState.UNAUTHENTICATED;
90
+ }
91
+ return AuthState.UNKNOWN;
92
+ }
93
+ catch (error) {
94
+ console.error('Error validating access token:', error);
95
+ return AuthState.UNKNOWN;
96
+ }
97
+ }
98
+ /**
99
+ * Exchange a stored refresh token for new tokens. Throws a
100
+ * StandardError(410) when no storage holds a usable refresh token (a
101
+ * definitive failure), or the transient error (status 0 / 5xx) when
102
+ * the server couldn't be reached.
103
+ */
63
104
  async fetchNewTokens() {
105
+ let transient = null;
64
106
  for (const storage of this.storages) {
65
107
  const cache = await storage.get();
66
108
  if (!cache || typeof cache === 'string' || !cache.refresh_token)
@@ -79,13 +121,19 @@ export class AuthManager {
79
121
  return newTokens;
80
122
  }
81
123
  if (response.status === 401 || response.status === 422) {
82
- storage.clear();
124
+ await storage.clear();
125
+ }
126
+ else {
127
+ transient = new StandardError(response.status, `Token refresh failed (${response.status})`);
83
128
  }
84
129
  }
85
- catch {
86
- console.error('Error refreshing tokens from storage:', storage);
130
+ catch (err) {
131
+ console.error('Error refreshing tokens from storage:', err);
132
+ transient = new StandardError(0, 'Token refresh failed: network error');
87
133
  }
88
134
  }
135
+ if (transient)
136
+ throw transient;
89
137
  throw new StandardError(410, 'Failed to refresh tokens from all storages');
90
138
  }
91
139
  async accessToken() {
@@ -106,14 +154,42 @@ export class AuthManager {
106
154
  onTokenRefreshFailed(callback) {
107
155
  this.tokenRefreshFailedCallbacks.push(callback);
108
156
  }
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;
157
+ /**
158
+ * Refresh tokens, deduplicated: concurrent callers (parallel 401s, the
159
+ * socket, a re-check) share one /refresh round-trip. A definitive
160
+ * failure notifies `onTokenRefreshFailed` listeners (→ logout).
161
+ */
162
+ refreshTokens() {
163
+ if (this.refreshing)
164
+ return this.refreshing;
165
+ this.refreshing = (async () => {
166
+ try {
167
+ const newToken = await this.fetchNewTokens();
168
+ await Promise.all(this.storages.map((s) => s.set(newToken)));
169
+ this.tokenRefreshedCallbacks.forEach((cb) => {
170
+ if (newToken?.access_token)
171
+ cb(newToken.access_token);
172
+ });
173
+ return newToken;
174
+ }
175
+ catch (err) {
176
+ if (isDefinitiveAuthFailure(err)) {
177
+ this.tokenRefreshFailedCallbacks.forEach((cb) => {
178
+ try {
179
+ cb();
180
+ }
181
+ catch (cbErr) {
182
+ console.error('tokenRefreshFailed callback threw:', cbErr);
183
+ }
184
+ });
185
+ }
186
+ throw err;
187
+ }
188
+ finally {
189
+ this.refreshing = null;
190
+ }
191
+ })();
192
+ return this.refreshing;
117
193
  }
118
194
  async setTokens(tokens) {
119
195
  await Promise.all(this.storages.map((s) => s.set(tokens)));
@@ -724,7 +724,32 @@ export declare class AvroQueryClient {
724
724
  private _restored;
725
725
  private _emailTracking;
726
726
  private _emailListenersInit;
727
+ private _authCheck;
728
+ private _authRecheckTimer;
729
+ private _authRecheckDelay;
730
+ private _socketAuthRetried;
731
+ private _socketRetryTimer;
727
732
  constructor(config: AvroQueryClientConfig);
733
+ /**
734
+ * Re-validate the stored session (deduplicated). Call it when the app
735
+ * returns to the foreground or regains connectivity; the SDK also calls
736
+ * it on a backoff timer and after the next successful request while the
737
+ * state is UNKNOWN (e.g. after an offline cold start). A network error
738
+ * or 5xx never downgrades the state to UNAUTHENTICATED: only a
739
+ * definitive auth failure does.
740
+ */
741
+ recheckAuth(): Promise<AuthState>;
742
+ private scheduleAuthRecheck;
743
+ /** Called by the transports after any 2xx: the server is reachable again. */
744
+ _noteRequestSucceeded(): void;
745
+ /**
746
+ * The server refuses the socket handshake when the access token has
747
+ * expired; socket.io then stops reconnecting (`active` is false).
748
+ * Refresh the token once (shared with any in-flight refresh) and
749
+ * reconnect with it. A definitive refresh failure logs out via
750
+ * onTokenRefreshFailed; a transient one retries after a delay.
751
+ */
752
+ private handleSocketConnectError;
728
753
  /** Handshake payload: the token plus, when known, this install's identity. */
729
754
  private socketAuth;
730
755
  /** The install identity sent with sockets and location pings, if any. */
@@ -757,13 +782,19 @@ export declare class AvroQueryClient {
757
782
  * Fire-and-forget: never throws, so it is safe inside error handlers.
758
783
  */
759
784
  reportClientError(report: ClientErrorReport): Promise<void>;
760
- post<T>({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, }: {
785
+ post<T>({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, }: {
761
786
  path: string;
762
787
  data?: any;
763
788
  cancelToken?: CancelToken;
764
789
  headers?: Record<string, string>;
765
790
  progressUpdateCallback?: (loaded: number, total: number) => void;
766
791
  maxRetries?: number;
792
+ /**
793
+ * Mark a read-only POST (list/search endpoints) as safe to retry on
794
+ * network errors / 5xx. Defaults to false: a POST that may have
795
+ * reached the server is never replayed.
796
+ */
797
+ idempotent?: boolean;
767
798
  }): Promise<T>;
768
799
  put<T>({ path, data, cancelToken, headers, progressUpdateCallback, }: {
769
800
  path: string;
@@ -778,6 +809,11 @@ export declare class AvroQueryClient {
778
809
  headers?: Record<string, string>;
779
810
  progressUpdateCallback?: (loaded: number, total: number) => void;
780
811
  }): Promise<T>;
812
+ /**
813
+ * Persist freshly issued tokens, then flip to AUTHENTICATED and connect
814
+ * the socket. Tokens are stored first so that anything reacting to the
815
+ * auth-state change (queries enabled on AUTHENTICATED) finds them.
816
+ */
781
817
  loginSuccess(tokens: Tokens): Promise<void>;
782
818
  useLogin(): ReturnType<typeof useMutation<LoginResponse, StandardError, {
783
819
  username: string;
@@ -860,6 +896,11 @@ export declare class AvroQueryClient {
860
896
  focus_point_latitude?: number;
861
897
  focus_point_longitude?: number;
862
898
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<AddressFeatureCollection>;
899
+ /**
900
+ * The caller's chats. The backend only exposes `GET /chat` (every chat
901
+ * the user belongs to, unpaged), so the id/query/paging filters are
902
+ * applied client-side.
903
+ */
863
904
  fetchChats(body?: {
864
905
  amt?: number;
865
906
  known_ids?: string[];
@@ -883,6 +924,8 @@ export declare class AvroQueryClient {
883
924
  unbilled?: boolean;
884
925
  billed?: boolean;
885
926
  paid?: boolean;
927
+ task_id?: string | null;
928
+ /** @deprecated ignored by the backend; use `task_id`. */
886
929
  taskId?: string | null;
887
930
  sort_by?: 'date' | 'amount' | 'name';
888
931
  direction?: 'asc' | 'desc';
@@ -917,6 +960,8 @@ export declare class AvroQueryClient {
917
960
  unbilled?: boolean;
918
961
  billed?: boolean;
919
962
  paid?: boolean;
963
+ job_id?: string | null;
964
+ /** @deprecated ignored by the backend; use `job_id`. */
920
965
  jobId?: string | null;
921
966
  sort_by?: 'date' | 'amount' | 'name';
922
967
  direction?: 'asc' | 'desc';
@@ -966,6 +1011,11 @@ export declare class AvroQueryClient {
966
1011
  query?: string;
967
1012
  offset?: number;
968
1013
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1014
+ /**
1015
+ * Company labels. There is no list endpoint for them: they are embedded
1016
+ * in `GET /company/<id>`, so the id/query/paging filters are applied
1017
+ * client-side.
1018
+ */
969
1019
  fetchLabels(body?: {
970
1020
  amt?: number;
971
1021
  known_ids?: string[];
@@ -973,6 +1023,11 @@ export declare class AvroQueryClient {
973
1023
  query?: string;
974
1024
  offset?: number;
975
1025
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1026
+ /**
1027
+ * Company groups. There is no list endpoint for them: they are embedded
1028
+ * in `GET /company/<id>`, so the id/query/paging filters are applied
1029
+ * client-side.
1030
+ */
976
1031
  fetchGroups(body?: {
977
1032
  amt?: number;
978
1033
  known_ids?: string[];