@go-avro/avro-js 0.0.109 → 0.0.111

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.
@@ -7,9 +7,10 @@ export interface AvroQueryClientProviderProps {
7
7
  authManager: AuthManager;
8
8
  queryClient: QueryClient;
9
9
  configOverrides?: Partial<AvroQueryClientConfig>;
10
+ client?: AvroQueryClient;
10
11
  children: ReactNode;
11
12
  }
12
- export declare const AvroQueryClientProvider: ({ baseUrl, authManager, queryClient, configOverrides, children, }: AvroQueryClientProviderProps) => React.JSX.Element;
13
+ export declare const AvroQueryClientProvider: ({ baseUrl, authManager, queryClient, configOverrides, client: providedClient, children, }: AvroQueryClientProviderProps) => React.JSX.Element;
13
14
  export declare const useAvroQueryClient: () => AvroQueryClient;
14
15
  export declare const useSocketEvent: (eventName: string, callback: (data: Record<string, unknown>) => void) => void;
15
16
  export default AvroQueryClientProvider;
@@ -1,15 +1,17 @@
1
1
  import React, { createContext, useContext, useMemo, useEffect, useRef, useCallback, } from 'react';
2
2
  import { AvroQueryClient } from './QueryClient';
3
3
  const AvroQueryClientContext = createContext(null);
4
- export const AvroQueryClientProvider = ({ baseUrl, authManager, queryClient, configOverrides, children, }) => {
4
+ export const AvroQueryClientProvider = ({ baseUrl, authManager, queryClient, configOverrides, client: providedClient, children, }) => {
5
5
  const client = useMemo(() => {
6
+ if (providedClient)
7
+ return providedClient;
6
8
  const cfg = {
7
9
  baseUrl,
8
10
  authManager,
9
11
  ...(configOverrides || {}),
10
12
  };
11
13
  return new AvroQueryClient(cfg);
12
- }, [baseUrl, authManager, configOverrides]);
14
+ }, [providedClient, baseUrl, authManager, configOverrides]);
13
15
  useEffect(() => {
14
16
  if (queryClient) {
15
17
  client.setupSocketInvalidation(queryClient);
@@ -678,6 +678,7 @@ export declare class AvroQueryClient {
678
678
  /** The install identity sent with sockets and location pings, if any. */
679
679
  get device(): DeviceInfo | undefined;
680
680
  setDevice(device: DeviceInfo | undefined): void;
681
+ private ensureSocketConnected;
681
682
  /** Tell the server which install this live socket belongs to. */
682
683
  private registerDevice;
683
684
  emit(eventName: string, data: unknown): void;
@@ -404,14 +404,11 @@ export class AvroQueryClient {
404
404
  config.authManager.isAuthenticated().then((isAuth) => {
405
405
  this.setAuthState(isAuth);
406
406
  if (!this.socket.connected && isAuth === AuthState.AUTHENTICATED) {
407
- // Resolve both companyId and access token before connecting so
408
- // the 'connect' handler in setupSocketInvalidation can immediately
409
- // join the company room.
410
407
  Promise.all([this.getCompanyId(), this.config.authManager.accessToken()])
411
408
  .then(([id, token]) => {
412
409
  this.companyId = id;
413
410
  this.socket.auth = this.socketAuth(token);
414
- this.socket.connect();
411
+ this.ensureSocketConnected();
415
412
  })
416
413
  .catch((err) => {
417
414
  console.error('Not logged in:', err);
@@ -438,7 +435,7 @@ export class AvroQueryClient {
438
435
  if (this.socket && newAccessToken) {
439
436
  this.setAuthState(AuthState.AUTHENTICATED);
440
437
  this.socket.auth = this.socketAuth(newAccessToken);
441
- this.socket.disconnect().connect();
438
+ this.ensureSocketConnected();
442
439
  }
443
440
  });
444
441
  config.authManager.onTokenRefreshFailed(() => {
@@ -463,6 +460,11 @@ export class AvroQueryClient {
463
460
  // the 'connect' handler repeats it on every (re)connect.
464
461
  this.registerDevice();
465
462
  }
463
+ ensureSocketConnected() {
464
+ if (!this.socket.connected && !this.socket.active) {
465
+ this.socket.connect();
466
+ }
467
+ }
466
468
  /** Tell the server which install this live socket belongs to. */
467
469
  registerDevice() {
468
470
  if (this.config.device && this.socket.connected) {
@@ -508,7 +510,37 @@ export class AvroQueryClient {
508
510
  predicate: (q) => matchesEntityKey(q, entityKey),
509
511
  });
510
512
  };
513
+ const patchMemberLocation = (data) => {
514
+ const userId = data?.user_id;
515
+ if (!userId || typeof userId !== 'string' || typeof data?.latitude !== 'number') {
516
+ queryClient.invalidateQueries({ queryKey: ['companies'] });
517
+ return;
518
+ }
519
+ queryClient.setQueriesData({ queryKey: ['companies'] }, (old) => {
520
+ if (!old || !Array.isArray(old.users))
521
+ return old;
522
+ let changed = false;
523
+ const users = old.users.map((u) => {
524
+ if (u?.user?.id !== userId)
525
+ return u;
526
+ changed = true;
527
+ return { ...u, last_location: data };
528
+ });
529
+ return changed ? { ...old, users } : old;
530
+ });
531
+ };
511
532
  for (const [event, config] of Object.entries(SOCKET_EVENT_CONFIG)) {
533
+ if (event === 'location_update' && isBulkEvent(config)) {
534
+ const handler = (data) => {
535
+ patchMemberLocation(data);
536
+ for (const key of config.invalidateKeys) {
537
+ queryClient.invalidateQueries({ queryKey: key });
538
+ }
539
+ };
540
+ this.socket.on(event, handler);
541
+ handlers.push({ event, handler });
542
+ continue;
543
+ }
512
544
  if (isBulkEvent(config)) {
513
545
  // ── Bulk: invalidate all specified keys ──────────────
514
546
  const handler = () => {
@@ -627,7 +659,7 @@ export class AvroQueryClient {
627
659
  this.setAuthState(AuthState.AUTHENTICATED);
628
660
  this.socket.auth = this.socketAuth(tokens.access_token);
629
661
  if (!this.socket.connected) {
630
- this.socket.connect();
662
+ this.ensureSocketConnected();
631
663
  }
632
664
  return this.config.authManager.setTokens(tokens);
633
665
  }
@@ -715,7 +747,7 @@ export class AvroQueryClient {
715
747
  this.setAuthState(AuthState.AUTHENTICATED);
716
748
  this.socket.auth = this.socketAuth(resp.access_token);
717
749
  if (!this.socket.connected) {
718
- this.socket.connect();
750
+ this.ensureSocketConnected();
719
751
  }
720
752
  await this.config.authManager.setTokens({
721
753
  access_token: resp.access_token,
@@ -746,7 +778,7 @@ export class AvroQueryClient {
746
778
  this.setAuthState(AuthState.AUTHENTICATED);
747
779
  this.socket.auth = this.socketAuth(resp.access_token);
748
780
  if (!this.socket.connected) {
749
- this.socket.connect();
781
+ this.ensureSocketConnected();
750
782
  }
751
783
  await this.config.authManager.setTokens({
752
784
  access_token: resp.access_token,
package/dist/index.d.ts CHANGED
@@ -40,7 +40,8 @@ import './client/hooks/email';
40
40
  export { defaultPassOnFeeMethod } from './billing/fees';
41
41
  export { reverseGeocode } from './geocode';
42
42
  export { fetchCensusFeatures } from './census';
43
- export { LOCATION_STALE_MINUTES, REPORTING_STATUSES, locationAgeMinutes, isLocationStale, isReportingStatus, isMobileDevice, mobileDevices, } from './presence';
43
+ export { LOCATION_STALE_MINUTES, LOCATION_RECENT_HOURS, isLocationRecent, REPORTING_STATUSES, locationAgeMinutes, isLocationStale, isReportingStatus, isMobileDevice, mobileDevices, userPresence, } from './presence';
44
+ export type { UserPresence } from './presence';
44
45
  export type { ReverseGeocodeResult } from './geocode';
45
46
  export * from './types/api';
46
47
  export * from './types/auth';
package/dist/index.js CHANGED
@@ -38,7 +38,7 @@ import './client/hooks/email';
38
38
  export { defaultPassOnFeeMethod } from './billing/fees';
39
39
  export { reverseGeocode } from './geocode';
40
40
  export { fetchCensusFeatures } from './census';
41
- export { LOCATION_STALE_MINUTES, REPORTING_STATUSES, locationAgeMinutes, isLocationStale, isReportingStatus, isMobileDevice, mobileDevices, } from './presence';
41
+ export { LOCATION_STALE_MINUTES, LOCATION_RECENT_HOURS, isLocationRecent, REPORTING_STATUSES, locationAgeMinutes, isLocationStale, isReportingStatus, isMobileDevice, mobileDevices, userPresence, } from './presence';
42
42
  export * from './types/api';
43
43
  export * from './types/auth';
44
44
  export * from './types/cache';
@@ -16,8 +16,18 @@ export declare const mobileDevices: (devices: Device[] | null | undefined) => De
16
16
  * stationary phone in the background on iOS). Distinct from
17
17
  * `location_status`, which reports permissions / app liveness.
18
18
  */
19
- export declare const LOCATION_STALE_MINUTES = 15;
19
+ export declare const LOCATION_STALE_MINUTES = 5;
20
20
  /** Age of a location fix in whole minutes, or null when there is none. */
21
21
  export declare const locationAgeMinutes: (location: Pick<Location, "time_collected"> | null | undefined, nowMs?: number) => number | null;
22
22
  /** True when the fix is missing or older than `staleMinutes`. */
23
23
  export declare const isLocationStale: (location: Pick<Location, "time_collected"> | null | undefined, staleMinutes?: number, nowMs?: number) => boolean;
24
+ /** Members with a fix newer than this still appear on the map. */
25
+ export declare const LOCATION_RECENT_HOURS = 24;
26
+ /** True when the fix exists and is newer than `hours` old. */
27
+ export declare const isLocationRecent: (location: Pick<Location, "time_collected"> | null | undefined, hours?: number, nowMs?: number) => boolean;
28
+ export type UserPresence = 'online' | 'background' | 'offline';
29
+ /**
30
+ * online: some device is connected and on screen; background: connected
31
+ * but nothing on screen (e.g. a phone tracking location); offline: none.
32
+ */
33
+ export declare const userPresence: (devices: Device[] | null | undefined) => UserPresence;
package/dist/presence.js CHANGED
@@ -19,7 +19,7 @@ export const mobileDevices = (devices) => (devices ?? []).filter(isMobileDevice)
19
19
  * stationary phone in the background on iOS). Distinct from
20
20
  * `location_status`, which reports permissions / app liveness.
21
21
  */
22
- export const LOCATION_STALE_MINUTES = 15;
22
+ export const LOCATION_STALE_MINUTES = 5;
23
23
  /** Age of a location fix in whole minutes, or null when there is none. */
24
24
  export const locationAgeMinutes = (location, nowMs = Date.now()) => {
25
25
  if (!location?.time_collected)
@@ -31,3 +31,20 @@ export const isLocationStale = (location, staleMinutes = LOCATION_STALE_MINUTES,
31
31
  const age = locationAgeMinutes(location, nowMs);
32
32
  return age === null || age >= staleMinutes;
33
33
  };
34
+ /** Members with a fix newer than this still appear on the map. */
35
+ export const LOCATION_RECENT_HOURS = 24;
36
+ /** True when the fix exists and is newer than `hours` old. */
37
+ export const isLocationRecent = (location, hours = LOCATION_RECENT_HOURS, nowMs = Date.now()) => {
38
+ const age = locationAgeMinutes(location, nowMs);
39
+ return age !== null && age < hours * 60;
40
+ };
41
+ /**
42
+ * online: some device is connected and on screen; background: connected
43
+ * but nothing on screen (e.g. a phone tracking location); offline: none.
44
+ */
45
+ export const userPresence = (devices) => {
46
+ const connected = (devices ?? []).filter((d) => d.online);
47
+ if (connected.some((d) => d.foreground))
48
+ return 'online';
49
+ return connected.length > 0 ? 'background' : 'offline';
50
+ };
@@ -18,6 +18,8 @@ export interface DeviceInfo {
18
18
  /** OS and version, e.g. "iOS 26.1" or "macOS 15". */
19
19
  os?: string;
20
20
  app_version?: string;
21
+ /** Whether the client is on screen (app active / tab visible). */
22
+ foreground?: boolean;
21
23
  }
22
24
  /** A device the user has connected from, as tracked by the server. */
23
25
  export interface Device {
@@ -31,6 +33,8 @@ export interface Device {
31
33
  location_status: LocationServicesStatus;
32
34
  /** Whether the device currently holds a socket. */
33
35
  online: boolean;
36
+ /** Whether the client is on screen; a backgrounded phone stays online for location. */
37
+ foreground: boolean;
34
38
  last_location: Location | null;
35
39
  last_seen: number | null;
36
40
  time_created: number | null;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "0.0.109";
1
+ export declare const AVRO_JS_VERSION = "0.0.111";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // AUTO-GENERATED by scripts/gen-version.js — do not edit by hand.
2
2
  // Regenerated from package.json by the `prebuild` npm hook.
3
- export const AVRO_JS_VERSION = '0.0.109';
3
+ export const AVRO_JS_VERSION = '0.0.111';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "0.0.109",
3
+ "version": "0.0.111",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",