Open History to see the last commit
1/**
2 * Virtual Properties for TanStack DB
3 *
4 * Virtual properties are computed, read-only properties that provide metadata about rows
5 * (sync status, source, selection state) without being part of the persisted data model.
6 *
7 * Virtual properties are prefixed with `$` to distinguish them from user data fields.
8 * User schemas should not include `$`-prefixed fields as they are reserved.
9 */
10
11/**
12 * Origin of the last confirmed change to a row, from the current client's perspective.
13 *
14 * - `'local'`: The change originated from this client (e.g., a mutation made here)
15 * - `'remote'`: The change was received via sync from another client/server
16 *
17 * Note: This reflects the client's perspective, not the original creator.
18 * User A creates order → $origin = 'local' on User A's client
19 * Order syncs to server
20 * User B receives order → $origin = 'remote' on User B's client
21 */
22export type VirtualOrigin = 'local' | 'remote'
23
24/**
25 * Virtual properties available on every row in TanStack DB collections.
26 *
27 * These properties are:
28 * - Computed (not stored in the data model)
29 * - Read-only (cannot be mutated directly)
30 * - Available in queries (WHERE, ORDER BY, SELECT)
31 * - Included when spreading rows (`...user`)
32 *
33 * @template TKey - The type of the row's key (string or number)
34 *
35 * @example
36 * ```typescript
37 * // Accessing virtual properties on a row
38 * const user = collection.get('user-1')
39 * if (user.$synced) {
40 * console.log('No pending local optimistic writes for this row')
41 * }
42 * if (user.$origin === 'local') {
43 * console.log('Created/modified locally')
44 * }
45 * ```
46 *
47 * @example
48 * ```typescript
49 * // Using virtual properties in queries
50 * const ordersWithoutLocalWrites = createLiveQueryCollection({
51 * query: (q) => q
52 * .from({ order: orders })
53 * .where(({ order }) => eq(order.$synced, true))
54 * })
55 * ```
56 */
57export interface VirtualRowProps<
58 TKey extends string | number = string | number,
59> {
60 /**
61 * Whether this row currently has no pending local optimistic writes.
62 *
63 * - `true`: No pending local optimistic mutation currently affects this row
64 * - `false`: One or more pending local optimistic mutations currently affect this row
65 *
66 * This is local mutation status. It does not prove that a backend has uploaded,
67 * confirmed, or read back the row. If you need backend-confirmed status, keep
68 * your mutation function pending until that backend observation has happened,
69 * or expose adapter-specific status.
70 *
71 * For local-only collections (no sync), this is always `true`.
72 * For live query collections, this is passed through from the source collection.
73 */
74 readonly $synced: boolean
75
76 /**
77 * Origin of the last confirmed change to this row, from the current client's perspective.
78 *
79 * - `'local'`: The change originated from this client
80 * - `'remote'`: The change was received via sync
81 *
82 * For local-only collections, this is always `'local'`.
83 * For live query collections, this is passed through from the source collection.
84 */
85 readonly $origin: VirtualOrigin
86
87 /**
88 * The row's key (primary identifier).
89 *
90 * This is the same value returned by `collection.config.getKey(row)`.
91 * Useful when you need the key in projections or computations.
92 */
93 readonly $key: TKey
94
95 /**
96 * The ID of the source collection this row originated from.
97 *
98 * In joins, this can help identify which collection each row came from.
99 * For live query collections, this is the ID of the upstream collection.
100 */
101 readonly $collectionId: string
102}
103
104/**
105 * Adds virtual properties to a row type.
106 *
107 * @template T - The base row type
108 * @template TKey - The type of the row's key
109 *
110 * @example
111 * ```typescript
112 * type User = { id: string; name: string }
113 * type UserWithVirtual = WithVirtualProps<User, string>
114 * // { id: string; name: string; $synced: boolean; $origin: 'local' | 'remote'; $key: string; $collectionId: string }
115 * ```
116 */
117export type WithVirtualProps<
118 T extends object,
119 TKey extends string | number = string | number,
120> = T & VirtualRowProps<TKey>
121
122/**
123 * Extracts the base type from a type that may have virtual properties.
124 * Useful when you need to work with the raw data without virtual properties.
125 *
126 * @template T - The type that may include virtual properties
127 *
128 * @example
129 * ```typescript
130 * type UserWithVirtual = { id: string; name: string; $synced: boolean; $origin: 'local' | 'remote' }
131 * type User = WithoutVirtualProps<UserWithVirtual>
132 * // { id: string; name: string }
133 * ```
134 */
135export type WithoutVirtualProps<T> = Omit<T, keyof VirtualRowProps>
136
137/**
138 * Checks if a value has virtual properties attached.
139 *
140 * @param value - The value to check
141 * @returns true if the value has virtual properties
142 *
143 * @example
144 * ```typescript
145 * if (hasVirtualProps(row)) {
146 * console.log('Synced:', row.$synced)
147 * }
148 * ```
149 */
150export function hasVirtualProps(
151 value: unknown,
152): value is VirtualRowProps<string | number> {
153 return (
154 typeof value === 'object' &&
155 value !== null &&
156 VIRTUAL_PROP_NAMES.every((name) => name in value)
157 )
158}
159
160/**
161 * Creates virtual properties for a row in a source collection.
162 *
163 * This is the internal function used by collections to add virtual properties
164 * to rows when emitting change messages.
165 *
166 * @param key - The row's key
167 * @param collectionId - The collection's ID
168 * @param isSynced - Whether the row is synced (not optimistic)
169 * @param origin - Whether the change was local or remote
170 * @returns Virtual properties object to merge with the row
171 *
172 * @internal
173 */
174export function createVirtualProps<TKey extends string | number>(
175 key: TKey,
176 collectionId: string,
177 isSynced: boolean,
178 origin: VirtualOrigin,
179): VirtualRowProps<TKey> {
180 return {
181 $synced: isSynced,
182 $origin: origin,
183 $key: key,
184 $collectionId: collectionId,
185 }
186}
187
188/**
189 * Enriches a row with virtual properties using the "add-if-missing" pattern.
190 *
191 * If the row already has virtual properties (from an upstream collection),
192 * they are preserved. If not, new virtual properties are computed and added.
193 *
194 * This is the key function that enables pass-through semantics for nested
195 * live query collections.
196 *
197 * @param row - The row to enrich
198 * @param key - The row's key
199 * @param collectionId - The collection's ID
200 * @param computeSynced - Function to compute $synced if missing
201 * @param computeOrigin - Function to compute $origin if missing
202 * @returns The row with virtual properties (possibly the same object if already present)
203 *
204 * @internal
205 */
206export function enrichRowWithVirtualProps<
207 T extends object,
208 TKey extends string | number,
209>(
210 row: T,
211 key: TKey,
212 collectionId: string,
213 computeSynced: () => boolean,
214 computeOrigin: () => VirtualOrigin,
215): WithVirtualProps<T, TKey> {
216 // Use nullish coalescing to preserve existing virtual properties (pass-through)
217 // This is the "add-if-missing" pattern described in the RFC
218 const existingRow = row as Partial<VirtualRowProps<TKey>>
219
220 return {
221 ...row,
222 $synced: existingRow.$synced ?? computeSynced(),
223 $origin: existingRow.$origin ?? computeOrigin(),
224 $key: existingRow.$key ?? key,
225 $collectionId: existingRow.$collectionId ?? collectionId,
226 } as WithVirtualProps<T, TKey>
227}
228
229/**
230 * Computes aggregate virtual properties for a group of rows.
231 *
232 * For aggregates:
233 * - `$synced`: true if ALL rows in the group are synced; false if ANY row is optimistic
234 * - `$origin`: 'local' if ANY row in the group is local; otherwise 'remote'
235 *
236 * @param rows - The rows in the group
237 * @param groupKey - The group key
238 * @param collectionId - The collection ID
239 * @returns Virtual properties for the aggregate row
240 *
241 * @internal
242 */
243export function computeAggregateVirtualProps<TKey extends string | number>(
244 rows: Array<Partial<VirtualRowProps<string | number>>>,
245 groupKey: TKey,
246 collectionId: string,
247): VirtualRowProps<TKey> {
248 // $synced = true only if ALL rows are synced (false if ANY is optimistic)
249 const allSynced = rows.every((row) => row.$synced ?? true)
250
251 // $origin = 'local' if ANY row is local (consistent with "local influence" semantics)
252 const hasLocal = rows.some((row) => row.$origin === 'local')
253
254 return {
255 $synced: allSynced,
256 $origin: hasLocal ? 'local' : 'remote',
257 $key: groupKey,
258 $collectionId: collectionId,
259 }
260}
261
262/**
263 * List of virtual property names for iteration and checking.
264 * @internal
265 */
266export const VIRTUAL_PROP_NAMES = [
267 '$synced',
268 '$origin',
269 '$key',
270 '$collectionId',
271] as const
272
273/**
274 * Checks if a property name is a virtual property.
275 * @internal
276 */
277export function isVirtualPropName(name: string): boolean {
278 return VIRTUAL_PROP_NAMES.includes(name as any)
279}
280
281/**
282 * Checks whether a property path references a virtual property.
283 * @internal
284 */
285export function hasVirtualPropPath(path: Array<string>): boolean {
286 return path.some((segment) => isVirtualPropName(segment))
287}