@go-avro/avro-js 1.6.6-rc9 → 1.7.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 (40) hide show
  1. package/dist/chat.d.ts +25 -0
  2. package/dist/chat.js +47 -0
  3. package/dist/client/QueryClient.d.ts +108 -26
  4. package/dist/client/QueryClient.js +103 -59
  5. package/dist/client/cache.d.ts +4 -0
  6. package/dist/client/cache.js +19 -0
  7. package/dist/client/core/uploads.js +226 -0
  8. package/dist/client/hooks/bills.js +15 -13
  9. package/dist/client/hooks/catalog_items.js +16 -4
  10. package/dist/client/hooks/chats.js +26 -0
  11. package/dist/client/hooks/devices.js +17 -3
  12. package/dist/client/hooks/messages.js +54 -1
  13. package/dist/client/hooks/routes.js +4 -1
  14. package/dist/client/hooks/teams.js +4 -1
  15. package/dist/client/hooks/{proposal_terms.js → terms.js} +14 -14
  16. package/dist/client/realtime.d.ts +26 -3
  17. package/dist/client/realtime.js +93 -16
  18. package/dist/client/requests.d.ts +7 -1
  19. package/dist/index.d.ts +4 -1
  20. package/dist/index.js +3 -1
  21. package/dist/types/api/AuditLog.d.ts +1 -1
  22. package/dist/types/api/Avro.d.ts +5 -0
  23. package/dist/types/api/CatalogItem.d.ts +3 -1
  24. package/dist/types/api/Company.d.ts +0 -2
  25. package/dist/types/api/Job.js +11 -2
  26. package/dist/types/api/MemberState.d.ts +3 -0
  27. package/dist/types/api/Notification.d.ts +39 -0
  28. package/dist/types/api/Proposal.d.ts +2 -2
  29. package/dist/types/api/Task.d.ts +16 -0
  30. package/dist/types/api/Task.js +30 -3
  31. package/dist/types/api/{ProposalTerms.d.ts → Terms.d.ts} +3 -3
  32. package/dist/types/api/Terms.js +1 -0
  33. package/dist/types/api.d.ts +1 -1
  34. package/dist/types/api.js +1 -1
  35. package/dist/types/client.d.ts +125 -0
  36. package/dist/version.d.ts +1 -1
  37. package/dist/version.js +1 -1
  38. package/package.json +1 -1
  39. /package/dist/client/{hooks/proposal_terms.d.ts → core/uploads.d.ts} +0 -0
  40. /package/dist/{types/api/ProposalTerms.js → client/hooks/terms.d.ts} +0 -0
package/dist/chat.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { Chat } from './types/api/Chat.js';
2
+ import { Reaction } from './types/api/Reaction.js';
3
+ /** The quick-pick reactions, as Unicode code points: 👍 ❤️ 😂 😮 😢 🙏. */
4
+ export declare const REACTION_CODE_POINTS: readonly [128077, 10084, 128514, 128558, 128546, 128591];
5
+ /**
6
+ * Render a reaction's code point. Older symbols (❤, ☺) default to text
7
+ * presentation, so they get the emoji variation selector.
8
+ */
9
+ export declare function reactionGlyph(codePoint: number): string;
10
+ export interface ReactionGroup {
11
+ reaction: number;
12
+ count: number;
13
+ /** Ids of the users who reacted, in reaction order. */
14
+ userIds: string[];
15
+ mine: boolean;
16
+ }
17
+ /** Group a message's reactions by emoji, in first-reacted order. */
18
+ export declare function groupReactions(reactions: Reaction[], selfId?: string): ReactionGroup[];
19
+ /** When a message was sent, preferring the server's clock. */
20
+ export declare function messageTime(message: {
21
+ time_created: number | null;
22
+ time_sent: number;
23
+ }): number;
24
+ /** Whether `chat` has a message from someone else the caller hasn't read. */
25
+ export declare function isChatUnread(chat: Chat, selfId?: string): boolean;
package/dist/chat.js ADDED
@@ -0,0 +1,47 @@
1
+ /** The quick-pick reactions, as Unicode code points: 👍 ❤️ 😂 😮 😢 🙏. */
2
+ export const REACTION_CODE_POINTS = [0x1f44d, 0x2764, 0x1f602, 0x1f62e, 0x1f622, 0x1f64f];
3
+ /**
4
+ * Render a reaction's code point. Older symbols (❤, ☺) default to text
5
+ * presentation, so they get the emoji variation selector.
6
+ */
7
+ export function reactionGlyph(codePoint) {
8
+ try {
9
+ const glyph = String.fromCodePoint(codePoint);
10
+ return codePoint < 0x1f000 ? `${glyph}️` : glyph;
11
+ }
12
+ catch {
13
+ return '';
14
+ }
15
+ }
16
+ /** Group a message's reactions by emoji, in first-reacted order. */
17
+ export function groupReactions(reactions, selfId) {
18
+ const groups = new Map();
19
+ for (const r of reactions ?? []) {
20
+ let group = groups.get(r.reaction);
21
+ if (!group) {
22
+ group = { reaction: r.reaction, count: 0, userIds: [], mine: false };
23
+ groups.set(r.reaction, group);
24
+ }
25
+ if (group.userIds.includes(r.sender_id))
26
+ continue;
27
+ group.userIds.push(r.sender_id);
28
+ group.count += 1;
29
+ if (r.sender_id === selfId)
30
+ group.mine = true;
31
+ }
32
+ return [...groups.values()];
33
+ }
34
+ /** When a message was sent, preferring the server's clock. */
35
+ export function messageTime(message) {
36
+ return message.time_created ?? (message.time_sent > 0 ? message.time_sent : 0);
37
+ }
38
+ /** Whether `chat` has a message from someone else the caller hasn't read. */
39
+ export function isChatUnread(chat, selfId) {
40
+ const last = chat.last_message;
41
+ if (!last || !selfId || last.sender_id === selfId)
42
+ return false;
43
+ const me = chat.user_state.find((m) => m.id === selfId);
44
+ if (!me)
45
+ return false;
46
+ return me.last_message_read_at == null || me.last_message_read_at < messageTime(last);
47
+ }
@@ -1,18 +1,19 @@
1
1
  import { Socket } from 'socket.io-client';
2
2
  import { InfiniteData, QueryClient, UseInfiniteQueryResult, useMutation, UseQueryResult } from '@tanstack/react-query';
3
3
  import { AuthManager } from '../auth/AuthManager.js';
4
- import { _Event, ActiveSessionSummary, AddressFeatureCollection, ApiInfo, Avro, StorageAnalytics, ClientErrorReport, ErrorLogEntry, PerformanceMetrics, AuditLogEntry, AuditQueryParams, Bill, BillInsightData, BillLineItemStatusUpdate, BillStatus, Chat, CheckIn, Company, CompanySummary, DelayEventCreatePayload, EventUpdatePayload, LineItemType, FinancialInsightData, RevenueInsightData, Job, JobUpdate, EventInsightData, AppleLinkProof, AppleLoginResult, MicrosoftLoginResult, LoginResponse, Message, Permission, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, UserMergeSummary, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogItem, Device, DeviceInfo, LocationServicesStatus, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus } from '../types/api.js';
4
+ import { _Event, ActiveSessionSummary, AddressFeatureCollection, ApiInfo, Avro, StorageAnalytics, ClientErrorReport, ErrorLogEntry, PerformanceMetrics, AuditLogEntry, AuditQueryParams, Bill, BillInsightData, BillLineItemStatusUpdate, BillStatus, Chat, CheckIn, Company, CompanySummary, DelayEventCreatePayload, EventUpdatePayload, LineItemType, FinancialInsightData, RevenueInsightData, Job, JobUpdate, EventInsightData, AppleLinkProof, AppleLoginResult, MicrosoftLoginResult, LoginResponse, Message, MemberState, Permission, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, UserMergeSummary, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogIndustry, CatalogItem, Device, DeviceInfo, LocationServicesStatus, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus, CreateNotificationPayload, NotificationCreated, SendEmailPayload } from '../types/api.js';
5
5
  import { AuthState, Tokens } from '../types/auth.js';
6
- import { CancelToken, ClientId, RetryStrategy } from '../types/client.js';
6
+ import { CancelToken, ClientId, RetryStrategy, EventPhotoLinks, EventPhotoLinksVars, PdfSource, SendBillEmailVars, SendEmailMessageVars, SendNotificationVars, ImageTarget, UploadImage, UploadImagesOptions, UploadImagesResult, UploadImagesVars } from '../types/client.js';
7
7
  import { StandardError } from '../types/error.js';
8
8
  import { CacheData } from '../types/cache.js';
9
9
  import { Waiver } from '../types/api/Waiver.js';
10
10
  import { Proposal } from '../types/api/Proposal.js';
11
- import { ProposalTerms } from '../types/api/ProposalTerms.js';
11
+ import { Terms } from '../types/api/Terms.js';
12
12
  import type { EmailSucceededPayload, EmailFailedPayload, EmailType } from '../types/api/EmailNotification.js';
13
13
  import type { BulkDeleteBillsResponse, BulkEmailBillsResponse } from './hooks/bills.js';
14
14
  import type { BillWritePayload, BreakWritePayload, CatalogItemCreatePayload, CatalogItemUpdatePayload, CompanyCreatePayload, CompanyUpdatePayload, EventCreatePayload, IntuitSyncStatus, MemberAddPayload, MemberUpdatePayload, PayoutStatusFilter, ProposalReviewPayload, ProposalWritePayload, SessionCreatePayload, SessionUpdatePayload, SkillCreatePayload, SkillUpdatePayload, TeamWritePayload, UserCreatePayload, UserUpdatePayload } from './requests.js';
15
15
  import { type QueryPersistOptions } from './persist.js';
16
+ import { type NsSnapshot } from './cache.js';
16
17
  export interface TrackEmailOptions {
17
18
  emailType?: EmailType;
18
19
  requestId?: string;
@@ -39,6 +40,50 @@ declare module './QueryClient.js' {
39
40
  _fetch<T>(method: string, path: string, body: any, cancelToken?: CancelToken, headers?: Record<string, string>, isIdempotent?: boolean, retryCount?: number): Promise<T>;
40
41
  getDelay(strategy: RetryStrategy, attempt: number): number;
41
42
  sleep(ms: number): Promise<void>;
43
+ _uploadImages(base: string, images: UploadImage[], options?: UploadImagesOptions): Promise<UploadImagesResult>;
44
+ /**
45
+ * Upload photos to an event or task straight to S3: allocate
46
+ * presigned URLs, upload each file (retrying network failures), then
47
+ * confirm. Resend a failed photo with the `upload` name its failure
48
+ * reported: one the server already stored is skipped, never stored
49
+ * twice. Components use `useUploadImages`.
50
+ */
51
+ uploadImages(target: ImageTarget, images: UploadImage[], options?: UploadImagesOptions): Promise<UploadImagesResult>;
52
+ /**
53
+ * Send a notification (in the current company unless `companyId` is
54
+ * given). Show photos by embedding `useEventPhotoLinks` URLs.
55
+ */
56
+ sendNotification(body: CreateNotificationPayload, options?: {
57
+ companyId?: string;
58
+ idempotencyKey?: string;
59
+ }): Promise<NotificationCreated>;
60
+ /**
61
+ * Send an email from a mailbox (show photos by embedding
62
+ * `useEventPhotoLinks` URLs); `requestId` is echoed in the
63
+ * `email_succeeded`/`email_failed` events.
64
+ */
65
+ sendEmailMessage(emailId: string, body: SendEmailPayload, options?: {
66
+ requestId?: string;
67
+ proposalId?: string;
68
+ idempotencyKey?: string;
69
+ }): Promise<void>;
70
+ /** `uploadImages` as a mutation; refreshes the event or job when done. */
71
+ useUploadImages(): ReturnType<typeof useMutation<UploadImagesResult, StandardError, UploadImagesVars>>;
72
+ /** `sendNotification` as a mutation. */
73
+ useSendNotification(): ReturnType<typeof useMutation<NotificationCreated, StandardError, SendNotificationVars>>;
74
+ /** Email a bill's invoice (PDF rendered server-side) as a mutation. */
75
+ useSendBillEmail(): ReturnType<typeof useMutation<{
76
+ msg: string;
77
+ }, StandardError, SendBillEmailVars>>;
78
+ /** `useEventPhotoLinks` outside React (e.g. an offline outbox). */
79
+ getEventPhotoLinks(vars: EventPhotoLinksVars): Promise<EventPhotoLinks>;
80
+ /**
81
+ * Fetch permanent, signed links to an event's photos to embed in an
82
+ * email (`<img>` per position plus a "View photos" page).
83
+ */
84
+ useEventPhotoLinks(): ReturnType<typeof useMutation<EventPhotoLinks, StandardError, EventPhotoLinksVars>>;
85
+ /** `sendEmailMessage` as a mutation. */
86
+ useSendEmailMessage(): ReturnType<typeof useMutation<void, StandardError, SendEmailMessageVars>>;
42
87
  useGetRoot(): UseQueryResult<ApiInfo, StandardError>;
43
88
  useJobAudit(jobId: string, params?: AuditQueryParams): UseQueryResult<AuditLogEntry[], StandardError>;
44
89
  useCompanyAudit(params?: AuditQueryParams): UseQueryResult<AuditLogEntry[], StandardError>;
@@ -180,21 +225,14 @@ declare module './QueryClient.js' {
180
225
  }, total: number, onProgress?: (fraction: number) => void): UseQueryResult<Group[], StandardError>;
181
226
  useGetPlans(code: string): UseQueryResult<Plan[], StandardError>;
182
227
  useGetCompanies(options?: {}): UseQueryResult<CompanySummary[], StandardError>;
183
- generatePDFFromBackend({ billId }: {
184
- billId: string;
185
- }): Promise<Blob>;
186
- sendBillingEmail(options: {
187
- billId: string;
188
- subject?: string;
189
- /** `[name, email]` pairs; omitted: the bill's own recipients. */
190
- recipients?: [string, string][];
191
- request_id?: string;
192
- }): Promise<{
193
- msg: string;
194
- }>;
228
+ /**
229
+ * Render a PDF on the server: a bill's invoice, or the hours report
230
+ * of the pay period containing `timecardsPeriodStart` (Unix time).
231
+ */
232
+ generatePDFFromBackend(source: PdfSource): Promise<Blob>;
195
233
  useGetProposal(proposal_id: string): UseQueryResult<Proposal, StandardError>;
196
- useGetProposalTerms(): UseQueryResult<ProposalTerms[], StandardError>;
197
- useCreateProposalTerms(): ReturnType<typeof useMutation<{
234
+ useGetTerms(): UseQueryResult<Terms[], StandardError>;
235
+ useCreateTerms(): ReturnType<typeof useMutation<{
198
236
  msg: string;
199
237
  id: string;
200
238
  }, StandardError, {
@@ -202,7 +240,7 @@ declare module './QueryClient.js' {
202
240
  body: string;
203
241
  archived?: boolean;
204
242
  }>>;
205
- useUpdateProposalTerms(): ReturnType<typeof useMutation<{
243
+ useUpdateTerms(): ReturnType<typeof useMutation<{
206
244
  msg: string;
207
245
  }, StandardError, {
208
246
  termsId: string;
@@ -252,6 +290,12 @@ declare module './QueryClient.js' {
252
290
  useGetRoute(routeId: string): UseQueryResult<Route, StandardError>;
253
291
  useGetChat(chatId: string): UseQueryResult<Chat, StandardError>;
254
292
  useGetCatalogItem(catalogItemId: string): UseQueryResult<CatalogItem, StandardError>;
293
+ useGetCatalogItems(body?: {
294
+ query?: string;
295
+ industry?: CatalogIndustry;
296
+ archived?: boolean;
297
+ companyId?: string;
298
+ }): UseQueryResult<CatalogItem[], StandardError>;
255
299
  useGetUserSessions(): UseQueryResult<Session[], StandardError>;
256
300
  useGetCompanySessionsByIds(sessionIds: string[], params?: {
257
301
  companyId?: string;
@@ -318,6 +362,30 @@ declare module './QueryClient.js' {
318
362
  time_sent?: number;
319
363
  id?: string;
320
364
  }>>;
365
+ useUpdateChat(): ReturnType<typeof useMutation<{
366
+ msg?: string;
367
+ }, StandardError, {
368
+ chatId: string;
369
+ name?: string;
370
+ status?: MemberState['state'];
371
+ users?: string[];
372
+ }>>;
373
+ useLeaveChat(): ReturnType<typeof useMutation<{
374
+ msg?: string;
375
+ }, StandardError, {
376
+ chatId: string;
377
+ }>>;
378
+ useReactToMessage(chatId: string): ReturnType<typeof useMutation<unknown, StandardError, {
379
+ message: Message;
380
+ reaction: number;
381
+ userId: string;
382
+ remove?: boolean;
383
+ }, {
384
+ snapshot: NsSnapshot;
385
+ }>>;
386
+ useMarkChatRead(chatId: string): ReturnType<typeof useMutation<unknown, StandardError, {
387
+ messageId: string;
388
+ }>>;
321
389
  useCreateProposal(): ReturnType<typeof useMutation<{
322
390
  msg: string;
323
391
  id: string;
@@ -761,6 +829,7 @@ export declare class AvroQueryClient {
761
829
  private _persister;
762
830
  private _presencePending;
763
831
  private _presenceTimer;
832
+ private _resyncTimer;
764
833
  /** Chat rooms to (re)join on every connect; socket rooms don't survive reconnects. */
765
834
  private _joinedChats;
766
835
  private _restored;
@@ -814,6 +883,15 @@ export declare class AvroQueryClient {
814
883
  setupSocketInvalidation(queryClient: QueryClient): void;
815
884
  /** Join the company room; resync if the ack version moved while away. */
816
885
  private joinCompanyRoom;
886
+ /**
887
+ * Mark matching queries stale now; refetch the ones on screen after a
888
+ * random delay. A deploy or restart reconnects every client at once
889
+ * (and resets the version counter), so an immediate refetch of
890
+ * everything sent the whole fleet's load at a just-restarted backend
891
+ * in the same second. Anything mounted meanwhile still refetches,
892
+ * since it is already stale.
893
+ */
894
+ private resync;
817
895
  /** Fallback for mutations when the socket is down (else the echo syncs). */
818
896
  syncAfterMutation(...types: string[]): void;
819
897
  /**
@@ -1027,6 +1105,8 @@ export declare class AvroQueryClient {
1027
1105
  offset?: number;
1028
1106
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1029
1107
  fetchMessages(chatId: string, body?: {
1108
+ /** Marks this message (and the chat) as read by the caller. */
1109
+ last_message_read?: string;
1030
1110
  amt?: number;
1031
1111
  known_ids?: string[];
1032
1112
  unknown_ids?: string[];
@@ -1156,6 +1236,16 @@ export declare class AvroQueryClient {
1156
1236
  query?: string;
1157
1237
  offset?: number;
1158
1238
  }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
1239
+ /** Any signed-in user may list a company's catalog (`companyId`). */
1240
+ fetchCatalogItems(body?: {
1241
+ amt?: number;
1242
+ unknown_ids?: string[];
1243
+ query?: string;
1244
+ offset?: number;
1245
+ industry?: CatalogIndustry;
1246
+ /** Only archived (`true`) or active (`false`) items; both if unset. */
1247
+ archived?: boolean;
1248
+ }, companyId?: string | undefined, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<CatalogItem[]>;
1159
1249
  fetchSkills(body?: {
1160
1250
  amt?: number;
1161
1251
  known_ids?: string[];
@@ -1174,12 +1264,4 @@ export declare class AvroQueryClient {
1174
1264
  }, cancelToken?: CancelToken, headers?: Record<string, string>, companyId?: string | undefined): Promise<any>;
1175
1265
  private _initEmailListeners;
1176
1266
  trackEmail(options?: TrackEmailOptions): string;
1177
- sendEmail(emailId: string, formData: FormData, progressUpdateCallback?: (loaded: number, total: number) => void): Promise<void>;
1178
- sendBillEmail(billId: string, body?: {
1179
- subject?: string;
1180
- /** `[name, email]` pairs; omitted: the bill's own recipients. */
1181
- recipients?: [string, string][];
1182
- base_url?: string;
1183
- request_id?: string;
1184
- }): Promise<void>;
1185
1267
  }
@@ -9,6 +9,7 @@ import { StandardError } from '../types/error.js';
9
9
  import { withoutEmpty } from './wire.js';
10
10
  import { ChangeApplier, fallbackInvalidate, patchMember, patchMemberLocation, patchTeamLocation, retryDenied, } from './realtime.js';
11
11
  import { QueryPersister } from './persist.js';
12
+ import { replaceRow } from './cache.js';
12
13
  /** Keep the original status (401/403/404/0…) when surfacing a list-fetch failure. */
13
14
  function fetchError(err, context) {
14
15
  if (err instanceof StandardError)
@@ -50,6 +51,8 @@ const MAX_MESSAGES_PER_PAGE = 100;
50
51
  const AUTH_RECHECK_MIN_MS = 2000;
51
52
  const AUTH_RECHECK_MAX_MS = 60000;
52
53
  const SOCKET_AUTH_RETRY_MS = 10000;
54
+ /** Spread of the refetch after a reconnect finds the company changed. */
55
+ const RESYNC_JITTER_MS = 10000;
53
56
  export class AvroQueryClient {
54
57
  constructor(config) {
55
58
  this._authState = AuthState.UNKNOWN;
@@ -63,6 +66,7 @@ export class AvroQueryClient {
63
66
  this._persister = null;
64
67
  this._presencePending = new Set();
65
68
  this._presenceTimer = null;
69
+ this._resyncTimer = null;
66
70
  /** Chat rooms to (re)join on every connect; socket rooms don't survive reconnects. */
67
71
  this._joinedChats = new Set();
68
72
  this._restored = null;
@@ -305,7 +309,47 @@ export class AvroQueryClient {
305
309
  if (this._socketInvalidationCleanup)
306
310
  return;
307
311
  this._queryClient = queryClient;
308
- const applier = new ChangeApplier(this, queryClient);
312
+ // Stale-mark only: an active refetch here turned backend
313
+ // trouble into a full-list refetch storm (every failing
314
+ // presence fetch scheduled a 400KB+ list download). The next
315
+ // mount/focus or realtime change refetches instead.
316
+ const markMembersStale = () => queryClient.invalidateQueries({
317
+ queryKey: ['users', 'company'],
318
+ refetchType: 'none',
319
+ });
320
+ // Fetch just the named members and patch them into every member
321
+ // list; used for presence flips and for `member` changes that
322
+ // name the user.
323
+ const refreshMembers = (userIds) => {
324
+ const companyId = this.companyId;
325
+ if (!companyId || userIds.length === 0)
326
+ return;
327
+ // `ListCompanyUsers.user_ids` holds at most 1000 ids.
328
+ for (let i = 0; i < userIds.length; i += 1000) {
329
+ const wanted = userIds.slice(i, i + 1000);
330
+ this.post({
331
+ path: `/company/${companyId}/users`,
332
+ data: JSON.stringify({ user_ids: wanted }),
333
+ headers: { 'Content-Type': 'application/json' },
334
+ idempotent: true,
335
+ })
336
+ .then((members) => {
337
+ if (!Array.isArray(members)) {
338
+ markMembersStale();
339
+ return;
340
+ }
341
+ for (const member of members)
342
+ patchMember(queryClient, member);
343
+ // A member the server no longer returns left the
344
+ // company; patching can't remove it.
345
+ const got = new Set(members.map((m) => m?.user?.id));
346
+ if (wanted.some((id) => !got.has(id)))
347
+ markMembersStale();
348
+ })
349
+ .catch(markMembersStale);
350
+ }
351
+ };
352
+ const applier = new ChangeApplier(this, queryClient, refreshMembers);
309
353
  this._applier = applier;
310
354
  const handlers = [];
311
355
  const on = (event, handler) => {
@@ -340,14 +384,6 @@ export class AvroQueryClient {
340
384
  // and patch those members instead of re-downloading every
341
385
  // member once per flip on every connected client.
342
386
  const PRESENCE_COALESCE_MS = 500;
343
- // Stale-mark only: an active refetch here turned backend
344
- // trouble into a full-list refetch storm (every failing
345
- // presence fetch scheduled a 400KB+ list download). The next
346
- // mount/focus or realtime change refetches instead.
347
- const markMembersStale = () => queryClient.invalidateQueries({
348
- queryKey: ['users', 'company'],
349
- refetchType: 'none',
350
- });
351
387
  on('update_presence', (data) => {
352
388
  const userId = data?.user_id;
353
389
  if (!userId || !this.companyId) {
@@ -361,26 +397,7 @@ export class AvroQueryClient {
361
397
  this._presenceTimer = null;
362
398
  const userIds = [...this._presencePending];
363
399
  this._presencePending.clear();
364
- if (!this.companyId || userIds.length === 0)
365
- return;
366
- // `ListCompanyUsers.user_ids` holds at most 1000 ids.
367
- for (let i = 0; i < userIds.length; i += 1000) {
368
- this.post({
369
- path: `/company/${this.companyId}/users`,
370
- data: JSON.stringify({ user_ids: userIds.slice(i, i + 1000) }),
371
- headers: { 'Content-Type': 'application/json' },
372
- idempotent: true,
373
- })
374
- .then((members) => {
375
- if (!Array.isArray(members)) {
376
- markMembersStale();
377
- return;
378
- }
379
- for (const member of members)
380
- patchMember(queryClient, member);
381
- })
382
- .catch(markMembersStale);
383
- }
400
+ refreshMembers(userIds);
384
401
  }, PRESENCE_COALESCE_MS);
385
402
  });
386
403
  on('location_update', (data) => {
@@ -410,9 +427,18 @@ export class AvroQueryClient {
410
427
  queryClient.invalidateQueries({ queryKey: ['companies'] });
411
428
  });
412
429
  }
413
- on('new_message', () => {
430
+ // Chat events reach every accepted member through their own room,
431
+ // so chat lists stay live without joining each chat's room.
432
+ on('new_message', (data) => {
414
433
  queryClient.invalidateQueries({ queryKey: ['chats'] });
415
- queryClient.invalidateQueries({ queryKey: ['messages'] });
434
+ queryClient.invalidateQueries({
435
+ queryKey: data?.chat_id ? ['messages', 'infinite', data.chat_id] : ['messages'],
436
+ });
437
+ });
438
+ // Carries the whole message (e.g. after a reaction change).
439
+ on('message_updated', (data) => {
440
+ if (data?.id)
441
+ replaceRow(queryClient, 'messages', data);
416
442
  });
417
443
  on('connect', () => {
418
444
  this.joinCompanyRoom();
@@ -430,6 +456,10 @@ export class AvroQueryClient {
430
456
  this._presenceTimer = null;
431
457
  }
432
458
  this._presencePending.clear();
459
+ if (this._resyncTimer) {
460
+ clearTimeout(this._resyncTimer);
461
+ this._resyncTimer = null;
462
+ }
433
463
  applier.dispose();
434
464
  this._applier = null;
435
465
  if (this.socket.connected && this.companyId) {
@@ -455,15 +485,33 @@ export class AvroQueryClient {
455
485
  // were never delivered. Refresh what loaded before now
456
486
  // once; later joins compare versions instead.
457
487
  const joinedAt = Date.now();
458
- this._queryClient?.invalidateQueries({
459
- predicate: (q) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < joinedAt,
460
- });
488
+ this.resync((q) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < joinedAt);
461
489
  }
462
490
  else if (known !== ack.version) {
463
- this._queryClient?.invalidateQueries();
491
+ this.resync(() => true);
464
492
  }
465
493
  });
466
494
  }
495
+ /**
496
+ * Mark matching queries stale now; refetch the ones on screen after a
497
+ * random delay. A deploy or restart reconnects every client at once
498
+ * (and resets the version counter), so an immediate refetch of
499
+ * everything sent the whole fleet's load at a just-restarted backend
500
+ * in the same second. Anything mounted meanwhile still refetches,
501
+ * since it is already stale.
502
+ */
503
+ resync(predicate) {
504
+ const qc = this._queryClient;
505
+ if (!qc)
506
+ return;
507
+ void qc.invalidateQueries({ predicate, refetchType: 'none' });
508
+ if (this._resyncTimer)
509
+ clearTimeout(this._resyncTimer);
510
+ this._resyncTimer = setTimeout(() => {
511
+ this._resyncTimer = null;
512
+ void this._queryClient?.refetchQueries({ predicate, type: 'active', stale: true });
513
+ }, Math.random() * RESYNC_JITTER_MS);
514
+ }
467
515
  /** Fallback for mutations when the socket is down (else the echo syncs). */
468
516
  syncAfterMutation(...types) {
469
517
  const qc = this._queryClient;
@@ -1332,6 +1380,26 @@ export class AvroQueryClient {
1332
1380
  throw fetchError(err, 'Failed to fetch groups');
1333
1381
  });
1334
1382
  }
1383
+ /** Any signed-in user may list a company's catalog (`companyId`). */
1384
+ fetchCatalogItems(body = {}, companyId = this.companyId, cancelToken, headers = {}) {
1385
+ if (!companyId || companyId.trim() === '') {
1386
+ throw new StandardError(400, 'Company ID is required');
1387
+ }
1388
+ return this._fetch('POST', `/company/${companyId}/catalog_items`, JSON.stringify(body), cancelToken, {
1389
+ ...headers,
1390
+ 'Content-Type': 'application/json',
1391
+ }, true)
1392
+ .then((response) => {
1393
+ if (!response || !Array.isArray(response)) {
1394
+ throw new StandardError(400, 'Invalid catalog items response');
1395
+ }
1396
+ return response;
1397
+ })
1398
+ .catch((err) => {
1399
+ console.error('Failed to fetch catalog items:', err);
1400
+ throw fetchError(err, 'Failed to fetch catalog items');
1401
+ });
1402
+ }
1335
1403
  fetchSkills(body = {}, cancelToken, headers = {}) {
1336
1404
  if (!this.companyId || this.companyId.trim() === '') {
1337
1405
  throw new StandardError(400, 'Company ID is required');
@@ -1417,28 +1485,4 @@ export class AvroQueryClient {
1417
1485
  });
1418
1486
  return requestId;
1419
1487
  }
1420
- sendEmail(emailId, formData, progressUpdateCallback) {
1421
- try {
1422
- return this.post({
1423
- path: `/email/${emailId}`,
1424
- data: formData,
1425
- progressUpdateCallback,
1426
- });
1427
- }
1428
- catch (error) {
1429
- throw new StandardError(500, `Failed to send email: ${error}`);
1430
- }
1431
- }
1432
- sendBillEmail(billId, body = {}) {
1433
- try {
1434
- return this.post({
1435
- path: `/bill/${billId}/email`,
1436
- data: JSON.stringify(body),
1437
- headers: { 'Content-Type': 'application/json' },
1438
- });
1439
- }
1440
- catch (error) {
1441
- throw new StandardError(500, `Failed to send bill email: ${error}`);
1442
- }
1443
- }
1444
1488
  }
@@ -22,3 +22,7 @@ export declare function seedDetails<T extends {
22
22
  }>(qc: QueryClient | null, ns: string, items: T[]): T[];
23
23
  /** Remove an optimistic row (by its temporary id) from every list in `ns`. */
24
24
  export declare function removeOptimisticRow(qc: QueryClient, ns: string, tempId: string): void;
25
+ /** Replace a row (matched by id) in every list in `ns` that holds it. */
26
+ export declare function replaceRow<T extends {
27
+ id?: string;
28
+ }>(qc: QueryClient, ns: string, row: T): void;
@@ -49,3 +49,22 @@ export function removeOptimisticRow(qc, ns, tempId) {
49
49
  return old;
50
50
  });
51
51
  }
52
+ /** Replace a row (matched by id) in every list in `ns` that holds it. */
53
+ export function replaceRow(qc, ns, row) {
54
+ if (!row?.id)
55
+ return;
56
+ const swap = (x) => (x?.id === row.id ? row : x);
57
+ qc.setQueriesData({ predicate: (q) => q.queryKey[0] === ns && isListKey(q.queryKey) }, (old) => {
58
+ if (!old)
59
+ return old;
60
+ if (Array.isArray(old))
61
+ return old.map(swap);
62
+ if (Array.isArray(old.pages)) {
63
+ return {
64
+ ...old,
65
+ pages: old.pages.map((p) => (Array.isArray(p) ? p.map(swap) : p)),
66
+ };
67
+ }
68
+ return old;
69
+ });
70
+ }