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