Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

schema-transform-conformance.test-d.ts

278 lines9.2 KB

1import { describe, expectTypeOf, it } from 'vitest'
2import { Schema, Table, column } from '@powersync/node'
3import { z } from 'zod'
4import { createCollection } from '@tanstack/db'
5import { powerSyncCollectionOptions } from '../src'
6import type {
7 ChangeMessageOrDeleteKeyMessage,
8 WithVirtualProps,
9} from '@tanstack/db'
10import type { PowerSyncDatabase } from '@powersync/node'
11import type { ConfigWithArbitraryCollectionTypes } from '../src'
12​
13const database = {} as PowerSyncDatabase
14const appSchema = new Schema({
15 rows: new Table({
16 created_at: column.text,
17 score: column.integer,
18 label: column.text,
19 note: column.text,
20 enabled: column.integer,
21 }),
22})
23​
24const sqliteTransformSchema = z.object({
25 id: z.string().brand<`PowerSyncRowId`>(),
26 created_at: z
27 .string()
28 .nullable()
29 .default(null)
30 .transform((value) =>
31 value ? new Date(value) : new Date(`1970-01-01T00:00:00.000Z`),
32 ),
33 score: z
34 .number()
35 .nullable()
36 .default(0)
37 .transform((value) => value ?? 0)
38 .brand<`Score`>(),
39 label: z
40 .string()
41 .nullable()
42 .default(`untitled`)
43 .transform((value) => value ?? `untitled`),
44 note: z.string().nullable().default(null),
45 enabled: z
46 .number()
47 .nullable()
48 .default(0)
49 .transform((value) => Boolean(value)),
50})
51​
52const applicationSchema = z.object({
53 id: z.string().brand<`PowerSyncRowId`>(),
54 created_at: z.date(),
55 score: z.number().brand<`Score`>(),
56 label: z.string(),
57 note: z.string().nullable(),
58 enabled: z.boolean(),
59})
60​
61const applicationDeserializer = z.object({
62 id: z.string().brand<`PowerSyncRowId`>(),
63 created_at: z
64 .string()
65 .nullable()
66 .transform((value) => new Date(value!)),
67 score: z
68 .number()
69 .nullable()
70 .transform(
71 (value) => (value ?? 0) as z.output<typeof applicationSchema>[`score`],
72 ),
73 label: z
74 .string()
75 .nullable()
76 .transform((value) => value ?? `untitled`),
77 note: z.string().nullable(),
78 enabled: z
79 .number()
80 .nullable()
81 .transform((value) => Boolean(value)),
82})
83​
84type SqliteInput = z.input<typeof sqliteTransformSchema>
85type SqliteOutput = z.output<typeof sqliteTransformSchema>
86type ApplicationInput = z.input<typeof applicationSchema>
87type ApplicationOutput = z.output<typeof applicationSchema>
88type ItemOf<T> = T extends Array<infer U> ? U : T
89​
90const sqliteInput = {
91 id: `row-1`,
92 created_at: `2026-09-18T12:00:00.000Z`,
93 score: 42,
94 note: null,
95 enabled: 1,
96} satisfies SqliteInput
97​
98const applicationInput = {
99 id: `row-1`,
100 created_at: new Date(`2026-09-18T12:00:00.000Z`),
101 score: 42,
102 label: `untitled`,
103 note: null,
104 enabled: true,
105} satisfies ApplicationInput
106​
107const synchronizedOutput = {
108 id: `row-1` as ApplicationOutput[`id`],
109 created_at: new Date(`2026-09-18T12:00:00.000Z`),
110 score: 42 as ApplicationOutput[`score`],
111 label: `untitled`,
112 note: null,
113 enabled: true,
114} satisfies ApplicationOutput
115​
116/**
117 * Adapter mapping for the shared schema input/output law:
118 * PowerSync has two supported production type paths. A transforming Collection
119 * schema maps SQLite-shaped input to Collection output. With an application
120 * schema, `deserializationSchema` maps SQLite rows to that schema's exact
121 * output. In both paths, public mutations accept the Collection schema input;
122 * compare, serializer, Collection rows, and sync change messages use output.
123 * PowerSync keys are strings because every runtime key comes from the table's
124 * string `id`; schema branding does not narrow the public Collection key.
125 *
126 * The assertions observe both paths after TypeScript resolves the public
127 * options and Collection types. Hostile controls reject SQLite values at an
128 * application mutation boundary, application values at a SQLite mutation
129 * boundary, input rows at the sync boundary, and a deserializer with the wrong
130 * output. This partial oracle does not execute database reads, parsing,
131 * serialization, or deserialization-error handling.
132 */
133describe(`PowerSync schema transform conformance`, () => {
134 it(`transforms SQLite-shaped mutation and sync rows to exact output`, () => {
135 const options = powerSyncCollectionOptions({
136 database,
137 table: appSchema.props.rows,
138 schema: sqliteTransformSchema,
139 onDeserializationError: () => {},
140 serializer: {
141 created_at: (value) => value.toISOString(),
142 score: (value) => value,
143 enabled: (value) => (value ? 1 : 0),
144 },
145 compare: (left, right) => {
146 expectTypeOf(left).toEqualTypeOf<SqliteOutput>()
147 expectTypeOf(right).toEqualTypeOf<SqliteOutput>()
148 expectTypeOf(left.id).toEqualTypeOf<SqliteOutput[`id`]>()
149 expectTypeOf(left.created_at).toEqualTypeOf<Date>()
150 expectTypeOf(left.score).toEqualTypeOf<ApplicationOutput[`score`]>()
151 expectTypeOf(left.label).toEqualTypeOf<string>()
152 expectTypeOf(left.note).toEqualTypeOf<string | null>()
153 expectTypeOf(left.enabled).toEqualTypeOf<boolean>()
154 return left.score - right.score
155 },
156 })
157 const collection = createCollection(options)
158​
159 expectTypeOf(options.getKey).returns.toEqualTypeOf<string>()
160 expectTypeOf(collection.toArray).toEqualTypeOf<
161 Array<WithVirtualProps<SqliteOutput, string>>
162 >()
163​
164 type Insert = ItemOf<Parameters<typeof collection.insert>[0]>
165 expectTypeOf<Insert>().toEqualTypeOf<SqliteInput>()
166 collection.update(`row-1`, (draft) => {
167 expectTypeOf(draft).toEqualTypeOf<SqliteInput>()
168 })
169​
170 const assertMutationInput = () => {
171 collection.insert(sqliteInput)
172 // @ts-expect-error SQLite-shaped mutations do not accept booleans
173 collection.insert({ ...sqliteInput, enabled: true })
174 }
175 expectTypeOf(assertMutationInput).toBeFunction()
176 })
177​
178 it(`respects the explicit SQLite deserialization boundary`, () => {
179 const options = powerSyncCollectionOptions({
180 database,
181 table: appSchema.props.rows,
182 schema: applicationSchema,
183 deserializationSchema: applicationDeserializer,
184 onDeserializationError: () => {},
185 serializer: {
186 created_at: (value) => {
187 expectTypeOf(value).toEqualTypeOf<Date>()
188 return value.toISOString()
189 },
190 score: (value) => {
191 expectTypeOf(value).toEqualTypeOf<ApplicationOutput[`score`]>()
192 return value
193 },
194 enabled: (value) => {
195 expectTypeOf(value).toEqualTypeOf<boolean>()
196 return value ? 1 : 0
197 },
198 },
199 compare: (left, right) => {
200 expectTypeOf(left).toEqualTypeOf<ApplicationOutput>()
201 expectTypeOf(right).toEqualTypeOf<ApplicationOutput>()
202 return left.score - right.score
203 },
204 })
205 const collection = createCollection(options)
206​
207 expectTypeOf(options.getKey).returns.toEqualTypeOf<string>()
208 expectTypeOf(collection.toArray).toEqualTypeOf<
209 Array<WithVirtualProps<ApplicationOutput, string>>
210 >()
211​
212 type Insert = ItemOf<Parameters<typeof collection.insert>[0]>
213 expectTypeOf<Insert>().toEqualTypeOf<ApplicationInput>()
214 collection.update(`row-1`, (draft) => {
215 expectTypeOf(draft).toEqualTypeOf<ApplicationInput>()
216 })
217​
218 type SyncParams = Parameters<(typeof options)[`sync`][`sync`]>[0]
219 type SyncMessage = Parameters<SyncParams[`write`]>[0]
220 expectTypeOf<SyncMessage>().toEqualTypeOf<
221 ChangeMessageOrDeleteKeyMessage<ApplicationOutput, string>
222 >()
223​
224 const assertSyncBoundary = (write: SyncParams[`write`]) => {
225 const wrongDate = {
226 ...synchronizedOutput,
227 created_at: sqliteInput.created_at,
228 }
229​
230 write({ type: `insert`, value: synchronizedOutput })
231 // @ts-expect-error one SQLite field cannot cross the sync boundary
232 write({ type: `insert`, value: wrongDate })
233 // @ts-expect-error SQLite/mutation input is not synchronized output
234 write({ type: `insert`, value: sqliteInput })
235 }
236 expectTypeOf(assertSyncBoundary).toBeFunction()
237​
238 const assertMutationInput = () => {
239 collection.insert(applicationInput)
240 // @ts-expect-error application mutations use booleans, not SQLite integers
241 collection.insert({ ...applicationInput, enabled: 1 })
242 }
243 expectTypeOf(assertMutationInput).toBeFunction()
244 })
245​
246 it(`rejects a deserializer whose output is not collection output`, () => {
247 const wrongDeserializer = z.object({
248 id: z.string(),
249 created_at: z.string().nullable(),
250 score: z.number().nullable(),
251 label: z.string().nullable(),
252 note: z.string().nullable(),
253 enabled: z.number().nullable(),
254 })
255​
256 type DeserializationSchema = ConfigWithArbitraryCollectionTypes<
257 (typeof appSchema.props)[`rows`],
258 typeof applicationSchema
259 >[`deserializationSchema`]
260 const acceptDeserializer = (_schema: DeserializationSchema) => {}
261​
262 // @ts-expect-error deserialization must produce collection output
263 acceptDeserializer(wrongDeserializer)
264​
265 // The member probe isolates the schema relation. This public call also
266 // protects overload and configuration-union selection.
267 const wrongPublicOptions = {
268 database,
269 table: appSchema.props.rows,
270 schema: applicationSchema,
271 deserializationSchema: wrongDeserializer,
272 onDeserializationError: () => {},
273 }
274​
275 // @ts-expect-error public options require exact collection output
276 powerSyncCollectionOptions(wrongPublicOptions)
277 })
278})