@lupinum/better-convex-vue 0.8.0-beta.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,2222 @@
1
+ import { ConvexCallError, normalizeConvexError } from './errors.mjs';
2
+ import { ConvexClient } from 'convex/browser';
3
+ import { shallowRef, readonly, watch, inject, getCurrentScope, onScopeDispose, computed, ref, isRef, toValue } from 'vue';
4
+ import { c as createBetterConvexAttachment, a as attachClientIdentity } from './shared/better-convex-vue.vyh3n_Te.mjs';
5
+ import { getFunctionName } from 'convex/server';
6
+ import { hash } from 'ohash';
7
+ import 'convex/values';
8
+
9
+ const IDENTITY_CHANGED = "IDENTITY_CHANGED";
10
+ function createIdentityChangedError(operation) {
11
+ const message = operation ? `Convex ${operation} rejected: the auth identity changed before it settled (${IDENTITY_CHANGED}).` : `Convex operation rejected: the auth identity changed (${IDENTITY_CHANGED}).`;
12
+ return new ConvexCallError({
13
+ kind: "authentication",
14
+ code: IDENTITY_CHANGED,
15
+ message
16
+ });
17
+ }
18
+ function isIdentityChangedError(error) {
19
+ return typeof error === "object" && error !== null && error.code === IDENTITY_CHANGED;
20
+ }
21
+
22
+ const CONFIRMATION_TIMEOUT_MS = 1e4;
23
+ function validateSnapshot(snapshot) {
24
+ if (!Number.isSafeInteger(snapshot.sessionGeneration) || snapshot.sessionGeneration < 0) {
25
+ throw new TypeError("Auth adapter sessionGeneration must be a non-negative safe integer.");
26
+ }
27
+ if (snapshot.status === "authenticated") {
28
+ if (typeof snapshot.identityKey !== "string" || snapshot.identityKey.length === 0) {
29
+ throw new TypeError(
30
+ "An authenticated auth adapter snapshot requires a non-empty identityKey."
31
+ );
32
+ }
33
+ } else if (snapshot.identityKey !== null) {
34
+ throw new TypeError(
35
+ "A non-authenticated auth adapter snapshot cannot carry a user identityKey."
36
+ );
37
+ }
38
+ if (snapshot.status === "error" && !(snapshot.error instanceof Error)) {
39
+ throw new TypeError("An error auth adapter snapshot requires an Error.");
40
+ }
41
+ return snapshot;
42
+ }
43
+ function clientIdentityKey(snapshot) {
44
+ return snapshot.status === "authenticated" ? `user:${snapshot.identityKey}` : "anonymous";
45
+ }
46
+ function publicError(snapshot) {
47
+ if (snapshot.status !== "error") return null;
48
+ return new ConvexCallError({
49
+ kind: "authentication",
50
+ message: "Authentication failed"
51
+ });
52
+ }
53
+ function createAuthAdapterIdentityPort(adapter) {
54
+ let desired = validateSnapshot(adapter.snapshot());
55
+ let identityGeneration = 0;
56
+ let disposed = false;
57
+ let currentClient = null;
58
+ let currentClientGeneration = -1;
59
+ const activeAuthConfiguration = /* @__PURE__ */ new WeakMap();
60
+ let initialSettled = desired.status !== "loading" && desired.status !== "authenticated";
61
+ let snapshot = {
62
+ authEnabled: true,
63
+ settled: initialSettled,
64
+ identityKey: clientIdentityKey(desired),
65
+ identityGeneration,
66
+ error: publicError(desired)
67
+ };
68
+ const listeners = /* @__PURE__ */ new Set();
69
+ const settlementWaiters = /* @__PURE__ */ new Set();
70
+ const generationSettlementWaiters = /* @__PURE__ */ new Set();
71
+ let activeConfirmation = null;
72
+ const notify = () => {
73
+ for (const listener of [...listeners]) {
74
+ try {
75
+ listener();
76
+ } catch {
77
+ }
78
+ }
79
+ };
80
+ const resolveSettlement = () => {
81
+ if (!snapshot.settled) return;
82
+ initialSettled = true;
83
+ for (const resolve of [...settlementWaiters]) resolve();
84
+ settlementWaiters.clear();
85
+ };
86
+ const publish = (next) => {
87
+ snapshot = Object.freeze(next);
88
+ resolveSettlement();
89
+ for (const waiter of [...generationSettlementWaiters]) waiter.check();
90
+ notify();
91
+ };
92
+ const waitForGenerationSettlement = (generation) => {
93
+ if (snapshot.identityGeneration !== generation) {
94
+ return Promise.reject(createIdentityChangedError("authentication refresh"));
95
+ }
96
+ if (snapshot.settled) {
97
+ return snapshot.error ? Promise.reject(snapshot.error) : Promise.resolve();
98
+ }
99
+ return new Promise((resolve, reject) => {
100
+ const waiter = {
101
+ check() {
102
+ if (snapshot.identityGeneration !== generation) {
103
+ waiter.cancel(createIdentityChangedError("authentication refresh"));
104
+ return;
105
+ }
106
+ if (!snapshot.settled) return;
107
+ generationSettlementWaiters.delete(waiter);
108
+ if (snapshot.error) reject(snapshot.error);
109
+ else resolve();
110
+ },
111
+ cancel(error) {
112
+ generationSettlementWaiters.delete(waiter);
113
+ reject(error);
114
+ }
115
+ };
116
+ generationSettlementWaiters.add(waiter);
117
+ waiter.check();
118
+ });
119
+ };
120
+ const failClosed = (failedGeneration, cause) => {
121
+ if (disposed || failedGeneration !== identityGeneration) return;
122
+ const rejection = cause instanceof ConvexCallError ? cause : new ConvexCallError({
123
+ kind: "authentication",
124
+ message: "Convex authentication failed"
125
+ });
126
+ identityGeneration += 1;
127
+ currentClient = null;
128
+ currentClientGeneration = -1;
129
+ desired = {
130
+ status: "error",
131
+ identityKey: null,
132
+ sessionGeneration: desired.sessionGeneration + 1,
133
+ error: rejection
134
+ };
135
+ publish({
136
+ authEnabled: true,
137
+ settled: true,
138
+ identityKey: "anonymous",
139
+ identityGeneration,
140
+ error: publicError(desired)
141
+ });
142
+ activeConfirmation?.cancel(rejection);
143
+ };
144
+ const confirm = (client, expectedGeneration) => {
145
+ if (activeConfirmation?.client === client && activeConfirmation.generation === expectedGeneration) {
146
+ return activeConfirmation.promise;
147
+ }
148
+ const superseded = createIdentityChangedError("authentication");
149
+ activeConfirmation?.cancel(superseded);
150
+ const configuration = {};
151
+ activeAuthConfiguration.set(client, configuration);
152
+ let resolvePromise;
153
+ let rejectPromise;
154
+ const promise = new Promise((resolve, reject) => {
155
+ resolvePromise = resolve;
156
+ rejectPromise = reject;
157
+ });
158
+ let done = false;
159
+ let timer = null;
160
+ const confirmation = {
161
+ client,
162
+ generation: expectedGeneration,
163
+ promise,
164
+ cancel(error) {
165
+ finish(error);
166
+ }
167
+ };
168
+ const finish = (error) => {
169
+ if (done) return;
170
+ done = true;
171
+ if (timer !== null) clearTimeout(timer);
172
+ timer = null;
173
+ if (activeConfirmation === confirmation) activeConfirmation = null;
174
+ if (error) rejectPromise(error);
175
+ else resolvePromise();
176
+ };
177
+ activeConfirmation = confirmation;
178
+ timer = setTimeout(() => {
179
+ const timeout = new ConvexCallError({
180
+ kind: "authentication",
181
+ code: "AUTH_CONFIRMATION_TIMEOUT",
182
+ message: "Convex authentication confirmation timed out"
183
+ });
184
+ failClosed(expectedGeneration, timeout);
185
+ finish(timeout);
186
+ }, CONFIRMATION_TIMEOUT_MS);
187
+ try {
188
+ client.setAuth(adapter.fetchToken, (authenticated) => {
189
+ if (disposed || expectedGeneration !== identityGeneration || client !== currentClient || activeAuthConfiguration.get(client) !== configuration) {
190
+ finish(createIdentityChangedError("authentication"));
191
+ return;
192
+ }
193
+ if (!authenticated) {
194
+ const rejection = new ConvexCallError({
195
+ kind: "authentication",
196
+ message: "Convex rejected the authentication token"
197
+ });
198
+ failClosed(expectedGeneration, rejection);
199
+ finish(rejection);
200
+ return;
201
+ }
202
+ publish({ ...snapshot, settled: true, error: null });
203
+ finish();
204
+ });
205
+ } catch {
206
+ const rejection = new ConvexCallError({
207
+ kind: "authentication",
208
+ message: "Convex authentication setup failed"
209
+ });
210
+ failClosed(expectedGeneration, rejection);
211
+ finish(rejection);
212
+ }
213
+ return promise;
214
+ };
215
+ const transition = (nextValue) => {
216
+ const next = validateSnapshot(nextValue);
217
+ const previous = desired;
218
+ if (previous.status === next.status && previous.identityKey === next.identityKey && previous.sessionGeneration === next.sessionGeneration && previous.error === next.error) {
219
+ return;
220
+ }
221
+ desired = next;
222
+ const crossedIdentity = previous.status !== next.status || previous.identityKey !== next.identityKey || previous.sessionGeneration !== next.sessionGeneration;
223
+ if (crossedIdentity) {
224
+ const retired = createIdentityChangedError("authentication");
225
+ activeConfirmation?.cancel(retired);
226
+ identityGeneration += 1;
227
+ currentClient = null;
228
+ currentClientGeneration = -1;
229
+ publish({
230
+ authEnabled: true,
231
+ settled: next.status === "anonymous" || next.status === "error",
232
+ identityKey: clientIdentityKey(next),
233
+ identityGeneration,
234
+ error: publicError(next)
235
+ });
236
+ return;
237
+ }
238
+ publish({ ...snapshot, error: publicError(next) });
239
+ };
240
+ const unsubscribeAdapter = adapter.subscribe(() => {
241
+ if (disposed) return;
242
+ try {
243
+ transition(adapter.snapshot());
244
+ } catch (cause) {
245
+ transition({
246
+ status: "error",
247
+ identityKey: null,
248
+ sessionGeneration: desired.sessionGeneration + 1,
249
+ error: cause instanceof Error ? cause : new Error("Invalid auth adapter state")
250
+ });
251
+ }
252
+ });
253
+ return Object.freeze({
254
+ snapshot: () => snapshot,
255
+ waitForInitialSettlement: () => {
256
+ if (initialSettled || snapshot.settled) return Promise.resolve();
257
+ return new Promise((resolve) => settlementWaiters.add(resolve));
258
+ },
259
+ subscribe(listener) {
260
+ if (disposed) return () => {
261
+ };
262
+ listeners.add(listener);
263
+ return () => listeners.delete(listener);
264
+ },
265
+ async initializePrimary(candidate) {
266
+ if (disposed) throw new Error("Auth adapter identity port is disposed.");
267
+ const client = candidate;
268
+ const generation = identityGeneration;
269
+ currentClient = client;
270
+ currentClientGeneration = generation;
271
+ if (desired.status !== "authenticated") {
272
+ publish({ ...snapshot, settled: true });
273
+ return;
274
+ }
275
+ await confirm(client, generation);
276
+ },
277
+ failPrimary(failedGeneration, cause) {
278
+ failClosed(failedGeneration, cause);
279
+ },
280
+ async refresh() {
281
+ if (disposed) return;
282
+ await adapter.refreshSession();
283
+ if (disposed || desired.status === "anonymous") return;
284
+ if (desired.status !== "authenticated") {
285
+ throw snapshot.error ?? new ConvexCallError({
286
+ kind: "authentication",
287
+ message: "Authentication refresh failed"
288
+ });
289
+ }
290
+ const generation = identityGeneration;
291
+ const client = currentClient;
292
+ if (client) {
293
+ await confirm(client, currentClientGeneration);
294
+ return;
295
+ }
296
+ await waitForGenerationSettlement(generation);
297
+ },
298
+ dispose() {
299
+ if (disposed) return;
300
+ disposed = true;
301
+ const cancellation = new ConvexCallError({
302
+ kind: "authentication",
303
+ message: "Authentication runtime was disposed"
304
+ });
305
+ activeConfirmation?.cancel(cancellation);
306
+ for (const waiter of [...generationSettlementWaiters]) waiter.cancel(cancellation);
307
+ unsubscribeAdapter();
308
+ listeners.clear();
309
+ snapshot = Object.freeze({ ...snapshot, settled: true });
310
+ resolveSettlement();
311
+ currentClient = null;
312
+ }
313
+ });
314
+ }
315
+
316
+ const DEFAULT_CONNECTION_STATE = {
317
+ hasInflightRequests: false,
318
+ isWebSocketConnected: false,
319
+ timeOfOldestInflightRequest: null,
320
+ hasEverConnected: false,
321
+ connectionCount: 0,
322
+ connectionRetries: 0,
323
+ inflightMutations: 0,
324
+ inflightActions: 0
325
+ };
326
+ function createConvexClientOwner(input) {
327
+ const { primaryFactory, identityPort, anonymousFactory } = input;
328
+ let primary = identityPort ? null : primaryFactory();
329
+ let currentIdentityGeneration = 0;
330
+ let anonymous = null;
331
+ let disposed = false;
332
+ let resolveDisposed;
333
+ const disposedSignal = new Promise((resolve) => {
334
+ resolveDisposed = resolve;
335
+ });
336
+ let disposePromise = null;
337
+ let replacementInFlight = null;
338
+ let authPort = null;
339
+ const replacementCandidates = /* @__PURE__ */ new Set();
340
+ const closedReplacementCandidates = /* @__PURE__ */ new WeakSet();
341
+ const listeners = /* @__PURE__ */ new Set();
342
+ const pendingCalls = /* @__PURE__ */ new Set();
343
+ const disposers = /* @__PURE__ */ new Set();
344
+ const identityListeners = /* @__PURE__ */ new Set();
345
+ function closeReplacementCandidate(candidate) {
346
+ if (closedReplacementCandidates.has(candidate)) return Promise.resolve();
347
+ closedReplacementCandidates.add(candidate);
348
+ return candidate.close();
349
+ }
350
+ function closeRetiredPrimary(client) {
351
+ try {
352
+ void client.close().catch(() => {
353
+ });
354
+ } catch {
355
+ }
356
+ }
357
+ const connectionState = shallowRef({
358
+ ...DEFAULT_CONNECTION_STATE
359
+ });
360
+ let connectionUnsubscribe = null;
361
+ let connectionConsumers = 0;
362
+ function subscribeConnection() {
363
+ if (!primary || connectionUnsubscribe) return;
364
+ connectionState.value = primary.connectionState();
365
+ connectionUnsubscribe = primary.subscribeToConnectionState((state) => {
366
+ connectionState.value = state;
367
+ });
368
+ }
369
+ function unsubscribeConnection() {
370
+ connectionUnsubscribe?.();
371
+ connectionUnsubscribe = null;
372
+ }
373
+ function resetConnectionForReplacement() {
374
+ unsubscribeConnection();
375
+ connectionState.value = { ...DEFAULT_CONNECTION_STATE };
376
+ if (connectionConsumers > 0) subscribeConnection();
377
+ }
378
+ function subscribeEntry(entry) {
379
+ if (!primary || authPort && !authPort.snapshot().settled) return;
380
+ const subscribedClient = primary;
381
+ const subscribedGeneration = currentIdentityGeneration;
382
+ const isCurrentSubscription = () => entry.active && primary === subscribedClient && currentIdentityGeneration === subscribedGeneration;
383
+ entry.underlying = subscribedClient.onUpdate(
384
+ entry.query,
385
+ entry.args,
386
+ (result) => {
387
+ if (isCurrentSubscription()) return entry.callback(result);
388
+ },
389
+ (error) => {
390
+ if (isCurrentSubscription()) return entry.onError?.(error);
391
+ }
392
+ );
393
+ }
394
+ function detachEntry(entry) {
395
+ entry.underlying?.();
396
+ entry.underlying = null;
397
+ }
398
+ function rebindListeners(newClient) {
399
+ for (const entry of listeners) detachEntry(entry);
400
+ primary = newClient;
401
+ for (const entry of listeners) subscribeEntry(entry);
402
+ }
403
+ function rejectPendingForGeneration(generation) {
404
+ for (const pending of [...pendingCalls]) {
405
+ if (pending.generation === generation) {
406
+ pendingCalls.delete(pending);
407
+ pending.reject(createIdentityChangedError());
408
+ }
409
+ }
410
+ }
411
+ function rejectAllPending() {
412
+ for (const pending of [...pendingCalls]) {
413
+ pendingCalls.delete(pending);
414
+ pending.reject(createIdentityChangedError());
415
+ }
416
+ }
417
+ async function primaryForDispatch() {
418
+ if (authPort && !authPort.snapshot().settled) {
419
+ await Promise.race([authPort.waitForInitialSettlement(), disposedSignal]);
420
+ }
421
+ if (replacementInFlight) {
422
+ try {
423
+ await replacementInFlight;
424
+ } catch {
425
+ }
426
+ }
427
+ if (disposed || !primary) throw createIdentityChangedError();
428
+ return { client: primary, identityGeneration: currentIdentityGeneration };
429
+ }
430
+ async function dispatch(method, fn, args, options) {
431
+ const entryGeneration = authPort?.snapshot().identityGeneration ?? currentIdentityGeneration;
432
+ const target = await primaryForDispatch();
433
+ const { client, identityGeneration: generation } = target;
434
+ if (disposed || generation !== entryGeneration || (authPort?.snapshot().identityGeneration ?? currentIdentityGeneration) !== entryGeneration || primary !== client || currentIdentityGeneration !== generation) {
435
+ throw createIdentityChangedError(method);
436
+ }
437
+ let reject;
438
+ const aborted = new Promise((_, r) => {
439
+ reject = r;
440
+ });
441
+ const pending = { generation, reject };
442
+ pendingCalls.add(pending);
443
+ const underlying = client[method](fn, args, options);
444
+ underlying.catch(() => {
445
+ });
446
+ try {
447
+ const result = await Promise.race([underlying, aborted]);
448
+ if (disposed || currentIdentityGeneration !== generation || (authPort?.snapshot().identityGeneration ?? currentIdentityGeneration) !== entryGeneration) {
449
+ throw createIdentityChangedError(method);
450
+ }
451
+ return result;
452
+ } finally {
453
+ pendingCalls.delete(pending);
454
+ }
455
+ }
456
+ const handle = {
457
+ query: ((fn, args) => dispatch("query", fn, args)),
458
+ mutation: ((fn, args, options) => dispatch("mutation", fn, args, options)),
459
+ action: ((fn, args) => dispatch("action", fn, args)),
460
+ onUpdate: ((query, args, callback, onError) => {
461
+ if (disposed) {
462
+ const stop2 = () => {
463
+ };
464
+ const unsubscribe2 = stop2;
465
+ unsubscribe2.unsubscribe = stop2;
466
+ unsubscribe2.getCurrentValue = () => void 0;
467
+ unsubscribe2.getQueryLogs = () => void 0;
468
+ return unsubscribe2;
469
+ }
470
+ const entry = {
471
+ query,
472
+ args,
473
+ callback,
474
+ onError,
475
+ underlying: null,
476
+ active: true
477
+ };
478
+ listeners.add(entry);
479
+ subscribeEntry(entry);
480
+ const stop = () => {
481
+ if (!entry.active) return;
482
+ entry.active = false;
483
+ listeners.delete(entry);
484
+ detachEntry(entry);
485
+ };
486
+ const unsubscribe = stop;
487
+ unsubscribe.unsubscribe = stop;
488
+ unsubscribe.getCurrentValue = () => entry.underlying?.getCurrentValue?.();
489
+ unsubscribe.getQueryLogs = () => entry.underlying?.getQueryLogs?.();
490
+ return unsubscribe;
491
+ })
492
+ };
493
+ function replacePrimary(replaceInput) {
494
+ if (disposed) return Promise.reject(new Error("[client-owner] disposed"));
495
+ const previous = primary;
496
+ const previousGeneration = currentIdentityGeneration;
497
+ for (const entry of listeners) detachEntry(entry);
498
+ primary = null;
499
+ resetConnectionForReplacement();
500
+ rejectPendingForGeneration(previousGeneration);
501
+ if (previous) closeRetiredPrimary(previous);
502
+ let candidate = null;
503
+ const run = (async () => {
504
+ try {
505
+ candidate = primaryFactory();
506
+ replacementCandidates.add(candidate);
507
+ await Promise.race([replaceInput.initialize(candidate), disposedSignal]);
508
+ if (disposed) throw createIdentityChangedError();
509
+ } catch (error) {
510
+ if (candidate) await closeReplacementCandidate(candidate);
511
+ throw error;
512
+ }
513
+ if (!candidate) throw createIdentityChangedError();
514
+ if (disposed || !replaceInput.isCurrent()) {
515
+ await closeReplacementCandidate(candidate);
516
+ throw createIdentityChangedError();
517
+ }
518
+ currentIdentityGeneration = replaceInput.identityGeneration;
519
+ rebindListeners(candidate);
520
+ resetConnectionForReplacement();
521
+ for (const listener of [...identityListeners]) {
522
+ try {
523
+ listener();
524
+ } catch {
525
+ }
526
+ }
527
+ rejectPendingForGeneration(previousGeneration);
528
+ return candidate;
529
+ })().finally(() => {
530
+ if (candidate) replacementCandidates.delete(candidate);
531
+ });
532
+ replacementInFlight = run;
533
+ void run.catch(() => {
534
+ }).finally(() => {
535
+ if (replacementInFlight === run) replacementInFlight = null;
536
+ });
537
+ return run;
538
+ }
539
+ function attachIdentityPort(port) {
540
+ authPort = port;
541
+ let observedGeneration = port.snapshot().identityGeneration;
542
+ let observedSettled = port.snapshot().settled;
543
+ const replaceGeneration = (targetGeneration) => {
544
+ void replacePrimary({
545
+ identityGeneration: targetGeneration,
546
+ isCurrent: () => port.snapshot().identityGeneration === targetGeneration,
547
+ initialize: (candidate) => port.initializePrimary(candidate)
548
+ }).catch((error) => {
549
+ port.failPrimary(targetGeneration, error);
550
+ });
551
+ };
552
+ const unsubscribe = port.subscribe(() => {
553
+ const snapshot = port.snapshot();
554
+ const becameSettled = !observedSettled && snapshot.settled;
555
+ observedSettled = snapshot.settled;
556
+ if (becameSettled) {
557
+ for (const entry of listeners) {
558
+ if (!entry.underlying) subscribeEntry(entry);
559
+ }
560
+ }
561
+ if (snapshot.identityGeneration === observedGeneration) return;
562
+ const targetGeneration = snapshot.identityGeneration;
563
+ observedGeneration = targetGeneration;
564
+ replaceGeneration(targetGeneration);
565
+ });
566
+ const initialSnapshot = port.snapshot();
567
+ if (!primary && (initialSnapshot.settled || initialSnapshot.identityKey !== "anonymous")) {
568
+ replaceGeneration(initialSnapshot.identityGeneration);
569
+ }
570
+ addDisposer(() => {
571
+ unsubscribe();
572
+ if (authPort === port) authPort = null;
573
+ });
574
+ }
575
+ function getAnonymous() {
576
+ if (disposed) throw new Error("[client-owner] disposed");
577
+ if (anonymousFactory) {
578
+ if (!anonymous) anonymous = anonymousFactory();
579
+ return anonymous;
580
+ }
581
+ if (!primary) throw createIdentityChangedError();
582
+ return primary;
583
+ }
584
+ function addDisposer(dispose2) {
585
+ if (disposed) {
586
+ try {
587
+ dispose2();
588
+ } catch {
589
+ }
590
+ return;
591
+ }
592
+ disposers.add(dispose2);
593
+ }
594
+ function subscribeIdentityChange(listener) {
595
+ if (disposed) return () => {
596
+ };
597
+ identityListeners.add(listener);
598
+ let active = true;
599
+ return () => {
600
+ if (!active) return;
601
+ active = false;
602
+ identityListeners.delete(listener);
603
+ };
604
+ }
605
+ function dispose() {
606
+ if (disposePromise) return disposePromise;
607
+ disposed = true;
608
+ resolveDisposed();
609
+ disposePromise = (async () => {
610
+ for (const d of [...disposers]) {
611
+ try {
612
+ d();
613
+ } catch {
614
+ }
615
+ }
616
+ disposers.clear();
617
+ unsubscribeConnection();
618
+ for (const entry of [...listeners]) {
619
+ entry.active = false;
620
+ detachEntry(entry);
621
+ }
622
+ listeners.clear();
623
+ rejectAllPending();
624
+ identityListeners.clear();
625
+ await Promise.allSettled([...replacementCandidates].map(closeReplacementCandidate));
626
+ replacementCandidates.clear();
627
+ const clients = /* @__PURE__ */ new Set();
628
+ if (primary) clients.add(primary);
629
+ if (anonymous) clients.add(anonymous);
630
+ await Promise.allSettled([...clients].map((client) => client.close()));
631
+ primary = null;
632
+ anonymous = null;
633
+ })();
634
+ return disposePromise;
635
+ }
636
+ if (identityPort) attachIdentityPort(identityPort);
637
+ return {
638
+ handle,
639
+ getPrimary() {
640
+ if (!primary) return null;
641
+ return { client: primary, identityGeneration: currentIdentityGeneration };
642
+ },
643
+ getAnonymous,
644
+ replacePrimary,
645
+ attachIdentityPort,
646
+ connection: {
647
+ state: readonly(connectionState),
648
+ addConsumer() {
649
+ connectionConsumers += 1;
650
+ if (connectionConsumers === 1) subscribeConnection();
651
+ let removed = false;
652
+ return () => {
653
+ if (removed) return;
654
+ removed = true;
655
+ connectionConsumers -= 1;
656
+ if (connectionConsumers === 0) unsubscribeConnection();
657
+ };
658
+ }
659
+ },
660
+ addDisposer,
661
+ subscribeIdentityChange,
662
+ dispose
663
+ };
664
+ }
665
+
666
+ const ANONYMOUS_SNAPSHOT = Object.freeze({
667
+ authEnabled: false,
668
+ settled: true,
669
+ identityKey: "anonymous",
670
+ identityGeneration: 0,
671
+ error: null
672
+ });
673
+ const ANONYMOUS_OBSERVER = Object.freeze({
674
+ snapshot: () => ANONYMOUS_SNAPSHOT,
675
+ waitForInitialSettlement: () => Promise.resolve(),
676
+ subscribe: () => () => {
677
+ }
678
+ });
679
+ function createBetterConvexBrowserRuntime(input) {
680
+ const authPort = input.auth ? createAuthAdapterIdentityPort(input.auth) : null;
681
+ const owner = createConvexClientOwner({
682
+ primaryFactory: input.clientFactory,
683
+ ...authPort ? {
684
+ anonymousFactory: input.clientFactory,
685
+ identityPort: authPort
686
+ } : {}
687
+ });
688
+ const identity = authPort ?? ANONYMOUS_OBSERVER;
689
+ let disposed = false;
690
+ const primaryReady = owner.getPrimary() ? Promise.resolve() : new Promise((resolve) => {
691
+ let stop = () => {
692
+ };
693
+ const finish = () => {
694
+ stop();
695
+ resolve();
696
+ };
697
+ stop = owner.subscribeIdentityChange(finish);
698
+ owner.addDisposer(finish);
699
+ });
700
+ owner.addDisposer(() => authPort?.dispose());
701
+ const anonymousHandle = Object.freeze({
702
+ query: ((...args) => owner.getAnonymous().query(...args)),
703
+ mutation: ((...args) => owner.getAnonymous().mutation(...args)),
704
+ action: ((...args) => owner.getAnonymous().action(...args)),
705
+ onUpdate: ((...args) => owner.getAnonymous().onUpdate(...args))
706
+ });
707
+ const attachment = createBetterConvexAttachment({
708
+ client: owner.handle,
709
+ anonymousClient: anonymousHandle,
710
+ identity,
711
+ connection: {
712
+ snapshot: () => owner.connection.state.value,
713
+ subscribe(listener) {
714
+ const remove = owner.connection.addConsumer();
715
+ const stop = watch(owner.connection.state, listener, { flush: "sync" });
716
+ listener(owner.connection.state.value);
717
+ return () => {
718
+ stop();
719
+ remove();
720
+ };
721
+ }
722
+ }
723
+ });
724
+ return Object.freeze({
725
+ handle: owner.handle,
726
+ identity,
727
+ attachment,
728
+ connection: owner.connection,
729
+ clientFor(mode) {
730
+ return mode === "none" ? anonymousHandle : owner.handle;
731
+ },
732
+ async ready() {
733
+ await identity.waitForInitialSettlement();
734
+ await primaryReady;
735
+ },
736
+ async refreshAuth() {
737
+ await authPort?.refresh();
738
+ },
739
+ async dispose() {
740
+ if (disposed) return;
741
+ disposed = true;
742
+ await owner.dispose();
743
+ }
744
+ });
745
+ }
746
+
747
+ const BETTER_CONVEX_KEY = Symbol("@lupinum/better-convex-vue");
748
+ const INTERNAL_REFRESH_AUTH = Symbol.for("better-convex-vue:internal-refresh-auth");
749
+ function makeClient(convexUrl) {
750
+ return new ConvexClient(convexUrl, { unsavedChangesWarning: false });
751
+ }
752
+ function createBetterConvex(options) {
753
+ let installed = false;
754
+ let dispose = null;
755
+ let installedAttachment = null;
756
+ let ownedBrowser = null;
757
+ return Object.freeze({
758
+ install(app) {
759
+ if (installed) throw new Error("[better-convex-vue] plugin is already installed");
760
+ installed = true;
761
+ const attached = "attachment" in options ? options.attachment : null;
762
+ const browser = attached ? null : createBetterConvexBrowserRuntime({
763
+ clientFactory: () => makeClient(options.convexUrl),
764
+ auth: options.auth
765
+ });
766
+ ownedBrowser = browser;
767
+ const attachment = attached ?? browser.attachment;
768
+ const installedBrowser = browser ?? createAttachedBrowserFacade(attachment);
769
+ installedAttachment = attachment;
770
+ const identity = attachClientIdentity(attachment);
771
+ const runtime = Object.freeze({
772
+ browser: installedBrowser,
773
+ identity
774
+ });
775
+ app.provide(BETTER_CONVEX_KEY, runtime);
776
+ dispose = async () => {
777
+ identity.dispose();
778
+ await browser?.dispose();
779
+ };
780
+ app.onUnmount(() => void dispose?.());
781
+ },
782
+ attachment() {
783
+ if (!installedAttachment) {
784
+ throw new Error(
785
+ "[better-convex-vue] plugin must be installed before reading its attachment"
786
+ );
787
+ }
788
+ return installedAttachment;
789
+ },
790
+ async [INTERNAL_REFRESH_AUTH]() {
791
+ if (!ownedBrowser) {
792
+ throw new Error("[better-convex-vue] only the owning plugin can refresh authentication");
793
+ }
794
+ await ownedBrowser.refreshAuth();
795
+ }
796
+ });
797
+ }
798
+ function createAttachedBrowserFacade(attachment) {
799
+ const state = shallowRef(attachment.connection?.snapshot() ?? disconnectedState());
800
+ let consumers = 0;
801
+ let stop = null;
802
+ const addConsumer = () => {
803
+ consumers += 1;
804
+ if (consumers === 1 && attachment.connection) {
805
+ state.value = attachment.connection.snapshot();
806
+ stop = attachment.connection.subscribe((next) => {
807
+ state.value = next;
808
+ });
809
+ }
810
+ let active = true;
811
+ return () => {
812
+ if (!active) return;
813
+ active = false;
814
+ consumers -= 1;
815
+ if (consumers === 0) {
816
+ stop?.();
817
+ stop = null;
818
+ }
819
+ };
820
+ };
821
+ return {
822
+ handle: attachment.client,
823
+ identity: attachment.identity,
824
+ attachment,
825
+ connection: {
826
+ state: readonly(state),
827
+ addConsumer
828
+ },
829
+ clientFor: (mode) => mode === "none" ? attachment.anonymousClient : attachment.client,
830
+ ready: () => attachment.identity.waitForInitialSettlement(),
831
+ refreshAuth: async () => {
832
+ },
833
+ dispose: async () => {
834
+ }
835
+ };
836
+ }
837
+ function disconnectedState() {
838
+ return {
839
+ hasInflightRequests: false,
840
+ isWebSocketConnected: false,
841
+ timeOfOldestInflightRequest: null,
842
+ hasEverConnected: false,
843
+ connectionCount: 0,
844
+ connectionRetries: 0,
845
+ inflightMutations: 0,
846
+ inflightActions: 0
847
+ };
848
+ }
849
+ function useBetterConvexRuntime() {
850
+ const runtime = useOptionalBetterConvexRuntime();
851
+ if (!runtime) throw new Error("[better-convex-vue] plugin is not installed in this Vue app");
852
+ return runtime;
853
+ }
854
+ function useOptionalBetterConvexRuntime() {
855
+ return inject(BETTER_CONVEX_KEY, null);
856
+ }
857
+
858
+ function useConvex() {
859
+ return useBetterConvexRuntime().browser.handle;
860
+ }
861
+
862
+ function useConvexConnectionState() {
863
+ if (!getCurrentScope()) {
864
+ throw new Error(
865
+ "[better-convex-vue] useConvexConnectionState must run inside a Vue effect scope"
866
+ );
867
+ }
868
+ const { browser } = useBetterConvexRuntime();
869
+ const remove = browser.connection.addConsumer();
870
+ onScopeDispose(remove);
871
+ const state = computed(() => browser.connection.state.value);
872
+ return Object.freeze({
873
+ state,
874
+ isConnected: computed(() => state.value.isWebSocketConnected),
875
+ isReconnecting: computed(
876
+ () => state.value.hasEverConnected && !state.value.isWebSocketConnected
877
+ ),
878
+ pendingMutations: computed(() => state.value.inflightMutations),
879
+ pendingActions: computed(() => state.value.inflightActions)
880
+ });
881
+ }
882
+
883
+ function createClientCallState() {
884
+ let activeRequestId = 0;
885
+ const currentStatus = ref("idle");
886
+ const error = ref(void 0);
887
+ const data = ref(void 0);
888
+ const status = computed(() => currentStatus.value);
889
+ const pending = computed(() => currentStatus.value === "pending");
890
+ const start = () => {
891
+ const requestId = ++activeRequestId;
892
+ currentStatus.value = "pending";
893
+ error.value = void 0;
894
+ data.value = void 0;
895
+ return requestId;
896
+ };
897
+ const isCurrent = (requestId) => requestId === activeRequestId;
898
+ const commitSuccess = (requestId, result) => {
899
+ if (!isCurrent(requestId)) return false;
900
+ currentStatus.value = "success";
901
+ data.value = result;
902
+ return true;
903
+ };
904
+ const commitError = (requestId, err) => {
905
+ if (!isCurrent(requestId)) return false;
906
+ currentStatus.value = "error";
907
+ error.value = err;
908
+ return true;
909
+ };
910
+ const reset = () => {
911
+ activeRequestId += 1;
912
+ currentStatus.value = "idle";
913
+ error.value = void 0;
914
+ data.value = void 0;
915
+ };
916
+ return {
917
+ data,
918
+ status,
919
+ pending,
920
+ error,
921
+ start,
922
+ isCurrent,
923
+ commitSuccess,
924
+ commitError,
925
+ mask: reset,
926
+ reset
927
+ };
928
+ }
929
+
930
+ function createCallableController(input) {
931
+ const { operation, getIdentityGeneration, handlers } = input;
932
+ const callState = createClientCallState();
933
+ let lastSeenGeneration = getIdentityGeneration();
934
+ let attemptRevision = 0;
935
+ let disposed = false;
936
+ let stopIdentity = null;
937
+ const observe = (callback) => {
938
+ try {
939
+ callback();
940
+ } catch {
941
+ }
942
+ };
943
+ const run = async (args) => {
944
+ const startedAt = Date.now();
945
+ let event;
946
+ if (input.observer) {
947
+ observe(() => {
948
+ event = input.observer.startEvent(args, startedAt);
949
+ });
950
+ }
951
+ const generation = getIdentityGeneration();
952
+ const attempt = ++attemptRevision;
953
+ let requestId = callState.start();
954
+ try {
955
+ if (disposed) {
956
+ throw new ConvexCallError({
957
+ kind: "unknown",
958
+ code: "CALL_DISPOSED",
959
+ message: "Convex callable is no longer active"
960
+ });
961
+ }
962
+ if (handlers.settle) await handlers.settle();
963
+ if (getIdentityGeneration() !== generation) {
964
+ throw createIdentityChangedError(operation);
965
+ }
966
+ if (attempt === attemptRevision && !callState.isCurrent(requestId)) {
967
+ requestId = callState.start();
968
+ }
969
+ const result = await handlers.invoke(args);
970
+ if (getIdentityGeneration() !== generation) {
971
+ throw createIdentityChangedError(operation);
972
+ }
973
+ callState.commitSuccess(requestId, result);
974
+ if (input.observer) {
975
+ observe(() => input.observer.finishEvent(event, result, startedAt));
976
+ }
977
+ return result;
978
+ } catch (rawError) {
979
+ const normalized = normalizeConvexError(rawError);
980
+ const stale = isIdentityChangedError(normalized) || getIdentityGeneration() !== generation;
981
+ if (stale) {
982
+ if (callState.isCurrent(requestId)) callState.mask();
983
+ const identityError = isIdentityChangedError(normalized) ? normalized : createIdentityChangedError(operation);
984
+ if (input.observer) {
985
+ observe(() => input.observer.failEvent(event, identityError, startedAt));
986
+ }
987
+ throw identityError;
988
+ }
989
+ callState.commitError(requestId, normalized);
990
+ if (input.observer) {
991
+ observe(() => input.observer.failEvent(event, normalized, startedAt));
992
+ }
993
+ throw normalized;
994
+ }
995
+ };
996
+ const onIdentityMaybeChanged = () => {
997
+ const generation = getIdentityGeneration();
998
+ if (generation === lastSeenGeneration) return;
999
+ lastSeenGeneration = generation;
1000
+ callState.mask();
1001
+ };
1002
+ stopIdentity = input.subscribeIdentityChange?.(onIdentityMaybeChanged) ?? null;
1003
+ const reset = () => {
1004
+ attemptRevision += 1;
1005
+ callState.reset();
1006
+ };
1007
+ const dispose = () => {
1008
+ if (disposed) return;
1009
+ disposed = true;
1010
+ attemptRevision += 1;
1011
+ stopIdentity?.();
1012
+ stopIdentity = null;
1013
+ callState.mask();
1014
+ };
1015
+ return {
1016
+ run,
1017
+ data: callState.data,
1018
+ status: callState.status,
1019
+ pending: callState.pending,
1020
+ error: callState.error,
1021
+ reset,
1022
+ dispose
1023
+ };
1024
+ }
1025
+
1026
+ const CALLABLE_OBSERVER_KEY = Symbol.for("better-convex.callable-observer");
1027
+ function isPromiseLike(value) {
1028
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
1029
+ }
1030
+ function wrapOptimisticUpdate(update) {
1031
+ if (!update) return void 0;
1032
+ return (store, args) => {
1033
+ const result = update(store, args);
1034
+ if (isPromiseLike(result)) {
1035
+ console.warn(
1036
+ "[better-convex-vue] optimisticUpdate returned a Promise-like value. Optimistic updates must be synchronous."
1037
+ );
1038
+ }
1039
+ return void 0;
1040
+ };
1041
+ }
1042
+ function createCallable(operation, reference, options) {
1043
+ if (!getCurrentScope()) {
1044
+ throw new Error(
1045
+ `[better-convex-vue] useConvex${operation === "mutation" ? "Mutation" : "Action"} must run inside a Vue effect scope`
1046
+ );
1047
+ }
1048
+ const runtime = useOptionalBetterConvexRuntime();
1049
+ const lifecycle = createCallableController({
1050
+ operation,
1051
+ getIdentityGeneration: () => runtime?.identity.snapshot.value.identityGeneration ?? 0,
1052
+ subscribeIdentityChange: runtime ? (listener) => runtime.browser.identity.subscribe(listener) : void 0,
1053
+ observer: options?.[CALLABLE_OBSERVER_KEY],
1054
+ handlers: {
1055
+ settle: () => runtime?.browser.ready() ?? Promise.resolve(),
1056
+ invoke: async (args) => {
1057
+ if (!runtime) {
1058
+ throw new ConvexCallError({
1059
+ kind: "unknown",
1060
+ message: `[better-convex-vue] useConvex${operation === "mutation" ? "Mutation" : "Action"} cannot execute without an installed browser runtime`
1061
+ });
1062
+ }
1063
+ if (operation === "mutation") {
1064
+ return await runtime.browser.handle.mutation(reference, args, {
1065
+ optimisticUpdate: wrapOptimisticUpdate(options?.optimisticUpdate)
1066
+ });
1067
+ }
1068
+ return await runtime.browser.handle.action(reference, args);
1069
+ }
1070
+ }
1071
+ });
1072
+ onScopeDispose(lifecycle.dispose);
1073
+ const execute = (...args) => lifecycle.run(args[0] ?? {});
1074
+ return Object.freeze(
1075
+ Object.assign(execute, {
1076
+ data: readonly(lifecycle.data),
1077
+ status: lifecycle.status,
1078
+ pending: lifecycle.pending,
1079
+ error: readonly(lifecycle.error)
1080
+ })
1081
+ );
1082
+ }
1083
+ function useConvexMutation(mutation, options) {
1084
+ return createCallable("mutation", mutation, options);
1085
+ }
1086
+ function useConvexAction(action, options) {
1087
+ return createCallable("action", action, options);
1088
+ }
1089
+
1090
+ function isPlainObject(value) {
1091
+ if (!value || typeof value !== "object") return false;
1092
+ const proto = Object.getPrototypeOf(value);
1093
+ return proto === Object.prototype || proto === null;
1094
+ }
1095
+ function deepUnref(value) {
1096
+ const seen = /* @__PURE__ */ new WeakMap();
1097
+ const unwrap = (input) => {
1098
+ const unwrapped = isRef(input) ? input.value : input;
1099
+ if (!unwrapped || typeof unwrapped !== "object") {
1100
+ return unwrapped;
1101
+ }
1102
+ const objectValue = unwrapped;
1103
+ const existing = seen.get(objectValue);
1104
+ if (existing) {
1105
+ return existing;
1106
+ }
1107
+ if (Array.isArray(unwrapped)) {
1108
+ const arrayInput = unwrapped;
1109
+ const draft = Array.from({ length: arrayInput.length });
1110
+ seen.set(objectValue, draft);
1111
+ let changed = false;
1112
+ for (let i = 0; i < arrayInput.length; i++) {
1113
+ const next = unwrap(arrayInput[i]);
1114
+ draft[i] = next;
1115
+ if (next !== arrayInput[i]) {
1116
+ changed = true;
1117
+ }
1118
+ }
1119
+ const result = changed ? draft : arrayInput;
1120
+ seen.set(objectValue, result);
1121
+ return result;
1122
+ }
1123
+ if (isPlainObject(unwrapped)) {
1124
+ const objectInput = unwrapped;
1125
+ const draft = {};
1126
+ seen.set(objectValue, draft);
1127
+ let changed = false;
1128
+ for (const [key, entry] of Object.entries(objectInput)) {
1129
+ const next = unwrap(entry);
1130
+ draft[key] = next;
1131
+ if (next !== entry) {
1132
+ changed = true;
1133
+ }
1134
+ }
1135
+ const result = changed ? draft : objectInput;
1136
+ seen.set(objectValue, result);
1137
+ return result;
1138
+ }
1139
+ return unwrapped;
1140
+ };
1141
+ return unwrap(value);
1142
+ }
1143
+
1144
+ function normalizeConvexArgs(args) {
1145
+ const rawArgs = toValue(args);
1146
+ if (rawArgs === null || rawArgs === void 0) {
1147
+ throw new TypeError(
1148
+ '[better-convex-vue] query arguments cannot be null or undefined; pass {} or the literal "skip"'
1149
+ );
1150
+ }
1151
+ if (rawArgs === "skip") return rawArgs;
1152
+ return deepUnref(rawArgs);
1153
+ }
1154
+ function isConvexArgsSkipped(args) {
1155
+ return args === "skip";
1156
+ }
1157
+
1158
+ function sameTag$1(a, b) {
1159
+ return a.identityKey === b.identityKey && a.identityGeneration === b.identityGeneration;
1160
+ }
1161
+ function createQueryController(input) {
1162
+ const lastSettledArgsHash = shallowRef(void 0);
1163
+ let operationRevision = 0;
1164
+ let unsubscribe = null;
1165
+ let subscribedKey = null;
1166
+ let awaitingFirstValue = false;
1167
+ let disposed = false;
1168
+ function beginOperation() {
1169
+ return {
1170
+ ...input.getIsolationTag(),
1171
+ argsHash: input.getArgsHash(),
1172
+ boundaryKey: input.getBoundaryKey(),
1173
+ operationRevision
1174
+ };
1175
+ }
1176
+ function invalidateOperations() {
1177
+ operationRevision += 1;
1178
+ }
1179
+ function isOperationCurrent(operation) {
1180
+ return !disposed && operation.operationRevision === operationRevision && operation.argsHash === input.getArgsHash() && operation.boundaryKey === input.getBoundaryKey() && sameTag$1(operation, input.getIsolationTag());
1181
+ }
1182
+ function markSettled(operation) {
1183
+ lastSettledArgsHash.value = operation?.argsHash ?? input.getArgsHash();
1184
+ }
1185
+ function teardownSubscription() {
1186
+ const previousKey = subscribedKey;
1187
+ unsubscribe?.();
1188
+ unsubscribe = null;
1189
+ awaitingFirstValue = false;
1190
+ subscribedKey = null;
1191
+ if (previousKey) input.events?.onRemove?.(previousKey);
1192
+ }
1193
+ function setOperationError(error, operation) {
1194
+ if (!isOperationCurrent(operation)) return null;
1195
+ const normalized = normalizeConvexError(error);
1196
+ input.boundary.setError(normalized);
1197
+ return normalized;
1198
+ }
1199
+ function setupSubscription() {
1200
+ if (disposed) return null;
1201
+ const args = input.getArgs();
1202
+ if (args === "skip") return null;
1203
+ const key = input.getBoundaryKey();
1204
+ if (subscribedKey === key && unsubscribe) return null;
1205
+ teardownSubscription();
1206
+ const client = input.getClient();
1207
+ if (!client) return null;
1208
+ const operation = beginOperation();
1209
+ subscribedKey = key;
1210
+ awaitingFirstValue = true;
1211
+ unsubscribe = client.onUpdate(
1212
+ input.query,
1213
+ args,
1214
+ (raw) => {
1215
+ if (!isOperationCurrent(operation)) return;
1216
+ const value = raw;
1217
+ input.boundary.setError(void 0);
1218
+ input.boundary.writeData(value);
1219
+ markSettled(operation);
1220
+ awaitingFirstValue = false;
1221
+ input.events?.onUpdate?.({ key, args, value });
1222
+ },
1223
+ (error) => {
1224
+ if (!isOperationCurrent(operation)) return;
1225
+ const normalized = normalizeConvexError(error);
1226
+ input.boundary.setError(normalized);
1227
+ awaitingFirstValue = false;
1228
+ input.events?.onError?.({ key, args, error, normalized });
1229
+ }
1230
+ );
1231
+ input.events?.onSubscribe?.({ key, args });
1232
+ return operation;
1233
+ }
1234
+ function resetSettled() {
1235
+ lastSettledArgsHash.value = void 0;
1236
+ }
1237
+ function handleIdentityBoundary(boundary) {
1238
+ if (sameTag$1(boundary.nextTag, boundary.previousTag)) return;
1239
+ invalidateOperations();
1240
+ teardownSubscription();
1241
+ input.boundary.setError(void 0);
1242
+ resetSettled();
1243
+ input.boundary.clearData();
1244
+ }
1245
+ function handleExecutionBoundary(boundary) {
1246
+ if (boundary.nextBoundaryKey === boundary.previousBoundaryKey && boundary.nextLive === boundary.previousLive) {
1247
+ return;
1248
+ }
1249
+ input.boundary.setError(void 0);
1250
+ if (subscribedKey === boundary.nextBoundaryKey) return;
1251
+ invalidateOperations();
1252
+ teardownSubscription();
1253
+ if (boundary.nextIdle) {
1254
+ resetSettled();
1255
+ input.boundary.clearData();
1256
+ return;
1257
+ }
1258
+ if (!input.keepPreviousData && boundary.nextBoundaryKey !== boundary.previousBoundaryKey) {
1259
+ input.boundary.clearData();
1260
+ }
1261
+ if (boundary.nextLive) setupSubscription();
1262
+ }
1263
+ function hasSettledForCurrentArgs() {
1264
+ return lastSettledArgsHash.value === input.getArgsHash();
1265
+ }
1266
+ function data() {
1267
+ if (!input.boundary.hasData()) return void 0;
1268
+ return input.boundary.readData();
1269
+ }
1270
+ function isStale(state) {
1271
+ return !state.idle && input.boundary.hasData() && lastSettledArgsHash.value !== void 0 && (state.pending || state.errored || input.keepPreviousData && input.getArgsHash() !== lastSettledArgsHash.value);
1272
+ }
1273
+ function dispose() {
1274
+ if (disposed) return;
1275
+ invalidateOperations();
1276
+ teardownSubscription();
1277
+ disposed = true;
1278
+ }
1279
+ return {
1280
+ beginOperation,
1281
+ invalidateOperations,
1282
+ isOperationCurrent,
1283
+ markSettled,
1284
+ setOperationError,
1285
+ setupSubscription,
1286
+ teardownSubscription,
1287
+ isAwaitingFirstValue: () => awaitingFirstValue,
1288
+ hasData: input.boundary.hasData,
1289
+ hasSettledForCurrentArgs,
1290
+ data,
1291
+ isStale,
1292
+ handleIdentityBoundary,
1293
+ handleExecutionBoundary,
1294
+ dispose
1295
+ };
1296
+ }
1297
+
1298
+ function decideQueryExecution(input) {
1299
+ if (input.skipped) return "idle";
1300
+ if (input.auth === "none") return "execute";
1301
+ if (!input.identity.authEnabled) return input.auth === "required" ? "idle" : "execute";
1302
+ if (!input.identity.settled) return "wait";
1303
+ if (input.identity.error) return "error";
1304
+ if (input.identity.identityKey === "anonymous")
1305
+ return input.auth === "required" ? "idle" : "execute";
1306
+ return "execute";
1307
+ }
1308
+
1309
+ function useConvexQuery(query, ...parameters) {
1310
+ if (!getCurrentScope()) {
1311
+ throw new Error("[better-convex-vue] useConvexQuery must run inside a Vue effect scope");
1312
+ }
1313
+ const [providedArgs, options, hydrationSeed] = parameters;
1314
+ const args = parameters.length === 0 ? {} : providedArgs;
1315
+ const runtime = useBetterConvexRuntime();
1316
+ const auth = options?.auth ?? "optional";
1317
+ const currentArgs = computed(() => normalizeConvexArgs(args));
1318
+ const argsHash = computed(() => hash(currentArgs.value));
1319
+ const noQueryValue = Symbol("no-query-value");
1320
+ const initialValue = hydrationSeed === void 0 ? noQueryValue : hydrationSeed.value;
1321
+ const raw = shallowRef(initialValue);
1322
+ const boundaryError = shallowRef(void 0);
1323
+ const loading = ref(false);
1324
+ const identity = runtime.identity.snapshot;
1325
+ const functionName = getFunctionName(query);
1326
+ const gate = computed(
1327
+ () => decideQueryExecution({
1328
+ auth,
1329
+ skipped: isConvexArgsSkipped(currentArgs.value),
1330
+ identity: identity.value
1331
+ })
1332
+ );
1333
+ const tag = computed(() => ({
1334
+ identityKey: auth === "none" ? "anonymous" : identity.value.identityKey ?? "anonymous",
1335
+ identityGeneration: auth === "none" ? 0 : identity.value.identityGeneration
1336
+ }));
1337
+ const boundaryKey = computed(
1338
+ () => `${functionName}:${auth}:${tag.value.identityKey}:${argsHash.value}`
1339
+ );
1340
+ const controller = createQueryController({
1341
+ query,
1342
+ keepPreviousData: options?.keepPreviousData ?? false,
1343
+ getArgs: () => isConvexArgsSkipped(currentArgs.value) ? "skip" : currentArgs.value,
1344
+ getArgsHash: () => argsHash.value,
1345
+ getBoundaryKey: () => boundaryKey.value,
1346
+ getIsolationTag: () => tag.value,
1347
+ getClient: () => gate.value === "execute" ? runtime.browser.clientFor(auth) : null,
1348
+ boundary: {
1349
+ hasData: () => raw.value !== noQueryValue,
1350
+ readData: () => {
1351
+ if (raw.value === noQueryValue) {
1352
+ throw new Error("[better-convex-vue] attempted to read an unsettled query value");
1353
+ }
1354
+ return raw.value;
1355
+ },
1356
+ writeData: (value) => {
1357
+ raw.value = value;
1358
+ },
1359
+ setError: (error2) => {
1360
+ boundaryError.value = error2;
1361
+ },
1362
+ clearData: () => {
1363
+ raw.value = noQueryValue;
1364
+ }
1365
+ },
1366
+ events: {
1367
+ onUpdate: () => {
1368
+ loading.value = false;
1369
+ },
1370
+ onError: () => {
1371
+ loading.value = false;
1372
+ }
1373
+ }
1374
+ });
1375
+ if (hydrationSeed !== void 0) controller.markSettled();
1376
+ let previousTag = tag.value;
1377
+ let previousBoundaryKey = boundaryKey.value;
1378
+ let previousLive = false;
1379
+ let refreshSequence = 0;
1380
+ const reconcile = () => {
1381
+ const nextTag = tag.value;
1382
+ const nextBoundaryKey = boundaryKey.value;
1383
+ const nextLive = gate.value === "execute";
1384
+ const nextIdle = gate.value === "idle" || gate.value === "error";
1385
+ if (nextTag.identityGeneration !== previousTag.identityGeneration || nextTag.identityKey !== previousTag.identityKey) {
1386
+ controller.handleIdentityBoundary({ nextTag, previousTag });
1387
+ } else {
1388
+ controller.handleExecutionBoundary({
1389
+ nextBoundaryKey,
1390
+ previousBoundaryKey,
1391
+ nextLive,
1392
+ previousLive,
1393
+ nextIdle
1394
+ });
1395
+ }
1396
+ previousTag = nextTag;
1397
+ previousBoundaryKey = nextBoundaryKey;
1398
+ previousLive = nextLive;
1399
+ if (gate.value === "error") {
1400
+ boundaryError.value = identity.value.error ?? void 0;
1401
+ loading.value = false;
1402
+ return;
1403
+ }
1404
+ if (gate.value === "wait") {
1405
+ loading.value = true;
1406
+ void runtime.browser.ready().then(reconcile);
1407
+ return;
1408
+ }
1409
+ if (gate.value === "idle") {
1410
+ loading.value = false;
1411
+ boundaryError.value = void 0;
1412
+ return;
1413
+ }
1414
+ boundaryError.value = void 0;
1415
+ controller.setupSubscription();
1416
+ loading.value = controller.isAwaitingFirstValue() && !controller.hasSettledForCurrentArgs();
1417
+ };
1418
+ async function refresh() {
1419
+ if (gate.value !== "execute" || isConvexArgsSkipped(currentArgs.value)) return;
1420
+ const sequence = ++refreshSequence;
1421
+ const operation = controller.beginOperation();
1422
+ const isCurrentRefresh = () => sequence === refreshSequence && controller.isOperationCurrent(operation);
1423
+ loading.value = true;
1424
+ boundaryError.value = void 0;
1425
+ try {
1426
+ const value = await runtime.browser.clientFor(auth).query(query, currentArgs.value);
1427
+ if (!isCurrentRefresh()) return;
1428
+ raw.value = value;
1429
+ controller.markSettled(operation);
1430
+ } catch (error2) {
1431
+ if (!isCurrentRefresh()) return;
1432
+ const normalized = controller.setOperationError(error2, operation);
1433
+ if (!normalized) return;
1434
+ boundaryError.value = normalized;
1435
+ } finally {
1436
+ if (isCurrentRefresh()) loading.value = false;
1437
+ }
1438
+ }
1439
+ const stop = watch([argsHash, gate, () => identity.value.identityGeneration], reconcile, {
1440
+ immediate: true,
1441
+ flush: "sync"
1442
+ });
1443
+ onScopeDispose(() => {
1444
+ stop();
1445
+ loading.value = false;
1446
+ controller.dispose();
1447
+ });
1448
+ const data = computed(() => controller.data());
1449
+ const error = computed(() => boundaryError.value);
1450
+ const pending = computed(() => loading.value);
1451
+ const status = computed(
1452
+ () => loading.value ? "pending" : boundaryError.value ? "error" : controller.hasData() ? "success" : "idle"
1453
+ );
1454
+ const isStale = computed(
1455
+ () => controller.isStale({
1456
+ idle: gate.value !== "execute",
1457
+ pending: loading.value,
1458
+ errored: boundaryError.value !== void 0
1459
+ })
1460
+ );
1461
+ return Object.freeze({
1462
+ data,
1463
+ error,
1464
+ pending,
1465
+ status,
1466
+ isStale,
1467
+ refresh
1468
+ });
1469
+ }
1470
+
1471
+ function createPaginationGeneration() {
1472
+ return Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER - 1)) + 1;
1473
+ }
1474
+ function createPaginationOperationFence(input) {
1475
+ let operationRevision = 0;
1476
+ const capture = () => ({
1477
+ ...input.getIsolationTag(),
1478
+ argsHash: input.getArgsHash(),
1479
+ boundaryKey: input.getBoundaryKey(),
1480
+ paginationGeneration: input.getPaginationGeneration(),
1481
+ operationId: operationRevision
1482
+ });
1483
+ const invalidate = () => {
1484
+ operationRevision += 1;
1485
+ };
1486
+ const isCurrent = (operation) => {
1487
+ const tag = input.getIsolationTag();
1488
+ return !input.isDisposed() && operation.operationId === operationRevision && operation.argsHash === input.getArgsHash() && operation.boundaryKey === input.getBoundaryKey() && operation.paginationGeneration === input.getPaginationGeneration() && operation.identityKey === tag.identityKey && operation.identityGeneration === tag.identityGeneration;
1489
+ };
1490
+ return { capture, invalidate, isCurrent };
1491
+ }
1492
+ function createPendingPaginationPage(paginationOpts) {
1493
+ return {
1494
+ paginationOpts,
1495
+ result: void 0,
1496
+ error: void 0,
1497
+ pending: true,
1498
+ unsubscribe: null
1499
+ };
1500
+ }
1501
+ function commitPaginationPageResult(pages, pageIndex, result) {
1502
+ const page = pages[pageIndex];
1503
+ if (!page) return pages;
1504
+ const nextPages = [...pages];
1505
+ nextPages[pageIndex] = {
1506
+ ...page,
1507
+ result,
1508
+ error: void 0,
1509
+ pending: false
1510
+ };
1511
+ return nextPages;
1512
+ }
1513
+ function commitPaginationPageError(pages, pageIndex, error) {
1514
+ const page = pages[pageIndex];
1515
+ if (!page) return pages;
1516
+ const nextPages = [...pages];
1517
+ nextPages[pageIndex] = {
1518
+ ...page,
1519
+ error: normalizeConvexError(error),
1520
+ pending: false
1521
+ };
1522
+ return nextPages;
1523
+ }
1524
+ function getLastLoadedPaginationResult(firstPage, additionalPages) {
1525
+ const lastPage = additionalPages[additionalPages.length - 1];
1526
+ if (!lastPage) return firstPage ?? void 0;
1527
+ if (lastPage.pending) return void 0;
1528
+ return lastPage.result;
1529
+ }
1530
+ function computePaginationStatus(input) {
1531
+ if (input.hasError) return "error";
1532
+ if (input.disabled) return "idle";
1533
+ if (input.refresh === "pending" || input.firstPage.state === "loading" || input.nextPage.state === "loading")
1534
+ return "pending";
1535
+ return "success";
1536
+ }
1537
+ function computePaginationStale(input) {
1538
+ return input.keepPreviousData && input.status === "pending" && !input.hasCurrentData && input.hasLastSettledData;
1539
+ }
1540
+
1541
+ function sameTag(a, b) {
1542
+ return a.identityKey === b.identityKey && a.identityGeneration === b.identityGeneration;
1543
+ }
1544
+ function deferredSettlement() {
1545
+ let resolve;
1546
+ const promise = new Promise((resolvePromise) => {
1547
+ resolve = resolvePromise;
1548
+ });
1549
+ return { promise, resolve };
1550
+ }
1551
+ function createPaginationController(input) {
1552
+ const generation = shallowRef(createPaginationGeneration());
1553
+ const pages = shallowRef([]);
1554
+ const firstPageRealtime = shallowRef(null);
1555
+ const firstPageOptions = shallowRef(null);
1556
+ const firstPageWithheld = shallowRef(false);
1557
+ const manualRefreshPending = shallowRef(false);
1558
+ const lastSettledResults = shallowRef(void 0);
1559
+ let firstPageUnsubscribe = null;
1560
+ let pendingFirstPageSettlement = null;
1561
+ let stopSettledWatch = null;
1562
+ const pendingSplits = [];
1563
+ let disposed = false;
1564
+ const initialOptions = computed(() => ({
1565
+ numItems: input.initialNumItems,
1566
+ cursor: null,
1567
+ id: generation.value
1568
+ }));
1569
+ const fence = createPaginationOperationFence({
1570
+ getArgsHash: input.getArgsHash,
1571
+ getBoundaryKey: input.getBoundaryKey,
1572
+ getPaginationGeneration: () => generation.value,
1573
+ getIsolationTag: input.getIsolationTag,
1574
+ isDisposed: () => disposed
1575
+ });
1576
+ const visiblePage = (result) => result?.pageStatus === "SplitRequired" ? null : result ?? null;
1577
+ const firstPage = () => firstPageWithheld.value ? null : visiblePage(firstPageRealtime.value) ?? visiblePage(input.getBoundaryFirstPage());
1578
+ function settleFirstPageIfTerminal() {
1579
+ if (!pendingFirstPageSettlement || !disposed && !input.isIdle() && firstPage() === null && input.getBoundaryError() === void 0)
1580
+ return;
1581
+ pendingFirstPageSettlement.resolve();
1582
+ pendingFirstPageSettlement = null;
1583
+ }
1584
+ function firstPageSettled() {
1585
+ if (disposed || input.isIdle() || firstPage() !== null || input.getBoundaryError() !== void 0)
1586
+ return Promise.resolve();
1587
+ pendingFirstPageSettlement ??= deferredSettlement();
1588
+ return pendingFirstPageSettlement.promise;
1589
+ }
1590
+ async function fetchForOperation(options, operation) {
1591
+ const result = await input.fetchPage(options);
1592
+ return result && fence.isCurrent(operation) ? result : null;
1593
+ }
1594
+ function retirePagesFrom(index) {
1595
+ for (const page of pages.value.slice(index)) page.unsubscribe?.();
1596
+ pages.value = pages.value.slice(0, index);
1597
+ }
1598
+ function isSplitResult(result) {
1599
+ return typeof result.splitCursor === "string" && (result.pageStatus === "SplitRecommended" || result.pageStatus === "SplitRequired");
1600
+ }
1601
+ function removePendingSplit(split) {
1602
+ const index = pendingSplits.indexOf(split);
1603
+ if (index >= 0) pendingSplits.splice(index, 1);
1604
+ }
1605
+ function failPendingSplit(split, error2) {
1606
+ if (!fence.isCurrent(split.operation)) return;
1607
+ for (const part of split.parts) part.page.unsubscribe?.();
1608
+ removePendingSplit(split);
1609
+ input.setBoundaryError(normalizeConvexError(error2), split.operation.boundaryKey);
1610
+ if (split.target === "first") settleFirstPageIfTerminal();
1611
+ }
1612
+ function finishPendingSplit(split) {
1613
+ if (!fence.isCurrent(split.operation) || split.parts.some((part) => part.received === null))
1614
+ return;
1615
+ removePendingSplit(split);
1616
+ const promoted = split.parts.map(({ page, received }) => ({
1617
+ ...page,
1618
+ result: visiblePage(received) ?? void 0,
1619
+ error: void 0,
1620
+ pending: received.pageStatus === "SplitRequired"
1621
+ }));
1622
+ if (split.target === "first") {
1623
+ firstPageUnsubscribe?.();
1624
+ firstPageOptions.value = promoted[0].paginationOpts;
1625
+ firstPageUnsubscribe = promoted[0].unsubscribe;
1626
+ firstPageRealtime.value = promoted[0].result ?? null;
1627
+ firstPageWithheld.value = promoted[0].pending;
1628
+ pages.value = [promoted[1], ...pages.value];
1629
+ } else {
1630
+ const index = pages.value.findIndex((candidate) => candidate.paginationOpts === split.target);
1631
+ if (index < 0) {
1632
+ for (const page of promoted) page.unsubscribe?.();
1633
+ return;
1634
+ }
1635
+ pages.value[index]?.unsubscribe?.();
1636
+ pages.value = [...pages.value.slice(0, index), ...promoted, ...pages.value.slice(index + 1)];
1637
+ }
1638
+ input.setBoundaryError(void 0, split.operation.boundaryKey);
1639
+ const firstResult = split.parts[0].received;
1640
+ const secondResult = split.parts[1].received;
1641
+ const promotedFirstTarget = split.target === "first" ? "first" : promoted[0].paginationOpts;
1642
+ if (firstResult.pageStatus === "SplitRecommended" || firstResult.pageStatus === "SplitRequired")
1643
+ beginPageSplit(promotedFirstTarget, firstResult);
1644
+ if (secondResult.pageStatus === "SplitRecommended" || secondResult.pageStatus === "SplitRequired")
1645
+ beginPageSplit(promoted[1].paginationOpts, secondResult);
1646
+ if (split.target === "first") settleFirstPageIfTerminal();
1647
+ }
1648
+ function subscribeSplitPart(split, partIndex) {
1649
+ const client = input.getClient();
1650
+ const args = input.getArgs();
1651
+ if (!client || args === "skip") return;
1652
+ const part = split.parts[partIndex];
1653
+ const unsubscribe = client.onUpdate(
1654
+ input.query,
1655
+ { ...args, paginationOpts: part.page.paginationOpts },
1656
+ (raw) => {
1657
+ if (!fence.isCurrent(split.operation)) return;
1658
+ const result = raw;
1659
+ if (pendingSplits.includes(split)) {
1660
+ part.received = result;
1661
+ finishPendingSplit(split);
1662
+ return;
1663
+ }
1664
+ if (split.target === "first" && partIndex === 0 && firstPageOptions.value === part.page.paginationOpts) {
1665
+ acceptFirstPageResult(result, split.operation);
1666
+ return;
1667
+ }
1668
+ acceptPageResult(part.page.paginationOpts, result);
1669
+ },
1670
+ (error2) => {
1671
+ if (!fence.isCurrent(split.operation)) return;
1672
+ if (pendingSplits.includes(split)) {
1673
+ failPendingSplit(split, error2);
1674
+ return;
1675
+ }
1676
+ if (split.target === "first" && partIndex === 0 && firstPageOptions.value === part.page.paginationOpts) {
1677
+ input.setBoundaryError(normalizeConvexError(error2), split.operation.boundaryKey);
1678
+ return;
1679
+ }
1680
+ const index = pages.value.findIndex(
1681
+ (candidate) => candidate.paginationOpts === part.page.paginationOpts
1682
+ );
1683
+ if (index >= 0) pages.value = commitPaginationPageError(pages.value, index, error2);
1684
+ }
1685
+ );
1686
+ part.page.unsubscribe = unsubscribe;
1687
+ }
1688
+ function beginPageSplit(target, result) {
1689
+ if (disposed) return;
1690
+ if (!input.isLive()) {
1691
+ if (result.pageStatus === "SplitRequired") {
1692
+ input.setBoundaryError(
1693
+ normalizeConvexError(
1694
+ new Error(
1695
+ "[better-convex-vue] SplitRequired pagination result needs a live bounded split"
1696
+ )
1697
+ ),
1698
+ input.getBoundaryKey()
1699
+ );
1700
+ if (target === "first") settleFirstPageIfTerminal();
1701
+ }
1702
+ return;
1703
+ }
1704
+ if (pendingSplits.some((split2) => split2.target === target)) return;
1705
+ if (!isSplitResult(result)) {
1706
+ if (result.pageStatus === "SplitRequired") {
1707
+ input.setBoundaryError(
1708
+ normalizeConvexError(
1709
+ new Error("[better-convex-vue] SplitRequired pagination result has no split cursor")
1710
+ ),
1711
+ input.getBoundaryKey()
1712
+ );
1713
+ if (target === "first") settleFirstPageIfTerminal();
1714
+ }
1715
+ return;
1716
+ }
1717
+ const targetOptions = target === "first" ? firstPageOptions.value ?? initialOptions.value : pages.value.find((page) => page.paginationOpts === target)?.paginationOpts;
1718
+ if (!targetOptions) return;
1719
+ const firstOptions = {
1720
+ ...targetOptions,
1721
+ endCursor: result.splitCursor
1722
+ };
1723
+ const secondOptions = {
1724
+ ...targetOptions,
1725
+ cursor: result.splitCursor,
1726
+ endCursor: result.continueCursor
1727
+ };
1728
+ const split = {
1729
+ target,
1730
+ operation: fence.capture(),
1731
+ required: result.pageStatus === "SplitRequired",
1732
+ parts: [
1733
+ { page: createPendingPaginationPage(firstOptions), received: null },
1734
+ { page: createPendingPaginationPage(secondOptions), received: null }
1735
+ ]
1736
+ };
1737
+ pendingSplits.push(split);
1738
+ if (split.required) {
1739
+ if (target === "first") {
1740
+ firstPageWithheld.value = true;
1741
+ firstPageRealtime.value = null;
1742
+ } else {
1743
+ const index = pages.value.findIndex((page) => page.paginationOpts === target);
1744
+ if (index >= 0) {
1745
+ const page = pages.value[index];
1746
+ pages.value = [
1747
+ ...pages.value.slice(0, index),
1748
+ { ...page, result: void 0, error: void 0, pending: true },
1749
+ ...pages.value.slice(index + 1)
1750
+ ];
1751
+ }
1752
+ }
1753
+ }
1754
+ subscribeSplitPart(split, 0);
1755
+ subscribeSplitPart(split, 1);
1756
+ }
1757
+ function acceptFirstPageResult(result, operation) {
1758
+ if (result.pageStatus === "SplitRequired") {
1759
+ beginPageSplit("first", result);
1760
+ return;
1761
+ }
1762
+ const previous = firstPage();
1763
+ if (previous && previous.continueCursor !== result.continueCursor && pages.value.length > 0)
1764
+ retirePagesFrom(0);
1765
+ firstPageWithheld.value = false;
1766
+ firstPageRealtime.value = result;
1767
+ input.setBoundaryError(void 0, operation.boundaryKey);
1768
+ if (result.pageStatus === "SplitRecommended") beginPageSplit("first", result);
1769
+ settleFirstPageIfTerminal();
1770
+ }
1771
+ function acceptPageResult(pageOptions, result) {
1772
+ const index = pages.value.findIndex((candidate) => candidate.paginationOpts === pageOptions);
1773
+ if (index < 0) return;
1774
+ if (result.pageStatus === "SplitRequired") {
1775
+ beginPageSplit(pageOptions, result);
1776
+ return;
1777
+ }
1778
+ const previous = pages.value[index]?.result;
1779
+ const nextPages = commitPaginationPageResult(pages.value, index, result);
1780
+ if (previous && previous.continueCursor !== result.continueCursor && nextPages.length > index + 1) {
1781
+ for (const laterPage of nextPages.slice(index + 1)) laterPage.unsubscribe?.();
1782
+ pages.value = nextPages.slice(0, index + 1);
1783
+ } else {
1784
+ pages.value = nextPages;
1785
+ }
1786
+ input.setBoundaryError(void 0, input.getBoundaryKey());
1787
+ if (result.pageStatus === "SplitRecommended") beginPageSplit(pageOptions, result);
1788
+ }
1789
+ function subscribeFirstPage(options = initialOptions.value) {
1790
+ if (disposed || firstPageUnsubscribe || !input.isLive()) return;
1791
+ const client = input.getClient();
1792
+ const args = input.getArgs();
1793
+ if (!client || args === "skip") return;
1794
+ const operation = fence.capture();
1795
+ firstPageOptions.value = options;
1796
+ firstPageUnsubscribe = client.onUpdate(
1797
+ input.query,
1798
+ { ...args, paginationOpts: options },
1799
+ (raw) => {
1800
+ if (!fence.isCurrent(operation)) return;
1801
+ acceptFirstPageResult(raw, operation);
1802
+ },
1803
+ (error2) => {
1804
+ if (!fence.isCurrent(operation)) return;
1805
+ input.setBoundaryError(normalizeConvexError(error2), operation.boundaryKey);
1806
+ settleFirstPageIfTerminal();
1807
+ }
1808
+ );
1809
+ }
1810
+ function subscribePage(pageIndex) {
1811
+ if (disposed || !input.isLive()) return;
1812
+ const page = pages.value[pageIndex];
1813
+ const client = input.getClient();
1814
+ const args = input.getArgs();
1815
+ if (!page || !client || args === "skip") return;
1816
+ const operation = fence.capture();
1817
+ const pageOptions = page.paginationOpts;
1818
+ page.unsubscribe?.();
1819
+ const unsubscribe = client.onUpdate(
1820
+ input.query,
1821
+ { ...args, paginationOpts: page.paginationOpts },
1822
+ (raw) => {
1823
+ if (!fence.isCurrent(operation)) return;
1824
+ acceptPageResult(pageOptions, raw);
1825
+ },
1826
+ (error2) => {
1827
+ if (!fence.isCurrent(operation)) return;
1828
+ const index = pages.value.findIndex((candidate) => candidate.paginationOpts === pageOptions);
1829
+ if (index < 0) return;
1830
+ pages.value = commitPaginationPageError(pages.value, index, error2);
1831
+ }
1832
+ );
1833
+ page.unsubscribe = unsubscribe;
1834
+ }
1835
+ function teardownSubscriptions() {
1836
+ firstPageUnsubscribe?.();
1837
+ firstPageUnsubscribe = null;
1838
+ firstPageOptions.value = null;
1839
+ for (const split of pendingSplits.splice(0)) {
1840
+ for (const part of split.parts) part.page.unsubscribe?.();
1841
+ }
1842
+ for (const page of pages.value) {
1843
+ page.unsubscribe?.();
1844
+ page.unsubscribe = null;
1845
+ }
1846
+ }
1847
+ const status = computed(() => {
1848
+ const currentFirstPage = firstPage();
1849
+ const lastPage = pages.value.at(-1);
1850
+ const firstPageState = currentFirstPage ? { state: "ready", isDone: currentFirstPage.isDone } : { state: "loading" };
1851
+ const nextPageState = lastPage?.pending ? { state: "loading" } : lastPage?.result?.isDone ? { state: "exhausted" } : { state: "idle" };
1852
+ return computePaginationStatus({
1853
+ disabled: input.isIdle(),
1854
+ refresh: manualRefreshPending.value ? "pending" : "idle",
1855
+ hasError: input.getBoundaryError() !== void 0 || pages.value.some((page) => page.error !== void 0),
1856
+ firstPage: firstPageState,
1857
+ nextPage: nextPageState
1858
+ });
1859
+ });
1860
+ const currentData = computed(() => {
1861
+ if (input.isIdle()) return void 0;
1862
+ const items = [];
1863
+ const currentFirstPage = firstPage();
1864
+ if (currentFirstPage) items.push(...currentFirstPage.page);
1865
+ for (const page of pages.value) if (page.result) items.push(...page.result.page);
1866
+ if (currentFirstPage || pages.value.some((page) => page.result !== void 0)) return items;
1867
+ return void 0;
1868
+ });
1869
+ const isStale = computed(
1870
+ () => computePaginationStale({
1871
+ keepPreviousData: input.keepPreviousData,
1872
+ status: status.value,
1873
+ hasCurrentData: currentData.value !== void 0,
1874
+ hasLastSettledData: lastSettledResults.value !== void 0
1875
+ })
1876
+ );
1877
+ const data = computed(
1878
+ () => isStale.value ? lastSettledResults.value : currentData.value
1879
+ );
1880
+ const isLoading = computed(() => status.value === "pending");
1881
+ const canLoadMore = computed(() => {
1882
+ if (status.value !== "success") return false;
1883
+ return getLastLoadedPaginationResult(firstPage(), pages.value)?.isDone === false;
1884
+ });
1885
+ const error = computed(() => {
1886
+ const boundaryError = input.getBoundaryError();
1887
+ if (boundaryError) return boundaryError;
1888
+ return pages.value.find((page) => page.error)?.error;
1889
+ });
1890
+ function start() {
1891
+ if (disposed || stopSettledWatch) return;
1892
+ stopSettledWatch = watch(
1893
+ [status, currentData],
1894
+ ([nextStatus, nextData]) => {
1895
+ if (input.isIdle() || nextStatus !== "success" || nextData === void 0) return;
1896
+ lastSettledResults.value = nextData;
1897
+ },
1898
+ { immediate: true, flush: "sync" }
1899
+ );
1900
+ if (input.isLive()) subscribeFirstPage();
1901
+ }
1902
+ function boundLastLoadedPage(endCursor) {
1903
+ if (!input.isLive()) return;
1904
+ const lastIndex = pages.value.length - 1;
1905
+ if (lastIndex < 0) {
1906
+ const options = firstPageOptions.value ?? initialOptions.value;
1907
+ if (options.endCursor === endCursor) return;
1908
+ firstPageUnsubscribe?.();
1909
+ firstPageUnsubscribe = null;
1910
+ subscribeFirstPage({ ...options, endCursor });
1911
+ return;
1912
+ }
1913
+ const page = pages.value[lastIndex];
1914
+ if (!page || page.paginationOpts.endCursor === endCursor) return;
1915
+ page.unsubscribe?.();
1916
+ const boundedPage = {
1917
+ ...page,
1918
+ paginationOpts: { ...page.paginationOpts, endCursor },
1919
+ unsubscribe: null
1920
+ };
1921
+ pages.value = [...pages.value.slice(0, lastIndex), boundedPage];
1922
+ subscribePage(lastIndex);
1923
+ }
1924
+ function loadMore(numItems) {
1925
+ if (!Number.isSafeInteger(numItems) || numItems < 1) {
1926
+ throw new Error("[better-convex-vue] loadMore numItems must be a positive safe integer");
1927
+ }
1928
+ if (disposed || input.isIdle() || manualRefreshPending.value) return;
1929
+ if (pages.value.at(-1)?.pending) return;
1930
+ const lastResult = getLastLoadedPaginationResult(firstPage(), pages.value);
1931
+ if (!lastResult || lastResult.isDone) return;
1932
+ boundLastLoadedPage(lastResult.continueCursor);
1933
+ const page = createPendingPaginationPage({
1934
+ numItems,
1935
+ cursor: lastResult.continueCursor,
1936
+ id: generation.value
1937
+ });
1938
+ pages.value = [...pages.value, page];
1939
+ const index = pages.value.length - 1;
1940
+ const operation = fence.capture();
1941
+ if (input.isLive() && input.getClient()) {
1942
+ subscribePage(index);
1943
+ return;
1944
+ }
1945
+ void fetchForOperation(page.paginationOpts, operation).then((result) => {
1946
+ if (!result || !fence.isCurrent(operation) || pages.value[index] !== page) return;
1947
+ if (result.pageStatus === "SplitRequired") {
1948
+ pages.value = [
1949
+ ...pages.value.slice(0, index),
1950
+ { ...page, result: void 0, error: void 0, pending: false },
1951
+ ...pages.value.slice(index + 1)
1952
+ ];
1953
+ beginPageSplit(page.paginationOpts, result);
1954
+ return;
1955
+ }
1956
+ pages.value = commitPaginationPageResult(pages.value, index, result);
1957
+ }).catch((cause) => {
1958
+ if (!fence.isCurrent(operation) || pages.value[index] !== page) return;
1959
+ pages.value = commitPaginationPageError(pages.value, index, cause);
1960
+ });
1961
+ }
1962
+ async function refresh() {
1963
+ if (disposed || input.isIdle() || manualRefreshPending.value) return;
1964
+ manualRefreshPending.value = true;
1965
+ input.setBoundaryError(void 0, input.getBoundaryKey());
1966
+ const loadedPages = [...pages.value];
1967
+ const operation = fence.capture();
1968
+ try {
1969
+ const firstResult = await fetchForOperation(
1970
+ firstPageOptions.value ?? initialOptions.value,
1971
+ operation
1972
+ );
1973
+ if (!firstResult) return;
1974
+ const refreshed = [];
1975
+ const splitResults = [];
1976
+ let previous = firstResult;
1977
+ for (let index = 0; index < loadedPages.length; index += 1) {
1978
+ if (previous.isDone || previous.pageStatus === "SplitRequired") break;
1979
+ const page = loadedPages[index];
1980
+ if (!page) continue;
1981
+ const result = await fetchForOperation(
1982
+ {
1983
+ ...page.paginationOpts,
1984
+ cursor: previous.continueCursor
1985
+ },
1986
+ operation
1987
+ );
1988
+ if (!result) return;
1989
+ const cursor = previous.continueCursor;
1990
+ refreshed.push({
1991
+ ...page,
1992
+ paginationOpts: cursor === page.paginationOpts.cursor ? page.paginationOpts : { ...page.paginationOpts, cursor },
1993
+ result: visiblePage(result) ?? void 0,
1994
+ error: void 0,
1995
+ pending: result.pageStatus === "SplitRequired"
1996
+ });
1997
+ if (result.pageStatus === "SplitRecommended" || result.pageStatus === "SplitRequired") {
1998
+ splitResults.push({
1999
+ options: refreshed.at(-1).paginationOpts,
2000
+ result
2001
+ });
2002
+ }
2003
+ previous = result;
2004
+ }
2005
+ if (!fence.isCurrent(operation) || pages.value.length !== loadedPages.length) return;
2006
+ for (const retiredPage of loadedPages.slice(refreshed.length)) retiredPage.unsubscribe?.();
2007
+ firstPageWithheld.value = firstResult.pageStatus === "SplitRequired";
2008
+ firstPageRealtime.value = visiblePage(firstResult);
2009
+ pages.value = refreshed;
2010
+ if (input.isLive()) {
2011
+ for (let index = 0; index < refreshed.length; index += 1) {
2012
+ if (loadedPages[index]?.paginationOpts.cursor !== refreshed[index]?.paginationOpts.cursor) {
2013
+ subscribePage(index);
2014
+ }
2015
+ }
2016
+ }
2017
+ input.setBoundaryError(void 0, operation.boundaryKey);
2018
+ if (firstResult.pageStatus === "SplitRecommended" || firstResult.pageStatus === "SplitRequired")
2019
+ beginPageSplit("first", firstResult);
2020
+ for (const split of splitResults) beginPageSplit(split.options, split.result);
2021
+ } catch (cause) {
2022
+ if (fence.isCurrent(operation)) {
2023
+ input.setBoundaryError(normalizeConvexError(cause), operation.boundaryKey);
2024
+ }
2025
+ } finally {
2026
+ if (fence.isCurrent(operation)) manualRefreshPending.value = false;
2027
+ }
2028
+ }
2029
+ function handleIdentityBoundary(boundary) {
2030
+ if (sameTag(boundary.nextTag, boundary.previousTag)) return;
2031
+ fence.invalidate();
2032
+ teardownSubscriptions();
2033
+ generation.value = createPaginationGeneration();
2034
+ manualRefreshPending.value = false;
2035
+ firstPageRealtime.value = null;
2036
+ firstPageWithheld.value = false;
2037
+ pages.value = [];
2038
+ input.setBoundaryError(void 0, boundary.previousBoundaryKey);
2039
+ lastSettledResults.value = void 0;
2040
+ if (input.isLive()) subscribeFirstPage();
2041
+ else settleFirstPageIfTerminal();
2042
+ }
2043
+ async function handleExecutionBoundary(boundary) {
2044
+ if (boundary.nextBoundaryKey === boundary.previousBoundaryKey && boundary.nextLive === boundary.previousLive)
2045
+ return;
2046
+ if (boundary.nextBoundaryKey === boundary.previousBoundaryKey && boundary.nextLive && !boundary.previousLive) {
2047
+ fence.invalidate();
2048
+ manualRefreshPending.value = false;
2049
+ subscribeFirstPage();
2050
+ return;
2051
+ }
2052
+ fence.invalidate();
2053
+ manualRefreshPending.value = false;
2054
+ input.setBoundaryError(void 0, boundary.previousBoundaryKey);
2055
+ teardownSubscriptions();
2056
+ firstPageRealtime.value = null;
2057
+ firstPageWithheld.value = false;
2058
+ if (input.isIdle()) {
2059
+ pages.value = [];
2060
+ lastSettledResults.value = void 0;
2061
+ input.setBoundaryError(void 0, input.getBoundaryKey());
2062
+ settleFirstPageIfTerminal();
2063
+ return;
2064
+ }
2065
+ generation.value = createPaginationGeneration();
2066
+ pages.value = [];
2067
+ input.setBoundaryError(void 0, input.getBoundaryKey());
2068
+ if (boundary.nextLive) subscribeFirstPage();
2069
+ else settleFirstPageIfTerminal();
2070
+ }
2071
+ function dispose() {
2072
+ if (disposed) return;
2073
+ disposed = true;
2074
+ fence.invalidate();
2075
+ teardownSubscriptions();
2076
+ stopSettledWatch?.();
2077
+ stopSettledWatch = null;
2078
+ settleFirstPageIfTerminal();
2079
+ }
2080
+ return {
2081
+ generation,
2082
+ initialOptions,
2083
+ pages,
2084
+ data,
2085
+ status,
2086
+ isLoading,
2087
+ isStale,
2088
+ canLoadMore,
2089
+ error,
2090
+ start,
2091
+ captureOperation: fence.capture,
2092
+ isOperationCurrent: fence.isCurrent,
2093
+ fetchForOperation,
2094
+ firstPageSettled,
2095
+ loadMore,
2096
+ refresh,
2097
+ handleIdentityBoundary,
2098
+ handleExecutionBoundary,
2099
+ dispose
2100
+ };
2101
+ }
2102
+
2103
+ function useConvexPaginatedQuery(query, ...parameters) {
2104
+ const [args, options, bridge] = parameters;
2105
+ if (!getCurrentScope()) {
2106
+ throw new Error(
2107
+ "[better-convex-vue] useConvexPaginatedQuery must run inside a Vue effect scope"
2108
+ );
2109
+ }
2110
+ if (!Number.isSafeInteger(options.initialNumItems) || options.initialNumItems < 1) {
2111
+ throw new Error("[better-convex-vue] initialNumItems must be a positive safe integer");
2112
+ }
2113
+ const runtime = useBetterConvexRuntime();
2114
+ const auth = options.auth ?? "optional";
2115
+ const initialNumItems = options.initialNumItems;
2116
+ const identity = runtime.identity.snapshot;
2117
+ const currentArgs = computed(() => normalizeConvexArgs(args));
2118
+ const argsHash = computed(() => hash(currentArgs.value));
2119
+ const functionName = getFunctionName(query);
2120
+ const boundaryFirstPage = shallowRef(bridge?.initialPage ?? null);
2121
+ const boundaryError = shallowRef(void 0);
2122
+ const gate = computed(
2123
+ () => decideQueryExecution({
2124
+ auth,
2125
+ skipped: isConvexArgsSkipped(currentArgs.value),
2126
+ identity: identity.value
2127
+ })
2128
+ );
2129
+ const idle = computed(() => gate.value === "idle" || gate.value === "error");
2130
+ const live = computed(() => gate.value === "execute");
2131
+ const tag = computed(() => ({
2132
+ identityKey: auth === "none" ? "anonymous" : identity.value.identityKey ?? "anonymous",
2133
+ identityGeneration: auth === "none" ? 0 : identity.value.identityGeneration
2134
+ }));
2135
+ const boundaryKey = computed(
2136
+ () => `${functionName}:${auth}:${tag.value.identityKey}:${argsHash.value}:${initialNumItems}`
2137
+ );
2138
+ const fetchPage = async (paginationOpts) => {
2139
+ if (gate.value !== "execute" || isConvexArgsSkipped(currentArgs.value)) return null;
2140
+ return await runtime.browser.clientFor(auth).query(query, {
2141
+ ...currentArgs.value,
2142
+ paginationOpts
2143
+ });
2144
+ };
2145
+ const controller = createPaginationController({
2146
+ query,
2147
+ initialNumItems,
2148
+ keepPreviousData: options.keepPreviousData ?? false,
2149
+ getArgs: () => isConvexArgsSkipped(currentArgs.value) ? "skip" : currentArgs.value,
2150
+ getArgsHash: () => argsHash.value,
2151
+ getBoundaryKey: () => boundaryKey.value,
2152
+ getIsolationTag: () => tag.value,
2153
+ isIdle: () => idle.value,
2154
+ isLive: () => live.value,
2155
+ getBoundaryFirstPage: () => boundaryFirstPage.value,
2156
+ getBoundaryError: () => auth === "none" ? boundaryError.value : identity.value.error ?? boundaryError.value,
2157
+ setBoundaryError: (error) => {
2158
+ boundaryError.value = error;
2159
+ },
2160
+ getClient: () => gate.value === "execute" ? runtime.browser.clientFor(auth) : null,
2161
+ fetchPage
2162
+ });
2163
+ controller.start();
2164
+ bridge?.onFirstPageSettled(controller.firstPageSettled());
2165
+ let previousTag = tag.value;
2166
+ let previousBoundaryKey = boundaryKey.value;
2167
+ let previousLive = live.value;
2168
+ let initialized = false;
2169
+ const reconcile = () => {
2170
+ const nextTag = tag.value;
2171
+ const nextBoundaryKey = boundaryKey.value;
2172
+ if (!initialized) {
2173
+ initialized = true;
2174
+ previousTag = nextTag;
2175
+ previousBoundaryKey = nextBoundaryKey;
2176
+ previousLive = live.value;
2177
+ return;
2178
+ }
2179
+ const priorTag = previousTag;
2180
+ const priorBoundaryKey = previousBoundaryKey;
2181
+ const priorLive = previousLive;
2182
+ previousTag = nextTag;
2183
+ previousBoundaryKey = nextBoundaryKey;
2184
+ previousLive = live.value;
2185
+ if (nextTag.identityGeneration !== priorTag.identityGeneration || nextTag.identityKey !== priorTag.identityKey) {
2186
+ boundaryFirstPage.value = null;
2187
+ controller.handleIdentityBoundary({
2188
+ nextTag,
2189
+ previousTag: priorTag,
2190
+ previousBoundaryKey: priorBoundaryKey
2191
+ });
2192
+ } else {
2193
+ if (nextBoundaryKey !== priorBoundaryKey || idle.value) boundaryFirstPage.value = null;
2194
+ void controller.handleExecutionBoundary({
2195
+ nextBoundaryKey,
2196
+ previousBoundaryKey: priorBoundaryKey,
2197
+ nextLive: live.value,
2198
+ previousLive: priorLive
2199
+ });
2200
+ }
2201
+ };
2202
+ const stop = watch([argsHash, gate, live, () => identity.value.identityGeneration], reconcile, {
2203
+ immediate: true,
2204
+ flush: "sync"
2205
+ });
2206
+ onScopeDispose(() => {
2207
+ stop();
2208
+ controller.dispose();
2209
+ });
2210
+ return Object.freeze({
2211
+ data: controller.data,
2212
+ status: controller.status,
2213
+ isLoading: controller.isLoading,
2214
+ isStale: controller.isStale,
2215
+ canLoadMore: controller.canLoadMore,
2216
+ loadMore: controller.loadMore,
2217
+ error: controller.error,
2218
+ refresh: controller.refresh
2219
+ });
2220
+ }
2221
+
2222
+ export { ConvexCallError, createBetterConvex, useConvex, useConvexAction, useConvexConnectionState, useConvexMutation, useConvexPaginatedQuery, useConvexQuery };