UNPKG

1.16 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3*/
4
5"use strict";
6
7const RuntimeGlobals = require("../RuntimeGlobals");
8const RuntimeModule = require("../RuntimeModule");
9const Template = require("../Template");
10
11class GlobalRuntimeModule extends RuntimeModule {
12 constructor() {
13 super("global");
14 }
15
16 /**
17 * @returns {string} runtime code
18 */
19 generate() {
20 return Template.asString([
21 `${RuntimeGlobals.global} = (function() {`,
22 Template.indent([
23 "if (typeof globalThis === 'object') return globalThis;",
24 "try {",
25 Template.indent(
26 // This works in non-strict mode
27 // or
28 // This works if eval is allowed (see CSP)
29 "return this || new Function('return this')();"
30 ),
31 "} catch (e) {",
32 Template.indent(
33 // This works if the window reference is available
34 "if (typeof window === 'object') return window;"
35 ),
36 "}"
37 // It can still be `undefined`, but nothing to do about it...
38 // We return `undefined`, instead of nothing here, so it's
39 // easier to handle this case:
40 // if (!global) { … }
41 ]),
42 "})();"
43 ]);
44 }
45}
46
47module.exports = GlobalRuntimeModule;