@bevelo/query 0.0.0-stage → 0.1.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.
@@ -0,0 +1,2127 @@
1
+ import { a as partialMatchValue, c as computeBackoffMs, d as mutationSpec, f as querySpec, h as shouldRetryAttempt, i as matchesQueryFilter, l as infiniteQuerySpec, m as resolveStaleMs, n as keyStartsWith, o as serializeKey, p as resolveNetworkAction, r as matchesMutationFilter, s as clampPages, t as isPlainObject, u as isEntryStale } from "../key-BtYrMAlu.js";
2
+ import { DATA_TAG, ERROR_TAG, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, deriveInfiniteSnapshot, deriveMutationSnapshot, deriveQuerySnapshot, initialMutationState, initialQueryState, keepEqual, keepPrevious, packCache, reduceMutationState, reduceQueryState, selectHydrateQueries, skipToken } from "../pure/index.js";
3
+ import { createStoragePersister, persistQueryClient } from "./persist.js";
4
+ import { syncQueryClientAcrossTabs } from "./broadcast.js";
5
+ // src/live/drivers.ts
6
+ const MAX_32_BIT_TIMEOUT = 2147483647;
7
+ /** Real host clock backed by `Date.now` and chunked `globalThis.setTimeout`. */
8
+ function createSystemClock(options) {
9
+ return {
10
+ isServer: options?.isServer ?? typeof window === "undefined",
11
+ now: () => Date.now(),
12
+ setTimeout(callback, delayMs) {
13
+ let activeTimer;
14
+ let cancelled = false;
15
+ const targetAt = Date.now() + Math.max(0, delayMs);
16
+ const scheduleStep = () => {
17
+ if (cancelled) return;
18
+ const remaining = targetAt - Date.now();
19
+ if (remaining <= 0) {
20
+ callback();
21
+ return;
22
+ }
23
+ const chunk = Math.min(remaining, MAX_32_BIT_TIMEOUT);
24
+ activeTimer = globalThis.setTimeout(() => {
25
+ if (cancelled) return;
26
+ if (targetAt - Date.now() <= 0) callback();
27
+ else scheduleStep();
28
+ }, chunk);
29
+ };
30
+ const initialRemaining = Math.max(0, delayMs);
31
+ if (initialRemaining <= MAX_32_BIT_TIMEOUT) activeTimer = globalThis.setTimeout(() => {
32
+ if (!cancelled) callback();
33
+ }, initialRemaining);
34
+ else scheduleStep();
35
+ return { cancel() {
36
+ cancelled = true;
37
+ if (activeTimer !== void 0) {
38
+ globalThis.clearTimeout(activeTimer);
39
+ activeTimer = void 0;
40
+ }
41
+ } };
42
+ }
43
+ };
44
+ }
45
+ /** Deterministic clock for node unit tests with zero real timers. */
46
+ function createManualClock(startMs = 1e3) {
47
+ let currentNow = startMs;
48
+ let nextId = 1;
49
+ const timers = /* @__PURE__ */ new Map();
50
+ const runDue = (limitMs) => {
51
+ while (true) {
52
+ let earliest;
53
+ for (const entry of timers.values()) if (entry.fireAt <= limitMs) {
54
+ if (!earliest || entry.fireAt < earliest.fireAt || entry.fireAt === earliest.fireAt && entry.id < earliest.id) earliest = entry;
55
+ }
56
+ if (!earliest) break;
57
+ timers.delete(earliest.id);
58
+ currentNow = earliest.fireAt;
59
+ earliest.callback();
60
+ }
61
+ currentNow = limitMs;
62
+ };
63
+ return {
64
+ isServer: false,
65
+ now: () => currentNow,
66
+ setTimeout(callback, delayMs) {
67
+ const id = nextId++;
68
+ const fireAt = currentNow + Math.max(0, delayMs);
69
+ timers.set(id, {
70
+ id,
71
+ fireAt,
72
+ callback
73
+ });
74
+ return { cancel() {
75
+ timers.delete(id);
76
+ } };
77
+ },
78
+ advanceBy(ms) {
79
+ runDue(currentNow + Math.max(0, ms));
80
+ },
81
+ setNow(ms) {
82
+ if (ms > currentNow) runDue(ms);
83
+ else currentNow = ms;
84
+ },
85
+ pendingCount: () => timers.size
86
+ };
87
+ }
88
+ /** Mutable signal source for deterministic tests and custom platform adapters. */
89
+ function createManualSignal(initial) {
90
+ let value = initial;
91
+ const listeners = /* @__PURE__ */ new Set();
92
+ return {
93
+ get: () => value,
94
+ subscribe(listener) {
95
+ listeners.add(listener);
96
+ return () => {
97
+ listeners.delete(listener);
98
+ };
99
+ },
100
+ set(next) {
101
+ if (Object.is(value, next)) return;
102
+ value = next;
103
+ for (const listener of [...listeners]) if (listeners.has(listener)) listener();
104
+ }
105
+ };
106
+ }
107
+ /** Tracks page visibility in browsers; inert `true` when rendered on a server. */
108
+ function createBrowserFocusDriver() {
109
+ if (typeof window === "undefined" || typeof document === "undefined") return createManualSignal(true);
110
+ const listeners = /* @__PURE__ */ new Set();
111
+ let focused = document.visibilityState !== "hidden";
112
+ const onVisibilityChange = () => {
113
+ const next = document.visibilityState !== "hidden";
114
+ if (next === focused) return;
115
+ focused = next;
116
+ for (const listener of [...listeners]) if (listeners.has(listener)) listener();
117
+ };
118
+ let attached = false;
119
+ const attach = () => {
120
+ if (attached) return;
121
+ attached = true;
122
+ document.addEventListener("visibilitychange", onVisibilityChange, false);
123
+ };
124
+ const detachIfUnused = () => {
125
+ if (attached && listeners.size === 0) {
126
+ attached = false;
127
+ document.removeEventListener("visibilitychange", onVisibilityChange, false);
128
+ }
129
+ };
130
+ return {
131
+ get: () => focused,
132
+ subscribe(listener) {
133
+ listeners.add(listener);
134
+ attach();
135
+ return () => {
136
+ listeners.delete(listener);
137
+ detachIfUnused();
138
+ };
139
+ }
140
+ };
141
+ }
142
+ /** Tracks browser online status; inert `true` when rendered on a server. */
143
+ function createBrowserOnlineDriver() {
144
+ if (typeof window === "undefined" || typeof navigator === "undefined") return createManualSignal(true);
145
+ const listeners = /* @__PURE__ */ new Set();
146
+ let online = navigator.onLine ?? true;
147
+ const notify = (next) => {
148
+ if (next === online) return;
149
+ online = next;
150
+ for (const listener of [...listeners]) if (listeners.has(listener)) listener();
151
+ };
152
+ const onOnline = () => notify(true);
153
+ const onOffline = () => notify(false);
154
+ let attached = false;
155
+ const attach = () => {
156
+ if (attached) return;
157
+ attached = true;
158
+ window.addEventListener("online", onOnline, false);
159
+ window.addEventListener("offline", onOffline, false);
160
+ };
161
+ const detachIfUnused = () => {
162
+ if (attached && listeners.size === 0) {
163
+ attached = false;
164
+ window.removeEventListener("online", onOnline, false);
165
+ window.removeEventListener("offline", onOffline, false);
166
+ }
167
+ };
168
+ return {
169
+ get: () => online,
170
+ subscribe(listener) {
171
+ listeners.add(listener);
172
+ attach();
173
+ return () => {
174
+ listeners.delete(listener);
175
+ detachIfUnused();
176
+ };
177
+ }
178
+ };
179
+ }
180
+ /** Microtask-batched notification scheduler with synchronous `batch()` support. */
181
+ function createBatchScheduler() {
182
+ let queue = [];
183
+ let depth = 0;
184
+ let notifyWrapper = (fn) => fn();
185
+ const flush = () => {
186
+ const items = queue;
187
+ queue = [];
188
+ if (items.length === 0) return;
189
+ const run = () => {
190
+ for (const item of items) item();
191
+ };
192
+ if (items.length === 1) notifyWrapper(items[0]);
193
+ else notifyWrapper(run);
194
+ };
195
+ const schedule = (callback) => {
196
+ if (depth > 0) {
197
+ queue.push(callback);
198
+ return;
199
+ }
200
+ const hadItems = queue.length > 0;
201
+ queue.push(callback);
202
+ if (!hadItems) Promise.resolve().then(() => {
203
+ if (depth === 0) flush();
204
+ });
205
+ };
206
+ return {
207
+ schedule,
208
+ batch(fn) {
209
+ depth += 1;
210
+ try {
211
+ return fn();
212
+ } finally {
213
+ depth -= 1;
214
+ if (depth === 0) flush();
215
+ }
216
+ },
217
+ batchCalls(fn) {
218
+ return (...args) => {
219
+ schedule(() => fn(...args));
220
+ };
221
+ },
222
+ setNotifyWrapper(wrapper) {
223
+ notifyWrapper = wrapper;
224
+ }
225
+ };
226
+ }
227
+ // src/live/runner.ts
228
+ var TaskCancelledError = class extends Error {
229
+ revert;
230
+ silent;
231
+ constructor(options) {
232
+ super("Query task was cancelled");
233
+ this.name = "TaskCancelledError";
234
+ this.revert = options?.revert === true;
235
+ this.silent = options?.silent === true;
236
+ }
237
+ };
238
+ function isTaskCancelled(value) {
239
+ return value instanceof TaskCancelledError;
240
+ }
241
+ /** Wraps an `AbortController` lazily to record whether consumer code accessed `.signal`. */
242
+ function createDemandAbortHandle() {
243
+ let controller;
244
+ let consumed = false;
245
+ let aborted = false;
246
+ let abortReason;
247
+ return {
248
+ consumeAwareTarget: { get signal() {
249
+ consumed = true;
250
+ if (controller === void 0) {
251
+ controller = new AbortController();
252
+ if (aborted) controller.abort(abortReason);
253
+ }
254
+ return controller.signal;
255
+ } },
256
+ wasConsumed: () => consumed,
257
+ abort: (reason) => {
258
+ if (aborted) return;
259
+ aborted = true;
260
+ abortReason = reason;
261
+ if (controller !== void 0 && !controller.signal.aborted) controller.abort(reason);
262
+ }
263
+ };
264
+ }
265
+ /** Executes `config.fn` with injected clock retries and network/focus gating. */
266
+ function createTaskRunner(config) {
267
+ let settled = "pending";
268
+ let failureCount = 0;
269
+ let retryCancelled = false;
270
+ let hasStartedRun = false;
271
+ let pausedWaiting;
272
+ let activeTimer;
273
+ let resolveOuter;
274
+ let rejectOuter;
275
+ const outerPromise = new Promise((res, rej) => {
276
+ resolveOuter = res;
277
+ rejectOuter = rej;
278
+ });
279
+ const clearTimers = () => {
280
+ if (activeTimer !== void 0) {
281
+ activeTimer.cancel();
282
+ activeTimer = void 0;
283
+ }
284
+ };
285
+ const resolve = (value) => {
286
+ if (settled !== "pending") return;
287
+ settled = "resolved";
288
+ clearTimers();
289
+ pausedWaiting?.();
290
+ resolveOuter(value);
291
+ };
292
+ const reject = (error) => {
293
+ if (settled !== "pending") return;
294
+ settled = "rejected";
295
+ clearTimers();
296
+ pausedWaiting?.();
297
+ rejectOuter(error);
298
+ };
299
+ const canRunNow = () => {
300
+ if (config.canRun && !config.canRun()) return false;
301
+ return resolveNetworkAction(config.networkMode, config.online.get(), hasStartedRun) === "run";
302
+ };
303
+ const waitToResume = () => {
304
+ if (canRunNow() || settled !== "pending") return Promise.resolve();
305
+ config.onPause?.();
306
+ return new Promise((res) => {
307
+ const done = () => {
308
+ pausedWaiting = void 0;
309
+ res();
310
+ };
311
+ pausedWaiting = done;
312
+ });
313
+ };
314
+ const runLoop = async () => {
315
+ if (settled !== "pending") return;
316
+ const executeAttempt = async () => {
317
+ if (!canRunNow()) {
318
+ await waitToResume();
319
+ if (settled !== "pending") throw new TaskCancelledError({ silent: true });
320
+ }
321
+ hasStartedRun = true;
322
+ if (failureCount === 0 && config.initialPromise !== void 0) return await config.initialPromise;
323
+ return await Promise.resolve(config.fn());
324
+ };
325
+ try {
326
+ const data = await executeAttempt();
327
+ resolve(data);
328
+ } catch (error) {
329
+ if (settled !== "pending") return;
330
+ if (isTaskCancelled(error)) {
331
+ reject(error);
332
+ return;
333
+ }
334
+ const typedError = error;
335
+ failureCount += 1;
336
+ config.onFail?.(failureCount, typedError);
337
+ if (!(!retryCancelled && shouldRetryAttempt(config.retry, failureCount, typedError, config.clock.isServer))) {
338
+ reject(error);
339
+ return;
340
+ }
341
+ const delayMs = computeBackoffMs(config.retryDelay, failureCount - 1, typedError);
342
+ await new Promise((res) => {
343
+ activeTimer = config.clock.setTimeout(() => {
344
+ activeTimer = void 0;
345
+ res();
346
+ }, delayMs);
347
+ });
348
+ if (settled !== "pending") return;
349
+ await waitToResume();
350
+ if (settled !== "pending") return;
351
+ await runLoop();
352
+ }
353
+ };
354
+ return {
355
+ promise: outerPromise,
356
+ cancel(options) {
357
+ if (settled !== "pending") return;
358
+ const err = new TaskCancelledError(options);
359
+ if (!options?.silent) config.onCancel?.(err);
360
+ reject(err);
361
+ },
362
+ cancelRetry() {
363
+ retryCancelled = true;
364
+ },
365
+ continueRetry() {
366
+ retryCancelled = false;
367
+ },
368
+ continue() {
369
+ const wake = pausedWaiting;
370
+ if (wake && canRunNow()) {
371
+ wake();
372
+ config.onContinue?.();
373
+ }
374
+ return outerPromise.catch(() => void 0);
375
+ },
376
+ canStart: () => resolveNetworkAction(config.networkMode, config.online.get(), hasStartedRun) === "run",
377
+ start() {
378
+ runLoop();
379
+ return outerPromise;
380
+ },
381
+ status: () => settled
382
+ };
383
+ }
384
+ // src/live/stream.ts
385
+ /**
386
+ * Wraps an `AsyncIterable` source into a `QueryFn` that progressively publishes chunks
387
+ * through `context.commitChunk` while keeping `fetchPhase: "fetching"` until completion.
388
+ */
389
+ function streamedQuery(config) {
390
+ const mode = config.refetchMode ?? "reset";
391
+ const reduceChunk = config.reducer ?? ((acc, chunk) => [...acc, chunk]);
392
+ return async (context) => {
393
+ let acc = config.reducer !== void 0 ? config.initialValue : [];
394
+ if (mode === "reset" && context.commitChunk) context.commitChunk(acc);
395
+ const iterable = await config.streamFn(context);
396
+ for await (const chunk of iterable) {
397
+ if (context.signal.aborted) break;
398
+ acc = reduceChunk(acc, chunk);
399
+ if (mode !== "replace" && context.commitChunk) context.commitChunk(acc);
400
+ }
401
+ return acc;
402
+ };
403
+ }
404
+ // src/live/cache.ts
405
+ const DEFAULT_GC_TIME_MS = 3e5;
406
+ /** Single cached query instance managed by `QueryCache`. */
407
+ var QueryEntry = class {
408
+ queryKey;
409
+ queryHash;
410
+ cache;
411
+ env;
412
+ stateValue;
413
+ optionsValue;
414
+ watchers = /* @__PURE__ */ new Set();
415
+ runner;
416
+ abortHandle;
417
+ activePromise;
418
+ preFetchState;
419
+ gcTimer;
420
+ gcMs = DEFAULT_GC_TIME_MS;
421
+ hasExplicitGc = false;
422
+ countedFetching = false;
423
+ inActiveSet = false;
424
+ constructor(cache, env, options, queryHash, seededState) {
425
+ this.cache = cache;
426
+ this.env = env;
427
+ this.queryKey = options.queryKey;
428
+ this.queryHash = queryHash;
429
+ this.optionsValue = options;
430
+ if (seededState !== void 0) this.stateValue = seededState;
431
+ else {
432
+ const seedData = typeof options.initialData === "function" ? options.initialData() : options.initialData;
433
+ const seedUpdatedAt = seedData === void 0 ? void 0 : typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt ?? this.env.clock.now();
434
+ this.stateValue = initialQueryState(seedData === void 0 ? void 0 : {
435
+ data: seedData,
436
+ dataUpdatedAt: seedUpdatedAt,
437
+ status: "success"
438
+ });
439
+ }
440
+ if (typeof options.gcTime === "number") {
441
+ this.gcMs = options.gcTime;
442
+ this.hasExplicitGc = true;
443
+ }
444
+ this.syncFetchingCount();
445
+ this.scheduleGc();
446
+ }
447
+ get state() {
448
+ return this.stateValue;
449
+ }
450
+ get options() {
451
+ return this.optionsValue;
452
+ }
453
+ get staleTime() {
454
+ return this.optionsValue.staleTime;
455
+ }
456
+ get watcherCount() {
457
+ return this.watchers.size;
458
+ }
459
+ get observerCount() {
460
+ return this.watchers.size;
461
+ }
462
+ syncFetchingCount(forceFalse = false) {
463
+ const isFetching = !forceFalse && this.stateValue.fetchPhase === "fetching";
464
+ if (isFetching === this.countedFetching) return;
465
+ this.countedFetching = isFetching;
466
+ this.cache.adjustFetchingCount(isFetching ? 1 : -1);
467
+ }
468
+ syncActiveMembership(destroyed = false) {
469
+ const active = !destroyed && (this.watchers.size > 0 || this.stateValue.fetchPhase !== "idle");
470
+ if (active === this.inActiveSet) return;
471
+ this.inActiveSet = active;
472
+ if (active) this.cache.markActive(this);
473
+ else this.cache.markInactive(this);
474
+ }
475
+ get promise() {
476
+ return this.activePromise;
477
+ }
478
+ setOptions(options) {
479
+ const prev = this.optionsValue;
480
+ if (options === prev || prev.queryFn === options.queryFn && prev.staleTime === options.staleTime && prev.gcTime === options.gcTime && prev.retry === options.retry && prev.retryDelay === options.retryDelay && prev.networkMode === options.networkMode && prev.structuralSharing === options.structuralSharing && prev.meta === options.meta) return;
481
+ this.optionsValue = {
482
+ ...prev,
483
+ ...options
484
+ };
485
+ this.updateGcTime(options.gcTime);
486
+ }
487
+ updateGcTime(newGcTime) {
488
+ if (newGcTime === void 0) return;
489
+ if (!this.hasExplicitGc) {
490
+ this.gcMs = newGcTime;
491
+ this.hasExplicitGc = true;
492
+ } else this.gcMs = Math.max(this.gcMs, newGcTime);
493
+ }
494
+ clearGcTimer() {
495
+ if (this.gcTimer !== void 0) {
496
+ this.gcTimer.cancel();
497
+ this.gcTimer = void 0;
498
+ }
499
+ }
500
+ scheduleGc() {
501
+ this.clearGcTimer();
502
+ if (this.watchers.size > 0) return;
503
+ if (!Number.isFinite(this.gcMs) || this.gcMs === Infinity) return;
504
+ if (this.env.clock.isServer) return;
505
+ this.gcTimer = this.env.clock.setTimeout(() => {
506
+ this.gcTimer = void 0;
507
+ if (this.watchers.size === 0 && this.stateValue.fetchPhase === "idle") this.cache.remove(this);
508
+ }, this.gcMs);
509
+ }
510
+ addWatcher(watcher) {
511
+ if (this.watchers.has(watcher)) return;
512
+ this.watchers.add(watcher);
513
+ this.syncActiveMembership();
514
+ this.clearGcTimer();
515
+ this.updateGcTime(watcher.gcTime);
516
+ this.cache.emit({
517
+ type: "watcherAdded",
518
+ query: this
519
+ });
520
+ }
521
+ removeWatcher(watcher) {
522
+ if (!this.watchers.delete(watcher)) return;
523
+ this.syncActiveMembership();
524
+ this.cache.emit({
525
+ type: "watcherRemoved",
526
+ query: this
527
+ });
528
+ if (this.watchers.size === 0) {
529
+ if (this.runner && this.abortHandle?.wasConsumed()) this.cancel({
530
+ silent: true,
531
+ revert: true
532
+ });
533
+ this.scheduleGc();
534
+ }
535
+ }
536
+ isStale(staleTime) {
537
+ return isEntryStale(this.stateValue, staleTime ?? this.optionsValue.staleTime, this.env.clock.now());
538
+ }
539
+ dispatch(action) {
540
+ this.stateValue = reduceQueryState(this.stateValue, action);
541
+ this.syncFetchingCount();
542
+ this.syncActiveMembership();
543
+ if (this.watchers.size > 0 || this.cache.hasListeners) this.env.scheduler.batch(() => {
544
+ if (this.watchers.size === 1) this.watchers.values().next().value?.onEntryUpdate(action);
545
+ else if (this.watchers.size > 1) for (const watcher of [...this.watchers]) watcher.onEntryUpdate(action);
546
+ this.cache.emit({
547
+ type: "updated",
548
+ query: this,
549
+ action
550
+ });
551
+ });
552
+ if (action.type === "fetch" || action.type === "success" || action.type === "error" || action.type === "cancel" || action.type === "pause" || action.type === "continue") this.env.onActivity?.();
553
+ }
554
+ setData(newData, updatedAt) {
555
+ const structuralSharing = this.optionsValue.structuralSharing !== false;
556
+ this.dispatch({
557
+ type: "setData",
558
+ data: newData,
559
+ updatedAt: updatedAt ?? this.env.clock.now(),
560
+ structuralSharing
561
+ });
562
+ return this.stateValue.data;
563
+ }
564
+ invalidate() {
565
+ if (!this.stateValue.invalidated) this.dispatch({ type: "invalidate" });
566
+ }
567
+ cancel(options) {
568
+ const runner = this.runner;
569
+ if (!runner) return;
570
+ const prev = this.preFetchState;
571
+ this.abortHandle?.abort();
572
+ this.runner = void 0;
573
+ this.abortHandle = void 0;
574
+ this.activePromise = void 0;
575
+ this.preFetchState = void 0;
576
+ runner.cancel({
577
+ ...options?.silent !== void 0 ? { silent: options.silent } : {},
578
+ ...options?.revert !== void 0 ? { revert: options.revert } : {}
579
+ });
580
+ if (!options?.silent) this.dispatch(options?.revert && prev ? {
581
+ type: "cancel",
582
+ revert: prev
583
+ } : { type: "cancel" });
584
+ else if (options?.revert && prev) {
585
+ this.stateValue = prev;
586
+ this.syncFetchingCount();
587
+ this.syncActiveMembership();
588
+ this.env.onActivity?.();
589
+ } else {
590
+ this.stateValue = reduceQueryState(this.stateValue, { type: "cancel" });
591
+ this.syncFetchingCount();
592
+ this.syncActiveMembership();
593
+ this.env.onActivity?.();
594
+ }
595
+ this.scheduleGc();
596
+ }
597
+ continueFetch() {
598
+ if (this.runner && this.stateValue.fetchPhase === "paused") this.runner.continue();
599
+ }
600
+ onFocus() {
601
+ for (const watcher of [...this.watchers]) watcher.triggerRefetchFromSignal(watcher.refetchOnFocus, "focus");
602
+ }
603
+ onReconnect() {
604
+ this.continueFetch();
605
+ for (const watcher of [...this.watchers]) watcher.triggerRefetchFromSignal(watcher.refetchOnReconnect, "reconnect");
606
+ }
607
+ destroy() {
608
+ this.clearGcTimer();
609
+ this.cancel({ silent: true });
610
+ this.syncFetchingCount(true);
611
+ this.syncActiveMembership(true);
612
+ if (this.watchers.size === 1) this.watchers.values().next().value?.onEntryDestroy();
613
+ else if (this.watchers.size > 1) for (const watcher of [...this.watchers]) watcher.onEntryDestroy();
614
+ this.watchers.clear();
615
+ }
616
+ fetch(options, fetchOptions) {
617
+ if (options) this.setOptions(options);
618
+ if (this.stateValue.fetchPhase !== "idle" && this.activePromise !== void 0) {
619
+ if (!(this.stateValue.data !== void 0 && (fetchOptions?.cancelRefetch ?? true)) || !(fetchOptions?.cancelRefetch ?? true)) {
620
+ if (this.stateValue.fetchPhase === "paused" && this.runner?.canStart()) this.runner.continue();
621
+ return this.activePromise;
622
+ }
623
+ this.cancel({
624
+ silent: true,
625
+ revert: true
626
+ });
627
+ }
628
+ const queryFn = this.optionsValue.queryFn;
629
+ if (queryFn === void 0 || queryFn === skipToken) {
630
+ if (fetchOptions?.behavior?.onFetch === void 0) return Promise.reject(/* @__PURE__ */ new Error(`Missing queryFn for ${this.queryHash}`));
631
+ }
632
+ const abortHandle = createDemandAbortHandle();
633
+ this.abortHandle = abortHandle;
634
+ this.preFetchState = this.stateValue;
635
+ const context = {
636
+ queryKey: this.queryKey,
637
+ meta: fetchOptions?.meta ?? this.optionsValue.meta,
638
+ pageParam: fetchOptions?.pageParam,
639
+ direction: fetchOptions?.direction,
640
+ get signal() {
641
+ return abortHandle.consumeAwareTarget.signal;
642
+ },
643
+ commitChunk: (chunkData) => {
644
+ if (this.abortHandle !== abortHandle) return;
645
+ const structuralSharing = this.optionsValue.structuralSharing !== false;
646
+ const action = {
647
+ type: "setData",
648
+ data: chunkData,
649
+ updatedAt: this.env.clock.now(),
650
+ structuralSharing
651
+ };
652
+ this.stateValue = reduceQueryState(this.stateValue, action);
653
+ if (this.watchers.size > 0 || this.cache.hasListeners) {
654
+ const erasedAction = action;
655
+ this.env.scheduler.batch(() => {
656
+ if (this.watchers.size === 1) this.watchers.values().next().value?.onEntryUpdate(erasedAction);
657
+ else if (this.watchers.size > 1) for (const watcher of [...this.watchers]) watcher.onEntryUpdate(erasedAction);
658
+ this.cache.emit({
659
+ type: "updated",
660
+ query: this,
661
+ action: erasedAction
662
+ });
663
+ });
664
+ }
665
+ }
666
+ };
667
+ const runCore = () => {
668
+ if (fetchOptions?.behavior?.onFetch) return fetchOptions.behavior.onFetch({
669
+ state: this.stateValue,
670
+ fetchFn: () => queryFn(context),
671
+ setData: (d) => {
672
+ this.setData(d);
673
+ },
674
+ signal: abortHandle.consumeAwareTarget.signal,
675
+ pageParam: fetchOptions.pageParam,
676
+ direction: fetchOptions.direction
677
+ });
678
+ return queryFn(context);
679
+ };
680
+ this.dispatch({
681
+ type: "fetch",
682
+ meta: fetchOptions?.meta ?? this.optionsValue.meta ?? null
683
+ });
684
+ const runner = createTaskRunner({
685
+ fn: runCore,
686
+ clock: this.env.clock,
687
+ online: this.env.online,
688
+ focus: this.env.focus,
689
+ ...this.optionsValue.networkMode !== void 0 ? { networkMode: this.optionsValue.networkMode } : {},
690
+ ...this.optionsValue.retry !== void 0 ? { retry: this.optionsValue.retry } : {},
691
+ ...this.optionsValue.retryDelay !== void 0 ? { retryDelay: this.optionsValue.retryDelay } : {},
692
+ onFail: (_count, error) => {
693
+ if (this.runner !== runner) return;
694
+ this.dispatch({
695
+ type: "fail",
696
+ error
697
+ });
698
+ },
699
+ onPause: () => {
700
+ if (this.runner !== runner) return;
701
+ this.dispatch({ type: "pause" });
702
+ },
703
+ onContinue: () => {
704
+ if (this.runner !== runner) return;
705
+ this.dispatch({ type: "continue" });
706
+ },
707
+ onCancel: () => {}
708
+ });
709
+ this.runner = runner;
710
+ const structuralSharing = this.optionsValue.structuralSharing !== false;
711
+ const promise = runner.start().then((data) => {
712
+ if (this.runner === runner) {
713
+ this.runner = void 0;
714
+ this.abortHandle = void 0;
715
+ this.activePromise = void 0;
716
+ this.preFetchState = void 0;
717
+ this.dispatch({
718
+ type: "success",
719
+ data,
720
+ updatedAt: this.env.clock.now(),
721
+ structuralSharing
722
+ });
723
+ this.scheduleGc();
724
+ }
725
+ return data;
726
+ }).catch((error) => {
727
+ if (this.runner === runner) {
728
+ this.runner = void 0;
729
+ this.abortHandle = void 0;
730
+ this.activePromise = void 0;
731
+ if (isTaskCancelled(error)) {
732
+ if (!error.silent) this.dispatch(error.revert && this.preFetchState ? {
733
+ type: "cancel",
734
+ revert: this.preFetchState
735
+ } : { type: "cancel" });
736
+ } else this.dispatch({
737
+ type: "error",
738
+ error,
739
+ updatedAt: this.env.clock.now()
740
+ });
741
+ this.preFetchState = void 0;
742
+ this.scheduleGc();
743
+ }
744
+ throw error;
745
+ });
746
+ this.activePromise = promise;
747
+ promise.catch(() => void 0);
748
+ return promise;
749
+ }
750
+ };
751
+ /** Central repository of deduplicated `QueryEntry` objects. */
752
+ var QueryCache = class {
753
+ entries = /* @__PURE__ */ new Map();
754
+ entriesByRoot = /* @__PURE__ */ new Map();
755
+ activeEntries = /* @__PURE__ */ new Set();
756
+ listeners = /* @__PURE__ */ new Set();
757
+ env;
758
+ fetchingCountValue = 0;
759
+ constructor(env) {
760
+ this.env = env;
761
+ }
762
+ get fetchingCount() {
763
+ return this.fetchingCountValue;
764
+ }
765
+ get hasListeners() {
766
+ return this.listeners.size > 0;
767
+ }
768
+ adjustFetchingCount(delta) {
769
+ this.fetchingCountValue += delta;
770
+ }
771
+ markActive(entry) {
772
+ this.activeEntries.add(entry);
773
+ }
774
+ markInactive(entry) {
775
+ this.activeEntries.delete(entry);
776
+ }
777
+ indexEntry(entry) {
778
+ const root = entry.queryKey[0];
779
+ if (typeof root !== "string") return;
780
+ let bucket = this.entriesByRoot.get(root);
781
+ if (!bucket) {
782
+ bucket = /* @__PURE__ */ new Set();
783
+ this.entriesByRoot.set(root, bucket);
784
+ }
785
+ bucket.add(entry);
786
+ }
787
+ unindexEntry(entry) {
788
+ const root = entry.queryKey[0];
789
+ if (typeof root !== "string") return;
790
+ const bucket = this.entriesByRoot.get(root);
791
+ if (!bucket) return;
792
+ bucket.delete(entry);
793
+ if (bucket.size === 0) this.entriesByRoot.delete(root);
794
+ }
795
+ emit(event) {
796
+ if (this.listeners.size === 0) return;
797
+ this.env.scheduler.batch(() => {
798
+ if (this.listeners.size === 1) this.listeners.values().next().value?.(event);
799
+ else for (const listener of [...this.listeners]) listener(event);
800
+ });
801
+ }
802
+ subscribe(listener) {
803
+ this.listeners.add(listener);
804
+ return () => {
805
+ this.listeners.delete(listener);
806
+ };
807
+ }
808
+ get(queryHash) {
809
+ return this.entries.get(queryHash);
810
+ }
811
+ getAll() {
812
+ return [...this.entries.values()];
813
+ }
814
+ build(options, seededState) {
815
+ const queryHash = serializeKey(options.queryKey);
816
+ const existing = this.entries.get(queryHash);
817
+ if (existing) {
818
+ if (seededState !== void 0 && existing.state.dataUpdatedAt < seededState.dataUpdatedAt) existing.setData(seededState.data, seededState.dataUpdatedAt);
819
+ return existing;
820
+ }
821
+ const created = new QueryEntry(this, this.env, options, queryHash, seededState);
822
+ const erased = created;
823
+ this.entries.set(queryHash, erased);
824
+ this.indexEntry(erased);
825
+ this.emit({
826
+ type: "added",
827
+ query: erased
828
+ });
829
+ return created;
830
+ }
831
+ add(entry) {
832
+ if (this.entries.has(entry.queryHash)) return;
833
+ this.entries.set(entry.queryHash, entry);
834
+ this.indexEntry(entry);
835
+ this.emit({
836
+ type: "added",
837
+ query: entry
838
+ });
839
+ }
840
+ remove(entry) {
841
+ if (this.entries.get(entry.queryHash) !== entry) return;
842
+ entry.destroy();
843
+ this.entries.delete(entry.queryHash);
844
+ this.activeEntries.delete(entry);
845
+ this.unindexEntry(entry);
846
+ this.emit({
847
+ type: "removed",
848
+ query: entry
849
+ });
850
+ this.env.onActivity?.();
851
+ }
852
+ clear() {
853
+ for (const entry of [...this.entries.values()]) this.remove(entry);
854
+ this.entriesByRoot.clear();
855
+ this.activeEntries.clear();
856
+ this.fetchingCountValue = 0;
857
+ }
858
+ find(filter) {
859
+ const now = this.env.clock.now();
860
+ if (filter?.queryKey !== void 0 && filter.exact === true) {
861
+ const exactHash = serializeKey(filter.queryKey);
862
+ const entry = this.entries.get(exactHash);
863
+ if (!entry) return void 0;
864
+ return matchesQueryFilter(entry, filter, now, exactHash) ? entry : void 0;
865
+ }
866
+ const rootKey = filter?.queryKey !== void 0 && typeof filter.queryKey[0] === "string" ? filter.queryKey[0] : void 0;
867
+ const candidates = rootKey !== void 0 ? this.entriesByRoot.get(rootKey) : filter?.type === "active" ? this.activeEntries : this.entries.values();
868
+ if (!candidates) return void 0;
869
+ for (const entry of candidates) if (matchesQueryFilter(entry, filter, now)) return entry;
870
+ }
871
+ findAll(filter) {
872
+ if (!filter) return [...this.entries.values()];
873
+ const now = this.env.clock.now();
874
+ if (filter.queryKey !== void 0 && filter.exact === true) {
875
+ const exactHash = serializeKey(filter.queryKey);
876
+ const entry = this.entries.get(exactHash);
877
+ if (!entry) return [];
878
+ return matchesQueryFilter(entry, filter, now, exactHash) ? [entry] : [];
879
+ }
880
+ const rootKey = typeof filter.queryKey?.[0] === "string" ? filter.queryKey[0] : void 0;
881
+ const candidates = rootKey !== void 0 ? this.entriesByRoot.get(rootKey) : filter.type === "active" ? this.activeEntries : this.entries.values();
882
+ if (!candidates) return [];
883
+ const out = [];
884
+ for (const entry of candidates) if (matchesQueryFilter(entry, filter, now)) out.push(entry);
885
+ return out;
886
+ }
887
+ onFocus() {
888
+ if (this.activeEntries.size === 0) return;
889
+ this.env.scheduler.batch(() => {
890
+ if (this.activeEntries.size === 1) {
891
+ this.activeEntries.values().next().value?.onFocus();
892
+ return;
893
+ }
894
+ for (const entry of [...this.activeEntries]) entry.onFocus();
895
+ });
896
+ }
897
+ onOnline() {
898
+ if (this.activeEntries.size === 0) return;
899
+ this.env.scheduler.batch(() => {
900
+ if (this.activeEntries.size === 1) {
901
+ this.activeEntries.values().next().value?.onReconnect();
902
+ return;
903
+ }
904
+ for (const entry of [...this.activeEntries]) entry.onReconnect();
905
+ });
906
+ }
907
+ };
908
+ /** Single mutation invocation tracked in `MutationCache`. */
909
+ var MutationEntry = class {
910
+ mutationId;
911
+ mutationHash;
912
+ options;
913
+ cache;
914
+ env;
915
+ stateValue;
916
+ watchers = /* @__PURE__ */ new Set();
917
+ runner;
918
+ gcTimer;
919
+ countedPending = false;
920
+ constructor(cache, env, mutationId, options, seededState) {
921
+ this.cache = cache;
922
+ this.env = env;
923
+ this.mutationId = mutationId;
924
+ this.mutationHash = options.mutationKey !== void 0 ? serializeKey(options.mutationKey) : void 0;
925
+ this.options = options;
926
+ this.stateValue = seededState ?? initialMutationState();
927
+ this.syncMutatingCount();
928
+ }
929
+ syncMutatingCount(forceFalse = false) {
930
+ const isPending = !forceFalse && this.stateValue.status === "pending";
931
+ if (isPending === this.countedPending) return;
932
+ this.countedPending = isPending;
933
+ this.cache.adjustMutatingCount(isPending ? 1 : -1);
934
+ }
935
+ get state() {
936
+ return this.stateValue;
937
+ }
938
+ addWatcher(listener) {
939
+ this.watchers.add(listener);
940
+ if (this.gcTimer !== void 0) {
941
+ this.gcTimer.cancel();
942
+ this.gcTimer = void 0;
943
+ }
944
+ }
945
+ removeWatcher(listener) {
946
+ this.watchers.delete(listener);
947
+ this.scheduleGc();
948
+ }
949
+ scheduleGc() {
950
+ if (this.gcTimer !== void 0) {
951
+ this.gcTimer.cancel();
952
+ this.gcTimer = void 0;
953
+ }
954
+ if (this.watchers.size > 0 || this.env.clock.isServer) return;
955
+ const gcMs = this.options.gcTime ?? 3e5;
956
+ if (!Number.isFinite(gcMs) || gcMs === Infinity) return;
957
+ this.gcTimer = this.env.clock.setTimeout(() => {
958
+ this.gcTimer = void 0;
959
+ if (this.watchers.size === 0 && this.stateValue.status !== "pending") this.cache.remove(this);
960
+ }, gcMs);
961
+ }
962
+ dispatch(action) {
963
+ this.stateValue = reduceMutationState(this.stateValue, action);
964
+ this.syncMutatingCount();
965
+ if (this.watchers.size > 0 || this.cache.hasListeners) this.env.scheduler.batch(() => {
966
+ if (this.watchers.size === 1) this.watchers.values().next().value?.onMutationUpdate(action);
967
+ else if (this.watchers.size > 1) for (const listener of [...this.watchers]) listener.onMutationUpdate(action);
968
+ this.cache.emit({
969
+ type: "updated",
970
+ mutation: this,
971
+ action
972
+ });
973
+ });
974
+ this.env.onActivity?.();
975
+ }
976
+ continue() {
977
+ return this.runner ? this.runner.continue() : Promise.resolve();
978
+ }
979
+ async execute(variables) {
980
+ const fn = this.options.mutationFn;
981
+ if (!fn) throw new Error("Missing mutationFn");
982
+ const runExecution = async () => {
983
+ let context;
984
+ if (this.stateValue.status !== "pending") this.dispatch({
985
+ type: "pending",
986
+ variables,
987
+ context: void 0,
988
+ submittedAt: this.env.clock.now()
989
+ });
990
+ try {
991
+ if (this.options.onMutate) {
992
+ context = await this.options.onMutate(variables);
993
+ if (context !== this.stateValue.context) this.dispatch({
994
+ type: "context",
995
+ context
996
+ });
997
+ }
998
+ const runner = createTaskRunner({
999
+ fn: () => fn(variables),
1000
+ clock: this.env.clock,
1001
+ online: this.env.online,
1002
+ ...this.options.networkMode !== void 0 ? { networkMode: this.options.networkMode } : {},
1003
+ retry: this.options.retry ?? 0,
1004
+ ...this.options.retryDelay !== void 0 ? { retryDelay: this.options.retryDelay } : {},
1005
+ onFail: (_count, error) => {
1006
+ this.dispatch({
1007
+ type: "fail",
1008
+ error
1009
+ });
1010
+ },
1011
+ onPause: () => {
1012
+ this.dispatch({ type: "pause" });
1013
+ },
1014
+ onContinue: () => {
1015
+ this.dispatch({ type: "continue" });
1016
+ }
1017
+ });
1018
+ this.runner = runner;
1019
+ const data = await runner.start();
1020
+ await this.options.onSuccess?.(data, variables, context);
1021
+ await this.options.onSettled?.(data, null, variables, context);
1022
+ this.dispatch({
1023
+ type: "success",
1024
+ data
1025
+ });
1026
+ return data;
1027
+ } catch (error) {
1028
+ const typedError = error;
1029
+ await this.options.onError?.(typedError, variables, context);
1030
+ await this.options.onSettled?.(void 0, typedError, variables, context);
1031
+ this.dispatch({
1032
+ type: "error",
1033
+ error: typedError
1034
+ });
1035
+ throw error;
1036
+ } finally {
1037
+ this.runner = void 0;
1038
+ this.scheduleGc();
1039
+ }
1040
+ };
1041
+ const scopeId = this.options.scope?.id;
1042
+ if (!scopeId) return runExecution();
1043
+ return this.cache.runInScope(scopeId, runExecution);
1044
+ }
1045
+ };
1046
+ /** Central repository for mutations with per-scope serial queueing. */
1047
+ var MutationCache = class {
1048
+ entries = /* @__PURE__ */ new Set();
1049
+ listeners = /* @__PURE__ */ new Set();
1050
+ scopeQueues = /* @__PURE__ */ new Map();
1051
+ env;
1052
+ nextId = 1;
1053
+ mutatingCountValue = 0;
1054
+ constructor(env) {
1055
+ this.env = env;
1056
+ }
1057
+ get mutatingCount() {
1058
+ return this.mutatingCountValue;
1059
+ }
1060
+ get hasListeners() {
1061
+ return this.listeners.size > 0;
1062
+ }
1063
+ adjustMutatingCount(delta) {
1064
+ this.mutatingCountValue += delta;
1065
+ }
1066
+ emit(event) {
1067
+ if (this.listeners.size === 0) return;
1068
+ this.env.scheduler.batch(() => {
1069
+ if (this.listeners.size === 1) this.listeners.values().next().value?.(event);
1070
+ else for (const listener of [...this.listeners]) listener(event);
1071
+ });
1072
+ }
1073
+ subscribe(listener) {
1074
+ this.listeners.add(listener);
1075
+ return () => {
1076
+ this.listeners.delete(listener);
1077
+ };
1078
+ }
1079
+ build(options, seededState) {
1080
+ const mutation = new MutationEntry(this, this.env, this.nextId++, options, seededState);
1081
+ const erased = mutation;
1082
+ this.entries.add(erased);
1083
+ this.emit({
1084
+ type: "added",
1085
+ mutation: erased
1086
+ });
1087
+ this.env.onActivity?.();
1088
+ return mutation;
1089
+ }
1090
+ remove(mutation) {
1091
+ if (!this.entries.delete(mutation)) return;
1092
+ mutation.syncMutatingCount(true);
1093
+ this.emit({
1094
+ type: "removed",
1095
+ mutation
1096
+ });
1097
+ this.env.onActivity?.();
1098
+ }
1099
+ clear() {
1100
+ for (const m of [...this.entries]) this.remove(m);
1101
+ }
1102
+ getAll() {
1103
+ return [...this.entries];
1104
+ }
1105
+ findAll(filter) {
1106
+ if (!filter) return [...this.entries];
1107
+ const exactHash = filter.mutationKey !== void 0 && filter.exact === true ? serializeKey(filter.mutationKey) : void 0;
1108
+ const out = [];
1109
+ for (const m of this.entries) if (matchesMutationFilter({
1110
+ mutationKey: m.options.mutationKey,
1111
+ mutationHash: m.mutationHash,
1112
+ state: m.state
1113
+ }, filter, exactHash)) out.push(m);
1114
+ return out;
1115
+ }
1116
+ async resumePausedMutations() {
1117
+ const paused = [...this.entries].filter((m) => m.state.isPaused);
1118
+ await Promise.all(paused.map((m) => m.continue()));
1119
+ }
1120
+ runInScope(scopeId, fn) {
1121
+ const prev = this.scopeQueues.get(scopeId);
1122
+ const next = prev ? prev.catch(() => void 0).then(fn) : fn();
1123
+ const cleanup = next.catch(() => void 0).finally(() => {
1124
+ if (this.scopeQueues.get(scopeId) === cleanup) this.scopeQueues.delete(scopeId);
1125
+ });
1126
+ this.scopeQueues.set(scopeId, cleanup);
1127
+ return next;
1128
+ }
1129
+ };
1130
+ // src/live/observers.ts
1131
+ const PENDING_PROMISE = new Promise(() => void 0);
1132
+ function samePrimitiveKey(a, b) {
1133
+ if (a === b) return true;
1134
+ if (a.length !== b.length) return false;
1135
+ for (let i = 0; i < a.length; i += 1) {
1136
+ const item = a[i];
1137
+ if (item !== null && typeof item === "object") return false;
1138
+ if (!Object.is(item, b[i])) return false;
1139
+ }
1140
+ return true;
1141
+ }
1142
+ function evalEnabled(enabled, state, isSkipped) {
1143
+ if (isSkipped) return false;
1144
+ if (typeof enabled === "function") return enabled(state);
1145
+ return enabled !== false;
1146
+ }
1147
+ function evalTrigger(trigger, state) {
1148
+ if (typeof trigger === "function") return trigger(state);
1149
+ return trigger ?? true;
1150
+ }
1151
+ /** Creates a reactive watcher for a single query with tracked properties and select memoization. */
1152
+ function createQueryWatcher(client, initialOptions, behavior) {
1153
+ let options = client.defaultQueryOptions(initialOptions);
1154
+ let entry = resolveEntry(options);
1155
+ let currentResult;
1156
+ let fetchedAfterMount = false;
1157
+ let lastRawData;
1158
+ let lastSelectFn;
1159
+ let lastSelectedData;
1160
+ let prevCompletedData;
1161
+ let prevCompletedKeyHash;
1162
+ let intervalTimer;
1163
+ const listeners = /* @__PURE__ */ new Set();
1164
+ const trackedKeys = /* @__PURE__ */ new Set();
1165
+ let mounted = false;
1166
+ let lastEntryRef;
1167
+ let lastStateRef;
1168
+ let lastActivePromiseRef;
1169
+ let lastSelectRef;
1170
+ let lastPlaceholderRef;
1171
+ let lastStaleTimeRef;
1172
+ let lastFetchedAfterMount = false;
1173
+ let lastPromiseData;
1174
+ let lastResolvedPromise;
1175
+ let lastTrackedSnapshot;
1176
+ let lastTrackedProxy;
1177
+ function resolveEntry(spec) {
1178
+ return client.getQueryCache().build(spec);
1179
+ }
1180
+ function clearIntervalTimer() {
1181
+ if (intervalTimer !== void 0) {
1182
+ intervalTimer.cancel();
1183
+ intervalTimer = void 0;
1184
+ }
1185
+ }
1186
+ function scheduleRefetchInterval(targetEntry, spec) {
1187
+ if (spec.refetchInterval === void 0 && intervalTimer === void 0) return;
1188
+ clearIntervalTimer();
1189
+ if (!mounted) return;
1190
+ const rawInterval = spec.refetchInterval;
1191
+ const ms = typeof rawInterval === "function" ? rawInterval(targetEntry.state) : rawInterval;
1192
+ if (typeof ms !== "number" || ms <= 0 || !Number.isFinite(ms)) return;
1193
+ const env = client.getRuntimeEnv();
1194
+ intervalTimer = env.clock.setTimeout(() => {
1195
+ intervalTimer = void 0;
1196
+ if (!mounted) return;
1197
+ if (env.focus.get() || spec.refetchIntervalInBackground) {
1198
+ const isSkipped = spec.queryFn === skipToken;
1199
+ if (evalEnabled(spec.enabled, targetEntry.state, isSkipped)) executeFetch({ cancelRefetch: false });
1200
+ }
1201
+ scheduleRefetchInterval(entry, options);
1202
+ }, ms);
1203
+ }
1204
+ function computeResult(targetEntry, spec) {
1205
+ const state = targetEntry.state;
1206
+ const env = client.getRuntimeEnv();
1207
+ let selected;
1208
+ let isPlaceholder = false;
1209
+ if (state.data !== void 0) {
1210
+ if (spec.select) {
1211
+ if (Object.is(state.data, lastRawData) && spec.select === lastSelectFn) selected = lastSelectedData;
1212
+ else {
1213
+ const nextSel = spec.select(state.data);
1214
+ selected = spec.structuralSharing !== false ? keepEqual(lastSelectedData, nextSel) : nextSel;
1215
+ lastRawData = state.data;
1216
+ lastSelectFn = spec.select;
1217
+ lastSelectedData = selected;
1218
+ }
1219
+ } else {
1220
+ selected = state.data;
1221
+ lastRawData = state.data;
1222
+ lastSelectFn = void 0;
1223
+ lastSelectedData = selected;
1224
+ }
1225
+ prevCompletedData = selected;
1226
+ prevCompletedKeyHash = targetEntry.queryHash;
1227
+ } else if (state.status === "pending" && spec.placeholderData !== void 0) {
1228
+ const priorForPlaceholder = prevCompletedKeyHash !== targetEntry.queryHash ? prevCompletedData : prevCompletedData;
1229
+ const placeholder = typeof spec.placeholderData === "function" ? spec.placeholderData(priorForPlaceholder) : spec.placeholderData;
1230
+ if (placeholder !== void 0) {
1231
+ selected = placeholder;
1232
+ isPlaceholder = true;
1233
+ }
1234
+ }
1235
+ let promise;
1236
+ if (targetEntry.promise !== void 0) promise = targetEntry.promise;
1237
+ else if (state.status === "success" && selected !== void 0) {
1238
+ if (!Object.is(selected, lastPromiseData) || lastResolvedPromise === void 0) {
1239
+ lastPromiseData = selected;
1240
+ lastResolvedPromise = Promise.resolve(selected);
1241
+ }
1242
+ promise = lastResolvedPromise;
1243
+ } else promise = PENDING_PROMISE;
1244
+ lastEntryRef = targetEntry;
1245
+ lastStateRef = state;
1246
+ lastActivePromiseRef = targetEntry.promise;
1247
+ lastSelectRef = spec.select;
1248
+ lastPlaceholderRef = spec.placeholderData;
1249
+ lastStaleTimeRef = spec.staleTime;
1250
+ lastFetchedAfterMount = fetchedAfterMount;
1251
+ return deriveQuerySnapshot({
1252
+ state,
1253
+ selectedData: selected,
1254
+ isPlaceholder,
1255
+ isFetchedAfterMount: fetchedAfterMount,
1256
+ staleTime: spec.staleTime,
1257
+ now: env.clock.now(),
1258
+ refetch,
1259
+ promise
1260
+ });
1261
+ }
1262
+ function shouldFetch(targetEntry, spec, isNewEntry) {
1263
+ const isSkipped = spec.queryFn === skipToken;
1264
+ if (!evalEnabled(spec.enabled, targetEntry.state, isSkipped)) return false;
1265
+ const isStale = isEntryStale(targetEntry.state, spec.staleTime, client.getRuntimeEnv().clock.now());
1266
+ const mountPolicy = evalTrigger(spec.refetchOnMount, targetEntry.state);
1267
+ if (mountPolicy === false) return targetEntry.state.status === "pending" && targetEntry.state.data === void 0 && targetEntry.state.fetchPhase === "idle";
1268
+ if (targetEntry.state.status === "error" && spec.retryOnMount === false) return false;
1269
+ if (mountPolicy === "always") return isNewEntry || isStale || targetEntry.state.invalidated;
1270
+ return isStale;
1271
+ }
1272
+ async function executeFetch(fetchOpts) {
1273
+ await entry.fetch(options, {
1274
+ cancelRefetch: fetchOpts?.cancelRefetch ?? true,
1275
+ ...fetchOpts?.direction !== void 0 ? { direction: fetchOpts.direction } : {},
1276
+ ...fetchOpts?.pageParam !== void 0 ? { pageParam: fetchOpts.pageParam } : {},
1277
+ ...behavior ? { behavior } : {}
1278
+ }).catch(() => void 0);
1279
+ fetchedAfterMount = true;
1280
+ updateResult();
1281
+ return currentResult;
1282
+ }
1283
+ async function refetch(refetchOpts) {
1284
+ if (options.queryFn === skipToken) return currentResult;
1285
+ try {
1286
+ await entry.fetch(options, {
1287
+ cancelRefetch: refetchOpts?.cancelRefetch ?? true,
1288
+ ...behavior ? { behavior } : {}
1289
+ });
1290
+ fetchedAfterMount = true;
1291
+ updateResult();
1292
+ return currentResult;
1293
+ } catch (err) {
1294
+ fetchedAfterMount = true;
1295
+ updateResult();
1296
+ if (refetchOpts?.throwOnError) throw err;
1297
+ return currentResult;
1298
+ }
1299
+ }
1300
+ function hasTrackedDifference(prev, next) {
1301
+ if (options.trackedProps === "all" || trackedKeys.size === 0) {
1302
+ if (options.trackedProps === "all") return !shallowSnapshotEqual(prev, next);
1303
+ return prev.status !== next.status || prev.fetchPhase !== next.fetchPhase || !Object.is(prev.data, next.data) || !Object.is(prev.error, next.error) || prev.isPlaceholderData !== next.isPlaceholderData;
1304
+ }
1305
+ const prevRec = prev;
1306
+ const nextRec = next;
1307
+ for (const key of trackedKeys) if (!Object.is(prevRec[key], nextRec[key])) return true;
1308
+ return false;
1309
+ }
1310
+ function notifyListeners() {
1311
+ if (listeners.size === 0) return;
1312
+ if (listeners.size === 1) {
1313
+ listeners.values().next().value?.();
1314
+ return;
1315
+ }
1316
+ for (const listener of [...listeners]) if (listeners.has(listener)) listener();
1317
+ }
1318
+ function updateResult(silent = false) {
1319
+ const prev = currentResult;
1320
+ if (prev !== void 0 && entry === lastEntryRef && entry.state === lastStateRef && entry.promise === lastActivePromiseRef && options.select === lastSelectRef && options.placeholderData === lastPlaceholderRef && options.staleTime === lastStaleTimeRef && fetchedAfterMount === lastFetchedAfterMount && !(entry.state.data === void 0 && typeof options.placeholderData === "function")) {
1321
+ if ((prev.isPlaceholderData || isEntryStale(entry.state, options.staleTime, client.getRuntimeEnv().clock.now())) === prev.isStale) return;
1322
+ }
1323
+ const next = computeResult(entry, options);
1324
+ if (prev && shallowSnapshotEqual(prev, next)) return;
1325
+ currentResult = next;
1326
+ if (!silent && prev && hasTrackedDifference(prev, next)) notifyListeners();
1327
+ }
1328
+ const watcherRef = {
1329
+ get staleTime() {
1330
+ return options.staleTime;
1331
+ },
1332
+ get gcTime() {
1333
+ return options.gcTime;
1334
+ },
1335
+ get refetchOnFocus() {
1336
+ return options.refetchOnFocus;
1337
+ },
1338
+ get refetchOnReconnect() {
1339
+ return options.refetchOnReconnect;
1340
+ },
1341
+ onEntryUpdate(action) {
1342
+ if (action.type === "success" || action.type === "error") fetchedAfterMount = true;
1343
+ updateResult();
1344
+ scheduleRefetchInterval(entry, options);
1345
+ },
1346
+ onEntryDestroy() {},
1347
+ triggerRefetchFromSignal(trigger, forceType) {
1348
+ const isSkipped = options.queryFn === skipToken;
1349
+ if (!evalEnabled(options.enabled, entry.state, isSkipped)) return;
1350
+ const decision = evalTrigger(trigger, entry.state);
1351
+ if (decision === false) return;
1352
+ if (decision === "always" || entry.isStale(options.staleTime)) {
1353
+ if (forceType === "focus" || forceType === "reconnect") executeFetch({ cancelRefetch: false });
1354
+ }
1355
+ }
1356
+ };
1357
+ currentResult = computeResult(entry, options);
1358
+ return {
1359
+ get: () => currentResult,
1360
+ subscribe(listener) {
1361
+ const wasEmpty = listeners.size === 0;
1362
+ listeners.add(listener);
1363
+ if (wasEmpty) {
1364
+ mounted = true;
1365
+ entry.addWatcher(watcherRef);
1366
+ client.mount();
1367
+ if (shouldFetch(entry, options, true)) executeFetch({ cancelRefetch: false });
1368
+ scheduleRefetchInterval(entry, options);
1369
+ }
1370
+ return () => {
1371
+ listeners.delete(listener);
1372
+ if (listeners.size === 0) {
1373
+ mounted = false;
1374
+ clearIntervalTimer();
1375
+ entry.removeWatcher(watcherRef);
1376
+ client.unmount();
1377
+ }
1378
+ };
1379
+ },
1380
+ getOptimistic(nextSpec) {
1381
+ const merged = client.defaultQueryOptions(nextSpec);
1382
+ return computeResult(client.getQueryCache().build(merged), merged);
1383
+ },
1384
+ track(snapshot) {
1385
+ if (options.trackedProps === "all") return snapshot;
1386
+ if (snapshot === lastTrackedSnapshot && lastTrackedProxy !== void 0) return lastTrackedProxy;
1387
+ const proxy = new Proxy(snapshot, { get(target, prop, receiver) {
1388
+ if (typeof prop === "string") trackedKeys.add(prop);
1389
+ return Reflect.get(target, prop, receiver);
1390
+ } });
1391
+ lastTrackedSnapshot = snapshot;
1392
+ lastTrackedProxy = proxy;
1393
+ return proxy;
1394
+ },
1395
+ update(nextSpec) {
1396
+ const prevKeyHash = entry.queryHash;
1397
+ const wasEnabled = evalEnabled(options.enabled, entry.state, options.queryFn === skipToken);
1398
+ const merged = client.defaultQueryOptions(nextSpec);
1399
+ const nextHash = samePrimitiveKey(options.queryKey, merged.queryKey) ? prevKeyHash : serializeKey(merged.queryKey);
1400
+ const prevInterval = options.refetchInterval;
1401
+ options = merged;
1402
+ if (prevKeyHash !== nextHash) {
1403
+ if (mounted) entry.removeWatcher(watcherRef);
1404
+ fetchedAfterMount = false;
1405
+ lastRawData = void 0;
1406
+ lastSelectedData = void 0;
1407
+ lastSelectFn = void 0;
1408
+ entry = resolveEntry(merged);
1409
+ if (mounted) entry.addWatcher(watcherRef);
1410
+ } else entry.setOptions(merged);
1411
+ updateResult(prevKeyHash === nextHash);
1412
+ const isNowEnabled = evalEnabled(options.enabled, entry.state, options.queryFn === skipToken);
1413
+ if (mounted && (prevKeyHash !== nextHash || !wasEnabled && isNowEnabled)) {
1414
+ if (shouldFetch(entry, options, prevKeyHash !== nextHash)) executeFetch({ cancelRefetch: false });
1415
+ }
1416
+ if (mounted && (prevKeyHash !== nextHash || prevInterval !== merged.refetchInterval)) scheduleRefetchInterval(entry, options);
1417
+ },
1418
+ refetch,
1419
+ dispose() {
1420
+ listeners.clear();
1421
+ if (mounted) {
1422
+ mounted = false;
1423
+ clearIntervalTimer();
1424
+ entry.removeWatcher(watcherRef);
1425
+ client.unmount();
1426
+ }
1427
+ }
1428
+ };
1429
+ }
1430
+ function shallowSnapshotEqual(a, b) {
1431
+ return a.status === b.status && a.fetchPhase === b.fetchPhase && Object.is(a.data, b.data) && Object.is(a.error, b.error) && a.isPlaceholderData === b.isPlaceholderData && a.isStale === b.isStale && a.isFetchedAfterMount === b.isFetchedAfterMount && a.dataUpdatedAt === b.dataUpdatedAt && a.errorUpdatedAt === b.errorUpdatedAt && a.failureCount === b.failureCount;
1432
+ }
1433
+ function shallowInfiniteEqual(a, b) {
1434
+ return shallowSnapshotEqual(a, b) && a.hasNextPage === b.hasNextPage && a.hasPreviousPage === b.hasPreviousPage && a.isFetchingNextPage === b.isFetchingNextPage && a.isFetchingPreviousPage === b.isFetchingPreviousPage && a.isFetchNextPageError === b.isFetchNextPageError && a.isFetchPreviousPageError === b.isFetchPreviousPageError;
1435
+ }
1436
+ /** Creates an infinite query pagination behavior shared by `fetchQuery` and `createInfiniteWatcher`. */
1437
+ function createInfiniteBehavior(getSpec) {
1438
+ return { async onFetch(ctx) {
1439
+ const spec = getSpec();
1440
+ const queryFn = spec.queryFn;
1441
+ if (queryFn === void 0 || queryFn === skipToken) throw new Error("Missing queryFn for infinite query");
1442
+ const oldData = ctx.state.data;
1443
+ const oldPages = oldData?.pages ?? [];
1444
+ const oldParams = oldData?.pageParams ?? [];
1445
+ const direction = ctx.direction;
1446
+ const fetchSinglePage = async (pageParam, dir) => {
1447
+ return await Promise.resolve(queryFn({
1448
+ queryKey: spec.queryKey,
1449
+ signal: ctx.signal,
1450
+ meta: spec.meta,
1451
+ pageParam,
1452
+ direction: dir
1453
+ }));
1454
+ };
1455
+ if (direction === "forward" && oldPages.length > 0) {
1456
+ const lastPage = oldPages[oldPages.length - 1];
1457
+ const lastParam = oldParams[oldParams.length - 1];
1458
+ const nextParam = spec.getNextPageParam(lastPage, oldPages, lastParam, oldParams);
1459
+ if (nextParam === void 0 || nextParam === null) return oldData;
1460
+ const newPage = await fetchSinglePage(nextParam, "forward");
1461
+ const nextData = {
1462
+ pages: [...oldPages, newPage],
1463
+ pageParams: [...oldParams, nextParam]
1464
+ };
1465
+ return clampPages(nextData, spec.maxPages, "forward");
1466
+ }
1467
+ if (direction === "backward" && oldPages.length > 0 && spec.getPreviousPageParam) {
1468
+ const firstPage = oldPages[0];
1469
+ const firstParam = oldParams[0];
1470
+ const prevParam = spec.getPreviousPageParam(firstPage, oldPages, firstParam, oldParams);
1471
+ if (prevParam === void 0 || prevParam === null) return oldData;
1472
+ const nextData = {
1473
+ pages: [await fetchSinglePage(prevParam, "backward"), ...oldPages],
1474
+ pageParams: [prevParam, ...oldParams]
1475
+ };
1476
+ return clampPages(nextData, spec.maxPages, "backward");
1477
+ }
1478
+ const total = Math.max(1, oldParams.length);
1479
+ const firstParam = oldParams[0] ?? spec.initialPageParam;
1480
+ const pages = [];
1481
+ const pageParams = [];
1482
+ let currentParam = firstParam;
1483
+ for (let i = 0; i < total; i += 1) {
1484
+ if (ctx.signal.aborted || currentParam === void 0 || currentParam === null) break;
1485
+ const page = await fetchSinglePage(currentParam, direction);
1486
+ pages.push(page);
1487
+ pageParams.push(currentParam);
1488
+ if (i + 1 < total) currentParam = spec.getNextPageParam(page, pages, currentParam, pageParams);
1489
+ }
1490
+ return {
1491
+ pages,
1492
+ pageParams
1493
+ };
1494
+ } };
1495
+ }
1496
+ /** Creates a reactive watcher for paginated/infinite queries. */
1497
+ function createInfiniteWatcher(client, initialOptions) {
1498
+ let spec = initialOptions;
1499
+ let currentDirection;
1500
+ let currentInfiniteSnapshot;
1501
+ const listeners = /* @__PURE__ */ new Set();
1502
+ const behavior = createInfiniteBehavior(() => spec);
1503
+ const baseWatcher = createQueryWatcher(client, spec, behavior);
1504
+ function computeInfinite(base) {
1505
+ const pages = base.data?.pages ?? [];
1506
+ const params = base.data?.pageParams ?? [];
1507
+ const hasNextPage = pages.length > 0 && spec.getNextPageParam(pages[pages.length - 1], pages, params[params.length - 1], params) != null;
1508
+ const hasPreviousPage = pages.length > 0 && spec.getPreviousPageParam !== void 0 && spec.getPreviousPageParam(pages[0], pages, params[0], params) != null;
1509
+ const isFetchingNextPage = base.isFetching && currentDirection === "forward";
1510
+ const isFetchingPreviousPage = base.isFetching && currentDirection === "backward";
1511
+ const isFetchNextPageError = base.isError && currentDirection === "forward";
1512
+ const isFetchPreviousPageError = base.isError && currentDirection === "backward";
1513
+ return deriveInfiniteSnapshot(base, {
1514
+ hasNextPage,
1515
+ hasPreviousPage,
1516
+ isFetchingNextPage,
1517
+ isFetchingPreviousPage,
1518
+ isFetchNextPageError,
1519
+ isFetchPreviousPageError,
1520
+ fetchNextPage,
1521
+ fetchPreviousPage
1522
+ });
1523
+ }
1524
+ async function fetchDirection(direction, opts) {
1525
+ currentDirection = direction;
1526
+ const entry = client.getQueryCache().build(client.defaultQueryOptions(spec));
1527
+ try {
1528
+ await entry.fetch(void 0, {
1529
+ cancelRefetch: opts?.cancelRefetch ?? true,
1530
+ direction,
1531
+ behavior
1532
+ });
1533
+ currentDirection = void 0;
1534
+ currentInfiniteSnapshot = computeInfinite(baseWatcher.get());
1535
+ return currentInfiniteSnapshot;
1536
+ } catch (err) {
1537
+ if (opts?.throwOnError) throw err;
1538
+ currentInfiniteSnapshot = computeInfinite(baseWatcher.get());
1539
+ return currentInfiniteSnapshot;
1540
+ }
1541
+ }
1542
+ function fetchNextPage(opts) {
1543
+ return fetchDirection("forward", opts);
1544
+ }
1545
+ function fetchPreviousPage(opts) {
1546
+ return fetchDirection("backward", opts);
1547
+ }
1548
+ currentInfiniteSnapshot = computeInfinite(baseWatcher.get());
1549
+ let baseUnsub;
1550
+ return {
1551
+ get: () => currentInfiniteSnapshot,
1552
+ subscribe(listener) {
1553
+ const first = listeners.size === 0;
1554
+ listeners.add(listener);
1555
+ if (first) baseUnsub = baseWatcher.subscribe(() => {
1556
+ const next = computeInfinite(baseWatcher.get());
1557
+ if (shallowInfiniteEqual(currentInfiniteSnapshot, next)) return;
1558
+ currentInfiniteSnapshot = next;
1559
+ for (const l of [...listeners]) if (listeners.has(l)) l();
1560
+ });
1561
+ return () => {
1562
+ listeners.delete(listener);
1563
+ if (listeners.size === 0 && baseUnsub) {
1564
+ baseUnsub();
1565
+ baseUnsub = void 0;
1566
+ }
1567
+ };
1568
+ },
1569
+ update(nextOptions) {
1570
+ spec = nextOptions;
1571
+ baseWatcher.update(nextOptions);
1572
+ const next = computeInfinite(baseWatcher.get());
1573
+ if (!shallowInfiniteEqual(currentInfiniteSnapshot, next)) currentInfiniteSnapshot = next;
1574
+ },
1575
+ getOptimistic(nextOptions) {
1576
+ spec = nextOptions;
1577
+ return computeInfinite(baseWatcher.getOptimistic(nextOptions));
1578
+ },
1579
+ track: (snap) => baseWatcher.track(snap),
1580
+ fetchNextPage,
1581
+ fetchPreviousPage,
1582
+ async refetch(opts) {
1583
+ currentDirection = void 0;
1584
+ currentInfiniteSnapshot = computeInfinite(await baseWatcher.refetch(opts));
1585
+ return currentInfiniteSnapshot;
1586
+ },
1587
+ dispose() {
1588
+ listeners.clear();
1589
+ baseUnsub?.();
1590
+ baseUnsub = void 0;
1591
+ baseWatcher.dispose();
1592
+ }
1593
+ };
1594
+ }
1595
+ /** Watches multiple queries in parallel with optional result combiner. */
1596
+ function createQueriesWatcher(client, initialQueries, initialCombine) {
1597
+ let watchers = [];
1598
+ let unsubs = [];
1599
+ let combineFn = initialCombine;
1600
+ let currentValue;
1601
+ let lastRaw = [];
1602
+ let hasComputed = false;
1603
+ const listeners = /* @__PURE__ */ new Set();
1604
+ let mounted = false;
1605
+ const combineResults = (raw) => {
1606
+ if (combineFn) return combineFn(raw);
1607
+ return raw;
1608
+ };
1609
+ const rebuildWatchers = (specs) => {
1610
+ const prevLen = watchers.length;
1611
+ const nextLen = specs.length;
1612
+ const shared = Math.min(prevLen, nextLen);
1613
+ for (let i = 0; i < shared; i += 1) watchers[i].update(specs[i]);
1614
+ for (let i = shared; i < nextLen; i += 1) {
1615
+ const created = createQueryWatcher(client, specs[i]);
1616
+ watchers.push(created);
1617
+ if (mounted) unsubs.push(created.subscribe(() => {
1618
+ recomputeAndNotify();
1619
+ }));
1620
+ }
1621
+ if (prevLen > nextLen) {
1622
+ for (let i = nextLen; i < prevLen; i += 1) {
1623
+ if (mounted) unsubs[i]?.();
1624
+ watchers[i].dispose();
1625
+ }
1626
+ watchers.length = nextLen;
1627
+ if (mounted) unsubs.length = nextLen;
1628
+ }
1629
+ };
1630
+ const recompute = () => {
1631
+ const len = watchers.length;
1632
+ if (hasComputed && len === lastRaw.length) {
1633
+ let unchanged = true;
1634
+ for (let i = 0; i < len; i += 1) if (!Object.is(watchers[i].get(), lastRaw[i])) {
1635
+ unchanged = false;
1636
+ break;
1637
+ }
1638
+ if (unchanged) return currentValue;
1639
+ }
1640
+ const raw = new Array(len);
1641
+ for (let i = 0; i < len; i += 1) raw[i] = watchers[i].get();
1642
+ lastRaw = raw;
1643
+ hasComputed = true;
1644
+ return combineResults(raw);
1645
+ };
1646
+ const recomputeAndNotify = () => {
1647
+ const prev = currentValue;
1648
+ const next = recompute();
1649
+ if (Object.is(prev, next)) return;
1650
+ currentValue = next;
1651
+ for (const l of [...listeners]) if (listeners.has(l)) l();
1652
+ };
1653
+ rebuildWatchers(initialQueries);
1654
+ currentValue = recompute();
1655
+ return {
1656
+ get: () => currentValue,
1657
+ subscribe(listener) {
1658
+ const first = listeners.size === 0;
1659
+ listeners.add(listener);
1660
+ if (first) {
1661
+ mounted = true;
1662
+ unsubs = watchers.map((w) => w.subscribe(() => {
1663
+ recomputeAndNotify();
1664
+ }));
1665
+ }
1666
+ return () => {
1667
+ listeners.delete(listener);
1668
+ if (listeners.size === 0) {
1669
+ mounted = false;
1670
+ for (const u of unsubs) u();
1671
+ unsubs = [];
1672
+ }
1673
+ };
1674
+ },
1675
+ update(queries, combine) {
1676
+ if (combine !== combineFn) hasComputed = false;
1677
+ combineFn = combine;
1678
+ rebuildWatchers(queries);
1679
+ currentValue = recompute();
1680
+ },
1681
+ getOptimistic(queries, combine) {
1682
+ const results = queries.map((spec, idx) => {
1683
+ const w = watchers[idx];
1684
+ return w ? w.getOptimistic(spec) : createQueryWatcher(client, spec).getOptimistic(spec);
1685
+ });
1686
+ return combine ? combine(results) : results;
1687
+ },
1688
+ dispose() {
1689
+ listeners.clear();
1690
+ mounted = false;
1691
+ for (const u of unsubs) u();
1692
+ unsubs = [];
1693
+ for (const w of watchers) w.dispose();
1694
+ watchers = [];
1695
+ }
1696
+ };
1697
+ }
1698
+ /** Creates a reactive watcher for executing mutations with optimistic rollback and callbacks. */
1699
+ function createMutationWatcher(client, initialOptions) {
1700
+ let options = client.defaultMutationOptions(initialOptions);
1701
+ let currentEntry;
1702
+ let currentResult;
1703
+ const listeners = /* @__PURE__ */ new Set();
1704
+ const listenerRef = { onMutationUpdate() {
1705
+ recompute(false);
1706
+ } };
1707
+ function recompute(silent = false) {
1708
+ const prev = currentResult;
1709
+ const state = currentEntry ? currentEntry.state : {
1710
+ context: void 0,
1711
+ data: void 0,
1712
+ error: null,
1713
+ failureCount: 0,
1714
+ failureReason: null,
1715
+ isPaused: false,
1716
+ status: "idle",
1717
+ variables: void 0,
1718
+ submittedAt: 0
1719
+ };
1720
+ currentResult = deriveMutationSnapshot(state, {
1721
+ reset,
1722
+ mutate,
1723
+ mutateAsync
1724
+ });
1725
+ if (!silent && prev !== void 0) {
1726
+ for (const l of [...listeners]) if (listeners.has(l)) l();
1727
+ }
1728
+ }
1729
+ function reset() {
1730
+ if (currentEntry) {
1731
+ currentEntry.removeWatcher(listenerRef);
1732
+ currentEntry = void 0;
1733
+ }
1734
+ recompute(false);
1735
+ }
1736
+ async function mutateAsync(variables, callOptions) {
1737
+ if (currentEntry) currentEntry.removeWatcher(listenerRef);
1738
+ options = client.defaultMutationOptions(options);
1739
+ const entry = client.getMutationCache().build(options);
1740
+ currentEntry = entry;
1741
+ entry.addWatcher(listenerRef);
1742
+ recompute(false);
1743
+ try {
1744
+ const data = await entry.execute(variables);
1745
+ await callOptions?.onSuccess?.(data, variables, entry.state.context);
1746
+ await callOptions?.onSettled?.(data, null, variables, entry.state.context);
1747
+ return data;
1748
+ } catch (error) {
1749
+ await callOptions?.onError?.(error, variables, entry.state.context);
1750
+ await callOptions?.onSettled?.(void 0, error, variables, entry.state.context);
1751
+ throw error;
1752
+ }
1753
+ }
1754
+ function mutate(variables, callOptions) {
1755
+ mutateAsync(variables, callOptions).catch(() => void 0);
1756
+ }
1757
+ recompute(true);
1758
+ return {
1759
+ get: () => currentResult,
1760
+ subscribe(listener) {
1761
+ listeners.add(listener);
1762
+ return () => {
1763
+ listeners.delete(listener);
1764
+ };
1765
+ },
1766
+ update(nextOptions) {
1767
+ options = client.defaultMutationOptions(nextOptions);
1768
+ },
1769
+ mutate,
1770
+ mutateAsync,
1771
+ reset,
1772
+ dispose() {
1773
+ listeners.clear();
1774
+ if (currentEntry) {
1775
+ currentEntry.removeWatcher(listenerRef);
1776
+ currentEntry = void 0;
1777
+ }
1778
+ }
1779
+ };
1780
+ }
1781
+ // src/live/client.ts
1782
+ /** Coordinates query and mutation caches, defaults, SSR hydration, and platform signals. */
1783
+ var QueryClient = class {
1784
+ queryCache;
1785
+ mutationCache;
1786
+ runtimeEnv;
1787
+ defaultOptions;
1788
+ queryDefaults = /* @__PURE__ */ new Map();
1789
+ mutationDefaults = /* @__PURE__ */ new Map();
1790
+ onActivityChange;
1791
+ lastActivity = {
1792
+ fetching: 0,
1793
+ mutating: 0
1794
+ };
1795
+ mountCount = 0;
1796
+ unsubFocus;
1797
+ unsubOnline;
1798
+ constructor(config = {}) {
1799
+ const clock = config.clock ?? createSystemClock();
1800
+ const focus = config.focus ?? createBrowserFocusDriver();
1801
+ const online = config.online ?? createBrowserOnlineDriver();
1802
+ const scheduler = config.scheduler ?? createBatchScheduler();
1803
+ this.defaultOptions = config.defaultOptions ?? {};
1804
+ this.onActivityChange = config.onActivityChange;
1805
+ this.runtimeEnv = {
1806
+ clock,
1807
+ focus,
1808
+ online,
1809
+ scheduler,
1810
+ onActivity: () => this.notifyActivityIfChanged()
1811
+ };
1812
+ this.queryCache = new QueryCache(this.runtimeEnv);
1813
+ this.mutationCache = new MutationCache(this.runtimeEnv);
1814
+ }
1815
+ notifyActivityIfChanged() {
1816
+ if (!this.onActivityChange) return;
1817
+ const fetching = this.isFetching();
1818
+ const mutating = this.isMutating();
1819
+ if (fetching !== this.lastActivity.fetching || mutating !== this.lastActivity.mutating) {
1820
+ this.lastActivity = {
1821
+ fetching,
1822
+ mutating
1823
+ };
1824
+ this.onActivityChange(this.lastActivity);
1825
+ }
1826
+ }
1827
+ getRuntimeEnv() {
1828
+ return this.runtimeEnv;
1829
+ }
1830
+ getQueryCache() {
1831
+ return this.queryCache;
1832
+ }
1833
+ getMutationCache() {
1834
+ return this.mutationCache;
1835
+ }
1836
+ getDefaultOptions() {
1837
+ return this.defaultOptions;
1838
+ }
1839
+ setDefaultOptions(options) {
1840
+ this.defaultOptions = options;
1841
+ }
1842
+ setQueryDefaults(queryKey, options) {
1843
+ this.queryDefaults.set(serializeKey(queryKey), {
1844
+ queryKey,
1845
+ defaultOptions: options
1846
+ });
1847
+ }
1848
+ getQueryDefaults(queryKey) {
1849
+ if (this.queryDefaults.size === 0) return void 0;
1850
+ let matched;
1851
+ for (const entry of this.queryDefaults.values()) if (keyStartsWith(queryKey, entry.queryKey)) matched = {
1852
+ ...matched,
1853
+ ...entry.defaultOptions
1854
+ };
1855
+ return matched;
1856
+ }
1857
+ setMutationDefaults(mutationKey, options) {
1858
+ this.mutationDefaults.set(serializeKey(mutationKey), {
1859
+ queryKey: mutationKey,
1860
+ defaultOptions: options
1861
+ });
1862
+ }
1863
+ getMutationDefaults(mutationKey) {
1864
+ if (this.mutationDefaults.size === 0) return void 0;
1865
+ let matched;
1866
+ for (const entry of this.mutationDefaults.values()) if (keyStartsWith(mutationKey, entry.queryKey)) matched = {
1867
+ ...matched,
1868
+ ...entry.defaultOptions
1869
+ };
1870
+ return matched;
1871
+ }
1872
+ defaultQueryOptions(options) {
1873
+ const globalDefaults = this.defaultOptions.queries;
1874
+ const keyDefaults = this.queryDefaults.size > 0 ? this.getQueryDefaults(options.queryKey) : void 0;
1875
+ if (globalDefaults === void 0 && keyDefaults === void 0) return options;
1876
+ return {
1877
+ ...globalDefaults,
1878
+ ...keyDefaults,
1879
+ ...options
1880
+ };
1881
+ }
1882
+ defaultMutationOptions(options) {
1883
+ const globalDefaults = this.defaultOptions.mutations;
1884
+ const keyDefaults = options.mutationKey && this.mutationDefaults.size > 0 ? this.getMutationDefaults(options.mutationKey) : void 0;
1885
+ if (globalDefaults === void 0 && keyDefaults === void 0) return options;
1886
+ return {
1887
+ ...globalDefaults,
1888
+ ...keyDefaults,
1889
+ ...options
1890
+ };
1891
+ }
1892
+ mount() {
1893
+ this.mountCount += 1;
1894
+ if (this.mountCount !== 1) return;
1895
+ this.unsubFocus = this.runtimeEnv.focus.subscribe(() => {
1896
+ if (this.runtimeEnv.focus.get()) this.queryCache.onFocus();
1897
+ });
1898
+ this.unsubOnline = this.runtimeEnv.online.subscribe(() => {
1899
+ if (this.runtimeEnv.online.get()) {
1900
+ this.queryCache.onOnline();
1901
+ this.resumePausedMutations();
1902
+ }
1903
+ });
1904
+ }
1905
+ unmount() {
1906
+ this.mountCount = Math.max(0, this.mountCount - 1);
1907
+ if (this.mountCount === 0) {
1908
+ this.unsubFocus?.();
1909
+ this.unsubFocus = void 0;
1910
+ this.unsubOnline?.();
1911
+ this.unsubOnline = void 0;
1912
+ }
1913
+ }
1914
+ clear() {
1915
+ this.queryCache.clear();
1916
+ this.mutationCache.clear();
1917
+ }
1918
+ dispose() {
1919
+ this.clear();
1920
+ this.mountCount = 0;
1921
+ this.unsubFocus?.();
1922
+ this.unsubFocus = void 0;
1923
+ this.unsubOnline?.();
1924
+ this.unsubOnline = void 0;
1925
+ }
1926
+ getQueryData(queryKey) {
1927
+ return this.queryCache.get(serializeKey(queryKey))?.state.data;
1928
+ }
1929
+ getQueriesData(filter) {
1930
+ return this.queryCache.findAll(filter).map((entry) => [entry.queryKey, entry.state.data]);
1931
+ }
1932
+ setQueryData(queryKey, updater, options) {
1933
+ const defaulted = this.defaultQueryOptions({ queryKey });
1934
+ const entry = this.queryCache.build(defaulted);
1935
+ const nextData = typeof updater === "function" ? updater(entry.state.data) : updater;
1936
+ if (nextData === void 0) return entry.state.data;
1937
+ return entry.setData(nextData, options?.updatedAt);
1938
+ }
1939
+ setQueriesData(filter, updater, options) {
1940
+ const matched = this.queryCache.findAll(filter);
1941
+ return this.runtimeEnv.scheduler.batch(() => matched.map((entry) => {
1942
+ const next = typeof updater === "function" ? updater(entry.state.data) : updater;
1943
+ if (next !== void 0) entry.setData(next, options?.updatedAt);
1944
+ return [entry.queryKey, entry.state.data];
1945
+ }));
1946
+ }
1947
+ getQueryState(queryKey) {
1948
+ return this.queryCache.get(serializeKey(queryKey))?.state;
1949
+ }
1950
+ async fetchQuery(options, fetchOptions) {
1951
+ const defaulted = this.defaultQueryOptions(options);
1952
+ const entry = this.queryCache.build(defaulted);
1953
+ const now = this.runtimeEnv.clock.now();
1954
+ if (!isEntryStale(entry.state, defaulted.staleTime, now) && entry.state.data !== void 0) return entry.state.data;
1955
+ return await entry.fetch(defaulted, fetchOptions);
1956
+ }
1957
+ async ensureQueryData(options) {
1958
+ const hash = serializeKey(options.queryKey);
1959
+ const entry = this.queryCache.get(hash);
1960
+ if (entry?.state.data !== void 0) {
1961
+ if (options.revalidateIfStale && entry.isStale(options.staleTime)) this.prefetchQuery(options);
1962
+ return entry.state.data;
1963
+ }
1964
+ return await this.fetchQuery(options);
1965
+ }
1966
+ async prefetchQuery(options) {
1967
+ await this.fetchQuery(options).catch(() => void 0);
1968
+ }
1969
+ async fetchInfiniteQuery(options) {
1970
+ const behavior = createInfiniteBehavior(() => options);
1971
+ return await this.fetchQuery(options, { behavior });
1972
+ }
1973
+ async ensureInfiniteQueryData(options) {
1974
+ const hash = serializeKey(options.queryKey);
1975
+ const entry = this.queryCache.get(hash);
1976
+ if (entry?.state.data !== void 0) {
1977
+ if (options.revalidateIfStale && entry.isStale(options.staleTime)) this.prefetchInfiniteQuery(options);
1978
+ return entry.state.data;
1979
+ }
1980
+ return await this.fetchInfiniteQuery(options);
1981
+ }
1982
+ async prefetchInfiniteQuery(options) {
1983
+ await this.fetchInfiniteQuery(options).catch(() => void 0);
1984
+ }
1985
+ async invalidateQueries(filter, options) {
1986
+ const matched = this.queryCache.findAll(filter);
1987
+ if (matched.length > 0) this.runtimeEnv.scheduler.batch(() => {
1988
+ for (let i = 0; i < matched.length; i += 1) matched[i].invalidate();
1989
+ });
1990
+ const refetchType = filter?.refetchType ?? "active";
1991
+ if (refetchType === "none") return;
1992
+ if (filter?.type !== void 0 && filter.type !== "all" && filter.type !== refetchType) {
1993
+ await this.refetchQueries({
1994
+ ...filter,
1995
+ type: refetchType
1996
+ }, options);
1997
+ return;
1998
+ }
1999
+ if (matched.length === 0) return;
2000
+ const cancelRefetch = options?.cancelRefetch ?? true;
2001
+ const results = [];
2002
+ for (let i = 0; i < matched.length; i += 1) {
2003
+ const entry = matched[i];
2004
+ if (refetchType === "all" || refetchType === "active" && entry.watcherCount > 0 || refetchType === "inactive" && entry.watcherCount === 0) results.push(entry.fetch(void 0, { cancelRefetch }));
2005
+ }
2006
+ if (results.length === 0) return;
2007
+ if (options?.throwOnError) await Promise.all(results);
2008
+ else await Promise.allSettled(results);
2009
+ }
2010
+ async refetchQueries(filter, options) {
2011
+ const results = this.queryCache.findAll(filter).map((entry) => entry.fetch(void 0, { cancelRefetch: options?.cancelRefetch ?? true }));
2012
+ if (options?.throwOnError) await Promise.all(results);
2013
+ else await Promise.allSettled(results);
2014
+ }
2015
+ async cancelQueries(filter, options) {
2016
+ const matched = this.queryCache.findAll(filter);
2017
+ if (matched.length === 0) return;
2018
+ this.runtimeEnv.scheduler.batch(() => {
2019
+ for (let i = 0; i < matched.length; i += 1) matched[i].cancel(options);
2020
+ });
2021
+ }
2022
+ removeQueries(filter) {
2023
+ const matched = this.queryCache.findAll(filter);
2024
+ if (matched.length === 0) return;
2025
+ this.runtimeEnv.scheduler.batch(() => {
2026
+ for (let i = 0; i < matched.length; i += 1) this.queryCache.remove(matched[i]);
2027
+ });
2028
+ }
2029
+ async resetQueries(filter) {
2030
+ const matched = this.queryCache.findAll(filter);
2031
+ if (matched.length === 0) return;
2032
+ const fetches = [];
2033
+ this.runtimeEnv.scheduler.batch(() => {
2034
+ for (let i = 0; i < matched.length; i += 1) {
2035
+ const entry = matched[i];
2036
+ const hadWatchers = entry.watcherCount > 0;
2037
+ const key = entry.queryKey;
2038
+ const opts = entry.options;
2039
+ this.queryCache.remove(entry);
2040
+ if (hadWatchers) {
2041
+ const rebuilt = this.queryCache.build({
2042
+ ...opts,
2043
+ queryKey: key
2044
+ });
2045
+ fetches.push(rebuilt.fetch().catch(() => void 0));
2046
+ }
2047
+ }
2048
+ });
2049
+ if (fetches.length > 0) await Promise.all(fetches);
2050
+ }
2051
+ isFetching(filter) {
2052
+ if (filter === void 0) return this.queryCache.fetchingCount;
2053
+ return this.queryCache.findAll({
2054
+ ...filter,
2055
+ fetchPhase: "fetching"
2056
+ }).length;
2057
+ }
2058
+ isMutating(filter) {
2059
+ if (filter === void 0) return this.mutationCache.mutatingCount;
2060
+ return this.mutationCache.findAll({
2061
+ ...filter,
2062
+ status: "pending"
2063
+ }).length;
2064
+ }
2065
+ resumePausedMutations() {
2066
+ return this.mutationCache.resumePausedMutations();
2067
+ }
2068
+ dehydrate(options) {
2069
+ const queries = this.queryCache.getAll().map((entry) => ({
2070
+ queryHash: entry.queryHash,
2071
+ queryKey: entry.queryKey,
2072
+ state: entry.state,
2073
+ promise: entry.promise,
2074
+ meta: entry.options.meta
2075
+ }));
2076
+ const mutations = this.mutationCache.getAll().map((m) => ({
2077
+ mutationKey: m.options.mutationKey,
2078
+ state: m.state,
2079
+ meta: m.options.meta,
2080
+ scope: m.options.scope
2081
+ }));
2082
+ return packCache(queries, mutations, options);
2083
+ }
2084
+ hydrate(dehydrated, options) {
2085
+ const selected = selectHydrateQueries(dehydrated, (hash) => this.queryCache.get(hash)?.state.dataUpdatedAt, options);
2086
+ this.runtimeEnv.scheduler.batch(() => {
2087
+ for (const q of selected) {
2088
+ const defaults = this.defaultQueryOptions({
2089
+ queryKey: q.queryKey,
2090
+ meta: q.meta
2091
+ });
2092
+ const existing = this.queryCache.get(q.queryHash);
2093
+ if (existing) {
2094
+ if (q.state.data !== void 0) existing.setData(q.state.data, q.state.dataUpdatedAt);
2095
+ } else {
2096
+ const entry = this.queryCache.build(defaults, q.state);
2097
+ if (q.promise !== void 0 && q.state.status === "pending") q.promise.then((resolved) => entry.setData(resolved, this.runtimeEnv.clock.now()), () => void 0);
2098
+ }
2099
+ }
2100
+ for (const m of dehydrated.mutations) {
2101
+ const defaults = this.defaultMutationOptions({
2102
+ mutationKey: m.mutationKey,
2103
+ meta: m.meta,
2104
+ scope: m.scope
2105
+ });
2106
+ this.mutationCache.build(defaults, m.state);
2107
+ }
2108
+ });
2109
+ }
2110
+ watchQuery(options) {
2111
+ return createQueryWatcher(this, options);
2112
+ }
2113
+ watchInfiniteQuery(options) {
2114
+ return createInfiniteWatcher(this, options);
2115
+ }
2116
+ watchQueries(queries, combine) {
2117
+ return createQueriesWatcher(this, queries, combine);
2118
+ }
2119
+ watchMutation(options) {
2120
+ return createMutationWatcher(this, options);
2121
+ }
2122
+ };
2123
+ /** Convenience factory matching Bevelo engine naming alongside `new QueryClient()`. */
2124
+ function createQueryClient(config) {
2125
+ return new QueryClient(config);
2126
+ }
2127
+ export { DATA_TAG, DEFAULT_GC_TIME_MS, ERROR_TAG, MutationCache, MutationEntry, QueryCache, QueryClient, QueryEntry, TaskCancelledError, clampPages, computeBackoffMs, createBatchScheduler, createBrowserFocusDriver, createBrowserOnlineDriver, createDemandAbortHandle, createInfiniteBehavior, createInfiniteWatcher, createManualClock, createManualSignal, createMutationWatcher, createQueriesWatcher, createQueryClient, createQueryWatcher, createStoragePersister, createSystemClock, createTaskRunner, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, deriveInfiniteSnapshot, deriveMutationSnapshot, deriveQuerySnapshot, infiniteQuerySpec, initialMutationState, initialQueryState, isEntryStale, isPlainObject, isTaskCancelled, keepEqual, keepPrevious, keyStartsWith, matchesMutationFilter, matchesQueryFilter, mutationSpec, packCache, partialMatchValue, persistQueryClient, querySpec, reduceMutationState, reduceQueryState, resolveNetworkAction, resolveStaleMs, selectHydrateQueries, serializeKey, shouldRetryAttempt, skipToken, streamedQuery, syncQueryClientAcrossTabs };