@go-avro/avro-js 0.0.77 → 0.0.78

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.
@@ -0,0 +1,8 @@
1
+ import { AddressFeature } from './types/api';
2
+ /**
3
+ * Geocode an address with the US Census geocoder, directly from the
4
+ * client so requests come from each user's own IP rather than funneling
5
+ * through the backend. Returns [] on any failure — census results only
6
+ * ever supplement Pelias results.
7
+ */
8
+ export declare const fetchCensusFeatures: (address: string) => Promise<AddressFeature[]>;
package/dist/census.js ADDED
@@ -0,0 +1,76 @@
1
+ const CENSUS_GEOCODER_URL = 'https://geocoding.geo.census.gov/geocoder/locations/onelineaddress';
2
+ const CENSUS_BENCHMARK = 'Public_AR_Census2020';
3
+ const CENSUS_TIMEOUT_MS = 3000;
4
+ // The census geocoder sends no CORS headers, so browsers can only reach
5
+ // it via JSONP (script-tag injection).
6
+ const jsonpRequest = (url, timeoutMs) => new Promise((resolve, reject) => {
7
+ const host = window;
8
+ const callbackName = `__avro_census_cb_${Math.random().toString(36).slice(2)}`;
9
+ const script = document.createElement('script');
10
+ const cleanup = () => {
11
+ delete host[callbackName];
12
+ script.remove();
13
+ clearTimeout(timer);
14
+ };
15
+ const timer = setTimeout(() => {
16
+ cleanup();
17
+ reject(new Error('Census request timed out'));
18
+ }, timeoutMs);
19
+ host[callbackName] = (data) => {
20
+ cleanup();
21
+ resolve(data);
22
+ };
23
+ script.onerror = () => {
24
+ cleanup();
25
+ reject(new Error('Census request failed'));
26
+ };
27
+ script.src = `${url}&callback=${callbackName}`;
28
+ document.head.appendChild(script);
29
+ });
30
+ // React Native has no DOM for JSONP, but also enforces no CORS, so a
31
+ // plain fetch works there.
32
+ const fetchRequest = async (url, timeoutMs) => {
33
+ const controller = new AbortController();
34
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
35
+ try {
36
+ const res = await fetch(url, { signal: controller.signal });
37
+ if (!res.ok) {
38
+ throw new Error(`Census request failed: ${res.status}`);
39
+ }
40
+ return await res.json();
41
+ }
42
+ finally {
43
+ clearTimeout(timer);
44
+ }
45
+ };
46
+ /**
47
+ * Geocode an address with the US Census geocoder, directly from the
48
+ * client so requests come from each user's own IP rather than funneling
49
+ * through the backend. Returns [] on any failure — census results only
50
+ * ever supplement Pelias results.
51
+ */
52
+ export const fetchCensusFeatures = async (address) => {
53
+ const useJsonp = typeof document !== 'undefined';
54
+ const params = new URLSearchParams({
55
+ address: address.trim(),
56
+ benchmark: CENSUS_BENCHMARK,
57
+ format: useJsonp ? 'jsonp' : 'json',
58
+ });
59
+ const url = `${CENSUS_GEOCODER_URL}?${params.toString()}`;
60
+ try {
61
+ const data = (useJsonp
62
+ ? await jsonpRequest(url, CENSUS_TIMEOUT_MS)
63
+ : await fetchRequest(url, CENSUS_TIMEOUT_MS));
64
+ return (data.result?.addressMatches ?? []).map((match) => ({
65
+ type: 'Feature',
66
+ geometry: {
67
+ type: 'Point',
68
+ coordinates: [match.coordinates.x, match.coordinates.y],
69
+ },
70
+ properties: { label: match.matchedAddress },
71
+ }));
72
+ }
73
+ catch {
74
+ return [];
75
+ }
76
+ };
@@ -1,7 +1,7 @@
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';
4
- import { _Event, ActiveSessionSummary, ApiInfo, Avro, Bill, BillInsightData, BillLineItemStatusUpdate, BillStatus, Break, Chat, CheckIn, Company, EventUpdatePayload, FinancialInsightData, RevenueInsightData, Job, EventInsightData, LoginResponse, Message, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogItem, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus } from '../types/api';
4
+ import { _Event, ActiveSessionSummary, AddressFeatureCollection, ApiInfo, Avro, Bill, BillInsightData, BillLineItemStatusUpdate, BillStatus, Break, Chat, CheckIn, Company, EventUpdatePayload, FinancialInsightData, RevenueInsightData, Job, EventInsightData, LoginResponse, Message, Plan, Route, ServiceMonth, Session, Team, User, UserCompanyAssociation, Skill, Group, Label, RouteScheduleConfig, RouteWritePayload, CatalogItem, Payout, Prepayment, Timecard, TimecardActionType, TimecardStatus } from '../types/api';
5
5
  import { AuthState, Tokens } from '../types/auth';
6
6
  import { CancelToken, ClientId, RetryStrategy } from '../types/client';
7
7
  import { StandardError } from '../types/error';
@@ -166,6 +166,18 @@ declare module '../client/QueryClient' {
166
166
  msg: string;
167
167
  }>;
168
168
  useGetProposal(proposal_id: string): UseQueryResult<any, StandardError>;
169
+ useAutocompleteAddress(address: string, options?: {
170
+ size?: number;
171
+ minLength?: number;
172
+ debounceMs?: number;
173
+ includeCensus?: boolean;
174
+ }): UseQueryResult<AddressFeatureCollection, StandardError>;
175
+ useSearchAddress(address: string, options?: {
176
+ focusPointLatitude?: number;
177
+ focusPointLongitude?: number;
178
+ minLength?: number;
179
+ debounceMs?: number;
180
+ }): UseQueryResult<AddressFeatureCollection, StandardError>;
169
181
  useGetAnalytics(): UseQueryResult<any, StandardError>;
170
182
  useFinanceAnalytics({ periods, cumulative, }: {
171
183
  periods: number[][];
@@ -727,6 +739,16 @@ export declare class AvroQueryClient {
727
739
  offset?: number;
728
740
  route_id?: string;
729
741
  }, companyId?: string, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
742
+ autocompleteAddress({ address, size, include_census, }: {
743
+ address: string;
744
+ size?: number;
745
+ include_census?: boolean;
746
+ }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<AddressFeatureCollection>;
747
+ searchAddress({ address, focus_point_latitude, focus_point_longitude, }: {
748
+ address: string;
749
+ focus_point_latitude?: number;
750
+ focus_point_longitude?: number;
751
+ }, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<AddressFeatureCollection>;
730
752
  fetchChats(body?: {
731
753
  amt?: number;
732
754
  known_ids?: string[];
@@ -1,6 +1,7 @@
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 { fetchCensusFeatures } from '../census';
4
5
  import { _Event, Job, LoginResponse, Route, } from '../types/api';
5
6
  import { AuthState } from '../types/auth';
6
7
  import { StandardError } from '../types/error';
@@ -920,6 +921,54 @@ export class AvroQueryClient {
920
921
  throw new StandardError(500, `Failed to fetch jobs: ${err.message ?? err}`);
921
922
  });
922
923
  }
924
+ async autocompleteAddress({ address, size = 10, include_census = true, }, cancelToken, headers = {}) {
925
+ const peliasPromise = this.post({
926
+ path: '/address/autocomplete',
927
+ data: JSON.stringify({ address, size }),
928
+ cancelToken,
929
+ headers: {
930
+ ...headers,
931
+ 'Content-Type': 'application/json',
932
+ },
933
+ });
934
+ if (!include_census) {
935
+ return peliasPromise;
936
+ }
937
+ // The census lookup runs client-side (each user's own IP) and in
938
+ // parallel with the backend call; fetchCensusFeatures never rejects.
939
+ const [pelias, census] = await Promise.all([
940
+ peliasPromise.then((value) => ({ value, error: null }), (error) => ({ value: null, error })),
941
+ fetchCensusFeatures(address),
942
+ ]);
943
+ if (!pelias.value && census.length === 0) {
944
+ throw pelias.error;
945
+ }
946
+ const features = pelias.value?.features ?? [];
947
+ const knownLabels = new Set(features.map((feature) => feature.properties.label.toLowerCase()));
948
+ return {
949
+ ...pelias.value,
950
+ type: 'FeatureCollection',
951
+ features: [
952
+ ...features,
953
+ ...census.filter((feature) => !knownLabels.has(feature.properties.label.toLowerCase())),
954
+ ],
955
+ };
956
+ }
957
+ searchAddress({ address, focus_point_latitude, focus_point_longitude, }, cancelToken, headers = {}) {
958
+ return this.post({
959
+ path: '/address/search',
960
+ data: JSON.stringify({
961
+ address,
962
+ ...(focus_point_latitude !== undefined && { focus_point_latitude }),
963
+ ...(focus_point_longitude !== undefined && { focus_point_longitude }),
964
+ }),
965
+ cancelToken,
966
+ headers: {
967
+ ...headers,
968
+ 'Content-Type': 'application/json',
969
+ },
970
+ });
971
+ }
923
972
  fetchChats(body = {}, cancelToken, headers = {}) {
924
973
  if (!this.companyId || this.companyId.trim() === '') {
925
974
  throw new StandardError(400, 'Company ID is required');
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,43 @@
1
+ import { keepPreviousData, useQuery } from '@tanstack/react-query';
2
+ import { useEffect, useState } from 'react';
3
+ import { AvroQueryClient } from '../../client/QueryClient';
4
+ const useDebouncedValue = (value, delayMs) => {
5
+ const [debounced, setDebounced] = useState(value);
6
+ useEffect(() => {
7
+ const handle = setTimeout(() => setDebounced(value), delayMs);
8
+ return () => clearTimeout(handle);
9
+ }, [value, delayMs]);
10
+ return debounced;
11
+ };
12
+ AvroQueryClient.prototype.useAutocompleteAddress = function (address, { size = 10, minLength = 3, debounceMs = 500, includeCensus = true, } = {}) {
13
+ const trimmed = address.trim();
14
+ const debouncedAddress = useDebouncedValue(trimmed, debounceMs);
15
+ return useQuery({
16
+ queryKey: ['address', 'autocomplete', debouncedAddress, size, includeCensus],
17
+ queryFn: () => this.autocompleteAddress({
18
+ address: debouncedAddress,
19
+ size,
20
+ include_census: includeCensus,
21
+ }),
22
+ // Gate on the live value too so clearing the input stops the
23
+ // debounced fetch from firing.
24
+ enabled: trimmed.length >= minLength && debouncedAddress.length >= minLength,
25
+ placeholderData: keepPreviousData,
26
+ staleTime: 5 * 60 * 1000,
27
+ });
28
+ };
29
+ AvroQueryClient.prototype.useSearchAddress = function (address, { focusPointLatitude, focusPointLongitude, minLength = 3, debounceMs = 500, } = {}) {
30
+ const trimmed = address.trim();
31
+ const debouncedAddress = useDebouncedValue(trimmed, debounceMs);
32
+ return useQuery({
33
+ queryKey: ['address', 'search', debouncedAddress, focusPointLatitude, focusPointLongitude],
34
+ queryFn: () => this.searchAddress({
35
+ address: debouncedAddress,
36
+ focus_point_latitude: focusPointLatitude,
37
+ focus_point_longitude: focusPointLongitude,
38
+ }),
39
+ enabled: trimmed.length >= minLength && debouncedAddress.length >= minLength,
40
+ placeholderData: keepPreviousData,
41
+ staleTime: 5 * 60 * 1000,
42
+ });
43
+ };
@@ -0,0 +1,9 @@
1
+ export interface ReverseGeocodeResult {
2
+ address: string;
3
+ suggestedName: string;
4
+ }
5
+ /**
6
+ * Reverse-geocode a coordinate pair via OSM Nominatim. Throws when the
7
+ * lookup fails or returns no result — callers decide the fallback.
8
+ */
9
+ export declare const reverseGeocode: (lat: number, lng: number) => Promise<ReverseGeocodeResult>;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Reverse-geocode a coordinate pair via OSM Nominatim. Throws when the
3
+ * lookup fails or returns no result — callers decide the fallback.
4
+ */
5
+ export const reverseGeocode = async (lat, lng) => {
6
+ const res = await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&addressdetails=1`);
7
+ if (!res.ok) {
8
+ throw new Error(`Reverse geocode failed: ${res.status}`);
9
+ }
10
+ const data = (await res.json());
11
+ if (!data?.display_name) {
12
+ throw new Error('Reverse geocode returned no result');
13
+ }
14
+ const addr = data.address || {};
15
+ const street = [addr.house_number, addr.road].filter(Boolean).join(' ').trim();
16
+ const city = addr.city || addr.town || addr.village || addr.hamlet;
17
+ const state = addr.state;
18
+ const postcode = addr.postcode;
19
+ const shortAddress = [street, city, state, postcode].filter(Boolean).join(', ');
20
+ const primary = street || city || data.display_name.split(',')[0]?.trim();
21
+ return {
22
+ address: shortAddress || data.display_name,
23
+ suggestedName: primary || data.display_name,
24
+ };
25
+ };
package/dist/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export { MemoryStorage, LocalStorage } from './auth/storage';
8
8
  import './client/core/xhr';
9
9
  import './client/core/fetch';
10
10
  import './client/core/utils';
11
+ import './client/hooks/address';
11
12
  import './client/hooks/root';
12
13
  import './client/hooks/jobs';
13
14
  import './client/hooks/routes';
@@ -35,6 +36,9 @@ import './client/hooks/timecards';
35
36
  import './client/hooks/waivers';
36
37
  import './client/hooks/email';
37
38
  export { defaultPassOnFeeMethod } from './billing/fees';
39
+ export { reverseGeocode } from './geocode';
40
+ export { fetchCensusFeatures } from './census';
41
+ export type { ReverseGeocodeResult } from './geocode';
38
42
  export * from './types/api';
39
43
  export * from './types/auth';
40
44
  export * from './types/cache';
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ export { MemoryStorage, LocalStorage } from './auth/storage';
6
6
  import './client/core/xhr';
7
7
  import './client/core/fetch';
8
8
  import './client/core/utils';
9
+ import './client/hooks/address';
9
10
  import './client/hooks/root';
10
11
  import './client/hooks/jobs';
11
12
  import './client/hooks/routes';
@@ -33,6 +34,8 @@ import './client/hooks/timecards';
33
34
  import './client/hooks/waivers';
34
35
  import './client/hooks/email';
35
36
  export { defaultPassOnFeeMethod } from './billing/fees';
37
+ export { reverseGeocode } from './geocode';
38
+ export { fetchCensusFeatures } from './census';
36
39
  export * from './types/api';
37
40
  export * from './types/auth';
38
41
  export * from './types/cache';
@@ -0,0 +1,22 @@
1
+ /**
2
+ * A single address suggestion, as returned by the backend's
3
+ * /address/autocomplete and /address/search endpoints (Pelias GeoJSON,
4
+ * optionally merged with US Census geocoder matches server-side).
5
+ */
6
+ export interface AddressFeature {
7
+ type: 'Feature';
8
+ geometry: {
9
+ type: 'Point';
10
+ /** GeoJSON order: [longitude, latitude]. */
11
+ coordinates: [number, number];
12
+ };
13
+ properties: {
14
+ label: string;
15
+ [key: string]: unknown;
16
+ };
17
+ id?: string;
18
+ }
19
+ export interface AddressFeatureCollection {
20
+ type: 'FeatureCollection';
21
+ features: AddressFeature[];
22
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -3,6 +3,7 @@ import { _Event } from '../types/api/_Event';
3
3
  import { Route } from '../types/api/Route';
4
4
  export * from '../types/api/_Event';
5
5
  export * from '../types/api/AdditionalCharge';
6
+ export * from '../types/api/Address';
6
7
  export * from '../types/api/Avro';
7
8
  export * from '../types/api/Bill';
8
9
  export * from '../types/api/BillPayment';
package/dist/types/api.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from '../types/api/_Event';
2
2
  export * from '../types/api/AdditionalCharge';
3
+ export * from '../types/api/Address';
3
4
  export * from '../types/api/Avro';
4
5
  export * from '../types/api/Bill';
5
6
  export * from '../types/api/BillPayment';
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "0.0.77";
1
+ export declare const AVRO_JS_VERSION = "0.0.78";
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.77';
3
+ export const AVRO_JS_VERSION = '0.0.78';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "0.0.77",
3
+ "version": "0.0.78",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",