Open History to see the last commit
1/**
2 * Vue driver for the shared live-query conformance suite.
3 *
4 * Realm-sensitive pieces (collection factories, query operators) are imported
5 * from Vue's `@tanstack/db` and handed to the shared scenarios. Vue composables
6 * run inside an `effectScope` so `unmount` can dispose them via `scope.stop()`,
7 * which triggers the `watchEffect` `onInvalidate` cleanup.
8 *
9 * All registered laws must pass; the driver has no whole-test waivers.
10 */
11import { describe, expect, it } from 'vitest'
12import {
13 coalesce,
14 count,
15 createCollection,
16 createLiveQueryCollection,
17 createOptimisticAction,
18 eq,
19 gt,
20 sum,
21} from '@tanstack/db'
22import { effectScope, nextTick, onScopeDispose, ref } from 'vue'
23import {
24 mockSyncCollectionOptions,
25 mockSyncCollectionOptionsNoInitialState,
26} from '../../db/tests/utils'
27import { useLiveQuery } from '../src/useLiveQuery'
28import { runSuite } from '../../db/tests/conformance/suite'
29import { makeLaggingSource } from '../../db/tests/conformance/lagging-source'
30import { expectResultSurface } from '../../db/tests/conformance/result-laws'
31import { withScopeSetup } from '../../db/tests/conformance/scope-setup'
32import type {
33 ConformanceResult,
34 ControllableHandle,
35 DeferredSourceHandle,
36 LiveQueryDriver,
37 LiveQueryHandle,
38 QueryBuild,
39 SourceHandle,
40} from '../../db/tests/conformance/contract'
41
42let sourceSeq = 0
43
44function writer<T extends { id: string }>(collection: any) {
45 return (type: `insert` | `update` | `delete`, value: T) => {
46 collection.utils.begin()
47 collection.utils.write({ type, value })
48 collection.utils.commit()
49 }
50}
51
52function makeSource<T extends { id: string }>(
53 initialData: ReadonlyArray<T>,
54): SourceHandle<T> {
55 const collection = createCollection(
56 mockSyncCollectionOptions<T>({
57 id: `conformance-vue-${sourceSeq++}`,
58 getKey: (r) => r.id,
59 initialData: [...initialData],
60 }),
61 )
62 const write = writer<T>(collection)
63 return {
64 collection,
65 insert: (row) => write(`insert`, row),
66 update: (row) => write(`update`, row),
67 remove: (row) => write(`delete`, row),
68 }
69}
70
71function makeDeferredSource<
72 T extends { id: string },
73>(): DeferredSourceHandle<T> {
74 const collection = createCollection(
75 mockSyncCollectionOptionsNoInitialState<T>({
76 id: `conformance-vue-${sourceSeq++}`,
77 getKey: (r) => r.id,
78 }),
79 )
80 collection.startSyncImmediate()
81 const write = writer<T>(collection)
82 return {
83 collection,
84 insert: (row) => write(`insert`, row),
85 update: (row) => write(`update`, row),
86 remove: (row) => write(`delete`, row),
87 emit: (rows) => {
88 collection.utils.begin()
89 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
90 collection.utils.commit()
91 },
92 markReady: () => collection.utils.markReady(),
93 }
94}
95
96function makePrecreated(build: QueryBuild, opts?: { startSync?: boolean }) {
97 const collection = createLiveQueryCollection({
98 query: build as any,
99 startSync: opts?.startSync ?? true,
100 })
101 return { collection }
102}
103
104function makeErrorSource() {
105 const expectedError = new Error(`conformance: sync failure`)
106 let startup: { returned: true } | { returned: false; error: unknown } = {
107 returned: true,
108 }
109 const collection = createCollection<{ id: string }>({
110 id: `conformance-vue-err-${sourceSeq++}`,
111 getKey: (r) => r.id,
112 startSync: false,
113 sync: {
114 sync: () => {
115 throw expectedError
116 },
117 },
118 })
119 try {
120 collection.startSyncImmediate()
121 } catch (error) {
122 startup = { returned: false, error }
123 }
124 return { collection, expectedError, startup }
125}
126
127async function settle() {
128 await nextTick()
129 await new Promise((resolve) => setTimeout(resolve, 10))
130}
131
132function makeHandle(result: any, scope: ReturnType<typeof effectScope>) {
133 const handle: LiveQueryHandle = {
134 current(): ConformanceResult {
135 return expectResultSurface({
136 data: result.data?.value,
137 state: result.state?.value,
138 status: result.status?.value,
139 isReady: result.isReady?.value,
140 persistedStatus: result.persistedStatus?.value,
141 isPersistedReady: result.isPersistedReady?.value,
142 persistedError: result.persistedError?.value,
143 isError: result.isError?.value,
144 // vue-db exposes no `isEnabled`; derive it from status (status-derived).
145 isEnabled: result.status?.value !== `disabled`,
146 })
147 },
148 flush: settle,
149 async apply(fn: () => void) {
150 fn()
151 await settle()
152 },
153 unmount() {
154 scope.stop()
155 },
156 }
157 return handle
158}
159
160function runInScope<R>(fn: () => R): {
161 result: R
162 scope: ReturnType<typeof effectScope>
163} {
164 const scope = effectScope()
165 let result!: R
166 withScopeSetup(
167 () =>
168 scope.run(() => {
169 result = fn()
170 }),
171 () => scope.stop(),
172 )
173 return { result, scope }
174}
175
176function mount(build: QueryBuild) {
177 const { result, scope } = runInScope(() => useLiveQuery(build as any))
178 return makeHandle(result, scope)
179}
180
181function mountCollection(collection: any) {
182 const { result, scope } = runInScope(() => useLiveQuery(collection))
183 return makeHandle(result, scope)
184}
185
186function mountConfig(build: QueryBuild) {
187 const { result, scope } = runInScope(() =>
188 useLiveQuery({ query: build } as any),
189 )
190 return makeHandle(result, scope)
191}
192
193function mountDisabled() {
194 // Vue's disabled convention: the query callback returns undefined.
195 const { result, scope } = runInScope(() =>
196 useLiveQuery(() => undefined as any),
197 )
198 return makeHandle(result, scope)
199}
200
201function mountControllable<P>(
202 build: (q: any, param: P) => any,
203 initial: P,
204): ControllableHandle<P> {
205 const param = ref(initial) as { value: P }
206 const { result, scope } = runInScope(() =>
207 useLiveQuery((q: any) => build(q, param.value), [() => param.value]),
208 )
209 const handle = makeHandle(result, scope)
210 return {
211 ...handle,
212 async setParam(next: P) {
213 param.value = next
214 await settle()
215 },
216 }
217}
218
219const vueDriver: LiveQueryDriver = {
220 name: `vue`,
221 disabledRepresentation: `empty-reactive`,
222 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
223 makeSource,
224 makeDeferredSource,
225 makeLaggingSource: <T extends { id: string }>() =>
226 makeLaggingSource<T>(
227 createCollection,
228 `conformance-vue-lagging-${sourceSeq++}`,
229 ),
230 makePrecreated,
231 makeErrorSource,
232 mount,
233 mountControllable,
234 mountCollection,
235 mountConfig,
236 mountDisabled,
237 knownGaps: [],
238 features: { serverSnapshot: false, suspense: false, pooledEqFilters: true },
239}
240
241describe(`owned native scope setup`, () => {
242 it(`keeps a successful scope alive until explicit disposal`, () => {
243 let calls = 0
244 const handle = runInScope(() => {
245 onScopeDispose(() => {
246 calls++
247 })
248 return 7
249 })
250 expect(calls).toBe(0)
251 handle.scope.stop()
252 expect(calls).toBe(1)
253 })
254
255 it.each([false, true])(
256 `disposes failed setup and retains errors, cleanupFails=%s`,
257 (cleanupFails) => {
258 const primary = new Error(`scope setup failure`)
259 const secondary = new Error(`scope cleanup failure`)
260 let calls = 0
261 let caught: unknown
262 try {
263 runInScope(() => {
264 onScopeDispose(() => {
265 calls++
266 if (cleanupFails) throw secondary
267 })
268 throw primary
269 })
270 } catch (error) {
271 caught = error
272 }
273 expect(calls).toBe(1)
274 if (cleanupFails) {
275 expect(caught).toBeInstanceOf(AggregateError)
276 expect((caught as AggregateError).errors).toEqual([primary, secondary])
277 expect((caught as AggregateError).cause).toBe(primary)
278 } else expect(caught).toBe(primary)
279 },
280 )
281})
282
283runSuite(vueDriver)
284it(`preserves raw result types through the actual driver reader`, () => {
285 const raw: Record<string, unknown> = {
286 data: [{ id: `a`, value: undefined }],
287 state: new Map(),
288 status: `disabled`,
289 isReady: false,
290 isError: false,
291 isEnabled: false,
292 }
293 const scope = effectScope()
294 const result = Object.fromEntries(
295 Object.keys(raw).map((key) => [
296 key,
297 {
298 get value() {
299 return raw[key]
300 },
301 },
302 ]),
303 )
304 const handle = makeHandle(result, scope)
305 try {
306 const healthy = handle.current()
307 expect(healthy.data).toBe(raw.data)
308 expect(healthy.state).toBe(raw.state)
309 expect(healthy.isReady).toBe(false)
310 expect(healthy.isError).toBe(false)
311 expect(healthy.isEnabled).toBe(false)
312 for (const key of [`status`, `isReady`, `isError`]) {
313 const original = raw[key]
314 delete raw[key]
315 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
316 for (const invalid of key === `status`
317 ? [undefined, 0]
318 : [undefined, 0, ``]) {
319 raw[key] = invalid
320 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
321 }
322 raw[key] = original
323 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
324 }
325 } finally {
326 handle.unmount()
327 }
328})