UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

376 lines (332 loc) • 11.2 kB
/** * Generic utility functions */ import type { CompareOptions } from './query/builder/types' interface TypedArray { length: number [index: number]: number } /** * Deep equality function that compares two values recursively * Handles primitives, objects, arrays, Date, RegExp, Map, Set, TypedArrays, and Temporal objects * * @param a - First value to compare * @param b - Second value to compare * @returns True if the values are deeply equal, false otherwise * * @example * ```typescript * deepEquals({ a: 1, b: 2 }, { b: 2, a: 1 }) // true (property order doesn't matter) * deepEquals([1, { x: 2 }], [1, { x: 2 }]) // true * deepEquals({ a: 1 }, { a: 2 }) // false * deepEquals(new Date('2023-01-01'), new Date('2023-01-01')) // true * deepEquals(new Map([['a', 1]]), new Map([['a', 1]])) // true * ``` */ export function deepEquals(a: any, b: any): boolean { return deepEqualsInternal(a, b, new Map()) } function isPlainPrototype(prototype: object | null): boolean { return prototype === null || Object.getPrototypeOf(prototype) === null } function enumerableOwnKeys(value: object): Array<string | symbol> { const keys: Array<string | symbol> = Object.keys(value) for (const key of Object.getOwnPropertySymbols(value)) { if (Object.prototype.propertyIsEnumerable.call(value, key)) keys.push(key) } return keys } /** * Internal implementation with cycle detection to prevent infinite recursion. * Internal callers can seed already-paired roots when comparing their children. * * `draft` selects the stricter equality used by change-tracking drafts: Map * and Set contents must match in order, RegExp match position must match, and * arrays compare as keyed objects (holes and extra enumerable keys count). */ export function deepEqualsInternal( a: any, b: any, visited: Map<object, object>, draft = false, ): boolean { // Handle strict equality (primitives, same reference) if (a === b || Object.is(a, b)) return true // Handle null/undefined if (a == null || b == null) return false // Handle different types if (typeof a !== typeof b) return false // Handle Date objects if (a instanceof Date) { if (!(b instanceof Date)) return false return Object.is(a.getTime(), b.getTime()) } // Symmetric check: if b is Date but a is not, they're not equal if (b instanceof Date) return false // Handle RegExp objects if (a instanceof RegExp) { if (!(b instanceof RegExp)) return false return ( a.source === b.source && a.flags === b.flags && (!draft || a.lastIndex === b.lastIndex) ) } // Symmetric check: if b is RegExp but a is not, they're not equal if (b instanceof RegExp) return false // Handle Map objects - only if both are Maps if (a instanceof Map) { if (!(b instanceof Map)) return false if (a.size !== b.size) return false // Check for circular references if (visited.has(a)) { return visited.get(a) === b } visited.set(a, b) // A draft compares entries in order; general equality looks keys up. const bEntries = draft && Array.from(b.entries()) const result = Array.from(a.entries()).every(([key, val], index) => bEntries ? Object.is(key, bEntries[index]![0]) && deepEqualsInternal(val, bEntries[index]![1], visited, true) : b.has(key) && deepEqualsInternal(val, b.get(key), visited), ) visited.delete(a) return result } // Symmetric check: if b is Map but a is not, they're not equal if (b instanceof Map) return false // Handle Set objects - only if both are Sets if (a instanceof Set) { if (!(b instanceof Set)) return false if (a.size !== b.size) return false // Check for circular references if (visited.has(a)) { return visited.get(a) === b } visited.set(a, b) // Convert to arrays for comparison const aValues = Array.from(a) const bValues = Array.from(b) if (draft) { const result = aValues.every((val, index) => deepEqualsInternal(val, bValues[index], visited, draft), ) visited.delete(a) return result } // Simple comparison for primitive values if (aValues.every((val) => typeof val !== `object`)) { visited.delete(a) return aValues.every((val) => b.has(val)) } // Object-valued Sets are unordered. Match each value once, carrying a // branch-local cycle map so a failed candidate cannot poison the next. const matchValues = ( index: number, remaining: ReadonlyArray<number>, branchVisited: Map<object, object>, ): boolean => { if (index === aValues.length) return true const value = aValues[index] for (const [remainingIndex, candidateIndex] of remaining.entries()) { const candidateVisited = new Map(branchVisited) if ( deepEqualsInternal( value, bValues[candidateIndex], candidateVisited, ) && matchValues( index + 1, remaining.filter((_, otherIndex) => otherIndex !== remainingIndex), candidateVisited, ) ) { return true } } return false } const result = matchValues( 0, bValues.map((_, index) => index), visited, ) visited.delete(a) return result } // Symmetric check: if b is Set but a is not, they're not equal if (b instanceof Set) return false // Handle TypedArrays if ( ArrayBuffer.isView(a) && ArrayBuffer.isView(b) && !(a instanceof DataView) && !(b instanceof DataView) ) { const typedA = a as unknown as TypedArray const typedB = b as unknown as TypedArray // Elements compare like numbers: -0 equals 0, NaN equals NaN. Only a // draft treats a change of typed-array class as a change. if ( (draft && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) || typedA.length !== typedB.length ) return false for (let i = 0; i < typedA.length; i++) { const x = typedA[i]! const y = typedB[i]! if (x !== y && !(x !== x && y !== y)) return false } return true } // Symmetric check: if b is TypedArray but a is not, they're not equal if ( ArrayBuffer.isView(b) && !(b instanceof DataView) && !ArrayBuffer.isView(a) ) { return false } // Handle Temporal objects // Check if both are Temporal objects of the same type if (isTemporal(a) && isTemporal(b)) { const aTag = a[Symbol.toStringTag] const bTag = b[Symbol.toStringTag] // If they're different Temporal types, they're not equal if (aTag !== bTag) return false // Use Temporal's built-in equals method if available if (typeof a.equals === `function`) { return a.equals(b) } // Fallback to toString comparison for other types return a.toString() === b.toString() } // Symmetric check: if b is Temporal but a is not, they're not equal if (isTemporal(b)) return false // Handle arrays if (Array.isArray(a) !== Array.isArray(b)) return false if (Array.isArray(a) && a.length !== b.length) return false if (Array.isArray(a) && !draft) { // Check for circular references if (visited.has(a)) { return visited.get(a) === b } visited.set(a, b) const result = a.every((item, index) => deepEqualsInternal(item, b[index], visited), ) visited.delete(a) return result } // Handle objects if (typeof a === `object`) { // Instances of two different classes differ. A plain or null-prototype // object, from any realm, compares by keys with any class: a draft // snapshot and plain JSON both hold class instances as plain objects. const prototype = Object.getPrototypeOf(a) const prototypeB = Object.getPrototypeOf(b) const plain = isPlainPrototype(prototype) const plainB = isPlainPrototype(prototypeB) if (prototype !== prototypeB && !plain && !plainB) return false // Check for circular references if (visited.has(a)) { return visited.get(a) === b } visited.set(a, b) // Compare enumerable symbol keys as well as string keys. Query results may // use user-owned symbols, and a symbol-only update is still a value change. const keysA = enumerableOwnKeys(a) const keysB = enumerableOwnKeys(b) // Check if they have the same number of keys if (keysA.length !== keysB.length) { visited.delete(a) return false } // A class instance without enumerable keys (a File, an object with // private fields) keeps its state elsewhere, so it equals only itself. // A draft copies a URL by its href, so URLs compare by href. if (keysA.length === 0 && !Array.isArray(a) && !(plain && plainB)) { visited.delete(a) return a instanceof URL && a.href === b.href } // Check if all keys exist in both objects and their values are equal const result = keysA.every( (key) => Object.prototype.propertyIsEnumerable.call(b, key) && deepEqualsInternal(a[key], b[key], visited, draft), ) visited.delete(a) return result } // For primitives that aren't strictly equal return false } const temporalTypes = new Set([ `Temporal.Duration`, `Temporal.Instant`, `Temporal.PlainDate`, `Temporal.PlainDateTime`, `Temporal.PlainMonthDay`, `Temporal.PlainTime`, `Temporal.PlainYearMonth`, `Temporal.ZonedDateTime`, ]) export interface TemporalLike { [Symbol.toStringTag]: string toString: () => string equals?: (other: unknown) => boolean } /** Checks if the value is a Temporal object by checking for the Temporal brand */ export function isTemporal(a: unknown): a is TemporalLike { if (a == null || typeof a !== `object`) return false const tag = (a as Record<symbol, unknown>)[Symbol.toStringTag] return typeof tag === `string` && temporalTypes.has(tag) } export const DEFAULT_COMPARE_OPTIONS: Exclude< CompareOptions, { stringSort: `custom` } > = { direction: `asc`, nulls: `first`, stringSort: `locale`, } /** * Set of warning keys that have already been shown. * Used to prevent duplicate warnings from spamming the console. */ const warnedKeys = new Set<string>() /** * Log a warning message only once per unique key. * Subsequent calls with the same key will be silently ignored. * * @internal Used by first-party collection adapters. * * @param key - Unique identifier for this warning * @param message - The warning message to display * * @example * ```typescript * // First call logs the warning * warnOnce('deprecated-api', 'This API is deprecated') * * // Subsequent calls with same key are ignored * warnOnce('deprecated-api', 'This API is deprecated') // silent * ``` */ export function warnOnce(key: string, message: string): void { if (warnedKeys.has(key)) { return } warnedKeys.add(key) console.warn(message) } /** * Reset all warning states. Primarily useful for testing. * * @internal Used by first-party collection adapter tests. */ export function resetWarnings(): void { warnedKeys.clear() }