Open History to see the last commit
1/**
2 * Solid driver for the shared live-query conformance suite.
3 *
4 * Each mount runs inside a `createRoot` so `unmount` disposes via the captured
5 * dispose fn; the root stays alive between mount and reads so Solid's reactive
6 * getters stay current. Solid auto-tracks signals, so controllable inputs use a
7 * signal read inside the query fn (no deps array). Collection/config inputs are
8 * passed as accessors, per Solid's arity-based input detection.
9 *
10 * All registered laws must pass; the driver has no whole-test waivers.
11 */
12import { describe, expect, it } from 'vitest'
13import {
14 coalesce,
15 count,
16 createCollection,
17 createLiveQueryCollection,
18 createOptimisticAction,
19 eq,
20 gt,
21 sum,
22} from '@tanstack/db'
23import { createRoot, createSignal, onCleanup } from 'solid-js'
24import {
25 mockSyncCollectionOptions,
26 mockSyncCollectionOptionsNoInitialState,
27} from '../../db/tests/utils'
28import { useLiveQuery } from '../src/useLiveQuery'
29import { runSuite } from '../../db/tests/conformance/suite'
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-solid-${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-solid-${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-solid-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 new Promise((resolve) => setTimeout(resolve, 10))
129}
130
131function makeHandle(
132 getResult: () => any,
133 dispose: () => void,
134): LiveQueryHandle {
135 return {
136 current(): ConformanceResult {
137 const result = getResult()
138 return expectResultSurface({
139 data: result?.data,
140 state: result?.state,
141 status: result?.status,
142 isReady: result?.isReady,
143 isError: result?.isError,
144 // solid-db exposes no `isEnabled`; derive it from status (status-derived).
145 isEnabled: result?.status !== `disabled`,
146 })
147 },
148 flush: settle,
149 async apply(fn: () => void) {
150 fn()
151 await settle()
152 },
153 unmount() {
154 dispose()
155 },
156 }
157}
158
159function inRoot(fn: () => any): { getResult: () => any; dispose: () => void } {
160 let result: any
161 let dispose!: () => void
162 withScopeSetup(
163 () =>
164 createRoot((d) => {
165 dispose = d
166 result = fn()
167 }),
168 () => dispose(),
169 )
170 return { getResult: () => result, dispose }
171}
172
173function mount(build: QueryBuild) {
174 const { getResult, dispose } = inRoot(() => useLiveQuery(build as any))
175 return makeHandle(getResult, dispose)
176}
177
178function mountCollection(collection: any) {
179 // Solid accepts a pre-created collection via an accessor.
180 const { getResult, dispose } = inRoot(() => useLiveQuery(() => collection))
181 return makeHandle(getResult, dispose)
182}
183
184function mountConfig(build: QueryBuild) {
185 // Solid accepts the config-object form via an accessor.
186 const { getResult, dispose } = inRoot(() =>
187 useLiveQuery(() => ({ query: build })),
188 )
189 return makeHandle(getResult, dispose)
190}
191
192function mountDisabled() {
193 // Disabled: an accessor returning null.
194 const { getResult, dispose } = inRoot(() => useLiveQuery(() => null))
195 return makeHandle(getResult, dispose)
196}
197
198function mountControllable<P>(
199 build: (q: any, param: P) => any,
200 initial: P,
201): ControllableHandle<P> {
202 const [param, setParam] = createSignal<P>(initial)
203 const { getResult, dispose } = inRoot(() =>
204 // Reading param() inside the query fn makes Solid recompute on change.
205 useLiveQuery((q: any) => build(q, param())),
206 )
207 const handle = makeHandle(getResult, dispose)
208 return {
209 ...handle,
210 async setParam(next: P) {
211 setParam(() => next)
212 await settle()
213 },
214 }
215}
216
217const solidDriver: LiveQueryDriver = {
218 name: `solid`,
219 disabledRepresentation: `empty-reactive`,
220 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
221 makeSource,
222 makeDeferredSource,
223 makePrecreated,
224 makeErrorSource,
225 mount,
226 mountControllable,
227 mountCollection,
228 mountConfig,
229 mountDisabled,
230 // solid-db routes errors through its createResource/Suspense path: reading an
231 // errored query throws (CollectionStateError) for an <ErrorBoundary> to catch,
232 // rather than exposing a readable isError flag. That's a framework idiom, not a
233 // gap — the error-status scenario is parametrized to assert it via the boundary.
234 errorSurface: `throw`,
235 knownGaps: [],
236 features: { serverSnapshot: false, suspense: true },
237}
238
239describe(`owned native scope setup`, () => {
240 it(`keeps a successful scope alive until explicit disposal`, () => {
241 let calls = 0
242 const handle = inRoot(() => {
243 onCleanup(() => {
244 calls++
245 })
246 return 7
247 })
248 expect(calls).toBe(0)
249 handle.dispose()
250 expect(calls).toBe(1)
251 })
252
253 it.each([false, true])(
254 `disposes failed setup and retains errors, cleanupFails=%s`,
255 (cleanupFails) => {
256 const primary = new Error(`scope setup failure`)
257 const secondary = new Error(`scope cleanup failure`)
258 let calls = 0
259 let caught: unknown
260 try {
261 inRoot(() => {
262 onCleanup(() => {
263 calls++
264 if (cleanupFails) throw secondary
265 })
266 throw primary
267 })
268 } catch (error) {
269 caught = error
270 }
271 expect(calls).toBe(1)
272 if (cleanupFails) {
273 expect(caught).toBeInstanceOf(AggregateError)
274 expect((caught as AggregateError).errors).toEqual([primary, secondary])
275 expect((caught as AggregateError).cause).toBe(primary)
276 } else expect(caught).toBe(primary)
277 },
278 )
279})
280
281runSuite(solidDriver)
282it(`preserves raw result types through the actual driver reader`, () => {
283 const raw: Record<string, unknown> = {
284 data: [{ id: `a`, value: undefined }],
285 state: new Map(),
286 status: `disabled`,
287 isReady: false,
288 isError: false,
289 isEnabled: false,
290 }
291 const handle = makeHandle(
292 () => raw,
293 () => {},
294 )
295 try {
296 const healthy = handle.current()
297 expect(healthy.data).toBe(raw.data)
298 expect(healthy.state).toBe(raw.state)
299 expect(healthy.isReady).toBe(false)
300 expect(healthy.isError).toBe(false)
301 expect(healthy.isEnabled).toBe(false)
302 for (const key of [`status`, `isReady`, `isError`]) {
303 const original = raw[key]
304 delete raw[key]
305 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
306 for (const invalid of key === `status`
307 ? [undefined, 0]
308 : [undefined, 0, ``]) {
309 raw[key] = invalid
310 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
311 }
312 raw[key] = original
313 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
314 }
315 } finally {
316 handle.unmount()
317 }
318})