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

nativeObjectType.ts

70 lines2.1 KB

1type NativeObjectType = 'Map' | 'Set' | 'String'
2​
3/**
4 * Checks an object's internal slots with an intrinsic operation.
5 * @param value - The inspected object.
6 * @param type - The native brand to check.
7 * @returns Whether the intrinsic operation accepts the object.
8 */
9function hasNativeBrand(value: object, type: NativeObjectType): boolean {
10 try {
11 switch (type) {
12 case 'Map':
13 Map.prototype.has.call(value, undefined)
14 return true
15 case 'Set':
16 Set.prototype.has.call(value, undefined)
17 return true
18 case 'String':
19 String.prototype.valueOf.call(value)
20 return true
21 }
22 } catch {
23 return false
24 }
26​
27/**
28 * Identifies native collections and String wrappers across realms without reading accessors.
29 * @param value - The inspected value.
30 * @returns Its native brand, or undefined for other values and failed inspections.
31 */
32export function getNativeObjectType(
33 value: unknown,
34): NativeObjectType | undefined {
35 if (value === null || typeof value !== 'object') return undefined
36 try {
37 if (Array.isArray(value) || ArrayBuffer.isView(value)) return undefined
38 const length = Object.getOwnPropertyDescriptor(value, 'length')
39 if (
40 typeof length?.value === 'number' &&
41 !length.enumerable &&
42 !length.writable &&
43 !length.configurable &&
44 hasNativeBrand(value, 'String')
45 ) {
46 return 'String'
47 }
48 const parent = Object.getPrototypeOf(value)
49 if (parent === null) {
50 if (hasNativeBrand(value, 'Map')) return 'Map'
51 if (hasNativeBrand(value, 'Set')) return 'Set'
52 return undefined
53 }
54 if (parent === Object.prototype) return undefined
55 let prototype: object | null = value
56 for (let depth = 0; prototype && depth <= 500; depth++) {
57 const tag = Object.getOwnPropertyDescriptor(
58 prototype,
59 Symbol.toStringTag,
60 )?.value
61 if ((tag === 'Map' || tag === 'Set') && hasNativeBrand(value, tag)) {
62 return tag
63 }
64 prototype = Object.getPrototypeOf(prototype)
65 }
66 return undefined
67 } catch {
68 return undefined
69 }