@go-avro/avro-js 0.1.2 → 0.1.4
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.
- package/dist/client/AvroQueryClientProvider.d.ts +2 -1
- package/dist/client/AvroQueryClientProvider.js +30 -3
- package/dist/client/QueryClient.d.ts +20 -1
- package/dist/client/QueryClient.js +73 -3
- package/dist/client/hooks/jobs.js +45 -31
- package/dist/client/hooks/root.js +5 -1
- package/dist/client/persist.d.ts +70 -0
- package/dist/client/persist.js +212 -0
- package/dist/client/realtime.d.ts +1 -0
- package/dist/client/realtime.js +17 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/types/api/Job.d.ts +2 -1
- package/dist/types/api/Task.d.ts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -8,9 +8,10 @@ export interface AvroQueryClientProviderProps {
|
|
|
8
8
|
queryClient: QueryClient;
|
|
9
9
|
configOverrides?: Partial<AvroQueryClientConfig>;
|
|
10
10
|
client?: AvroQueryClient;
|
|
11
|
+
fallback?: ReactNode;
|
|
11
12
|
children: ReactNode;
|
|
12
13
|
}
|
|
13
|
-
export declare const AvroQueryClientProvider: ({ baseUrl, authManager, queryClient, configOverrides, client: providedClient, children, }: AvroQueryClientProviderProps) => React.JSX.Element;
|
|
14
|
+
export declare const AvroQueryClientProvider: ({ baseUrl, authManager, queryClient, configOverrides, client: providedClient, fallback, children, }: AvroQueryClientProviderProps) => React.JSX.Element;
|
|
14
15
|
export declare const useAvroQueryClient: () => AvroQueryClient;
|
|
15
16
|
export declare const useSocketEvent: (eventName: string, callback: (data: Record<string, unknown>) => void) => void;
|
|
16
17
|
export default AvroQueryClientProvider;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import React, { createContext, useContext, useMemo, useEffect, useRef, useCallback, } from 'react';
|
|
1
|
+
import React, { createContext, useContext, useMemo, useEffect, useRef, useCallback, useState, } from 'react';
|
|
2
2
|
import { AvroQueryClient } from './QueryClient';
|
|
3
3
|
const AvroQueryClientContext = createContext(null);
|
|
4
|
-
export const AvroQueryClientProvider = ({ baseUrl, authManager, queryClient, configOverrides, client: providedClient, children, }) => {
|
|
4
|
+
export const AvroQueryClientProvider = ({ baseUrl, authManager, queryClient, configOverrides, client: providedClient, fallback = null, children, }) => {
|
|
5
5
|
const client = useMemo(() => {
|
|
6
6
|
if (providedClient)
|
|
7
7
|
return providedClient;
|
|
@@ -12,6 +12,18 @@ export const AvroQueryClientProvider = ({ baseUrl, authManager, queryClient, con
|
|
|
12
12
|
};
|
|
13
13
|
return new AvroQueryClient(cfg);
|
|
14
14
|
}, [providedClient, baseUrl, authManager, configOverrides]);
|
|
15
|
+
const [restored, setRestored] = useState(false);
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
let cancelled = false;
|
|
18
|
+
setRestored(false);
|
|
19
|
+
client.enablePersistence(queryClient).then(() => {
|
|
20
|
+
if (!cancelled)
|
|
21
|
+
setRestored(true);
|
|
22
|
+
});
|
|
23
|
+
return () => {
|
|
24
|
+
cancelled = true;
|
|
25
|
+
};
|
|
26
|
+
}, [client, queryClient]);
|
|
15
27
|
useEffect(() => {
|
|
16
28
|
if (queryClient) {
|
|
17
29
|
client.setupSocketInvalidation(queryClient);
|
|
@@ -25,7 +37,22 @@ export const AvroQueryClientProvider = ({ baseUrl, authManager, queryClient, con
|
|
|
25
37
|
}
|
|
26
38
|
};
|
|
27
39
|
}, [client, queryClient]);
|
|
28
|
-
|
|
40
|
+
// Write pending persisted queries before the page goes away.
|
|
41
|
+
useEffect(() => {
|
|
42
|
+
if (typeof document === 'undefined' || typeof window === 'undefined')
|
|
43
|
+
return;
|
|
44
|
+
const flush = () => {
|
|
45
|
+
if (document.visibilityState === 'hidden')
|
|
46
|
+
void client.flushPersistence();
|
|
47
|
+
};
|
|
48
|
+
document.addEventListener('visibilitychange', flush);
|
|
49
|
+
window.addEventListener('pagehide', flush);
|
|
50
|
+
return () => {
|
|
51
|
+
document.removeEventListener('visibilitychange', flush);
|
|
52
|
+
window.removeEventListener('pagehide', flush);
|
|
53
|
+
};
|
|
54
|
+
}, [client]);
|
|
55
|
+
return (React.createElement(AvroQueryClientContext.Provider, { value: client }, restored ? children : fallback));
|
|
29
56
|
};
|
|
30
57
|
export const useAvroQueryClient = () => {
|
|
31
58
|
const ctx = useContext(AvroQueryClientContext);
|
|
@@ -9,6 +9,7 @@ import { CacheData } from '../types/cache';
|
|
|
9
9
|
import { Waiver } from '../types/api/Waiver';
|
|
10
10
|
import type { EmailSucceededPayload, EmailFailedPayload, EmailType } from '../types/api/EmailNotification';
|
|
11
11
|
import type { BulkDeleteBillsResponse, BulkEmailBillsResponse } from '../client/hooks/bills';
|
|
12
|
+
import { type QueryPersistOptions } from '../client/persist';
|
|
12
13
|
export interface TrackEmailOptions {
|
|
13
14
|
emailType?: EmailType;
|
|
14
15
|
requestId?: string;
|
|
@@ -26,6 +27,8 @@ export interface AvroQueryClientConfig {
|
|
|
26
27
|
clientId?: ClientId;
|
|
27
28
|
clientVersion?: string;
|
|
28
29
|
device?: DeviceInfo;
|
|
30
|
+
/** Keep large query namespaces on-device across reloads (see persist.ts). */
|
|
31
|
+
persistence?: QueryPersistOptions;
|
|
29
32
|
}
|
|
30
33
|
declare module '../client/QueryClient' {
|
|
31
34
|
interface AvroQueryClient {
|
|
@@ -43,6 +46,7 @@ declare module '../client/QueryClient' {
|
|
|
43
46
|
onProgress?: (fraction: number) => void;
|
|
44
47
|
}): UseQueryResult<Job[], StandardError>;
|
|
45
48
|
getJobsFromCache(queryClient?: QueryClient): Job[];
|
|
49
|
+
syncJobs(previous: Job[], companyId?: string, onProgress?: (fraction: number) => void): Promise<Job[]>;
|
|
46
50
|
useGetInfiniteJobs(body: {
|
|
47
51
|
amt?: number;
|
|
48
52
|
query?: string;
|
|
@@ -679,7 +683,7 @@ declare module '../client/QueryClient' {
|
|
|
679
683
|
}
|
|
680
684
|
}
|
|
681
685
|
export declare class AvroQueryClient {
|
|
682
|
-
protected config: Required<Omit<AvroQueryClientConfig, 'clientId' | 'clientVersion' | 'device'>> & Pick<AvroQueryClientConfig, 'clientId' | 'clientVersion' | 'device'>;
|
|
686
|
+
protected config: Required<Omit<AvroQueryClientConfig, 'clientId' | 'clientVersion' | 'device' | 'persistence'>> & Pick<AvroQueryClientConfig, 'clientId' | 'clientVersion' | 'device' | 'persistence'>;
|
|
683
687
|
readonly socket: Socket;
|
|
684
688
|
_authState: AuthState;
|
|
685
689
|
companyId: string | undefined;
|
|
@@ -689,6 +693,8 @@ export declare class AvroQueryClient {
|
|
|
689
693
|
private _socketInvalidationCleanup;
|
|
690
694
|
private _applier;
|
|
691
695
|
private _companyVersions;
|
|
696
|
+
private _persister;
|
|
697
|
+
private _restored;
|
|
692
698
|
private _emailTracking;
|
|
693
699
|
private _emailListenersInit;
|
|
694
700
|
constructor(config: AvroQueryClientConfig);
|
|
@@ -787,6 +793,17 @@ export declare class AvroQueryClient {
|
|
|
787
793
|
getAuthStateAsync(): Promise<AuthState>;
|
|
788
794
|
getQueryClient(): QueryClient;
|
|
789
795
|
attachQueryClient(queryClient: QueryClient): void;
|
|
796
|
+
/**
|
|
797
|
+
* Hydrate `queryClient` from the configured store and keep it
|
|
798
|
+
* written back. Resolves once restored; mount data-bearing UI after
|
|
799
|
+
* it so the first render sees the persisted cache rather than
|
|
800
|
+
* kicking off a full download. No-op without `config.persistence`.
|
|
801
|
+
*/
|
|
802
|
+
enablePersistence(queryClient: QueryClient): Promise<void>;
|
|
803
|
+
/** Report the backend version seen on `GET /`; a change busts the persisted cache. */
|
|
804
|
+
noteApiVersion(version: string | undefined): void;
|
|
805
|
+
/** Write any pending persisted queries now (e.g. on page hide). */
|
|
806
|
+
flushPersistence(): Promise<void>;
|
|
790
807
|
peekQueryClient(): QueryClient | null;
|
|
791
808
|
/**
|
|
792
809
|
* Drop all local auth state without a server round-trip: stored
|
|
@@ -803,6 +820,8 @@ export declare class AvroQueryClient {
|
|
|
803
820
|
query?: string;
|
|
804
821
|
offset?: number;
|
|
805
822
|
route_id?: string;
|
|
823
|
+
/** Return `{id, v}` pairs only — the index `syncJobs` diffs against. */
|
|
824
|
+
ids_only?: boolean;
|
|
806
825
|
}, companyId?: string, cancelToken?: CancelToken, headers?: Record<string, string>): Promise<any>;
|
|
807
826
|
autocompleteAddress({ address, size, include_census, }: {
|
|
808
827
|
address: string;
|
|
@@ -5,7 +5,8 @@ import { fetchCensusFeatures } from '../census';
|
|
|
5
5
|
import { LoginResponse, } from '../types/api';
|
|
6
6
|
import { AuthState } from '../types/auth';
|
|
7
7
|
import { StandardError } from '../types/error';
|
|
8
|
-
import { ChangeApplier, fallbackInvalidate, patchMemberLocation, patchTeamLocation, } from '../client/realtime';
|
|
8
|
+
import { ChangeApplier, fallbackInvalidate, patchMember, patchMemberLocation, patchTeamLocation, } from '../client/realtime';
|
|
9
|
+
import { QueryPersister } from '../client/persist';
|
|
9
10
|
export class AvroQueryClient {
|
|
10
11
|
constructor(config) {
|
|
11
12
|
this._authState = AuthState.UNKNOWN;
|
|
@@ -16,6 +17,8 @@ export class AvroQueryClient {
|
|
|
16
17
|
this._socketInvalidationCleanup = null;
|
|
17
18
|
this._applier = null;
|
|
18
19
|
this._companyVersions = new Map();
|
|
20
|
+
this._persister = null;
|
|
21
|
+
this._restored = null;
|
|
19
22
|
this._emailTracking = new Map();
|
|
20
23
|
this._emailListenersInit = false;
|
|
21
24
|
this.config = {
|
|
@@ -27,6 +30,7 @@ export class AvroQueryClient {
|
|
|
27
30
|
clientId: config.clientId,
|
|
28
31
|
clientVersion: config.clientVersion,
|
|
29
32
|
device: config.device,
|
|
33
|
+
persistence: config.persistence,
|
|
30
34
|
};
|
|
31
35
|
this.socket = io(config.baseUrl, {
|
|
32
36
|
autoConnect: false,
|
|
@@ -131,6 +135,7 @@ export class AvroQueryClient {
|
|
|
131
135
|
on('changes', (payload) => {
|
|
132
136
|
if (payload?.company && typeof payload.version === 'number') {
|
|
133
137
|
this._companyVersions.set(payload.company, payload.version);
|
|
138
|
+
this._persister?.setCompanyVersion(payload.company, payload.version);
|
|
134
139
|
}
|
|
135
140
|
applier.apply(payload);
|
|
136
141
|
});
|
|
@@ -138,8 +143,29 @@ export class AvroQueryClient {
|
|
|
138
143
|
if (data?.company_id && data.company_id === this.companyId)
|
|
139
144
|
this.joinCompanyRoom();
|
|
140
145
|
});
|
|
141
|
-
|
|
142
|
-
|
|
146
|
+
// Presence names the member that changed; fetch and patch that
|
|
147
|
+
// one instead of re-downloading every member for every client.
|
|
148
|
+
on('update_presence', (data) => {
|
|
149
|
+
const userId = data?.user_id;
|
|
150
|
+
if (!userId || !this.companyId) {
|
|
151
|
+
queryClient.invalidateQueries({ queryKey: ['users', 'company'] });
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
this.post({
|
|
155
|
+
path: `/company/${this.companyId}/users`,
|
|
156
|
+
data: JSON.stringify({ user_ids: [userId] }),
|
|
157
|
+
headers: { 'Content-Type': 'application/json' },
|
|
158
|
+
})
|
|
159
|
+
.then((members) => {
|
|
160
|
+
const member = Array.isArray(members) ? members[0] : undefined;
|
|
161
|
+
if (member)
|
|
162
|
+
patchMember(queryClient, member);
|
|
163
|
+
else
|
|
164
|
+
queryClient.invalidateQueries({ queryKey: ['users', 'company'] });
|
|
165
|
+
})
|
|
166
|
+
.catch(() => {
|
|
167
|
+
queryClient.invalidateQueries({ queryKey: ['users', 'company'] });
|
|
168
|
+
});
|
|
143
169
|
});
|
|
144
170
|
on('location_update', (data) => {
|
|
145
171
|
if (!data || typeof data.latitude !== 'number') {
|
|
@@ -189,6 +215,7 @@ export class AvroQueryClient {
|
|
|
189
215
|
return;
|
|
190
216
|
const known = this._companyVersions.get(companyId);
|
|
191
217
|
this._companyVersions.set(companyId, ack.version);
|
|
218
|
+
this._persister?.setCompanyVersion(companyId, ack.version);
|
|
192
219
|
if (known !== undefined && known !== ack.version) {
|
|
193
220
|
this._queryClient?.invalidateQueries();
|
|
194
221
|
}
|
|
@@ -442,6 +469,48 @@ export class AvroQueryClient {
|
|
|
442
469
|
attachQueryClient(queryClient) {
|
|
443
470
|
this._queryClient ?? (this._queryClient = queryClient);
|
|
444
471
|
}
|
|
472
|
+
/**
|
|
473
|
+
* Hydrate `queryClient` from the configured store and keep it
|
|
474
|
+
* written back. Resolves once restored; mount data-bearing UI after
|
|
475
|
+
* it so the first render sees the persisted cache rather than
|
|
476
|
+
* kicking off a full download. No-op without `config.persistence`.
|
|
477
|
+
*/
|
|
478
|
+
enablePersistence(queryClient) {
|
|
479
|
+
if (this._restored)
|
|
480
|
+
return this._restored;
|
|
481
|
+
const options = this.config.persistence;
|
|
482
|
+
if (!options) {
|
|
483
|
+
this._restored = Promise.resolve();
|
|
484
|
+
return this._restored;
|
|
485
|
+
}
|
|
486
|
+
const persister = new QueryPersister(queryClient, options);
|
|
487
|
+
this._persister = persister;
|
|
488
|
+
this._restored = persister
|
|
489
|
+
.restore()
|
|
490
|
+
.then(({ companyVersions }) => {
|
|
491
|
+
for (const [companyId, version] of Object.entries(companyVersions)) {
|
|
492
|
+
// Seed the comparison so a room ack whose version
|
|
493
|
+
// moved while we were away triggers a (cheap) resync.
|
|
494
|
+
if (!this._companyVersions.has(companyId)) {
|
|
495
|
+
this._companyVersions.set(companyId, version);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
})
|
|
499
|
+
.catch((err) => {
|
|
500
|
+
console.warn('Query cache restore failed:', err);
|
|
501
|
+
})
|
|
502
|
+
.then(() => persister.start());
|
|
503
|
+
return this._restored;
|
|
504
|
+
}
|
|
505
|
+
/** Report the backend version seen on `GET /`; a change busts the persisted cache. */
|
|
506
|
+
noteApiVersion(version) {
|
|
507
|
+
if (version)
|
|
508
|
+
this._persister?.setApiVersion(version);
|
|
509
|
+
}
|
|
510
|
+
/** Write any pending persisted queries now (e.g. on page hide). */
|
|
511
|
+
flushPersistence() {
|
|
512
|
+
return this._persister?.flush() ?? Promise.resolve();
|
|
513
|
+
}
|
|
445
514
|
peekQueryClient() {
|
|
446
515
|
return this._queryClient;
|
|
447
516
|
}
|
|
@@ -453,6 +522,7 @@ export class AvroQueryClient {
|
|
|
453
522
|
*/
|
|
454
523
|
async forceLogout() {
|
|
455
524
|
await this.clearCache();
|
|
525
|
+
await this._persister?.clear();
|
|
456
526
|
this.setAuthState(AuthState.UNAUTHENTICATED);
|
|
457
527
|
if (this.socket && this.socket.connected) {
|
|
458
528
|
this.socket.disconnect();
|
|
@@ -1,49 +1,63 @@
|
|
|
1
1
|
import { useMutation, useQuery, useInfiniteQuery } from '@tanstack/react-query';
|
|
2
2
|
import { AvroQueryClient } from '../../client/QueryClient';
|
|
3
|
-
import { keys } from '../../client/realtime';
|
|
3
|
+
import { keys, constructJob } from '../../client/realtime';
|
|
4
4
|
import { Job } from '../../types/api';
|
|
5
5
|
AvroQueryClient.prototype.getJobsFromCache = function (queryClient) {
|
|
6
6
|
const client = queryClient ?? this.peekQueryClient();
|
|
7
7
|
if (!client) {
|
|
8
8
|
return [];
|
|
9
9
|
}
|
|
10
|
-
return client.getQueryData(
|
|
10
|
+
return client.getQueryData(keys.list('jobs', this.companyId)) ?? [];
|
|
11
|
+
};
|
|
12
|
+
const JOBS_SYNC_CHUNK = 50;
|
|
13
|
+
const JOBS_SYNC_CONCURRENCY = 3;
|
|
14
|
+
async function runLimited(items, limit, worker) {
|
|
15
|
+
let next = 0;
|
|
16
|
+
const lanes = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
17
|
+
while (next < items.length) {
|
|
18
|
+
const item = items[next++];
|
|
19
|
+
await worker(item);
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
await Promise.all(lanes);
|
|
23
|
+
}
|
|
24
|
+
AvroQueryClient.prototype.syncJobs = async function (previous, companyId, onProgress) {
|
|
25
|
+
const index = await this.fetchJobs({ ids_only: true }, companyId);
|
|
26
|
+
const known = new Map(previous.map((job) => [job.id, job]));
|
|
27
|
+
const stale = index
|
|
28
|
+
.filter((entry) => known.get(entry.id)?.cache_version !== entry.v)
|
|
29
|
+
.map((entry) => entry.id);
|
|
30
|
+
const chunks = [];
|
|
31
|
+
for (let i = 0; i < stale.length; i += JOBS_SYNC_CHUNK) {
|
|
32
|
+
chunks.push(stale.slice(i, i + JOBS_SYNC_CHUNK));
|
|
33
|
+
}
|
|
34
|
+
const fetched = new Map();
|
|
35
|
+
let completed = 0;
|
|
36
|
+
await runLimited(chunks, JOBS_SYNC_CONCURRENCY, async (ids) => {
|
|
37
|
+
const page = await this.fetchJobs({ unknown_ids: ids, amt: ids.length }, companyId);
|
|
38
|
+
for (const raw of page) {
|
|
39
|
+
const job = constructJob(raw);
|
|
40
|
+
fetched.set(job.id, job);
|
|
41
|
+
}
|
|
42
|
+
completed++;
|
|
43
|
+
onProgress?.(completed / chunks.length);
|
|
44
|
+
});
|
|
45
|
+
onProgress?.(1);
|
|
46
|
+
return index
|
|
47
|
+
.map((entry) => fetched.get(entry.id) ?? known.get(entry.id))
|
|
48
|
+
.filter((job) => Boolean(job));
|
|
11
49
|
};
|
|
12
50
|
AvroQueryClient.prototype.useGetJobs = function (params) {
|
|
13
51
|
const queryClient = this.getQueryClient();
|
|
14
|
-
const amt = 50;
|
|
15
52
|
const company_id = params?.companyId ?? this.companyId;
|
|
16
|
-
const
|
|
53
|
+
const queryKey = keys.list('jobs', company_id);
|
|
17
54
|
return useQuery({
|
|
18
|
-
queryKey
|
|
55
|
+
queryKey,
|
|
19
56
|
queryFn: async () => {
|
|
20
57
|
params?.onProgress?.(0);
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const trackedPromises = promises.map((promise) => promise.then((result) => {
|
|
25
|
-
completed++;
|
|
26
|
-
const fraction = completed / pageCount;
|
|
27
|
-
params?.onProgress?.(fraction);
|
|
28
|
-
return result;
|
|
29
|
-
}));
|
|
30
|
-
const pages = await Promise.all(trackedPromises);
|
|
31
|
-
const jobs = pages.flat().map((job) => new Job(job));
|
|
32
|
-
jobs.forEach((job) => {
|
|
33
|
-
job.current_event = job.tasks.reduce((latest, task) => {
|
|
34
|
-
return task.current_event &&
|
|
35
|
-
(!latest || task.current_event.time_started > latest.time_started)
|
|
36
|
-
? task.current_event
|
|
37
|
-
: latest;
|
|
38
|
-
}, job.current_event);
|
|
39
|
-
job.last_completed_event = job.tasks.reduce((latest, task) => {
|
|
40
|
-
return task.last_completed_event &&
|
|
41
|
-
(!latest || task.last_completed_event.time_started > latest.time_started)
|
|
42
|
-
? task.last_completed_event
|
|
43
|
-
: latest;
|
|
44
|
-
}, job.last_completed_event);
|
|
45
|
-
queryClient.setQueryData(['jobs', job.id], job);
|
|
46
|
-
});
|
|
58
|
+
const previous = queryClient.getQueryData(queryKey) ?? [];
|
|
59
|
+
const jobs = await this.syncJobs(previous, company_id, params?.onProgress);
|
|
60
|
+
jobs.forEach((job) => queryClient.setQueryData(['jobs', job.id], job));
|
|
47
61
|
return jobs;
|
|
48
62
|
},
|
|
49
63
|
enabled: Boolean(company_id),
|
|
@@ -3,6 +3,10 @@ import { AvroQueryClient } from '../../client/QueryClient';
|
|
|
3
3
|
AvroQueryClient.prototype.useGetRoot = function () {
|
|
4
4
|
return useQuery({
|
|
5
5
|
queryKey: ['health'],
|
|
6
|
-
queryFn: () =>
|
|
6
|
+
queryFn: async () => {
|
|
7
|
+
const info = await this.get({ path: '/' });
|
|
8
|
+
this.noteApiVersion(info?.app_semver);
|
|
9
|
+
return info;
|
|
10
|
+
},
|
|
7
11
|
});
|
|
8
12
|
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { QueryClient } from '@tanstack/react-query';
|
|
2
|
+
export interface KeyValueStore {
|
|
3
|
+
getItem(key: string): Promise<string | null>;
|
|
4
|
+
setItem(key: string, value: string): Promise<void>;
|
|
5
|
+
removeItem(key: string): Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export declare class MemoryKeyValueStore implements KeyValueStore {
|
|
8
|
+
private data;
|
|
9
|
+
getItem(key: string): Promise<string | null>;
|
|
10
|
+
setItem(key: string, value: string): Promise<void>;
|
|
11
|
+
removeItem(key: string): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
/** A minimal IndexedDB key-value store for browsers. */
|
|
14
|
+
export declare class IndexedDBStore implements KeyValueStore {
|
|
15
|
+
private readonly dbName;
|
|
16
|
+
private readonly storeName;
|
|
17
|
+
private dbPromise;
|
|
18
|
+
constructor(dbName?: string, storeName?: string);
|
|
19
|
+
static isSupported(): boolean;
|
|
20
|
+
private open;
|
|
21
|
+
private run;
|
|
22
|
+
getItem(key: string): Promise<string | null>;
|
|
23
|
+
setItem(key: string, value: string): Promise<void>;
|
|
24
|
+
removeItem(key: string): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
/** Pick the best store the runtime offers: IndexedDB, else memory. */
|
|
27
|
+
export declare function defaultKeyValueStore(): KeyValueStore;
|
|
28
|
+
/** Namespaces worth keeping across reloads: big, or needed at boot. */
|
|
29
|
+
export declare const PERSISTED_NAMESPACES: readonly string[];
|
|
30
|
+
export interface QueryPersistOptions {
|
|
31
|
+
store: KeyValueStore;
|
|
32
|
+
key?: string;
|
|
33
|
+
maxAgeMs?: number;
|
|
34
|
+
buster?: string;
|
|
35
|
+
namespaces?: readonly string[];
|
|
36
|
+
throttleMs?: number;
|
|
37
|
+
}
|
|
38
|
+
export interface RestoredMeta {
|
|
39
|
+
companyVersions: Record<string, number>;
|
|
40
|
+
}
|
|
41
|
+
export declare class QueryPersister {
|
|
42
|
+
private readonly qc;
|
|
43
|
+
private readonly opts;
|
|
44
|
+
private readonly key;
|
|
45
|
+
private readonly maxAgeMs;
|
|
46
|
+
private readonly buster;
|
|
47
|
+
private readonly namespaces;
|
|
48
|
+
private readonly throttleMs;
|
|
49
|
+
private timer;
|
|
50
|
+
private unsubscribe;
|
|
51
|
+
private saving;
|
|
52
|
+
private companyVersions;
|
|
53
|
+
private apiVersion;
|
|
54
|
+
constructor(qc: QueryClient, opts: QueryPersistOptions);
|
|
55
|
+
private persisted;
|
|
56
|
+
/** Load the stored cache into the QueryClient. Safe to call once, at boot. */
|
|
57
|
+
restore(): Promise<RestoredMeta>;
|
|
58
|
+
/** Watch the cache and write persisted namespaces after they settle. */
|
|
59
|
+
start(): void;
|
|
60
|
+
stop(): void;
|
|
61
|
+
setApiVersion(version: string): void;
|
|
62
|
+
/** Remember the last realtime version seen per company. */
|
|
63
|
+
setCompanyVersion(companyId: string, version: number): void;
|
|
64
|
+
private schedule;
|
|
65
|
+
/** Write now (e.g. when the page is being hidden). */
|
|
66
|
+
flush(): Promise<void>;
|
|
67
|
+
private save;
|
|
68
|
+
/** Forget everything stored (logout). */
|
|
69
|
+
clear(): Promise<void>;
|
|
70
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { dehydrate, hydrate } from '@tanstack/react-query';
|
|
2
|
+
import { constructJob } from '../client/realtime';
|
|
3
|
+
import { Route } from '../types/api/Route';
|
|
4
|
+
export class MemoryKeyValueStore {
|
|
5
|
+
constructor() {
|
|
6
|
+
this.data = new Map();
|
|
7
|
+
}
|
|
8
|
+
async getItem(key) {
|
|
9
|
+
return this.data.get(key) ?? null;
|
|
10
|
+
}
|
|
11
|
+
async setItem(key, value) {
|
|
12
|
+
this.data.set(key, value);
|
|
13
|
+
}
|
|
14
|
+
async removeItem(key) {
|
|
15
|
+
this.data.delete(key);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** A minimal IndexedDB key-value store for browsers. */
|
|
19
|
+
export class IndexedDBStore {
|
|
20
|
+
constructor(dbName = 'avro-query-cache', storeName = 'kv') {
|
|
21
|
+
this.dbName = dbName;
|
|
22
|
+
this.storeName = storeName;
|
|
23
|
+
this.dbPromise = null;
|
|
24
|
+
}
|
|
25
|
+
static isSupported() {
|
|
26
|
+
return typeof indexedDB !== 'undefined';
|
|
27
|
+
}
|
|
28
|
+
open() {
|
|
29
|
+
if (!this.dbPromise) {
|
|
30
|
+
this.dbPromise = new Promise((resolve, reject) => {
|
|
31
|
+
const request = indexedDB.open(this.dbName, 1);
|
|
32
|
+
request.onupgradeneeded = () => {
|
|
33
|
+
request.result.createObjectStore(this.storeName);
|
|
34
|
+
};
|
|
35
|
+
request.onsuccess = () => resolve(request.result);
|
|
36
|
+
request.onerror = () => reject(request.error);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return this.dbPromise;
|
|
40
|
+
}
|
|
41
|
+
async run(mode, op) {
|
|
42
|
+
const db = await this.open();
|
|
43
|
+
return new Promise((resolve, reject) => {
|
|
44
|
+
const tx = db.transaction(this.storeName, mode);
|
|
45
|
+
const request = op(tx.objectStore(this.storeName));
|
|
46
|
+
request.onsuccess = () => resolve(request.result);
|
|
47
|
+
request.onerror = () => reject(request.error);
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
async getItem(key) {
|
|
51
|
+
const value = await this.run('readonly', (s) => s.get(key));
|
|
52
|
+
return typeof value === 'string' ? value : null;
|
|
53
|
+
}
|
|
54
|
+
async setItem(key, value) {
|
|
55
|
+
await this.run('readwrite', (s) => s.put(value, key));
|
|
56
|
+
}
|
|
57
|
+
async removeItem(key) {
|
|
58
|
+
await this.run('readwrite', (s) => s.delete(key));
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Pick the best store the runtime offers: IndexedDB, else memory. */
|
|
62
|
+
export function defaultKeyValueStore() {
|
|
63
|
+
return IndexedDBStore.isSupported() ? new IndexedDBStore() : new MemoryKeyValueStore();
|
|
64
|
+
}
|
|
65
|
+
/** Namespaces worth keeping across reloads: big, or needed at boot. */
|
|
66
|
+
export const PERSISTED_NAMESPACES = ['jobs', 'routes', 'users', 'teams'];
|
|
67
|
+
/** JSON loses class instances; restore the ones hooks hand out. */
|
|
68
|
+
const REVIVERS = {
|
|
69
|
+
jobs: (data) => (Array.isArray(data) ? data.map((raw) => constructJob(raw)) : data),
|
|
70
|
+
routes: (data) => (Array.isArray(data) ? data.map((raw) => new Route(raw)) : data),
|
|
71
|
+
};
|
|
72
|
+
export class QueryPersister {
|
|
73
|
+
constructor(qc, opts) {
|
|
74
|
+
this.qc = qc;
|
|
75
|
+
this.opts = opts;
|
|
76
|
+
this.timer = null;
|
|
77
|
+
this.unsubscribe = null;
|
|
78
|
+
this.saving = Promise.resolve();
|
|
79
|
+
this.companyVersions = {};
|
|
80
|
+
this.apiVersion = null;
|
|
81
|
+
this.key = opts.key ?? 'avro-query-cache';
|
|
82
|
+
this.maxAgeMs = opts.maxAgeMs ?? 7 * 24 * 60 * 60 * 1000;
|
|
83
|
+
this.buster = opts.buster ?? '';
|
|
84
|
+
this.namespaces = opts.namespaces ?? PERSISTED_NAMESPACES;
|
|
85
|
+
this.throttleMs = opts.throttleMs ?? 2000;
|
|
86
|
+
}
|
|
87
|
+
persisted(queryKey) {
|
|
88
|
+
return typeof queryKey[0] === 'string' && this.namespaces.includes(queryKey[0]);
|
|
89
|
+
}
|
|
90
|
+
/** Load the stored cache into the QueryClient. Safe to call once, at boot. */
|
|
91
|
+
async restore() {
|
|
92
|
+
let envelope = null;
|
|
93
|
+
try {
|
|
94
|
+
const raw = await this.opts.store.getItem(this.key);
|
|
95
|
+
envelope = raw ? JSON.parse(raw) : null;
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
console.warn('Query cache restore failed:', err);
|
|
99
|
+
}
|
|
100
|
+
if (!envelope ||
|
|
101
|
+
envelope.buster !== this.buster ||
|
|
102
|
+
typeof envelope.savedAt !== 'number' ||
|
|
103
|
+
Date.now() - envelope.savedAt > this.maxAgeMs ||
|
|
104
|
+
!envelope.state?.queries) {
|
|
105
|
+
if (envelope)
|
|
106
|
+
await this.clear();
|
|
107
|
+
return { companyVersions: {} };
|
|
108
|
+
}
|
|
109
|
+
for (const query of envelope.state.queries) {
|
|
110
|
+
const ns = query.queryKey[0];
|
|
111
|
+
const revive = typeof ns === 'string' ? REVIVERS[ns] : undefined;
|
|
112
|
+
if (revive && query.state.data !== undefined) {
|
|
113
|
+
query.state.data = revive(query.state.data);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
hydrate(this.qc, envelope.state);
|
|
117
|
+
this.companyVersions = envelope.companyVersions ?? {};
|
|
118
|
+
this.apiVersion = envelope.apiVersion ?? null;
|
|
119
|
+
return { companyVersions: { ...this.companyVersions } };
|
|
120
|
+
}
|
|
121
|
+
/** Watch the cache and write persisted namespaces after they settle. */
|
|
122
|
+
start() {
|
|
123
|
+
if (this.unsubscribe)
|
|
124
|
+
return;
|
|
125
|
+
this.unsubscribe = this.qc.getQueryCache().subscribe((event) => {
|
|
126
|
+
if (!event?.query || !this.persisted(event.query.queryKey))
|
|
127
|
+
return;
|
|
128
|
+
if (event.type === 'removed') {
|
|
129
|
+
this.schedule();
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (event.type === 'updated' && event.action.type === 'success')
|
|
133
|
+
this.schedule();
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
stop() {
|
|
137
|
+
this.unsubscribe?.();
|
|
138
|
+
this.unsubscribe = null;
|
|
139
|
+
if (this.timer) {
|
|
140
|
+
clearTimeout(this.timer);
|
|
141
|
+
this.timer = null;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
setApiVersion(version) {
|
|
145
|
+
if (!version || this.apiVersion === version)
|
|
146
|
+
return;
|
|
147
|
+
const previous = this.apiVersion;
|
|
148
|
+
this.apiVersion = version;
|
|
149
|
+
if (previous === null) {
|
|
150
|
+
this.schedule();
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
this.companyVersions = {};
|
|
154
|
+
void this.qc.resetQueries({
|
|
155
|
+
predicate: (query) => this.persisted(query.queryKey),
|
|
156
|
+
});
|
|
157
|
+
this.schedule();
|
|
158
|
+
}
|
|
159
|
+
/** Remember the last realtime version seen per company. */
|
|
160
|
+
setCompanyVersion(companyId, version) {
|
|
161
|
+
if (this.companyVersions[companyId] === version)
|
|
162
|
+
return;
|
|
163
|
+
this.companyVersions[companyId] = version;
|
|
164
|
+
this.schedule();
|
|
165
|
+
}
|
|
166
|
+
schedule() {
|
|
167
|
+
if (this.timer)
|
|
168
|
+
return;
|
|
169
|
+
this.timer = setTimeout(() => {
|
|
170
|
+
this.timer = null;
|
|
171
|
+
void this.flush();
|
|
172
|
+
}, this.throttleMs);
|
|
173
|
+
}
|
|
174
|
+
/** Write now (e.g. when the page is being hidden). */
|
|
175
|
+
flush() {
|
|
176
|
+
this.saving = this.saving.then(() => this.save()).catch(() => undefined);
|
|
177
|
+
return this.saving;
|
|
178
|
+
}
|
|
179
|
+
async save() {
|
|
180
|
+
const state = dehydrate(this.qc, {
|
|
181
|
+
shouldDehydrateQuery: (query) => query.state.status === 'success' && this.persisted(query.queryKey),
|
|
182
|
+
});
|
|
183
|
+
const envelope = {
|
|
184
|
+
buster: this.buster,
|
|
185
|
+
apiVersion: this.apiVersion,
|
|
186
|
+
savedAt: Date.now(),
|
|
187
|
+
companyVersions: this.companyVersions,
|
|
188
|
+
state,
|
|
189
|
+
};
|
|
190
|
+
try {
|
|
191
|
+
await this.opts.store.setItem(this.key, JSON.stringify(envelope));
|
|
192
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
console.warn('Query cache save failed:', err);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/** Forget everything stored (logout). */
|
|
198
|
+
async clear() {
|
|
199
|
+
if (this.timer) {
|
|
200
|
+
clearTimeout(this.timer);
|
|
201
|
+
this.timer = null;
|
|
202
|
+
}
|
|
203
|
+
this.companyVersions = {};
|
|
204
|
+
this.apiVersion = null;
|
|
205
|
+
try {
|
|
206
|
+
await this.opts.store.removeItem(this.key);
|
|
207
|
+
}
|
|
208
|
+
catch (err) {
|
|
209
|
+
console.warn('Query cache clear failed:', err);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
@@ -63,4 +63,5 @@ export declare class ChangeApplier {
|
|
|
63
63
|
/** Namespaces a mutation should refetch when no socket can deliver the change. */
|
|
64
64
|
export declare function fallbackInvalidate(qc: QueryClient, types: string[]): void;
|
|
65
65
|
export declare function patchMemberLocation(qc: QueryClient, data: Record<string, any>): void;
|
|
66
|
+
export declare function patchMember(qc: QueryClient, member: any): void;
|
|
66
67
|
export declare function patchTeamLocation(qc: QueryClient, data: Record<string, any>): void;
|
package/dist/client/realtime.js
CHANGED
|
@@ -459,6 +459,23 @@ export function patchMemberLocation(qc, data) {
|
|
|
459
459
|
return changed ? next : old;
|
|
460
460
|
});
|
|
461
461
|
}
|
|
462
|
+
export function patchMember(qc, member) {
|
|
463
|
+
const userId = member?.user?.id;
|
|
464
|
+
if (!userId || typeof userId !== 'string')
|
|
465
|
+
return;
|
|
466
|
+
qc.setQueriesData({ queryKey: ['users', 'company'] }, (old) => {
|
|
467
|
+
if (!Array.isArray(old))
|
|
468
|
+
return old;
|
|
469
|
+
let changed = false;
|
|
470
|
+
const next = old.map((u) => {
|
|
471
|
+
if (u?.user?.id !== userId)
|
|
472
|
+
return u;
|
|
473
|
+
changed = true;
|
|
474
|
+
return member;
|
|
475
|
+
});
|
|
476
|
+
return changed ? next : old;
|
|
477
|
+
});
|
|
478
|
+
}
|
|
462
479
|
export function patchTeamLocation(qc, data) {
|
|
463
480
|
const teamId = data?.team_id;
|
|
464
481
|
if (!teamId || typeof teamId !== 'string')
|
package/dist/index.d.ts
CHANGED
|
@@ -5,6 +5,8 @@ export type { EmailResult, EmailResultStatus, UseEmailStatusOptions } from './cl
|
|
|
5
5
|
export type { BulkBillError, BulkDeleteBillsResponse, BulkEmailBillsResponse, } from './client/hooks/bills';
|
|
6
6
|
export { AuthManager } from './auth/AuthManager';
|
|
7
7
|
export { MemoryStorage, LocalStorage } from './auth/storage';
|
|
8
|
+
export { QueryPersister, IndexedDBStore, MemoryKeyValueStore, defaultKeyValueStore, PERSISTED_NAMESPACES, } from './client/persist';
|
|
9
|
+
export type { KeyValueStore, QueryPersistOptions } from './client/persist';
|
|
8
10
|
import './client/core/xhr';
|
|
9
11
|
import './client/core/fetch';
|
|
10
12
|
import './client/core/utils';
|
package/dist/index.js
CHANGED
|
@@ -3,6 +3,7 @@ export { AvroQueryClientProvider, useAvroQueryClient, useSocketEvent, } from './
|
|
|
3
3
|
export { useEmailStatus } from './client/hooks/email';
|
|
4
4
|
export { AuthManager } from './auth/AuthManager';
|
|
5
5
|
export { MemoryStorage, LocalStorage } from './auth/storage';
|
|
6
|
+
export { QueryPersister, IndexedDBStore, MemoryKeyValueStore, defaultKeyValueStore, PERSISTED_NAMESPACES, } from './client/persist';
|
|
6
7
|
import './client/core/xhr';
|
|
7
8
|
import './client/core/fetch';
|
|
8
9
|
import './client/core/utils';
|
package/dist/types/api/Job.d.ts
CHANGED
|
@@ -29,6 +29,7 @@ declare module '../../types/api/Job' {
|
|
|
29
29
|
current_checkins: CheckIn[];
|
|
30
30
|
labels: string[];
|
|
31
31
|
owner: string | null;
|
|
32
|
+
cache_version?: string;
|
|
32
33
|
}
|
|
33
34
|
}
|
|
34
35
|
export type JobUpdate = Partial<Omit<Job, 'subscribers'>> & {
|
|
@@ -39,7 +40,7 @@ export declare class Job {
|
|
|
39
40
|
isOverdue: () => boolean;
|
|
40
41
|
getOverdueLabel: () => string;
|
|
41
42
|
getStatus(): "PENDING_CUSTOMER" | "PENDING_COMPANY" | "ACTIVE" | "ARCHIVED" | "DRAFT" | "PENDING_PAYMENT" | "PENDING_ACTIVATION";
|
|
42
|
-
getStatusLabel(): "Active" | "
|
|
43
|
+
getStatusLabel(): "Active" | "Draft" | "Archived" | "Pending Activation" | "Customer Approval" | "Company Approval" | "Awaiting Payment";
|
|
43
44
|
/**
|
|
44
45
|
* Returns the sum of `service` (in seconds) for the tasks attached to a
|
|
45
46
|
* given routeJob. Use this to compute predicted completion time:
|
package/dist/types/api/Task.d.ts
CHANGED
|
@@ -68,7 +68,7 @@ declare module '../../types/api/Task' {
|
|
|
68
68
|
}
|
|
69
69
|
export declare class Task {
|
|
70
70
|
constructor(init?: Partial<Task>);
|
|
71
|
-
getStatusLabel: () => "Active" | "
|
|
71
|
+
getStatusLabel: () => "Active" | "Draft" | "Archived" | "Pending Customer Approval" | "Pending Company Approval" | "Pending Payment" | "Pending Activation";
|
|
72
72
|
getUnroutedReasonLabel: () => string | null;
|
|
73
73
|
isOverdue: () => boolean;
|
|
74
74
|
getOverdueLabel: () => string;
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const AVRO_JS_VERSION = "0.1.
|
|
1
|
+
export declare const AVRO_JS_VERSION = "0.1.4";
|
package/dist/version.js
CHANGED