Open History to see the last commit
1import type { AbstractPowerSyncDatabase, Table } from '@powersync/common'
2import type { StandardSchemaV1 } from '@standard-schema/spec'
3import type {
4 BaseCollectionConfig,
5 CleanupFn,
6 CollectionConfig,
7 InferSchemaOutput,
8 LoadSubsetOptions,
9} from '@tanstack/db'
10import type {
11 AnyTableColumnType,
12 ExtractedTable,
13 OptionalExtractedTable,
14 PowerSyncRecord,
15} from './helpers'
16
17/**
18 * Small helper which determines the output type if:
19 * - Standard SQLite types are to be used OR
20 * - If the provided schema should be used.
21 */
22export type InferPowerSyncOutputType<
23 TTable extends Table = Table,
24 TSchema extends StandardSchemaV1<PowerSyncRecord> = never,
25> = TSchema extends never ? ExtractedTable<TTable> : InferSchemaOutput<TSchema>
26
27/**
28 * A mapping type for custom serialization of object properties to SQLite-compatible values.
29 *
30 * This type allows you to override, for keys in the input object (`TOutput`), a function that transforms
31 * the value to the corresponding SQLite type (`TSQLite`). Keys not specified will use the default SQLite serialization.
32 *
33 * ## Generics
34 * - `TOutput`: The input object type, representing the row data to be serialized.
35 * - `TSQLite`: The target SQLite-compatible type for each property, typically inferred from the table schema.
36 *
37 * ## Usage
38 * Use this type to define a map of serialization functions for specific keys when you need custom handling
39 * (e.g., converting complex objects, formatting dates, or handling enums).
40 *
41 * Example:
42 * ```ts
43 * const serializer: CustomSQLiteSerializer<MyRowType, MySQLiteType> = {
44 * createdAt: (date) => date.toISOString(),
45 * status: (status) => status ? 1 : 0,
46 * meta: (meta) => JSON.stringify(meta),
47 * };
48 * ```
49 *
50 * ## Behavior
51 * - Each key maps to a function that receives the value and returns the SQLite-compatible value.
52 * - Used by `serializeForSQLite` to override default serialization for specific columns.
53 */
54export type CustomSQLiteSerializer<
55 TOutput extends Record<string, unknown>,
56 TSQLite extends Record<string, unknown>,
57> = Partial<{
58 [Key in keyof TOutput]: (
59 value: TOutput[Key],
60 ) => Key extends keyof TSQLite ? TSQLite[Key] : never
61}>
62
63export type SerializerConfig<
64 TOutput extends Record<string, unknown>,
65 TSQLite extends Record<string, unknown>,
66> = {
67 /**
68 * Optional partial serializer object for customizing how individual columns are serialized for SQLite.
69 *
70 * This should be a partial map of column keys to serialization functions, following the
71 * {@link CustomSQLiteSerializer} type. Each function receives the column value and returns a value
72 * compatible with SQLite storage.
73 *
74 * If not provided for a column, the default behavior is used:
75 * - `TEXT`: Strings are stored as-is; Dates are converted to ISO strings; other types are JSON-stringified.
76 * - `INTEGER`/`REAL`: Numbers are stored as-is; booleans are mapped to 1/0.
77 *
78 * Use this option to override serialization for specific columns, such as formatting dates, handling enums,
79 * or serializing complex objects.
80 *
81 * Example:
82 * ```typescript
83 * serializer: {
84 * createdAt: (date) => date.getTime(), // Store as timestamp
85 * meta: (meta) => JSON.stringify(meta), // Custom object serialization
86 * }
87 * ```
88 */
89 serializer?: CustomSQLiteSerializer<TOutput, TSQLite>
90
91 /**
92 * Application logic should ensure that incoming synced data is always valid.
93 * Failing to deserialize and apply incoming changes results in data inconsistency - which is a fatal error.
94 * Use this callback to react to deserialization errors.
95 */
96 onDeserializationError: (error: StandardSchemaV1.FailureResult) => void
97}
98
99/**
100 * Config for when TInput and TOutput are both the SQLite types.
101 */
102export type ConfigWithSQLiteTypes = {}
103
104/**
105 * Config where TInput is the SQLite types while TOutput can be defined by TSchema.
106 * We can use the same schema to validate TInput and incoming SQLite changes.
107 */
108export type ConfigWithSQLiteInputType<
109 TTable extends Table,
110 TSchema extends StandardSchemaV1<
111 // TInput is the SQLite types.
112 OptionalExtractedTable<TTable>,
113 AnyTableColumnType<TTable>
114 >,
115> = SerializerConfig<
116 StandardSchemaV1.InferOutput<TSchema>,
117 ExtractedTable<TTable>
118> & {
119 schema: TSchema
120}
121
122/**
123 * Config where TInput and TOutput have arbitrarily typed values.
124 * The keys of the types need to equal the SQLite types.
125 * Since TInput is not the SQLite types, we require a schema in order to deserialize incoming SQLite updates. The schema should validate from SQLite to TOutput.
126 */
127export type ConfigWithArbitraryCollectionTypes<
128 TTable extends Table,
129 TSchema extends StandardSchemaV1<
130 // The input and output must have the same keys, the value types can be arbitrary
131 AnyTableColumnType<TTable>,
132 AnyTableColumnType<TTable>
133 >,
134> = SerializerConfig<
135 StandardSchemaV1.InferOutput<TSchema>,
136 ExtractedTable<TTable>
137> & {
138 schema: TSchema
139 /**
140 * Schema for deserializing and validating input data from the sync stream.
141 *
142 * This schema defines how to transform and validate data coming from SQLite types (as stored in the database)
143 * into the desired output types (`TOutput`) expected by your application or validation logic.
144 *
145 * The generic parameters allow for arbitrary input and output types, so you can specify custom conversion rules
146 * for each column. This is especially useful when your application expects richer types (e.g., Date, enums, objects)
147 * than what SQLite natively supports.
148 *
149 * Use this to ensure that incoming data from the sync stream is properly converted and validated before use.
150 *
151 * Example:
152 * ```typescript
153 * deserializationSchema: z.object({
154 * createdAt: z.preprocess((val) => new Date(val as string), z.date()),
155 * meta: z.preprocess((val) => JSON.parse(val as string), z.object({ ... })),
156 * })
157 * ```
158 *
159 * This enables robust type safety and validation for incoming data, bridging the gap between SQLite storage
160 * and your application's expected types.
161 */
162 deserializationSchema: StandardSchemaV1<
163 ExtractedTable<TTable>,
164 StandardSchemaV1.InferOutput<TSchema>
165 >
166}
167/**
168 * Eager sync mode hooks.
169 * Called once when the collection sync starts and stops.
170 */
171export type EagerSyncHooks = {
172 syncMode?: 'eager'
173 /**
174 * Called when the collection sync starts.
175 * Use this to set up external data sources (e.g. subscribing to a sync stream).
176 *
177 * @returns A cleanup function that is called when the collection sync is cleaned up.
178 */
179 onLoad?: () => CleanupFn | void | Promise<CleanupFn | void>
180 onLoadSubset?: never
181}
182
183/**
184 * On-demand sync mode hooks.
185 * Called each time a subset is loaded or unloaded in response to live query changes.
186 */
187export type OnDemandSyncHooks = {
188 syncMode: 'on-demand'
189 onLoad?: never
190 /**
191 * Called when a subset of data is requested by a live query.
192 * Use this to set up external data sources for the requested subset
193 * (e.g. subscribing to a sync stream with parameters derived from the query predicate).
194 *
195 * @returns A cleanup function that is called when the subset is unloaded.
196 */
197
198 onLoadSubset?: (
199 options: LoadSubsetOptions,
200 ) => CleanupFn | void | Promise<CleanupFn | void>
201}
202
203export type BasePowerSyncCollectionConfig<
204 TTable extends Table = Table,
205 TSchema extends StandardSchemaV1 = never,
206> = Omit<
207 BaseCollectionConfig<ExtractedTable<TTable>, string, TSchema>,
208 `onInsert` | `onUpdate` | `onDelete` | `getKey` | `syncMode`
209> & {
210 /** The PowerSync schema Table definition */
211 table: TTable
212 /** The PowerSync database instance */
213 database: AbstractPowerSyncDatabase
214 /**
215 * The maximum number of documents to read from the SQLite table
216 * in a single batch during the initial sync between PowerSync and the
217 * in-memory TanStack DB collection.
218 *
219 * @remarks
220 * - Defaults to {@link DEFAULT_BATCH_SIZE} if not specified.
221 * - Larger values reduce the number of round trips to the storage
222 * engine but increase memory usage per batch.
223 * - Smaller values may lower memory usage and allow earlier
224 * streaming of initial results, at the cost of more query calls.
225 */
226 syncBatchSize?: number
227} & (EagerSyncHooks | OnDemandSyncHooks)
228
229/**
230 * Configuration interface for PowerSync collection options.
231 * @template TTable - The PowerSync table schema definition
232 * @template TSchema - The validation schema type
233 */
234/**
235 * Configuration options for creating a PowerSync collection.
236 *
237 * @example
238 * ```typescript
239 * const APP_SCHEMA = new Schema({
240 * documents: new Table({
241 * name: column.text,
242 * }),
243 * })
244 *
245 * const db = new PowerSyncDatabase({
246 * database: {
247 * dbFilename: "test.sqlite",
248 * },
249 * schema: APP_SCHEMA,
250 * })
251 *
252 * const collection = createCollection(
253 * powerSyncCollectionOptions({
254 * database: db,
255 * table: APP_SCHEMA.props.documents
256 * })
257 * )
258 * ```
259 */
260export type PowerSyncCollectionConfig<
261 TTable extends Table = Table,
262 TSchema extends StandardSchemaV1<any> = never,
263> = BasePowerSyncCollectionConfig<TTable, TSchema> &
264 (
265 | ConfigWithSQLiteTypes
266 | ConfigWithSQLiteInputType<TTable, TSchema>
267 | ConfigWithArbitraryCollectionTypes<TTable, TSchema>
268 )
269
270/**
271 * Metadata for the PowerSync Collection.
272 */
273export type PowerSyncCollectionMeta<TTable extends Table = Table> = {
274 /**
275 * The SQLite table representing the collection.
276 */
277 tableName: string
278 /**
279 * The internal table used to track diffs for the collection.
280 */
281 trackedTableName: string
282
283 /**
284 * Serializes a collection value to the SQLite type
285 */
286 serializeValue: (value: any) => ExtractedTable<TTable>
287
288 /**
289 * Whether the PowerSync table tracks metadata.
290 */
291 metadataIsTracked: boolean
292}
293
294/**
295 * A CollectionConfig which includes utilities for PowerSync.
296 */
297export type EnhancedPowerSyncCollectionConfig<
298 TTable extends Table,
299 OutputType extends Record<string, unknown> = Record<string, unknown>,
300 TSchema extends StandardSchemaV1 = never,
301> = CollectionConfig<
302 OutputType,
303 string,
304 TSchema,
305 PowerSyncCollectionUtils<TTable>
306> & {
307 id?: string
308 utils: PowerSyncCollectionUtils<TTable>
309 schema?: TSchema
310}
311
312/**
313 * Collection-level utilities for PowerSync.
314 */
315export type PowerSyncCollectionUtils<TTable extends Table = Table> = {
316 getMeta: () => PowerSyncCollectionMeta<TTable>
317}
318
319/**
320 * Default value for {@link PowerSyncCollectionConfig#syncBatchSize}.
321 */
322export const DEFAULT_BATCH_SIZE = 1000