GlobalRuntimeModule.js 1.2 KB

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