Open History to see the last commit
1import { dehydrate, hydrate } from '@tanstack/query-core'
2import { BroadcastChannel } from 'broadcast-channel'
3import type {
4 DehydrateOptions,
5 DehydratedState,
6 HydrateOptions,
7 QueryClient,
8 QueryKey,
9 QueryState,
10} from '@tanstack/query-core'
11import type { BroadcastChannelOptions } from 'broadcast-channel'
12β
13/**
14 * Metadata describing a broadcast that failed to be delivered to other tabs.
15 * Passed to BroadcastQueryClientOptions.onBroadcastError so callers can
16 * correlate failures with the originating query.
17 */
18export interface BroadcastErrorEvent {
19 type: 'updated' | 'removed' | 'added'
20 queryHash: string
21 queryKey: QueryKey
22}
23β
24/**
25 * Metadata describing a bootstrap request, response, or hydration failure.
26 */
27export interface BroadcastRestoreErrorEvent {
28 type: 'request' | 'response' | 'hydrate'
29 requestId: string
30 responderId?: string
31 responseId?: string
32 queryHash?: string
33 queryKey?: QueryKey
34}
35β
36type LiveBroadcastMessage =
37 | {
38 type: 'updated'
39 queryHash: string
40 queryKey: QueryKey
41 state: QueryState
42 }
43 | { type: 'removed'; queryHash: string; queryKey: QueryKey }
44 | { type: 'added'; queryHash: string; queryKey: QueryKey; state: QueryState }
45β
46type CacheRequest = {
47 type: 'cache-request'
48 requestId: string
49}
50β
51type DehydratedQuery = DehydratedState['queries'][number]
52β
53type CacheResponse = {
54 type: 'cache-response'
55 requestId: string
56 responderId: string
57 responseId: string
58 query: DehydratedQuery
59}
60β
61type BroadcastMessage = LiveBroadcastMessage | CacheRequest | CacheResponse
62β
63export interface BroadcastQueryClientOptions {
64 /** The QueryClient to sync. */
65 queryClient: QueryClient
66 /**
67 * Unique channel name used to communicate between tabs and windows.
68 * @default 'tanstack-query'
69 */
70 broadcastChannel?: string
71 /** Options forwarded to the underlying BroadcastChannel. */
72 options?: BroadcastChannelOptions
73 /**
74 * Called when a query event fails to broadcast to other tabs β most
75 * commonly because the query's state.data, state.error, or queryKey
76 * contains a value the structured-clone algorithm cannot serialize.
77 *
78 * Provide this to route failures to an error tracker. If omitted, a
79 * console.warn is emitted in development so failures are never silent.
80 *
81 * May return a Promise; any rejection is caught internally so it cannot
82 * cause a secondary unhandled rejection.
83 */
84 onBroadcastError?: (
85 error: unknown,
86 event: BroadcastErrorEvent,
87 ) => void | Promise<void>
88 /**
89 * Allows this live-sync session to respond to bootstrap requests from
90 * restore-enabled sessions. `broadcastQueryClientRestore` responds
91 * automatically and does not expose this option.
92 * @default false
93 */
94 respondToCacheRequests?: boolean
95 /**
96 * Query dehydration options used when this session responds to bootstrap
97 * requests. They have no effect on a live-only session unless
98 * `respondToCacheRequests` is enabled. Mutations are never included in
99 * bootstrap snapshots.
100 */
101 dehydrateOptions?: Pick<DehydrateOptions, 'shouldDehydrateQuery'>
102 /**
103 * Called when a bootstrap request, response, or hydration operation fails.
104 * Live synchronization failures continue to use `onBroadcastError`.
105 */
106 onBroadcastRestoreError?: (
107 error: unknown,
108 event: BroadcastRestoreErrorEvent,
109 ) => void | Promise<void>
110}
111β
112/**
113 * Options for live synchronization with an initial cache bootstrap. The
114 * restore session responds to cache requests automatically.
115 */
116export interface BroadcastQueryClientRestoreOptions extends Omit<
117 BroadcastQueryClientOptions,
118 'respondToCacheRequests'
119> {
120 /**
121 * Maximum time to wait for responses from configured responder sessions.
122 * @default 1000
123 */
124 timeout?: number
125 /** Options used when applying each incoming query snapshot. */
126 hydrateOptions?: HydrateOptions
127}
128β
129type InternalOptions = BroadcastQueryClientOptions & {
130 restoreOptions?: BroadcastQueryClientRestoreOptions
131}
132β
133type Session = {
134 cleanup: () => void
135 restorePromise?: Promise<void>
136}
137β
138const DEFAULT_RESTORE_TIMEOUT = 1000
139β
140function isRecord(value: unknown): value is Record<string, unknown> {
141 return typeof value === 'object' && value !== null
142}
143β
144function isCacheRequest(value: unknown): value is CacheRequest {
145 return (
146 isRecord(value) &&
147 value.type === 'cache-request' &&
148 typeof value.requestId === 'string'
149 )
150}
151β
152function isCacheResponse(value: unknown): value is CacheResponse {
153 if (
154 !isRecord(value) ||
155 value.type !== 'cache-response' ||
156 typeof value.requestId !== 'string' ||
157 typeof value.responderId !== 'string' ||
158 typeof value.responseId !== 'string' ||
159 !isRecord(value.query)
160 ) {
161 return false
162 }
163β
164 return (
165 typeof value.query.queryHash === 'string' &&
166 Array.isArray(value.query.queryKey) &&
167 isRecord(value.query.state)
168 )
169}
170β
171function isLiveBroadcastMessage(value: unknown): value is LiveBroadcastMessage {
172 if (
173 !isRecord(value) ||
174 (value.type !== 'updated' &&
175 value.type !== 'removed' &&
176 value.type !== 'added') ||
177 typeof value.queryHash !== 'string' ||
178 !Array.isArray(value.queryKey)
179 ) {
180 return false
181 }
182β
183 return value.type === 'removed' || isRecord(value.state)
184}
185β
186function createId(prefix: string): string {
187 return (
188 prefix +
189 '-' +
190 Date.now().toString(36) +
191 '-' +
192 Math.random().toString(36).slice(2)
193 )
194}
195β
196function createBroadcastSession({
197 queryClient,
198 broadcastChannel = 'tanstack-query',
199 options,
200 onBroadcastError,
201 respondToCacheRequests,
202 dehydrateOptions,
203 onBroadcastRestoreError,
204 restoreOptions,
205}: InternalOptions): Session {
206 const timeout = restoreOptions?.timeout ?? DEFAULT_RESTORE_TIMEOUT
207β
208 if (!Number.isFinite(timeout) || timeout < 0) {
209 throw new Error('broadcastQueryClientRestore timeout must be non-negative')
210 }
211β
212 let transaction = false
213 let cleaned = false
214 const tx = (cb: () => void) => {
215 transaction = true
216 try {
217 cb()
218 } finally {
219 // Guard against cb throwing while applying an incoming message.
220 transaction = false
221 }
222 }
223β
224 const channel = new BroadcastChannel<BroadcastMessage>(broadcastChannel, {
225 webWorkerSupport: false,
226 ...options,
227 })
228β
229 const queryCache = queryClient.getQueryCache()
230β
231 const safePost = (message: LiveBroadcastMessage): void => {
232 const handleError = (error: unknown) => {
233 const event: BroadcastErrorEvent = {
234 type: message.type,
235 queryHash: message.queryHash,
236 queryKey: message.queryKey,
237 }
238β
239 if (onBroadcastError) {
240 const warnCallbackError = (callbackError: unknown) => {
241 if (process.env.NODE_ENV !== 'production') {
242 console.warn(
243 '[broadcastQueryClient] onBroadcastError threw while handling "' +
244 event.type +
245 '" for query ' +
246 event.queryHash +
247 '.',
248 callbackError,
249 )
250 }
251 }
252 let result: void | Promise<void>
253 try {
254 result = onBroadcastError(error, event)
255 } catch (callbackError) {
256 warnCallbackError(callbackError)
257 return
258 }
259 result?.catch(warnCallbackError)
260 } else if (process.env.NODE_ENV !== 'production') {
261 console.warn(
262 '[broadcastQueryClient] Failed to broadcast "' +
263 event.type +
264 '" event for query ' +
265 event.queryHash +
266 '. ' +
267 'The query value could not be structured-cloned; cross-tab sync for this query was skipped.',
268 error,
269 )
270 }
271 }
272β
273 try {
274 Promise.resolve(channel.postMessage(message)).catch(handleError)
275 } catch (error) {
276 handleError(error)
277 }
278 }
279β
280 let resolveRestore = () => {}
281 let restoreActive = !!restoreOptions
282 let restoreTimer: ReturnType<typeof setTimeout> | undefined
283 const handledResponseIds = new Set<string>()
284 const requestId = restoreOptions ? createId('request') : undefined
285 const responderId = createId('responder')
286 let responseNumber = 0
287β
288 const restorePromise = restoreOptions
289 ? new Promise<void>((resolve) => {
290 resolveRestore = resolve
291 })
292 : undefined
293β
294 const warnRestoreError = (
295 error: unknown,
296 event: BroadcastRestoreErrorEvent,
297 ) => {
298 if (process.env.NODE_ENV !== 'production') {
299 console.warn(
300 '[broadcastQueryClient] Bootstrap ' +
301 event.type +
302 ' failed for request ' +
303 event.requestId +
304 '.',
305 error,
306 )
307 }
308 }
309β
310 const reportRestoreError = (
311 error: unknown,
312 event: BroadcastRestoreErrorEvent,
313 ) => {
314 if (!onBroadcastRestoreError) {
315 warnRestoreError(error, event)
316 return
317 }
318β
319 let result: void | Promise<void>
320 try {
321 result = onBroadcastRestoreError(error, event)
322 } catch (callbackError) {
323 warnRestoreError(callbackError, event)
324 return
325 }
326β
327 result?.catch((callbackError) => {
328 warnRestoreError(callbackError, event)
329 })
330 }
331β
332 const completeRestore = () => {
333 if (!restoreActive) {
334 return
335 }
336 restoreActive = false
337 if (restoreTimer !== undefined) {
338 clearTimeout(restoreTimer)
339 restoreTimer = undefined
340 }
341 resolveRestore()
342 }
343β
344 const safePostRestore = (
345 message: CacheResponse | CacheRequest,
346 event: BroadcastRestoreErrorEvent,
347 ) => {
348 try {
349 Promise.resolve(channel.postMessage(message)).catch((error: unknown) => {
350 reportRestoreError(error, event)
351 })
352 } catch (error) {
353 reportRestoreError(error, event)
354 }
355 }
356β
357 /**
358 * Answers bootstrap requests only for restore sessions or explicitly opted-in
359 * live-sync sessions, preserving the legacy API's live-only behavior.
360 */
361 const respondToCacheRequest = (request: CacheRequest) => {
362 if (!restoreOptions && !respondToCacheRequests) {
363 return
364 }
365β
366 let snapshot: DehydratedState
367 try {
368 snapshot = dehydrate(queryClient, {
369 ...dehydrateOptions,
370 ...restoreOptions?.dehydrateOptions,
371 shouldDehydrateMutation: () => false,
372 })
373 } catch (error) {
374 reportRestoreError(error, {
375 type: 'request',
376 requestId: request.requestId,
377 responderId,
378 })
379 return
380 }
381β
382 for (const query of snapshot.queries) {
383 responseNumber += 1
384 const responseId = responderId + '-' + responseNumber
385 safePostRestore(
386 {
387 type: 'cache-response',
388 requestId: request.requestId,
389 responderId,
390 responseId,
391 query,
392 },
393 {
394 type: 'response',
395 requestId: request.requestId,
396 responderId,
397 responseId,
398 queryHash: query.queryHash,
399 queryKey: query.queryKey,
400 },
401 )
402 }
403 }
404β
405 const applyCacheResponse = (message: CacheResponse) => {
406 if (!restoreOptions || !restoreActive || message.requestId !== requestId) {
407 return
408 }
409β
410 if (handledResponseIds.has(message.responseId)) {
411 return
412 }
413 handledResponseIds.add(message.responseId)
414β
415 try {
416 tx(() => {
417 hydrate(
418 queryClient,
419 {
420 mutations: [],
421 queries: [message.query],
422 },
423 restoreOptions.hydrateOptions,
424 )
425 })
426 } catch (error) {
427 reportRestoreError(error, {
428 type: 'hydrate',
429 requestId: message.requestId,
430 responderId: message.responderId,
431 responseId: message.responseId,
432 queryHash: message.query.queryHash,
433 queryKey: message.query.queryKey,
434 })
435 }
436 }
437β
438 const unsubscribe = queryCache.subscribe((queryEvent) => {
439 if (transaction || cleaned) {
440 return
441 }
442β
443 const {
444 query: { queryHash, queryKey, state, observers },
445 } = queryEvent
446β
447 if (queryEvent.type === 'updated' && queryEvent.action.type === 'success') {
448 safePost({
449 type: 'updated',
450 queryHash,
451 queryKey,
452 state,
453 })
454 }
455β
456 if (queryEvent.type === 'removed' && observers.length > 0) {
457 safePost({
458 type: 'removed',
459 queryHash,
460 queryKey,
461 })
462 }
463β
464 if (queryEvent.type === 'added') {
465 safePost({
466 type: 'added',
467 queryHash,
468 queryKey,
469 state,
470 })
471 }
472 })
473β
474 channel.onmessage = (action) => {
475 if (cleaned) {
476 return
477 }
478β
479 if (isCacheRequest(action)) {
480 respondToCacheRequest(action)
481 return
482 }
483β
484 if (isCacheResponse(action)) {
485 applyCacheResponse(action)
486 return
487 }
488β
489 if (!isLiveBroadcastMessage(action)) {
490 return
491 }
492β
493 tx(() => {
494 const { type, queryHash, queryKey } = action
495 const query = queryCache.get(queryHash)
496β
497 if (type === 'updated') {
498 if (query) {
499 if (action.state.dataUpdatedAt < query.state.dataUpdatedAt) {
500 return
501 }
502 query.setState(action.state)
503 return
504 }
505β
506 queryCache.build(
507 queryClient,
508 {
509 queryKey,
510 queryHash,
511 },
512 action.state,
513 )
514 } else if (type === 'removed') {
515 if (query) {
516 queryCache.remove(query)
517 }
518 } else {
519 if (query) {
520 if (action.state.dataUpdatedAt < query.state.dataUpdatedAt) {
521 return
522 }
523 query.setState(action.state)
524 return
525 }
526 queryCache.build(
527 queryClient,
528 {
529 queryKey,
530 queryHash,
531 },
532 action.state,
533 )
534 }
535 })
536 }
537β
538 if (restoreOptions && requestId) {
539 restoreTimer = setTimeout(completeRestore, timeout)
540 safePostRestore(
541 {
542 type: 'cache-request',
543 requestId,
544 },
545 {
546 type: 'request',
547 requestId,
548 },
549 )
550 }
551β
552 const cleanup = () => {
553 if (cleaned) {
554 return
555 }
556 cleaned = true
557 completeRestore()
558 unsubscribe()
559 channel.onmessage = null
560 const reportCloseError = (error: unknown) => {
561 if (restoreOptions && requestId) {
562 reportRestoreError(error, {
563 type: 'request',
564 requestId,
565 })
566 }
567 }
568 try {
569 void Promise.resolve(channel.close()).catch(reportCloseError)
570 } catch (error) {
571 reportCloseError(error)
572 }
573 }
574β
575 return { cleanup, restorePromise }
576}
577β
578/**
579 * Starts live synchronization for a QueryClient without requesting an initial
580 * cache snapshot. Set `respondToCacheRequests` to opt into answering restore
581 * requests from other sessions.
582 * @returns A function that stops synchronization and closes the channel.
583 */
584export function broadcastQueryClient(
585 options: BroadcastQueryClientOptions,
586): () => void {
587 return createBroadcastSession(options).cleanup
588}
589β
590/**
591 * Starts live synchronization, automatically answers restore requests, and
592 * requests an initial cache snapshot before resolving the restore promise.
593 * @returns Cleanup and a promise that settles when restore or cleanup completes.
594 */
595export function broadcastQueryClientRestore(
596 options: BroadcastQueryClientRestoreOptions,
597): [cleanup: () => void, restorePromise: Promise<void>] {
598 const session = createBroadcastSession({
599 ...options,
600 restoreOptions: options,
601 })
602β
603 return [session.cleanup, session.restorePromise!]
604}