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

utils.ts

358 lines9.2 KB

1import { isTemporal } from './hashing/temporal.js'
2​
3/**
4 * Simple assertion function for runtime checks.
5 * Throws an error if the condition is false.
6 */
7export function assert(
8 condition: unknown,
9 message?: string,
10): asserts condition {
11 if (!condition) {
12 throw new Error(message || `Assertion failed`)
13 }
15​
16// JS engines have various limits on how many args can be passed to a function
17// with a spread operator, so we need to split the operation into chunks
18// 32767 is the max for Chrome 14, all others are higher
19// TODO: investigate the performance of this and other approaches
20const chunkSize = 30000
21export function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>) {
22 if (other.length <= chunkSize) {
23 array.push(...other)
24 } else {
25 for (let i = 0; i < other.length; i += chunkSize) {
26 const chunk = other.slice(i, i + chunkSize)
27 array.push(...chunk)
28 }
29 }
31​
32export function binarySearch<T>(
33 array: Array<T>,
34 value: T,
35 comparator: (a: T, b: T) => number,
36): number {
37 let low = 0
38 let high = array.length
39 while (low < high) {
40 const mid = Math.floor((low + high) / 2)
41 const comparison = comparator(array[mid]!, value)
42 if (comparison < 0) {
43 low = mid + 1
44 } else if (comparison > 0) {
45 high = mid
46 } else {
47 return mid
48 }
49 }
50 return low
52​
53const objectIds = new WeakMap<object, number>()
54let nextObjectId = 0
55​
56/**
57 * A string identity for composite keys: primitives by value, objects by
58 * reference.
59 */
60export function getStringId(value: unknown): string {
61 if (value === null) return `null`
62 if (value === undefined) return `undefined`
63 if (typeof value !== `object`) return `str_${String(value)}`
64 let id = objectIds.get(value)
65 if (id === undefined) objectIds.set(value, (id = nextObjectId++))
66 return `obj_${id}`
68​
69export function* concatIterable<T>(
70 ...iterables: Array<Iterable<T>>
71): Iterable<T> {
72 for (const iterable of iterables) {
73 yield* iterable
74 }
76​
77export function* mapIterable<T, U>(
78 it: Iterable<T>,
79 fn: (t: T) => U,
80): Iterable<U> {
81 for (const t of it) {
82 yield fn(t)
83 }
85​
86export type HRange = [number, number] // half-open [start, end[ i.e. end is exclusive
87​
88/**
89 * Computes the difference between two half-open ranges.
90 * @param a - The first half-open range
91 * @param b - The second half-open range
92 * @returns The difference between the two ranges
93 */
94export function diffHalfOpen(a: HRange, b: HRange) {
95 const [a1, a2] = a
96 const [b1, b2] = b
97​
98 // A \ B can be up to two segments (left and right of the overlap)
99 const onlyInA: Array<number> = [
100 ...range(a1, Math.min(a2, b1)), // left side of A outside B
101 ...range(Math.max(a1, b2), a2), // right side of A outside B
102 ]
103​
104 // B \ A similarly
105 const onlyInB: Array<number> = [
106 ...range(b1, Math.min(b2, a1)),
107 ...range(Math.max(b1, a2), b2),
108 ]
109​
110 return { onlyInA, onlyInB }
112​
113function range(start: number, end: number): Array<number> {
114 const out: Array<number> = []
115 for (let i = start; i < end; i++) out.push(i)
116 return out
118​
119/**
120 * Compares two keys (string | number) in a consistent, deterministic way.
121 * Handles mixed types by ordering strings before numbers.
122 */
123export function compareKeys(a: string | number, b: string | number): number {
124 // Same type: compare directly
125 if (typeof a === typeof b) {
126 if (typeof a === `number` && typeof b === `number`) {
127 const aIsNaN = Number.isNaN(a)
128 const bIsNaN = Number.isNaN(b)
129 if (aIsNaN || bIsNaN) {
130 if (aIsNaN && bIsNaN) return 0
131 return aIsNaN ? 1 : -1
132 }
133 }
134 if (a < b) return -1
135 if (a > b) return 1
136 return 0
137 }
138 // Different types: strings come before numbers
139 return typeof a === `string` ? -1 : 1
141​
142type CanonicalValue =
143 | readonly [`undefined`]
144 | readonly [`null`]
145 | readonly [`boolean`, boolean]
146 | readonly [`number`, number | `NaN` | `Infinity` | `-Infinity`]
147 | readonly [`bigint`, string]
148 | readonly [`string`, string]
149 | readonly [`date`, number | `Invalid`]
150 | readonly [`temporal`, string, string]
151 | readonly [`regexp`, string, string]
152 | readonly [`bytes`, Array<number>]
153 | readonly [`array`, Array<CanonicalValue>]
154 | readonly [`map`, Array<readonly [CanonicalValue, CanonicalValue]>]
155 | readonly [`set`, Array<CanonicalValue>]
156 | readonly [`object`, Array<readonly [string, CanonicalValue]>]
157​
158/**
159 * Serializes a supported query value into one canonical key.
160 *
161 * JSON's native encoding is not suitable for relation keys: it merges BigInt
162 * with strings when a replacer is used, merges NaN with null, drops undefined,
163 * and depends on object insertion order. Ordinary JSON values keep their
164 * established wire form. Values that need richer types use a reserved prefix
165 * plus a structural, type-tagged encoding.
166 */
167export function serializeValue(value: unknown): string {
168 if (isJsonSafeStructuralValue(value, new Set())) {
169 return JSON.stringify(toStableJsonValue(value))
170 }
171​
172 return `~${JSON.stringify(toCanonicalValue(value, new Set()))}`
174​
175type JsonValue =
176 | null
177 | boolean
178 | number
179 | string
180 | Array<JsonValue>
181 | { [key: string]: JsonValue }
182​
183function isJsonSafeStructuralValue(
184 value: unknown,
185 ancestors: Set<object>,
186): boolean {
187 if (value === null) return true
188​
189 switch (typeof value) {
190 case `boolean`:
191 case `string`:
192 return true
193 case `number`:
194 return Number.isFinite(value)
195 case `undefined`:
196 case `bigint`:
197 case `symbol`:
198 case `function`:
199 return false
200 }
201​
202 return withAcyclicValue(value, ancestors, () => {
203 if (
204 value instanceof Date ||
205 value instanceof RegExp ||
206 value instanceof Uint8Array ||
207 isTemporal(value) ||
208 value instanceof Map ||
209 value instanceof Set
210 ) {
211 return false
212 }
213​
214 return Array.isArray(value)
215 ? value.every((item) => isJsonSafeStructuralValue(item, ancestors))
216 : Object.keys(value).every((key) =>
217 isJsonSafeStructuralValue(
218 (value as Record<string, unknown>)[key],
219 ancestors,
220 ),
221 )
222 })
224​
225function toStableJsonValue(value: unknown): JsonValue {
226 if (
227 value === null ||
228 typeof value === `boolean` ||
229 typeof value === `number` ||
230 typeof value === `string`
231 ) {
232 return value
233 }
234​
235 if (Array.isArray(value)) {
236 return value.map(toStableJsonValue)
237 }
238​
239 return Object.fromEntries(
240 Object.keys(value as object)
241 .sort()
242 .map((key) => [
243 key,
244 toStableJsonValue((value as Record<string, unknown>)[key]),
245 ]),
246 )
248​
249function toCanonicalValue(
250 value: unknown,
251 ancestors: Set<object>,
252): CanonicalValue {
253 if (value === undefined) return [`undefined`]
254 if (value === null) return [`null`]
255​
256 switch (typeof value) {
257 case `boolean`:
258 return [`boolean`, value]
259 case `number`:
260 if (Number.isNaN(value)) return [`number`, `NaN`]
261 if (value === Infinity) return [`number`, `Infinity`]
262 if (value === -Infinity) return [`number`, `-Infinity`]
263 return [`number`, value === 0 ? 0 : value]
264 case `bigint`:
265 return [`bigint`, value.toString()]
266 case `string`:
267 return [`string`, value]
268 case `symbol`:
269 case `function`:
270 throw new TypeError(
271 `Cannot serialize ${typeof value} as a structural relation key`,
272 )
273 }
274​
275 return withAcyclicValue(value, ancestors, () => {
276 if (value instanceof Date) {
277 const timestamp = value.getTime()
278 return Number.isNaN(timestamp)
279 ? ([`date`, `Invalid`] as const)
280 : ([`date`, timestamp] as const)
281 }
282​
283 if (value instanceof RegExp) {
284 return [`regexp`, value.source, value.flags]
285 }
286​
287 if (value instanceof Uint8Array) {
288 return [`bytes`, Array.from(value)]
289 }
290​
291 if (isTemporal(value)) {
292 return [`temporal`, value[Symbol.toStringTag], value.toString()]
293 }
294​
295 if (Array.isArray(value)) {
296 return [`array`, value.map((item) => toCanonicalValue(item, ancestors))]
297 }
298​
299 if (value instanceof Map) {
300 const entries = [...value.entries()].map(
301 ([key, entryValue]) =>
302 [
303 toCanonicalValue(key, ancestors),
304 toCanonicalValue(entryValue, ancestors),
305 ] as const,
306 )
307 entries.sort((left, right) =>
308 compareSerializedValues(JSON.stringify(left), JSON.stringify(right)),
309 )
310 return [`map`, entries]
311 }
312​
313 if (value instanceof Set) {
314 const entries = [...value].map((entry) =>
315 toCanonicalValue(entry, ancestors),
316 )
317 entries.sort((left, right) =>
318 compareSerializedValues(JSON.stringify(left), JSON.stringify(right)),
319 )
320 return [`set`, entries]
321 }
322​
323 const entries = Object.keys(value)
324 .sort()
325 .map(
326 (key) =>
327 [
328 key,
329 toCanonicalValue(
330 (value as Record<string, unknown>)[key],
331 ancestors,
332 ),
333 ] as const,
334 )
335 return [`object`, entries]
336 })
338​
339function compareSerializedValues(left: string, right: string): number {
340 return left < right ? -1 : left > right ? 1 : 0
342​
343function withAcyclicValue<T>(
344 value: object,
345 ancestors: Set<object>,
346 encode: () => T,
347): T {
348 if (ancestors.has(value)) {
349 throw new TypeError(`Cannot serialize a cyclic structural relation key`)
350 }
351​
352 ancestors.add(value)
353 try {
354 return encode()
355 } finally {
356 ancestors.delete(value)
357 }