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