-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathglobalObject.ts
More file actions
63 lines (51 loc) · 1.83 KB
/
globalObject.ts
File metadata and controls
63 lines (51 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* inspired by https://mathiasbynens.be/notes/globalthis
*/
// Extend/Create the WorkerGlobalScope interface to avoid issues when used in a non-browser tsconfig environment
interface WorkerGlobalScope {
empty: never
}
// Utility type to enforce that exactly one of the two types is used
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never }
type XOR<T, U> = T | U extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U
export type GlobalObject = XOR<Window, WorkerGlobalScope>
export function getGlobalObject<T = typeof globalThis>(): T {
if (typeof globalThis === 'object') {
return globalThis as unknown as T
}
// Under Lightning Web Security, third-party code should rely on `self` to
// access the sandbox global object. The Object.prototype fallback below can
// also fail there because Object.prototype is sealed.
if (typeof self === 'object') {
return self as unknown as T
}
if (typeof window === 'object') {
return window as unknown as T
}
let globalObject: unknown
try {
Object.defineProperty(Object.prototype, '_dd_temp_', {
get() {
return this as object
},
configurable: true,
})
// @ts-ignore _dd_temp is defined using defineProperty
globalObject = _dd_temp_
// @ts-ignore _dd_temp is defined using defineProperty
delete Object.prototype._dd_temp_
} catch {
globalObject = {}
}
if (typeof globalObject !== 'object') {
globalObject = {}
}
return globalObject as T
}
/**
* Cached reference to the global object so it can be imported and re-used without
* re-evaluating the heavyweight fallback logic in `getGlobalObject()`.
*/
// eslint-disable-next-line local-rules/disallow-side-effects
export const globalObject = getGlobalObject<GlobalObject>()
export const isWorkerEnvironment = 'WorkerGlobalScope' in globalObject