GlobalRuntimeModule.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. * @returns {string | null} runtime code
  14. */
  15. generate() {
  16. return Template.asString([
  17. `${RuntimeGlobals.global} = (function() {`,
  18. Template.indent([
  19. "if (typeof globalThis === 'object') return globalThis;",
  20. "try {",
  21. Template.indent(
  22. // This works in non-strict mode
  23. // or
  24. // This works if eval is allowed (see CSP)
  25. "return this || new Function('return this')();"
  26. ),
  27. "} catch (e) {",
  28. Template.indent(
  29. // This works if the window reference is available
  30. "if (typeof window === 'object') return window;"
  31. ),
  32. "}"
  33. // It can still be `undefined`, but nothing to do about it...
  34. // We return `undefined`, instead of nothing here, so it's
  35. // easier to handle this case:
  36. // if (!global) { … }
  37. ]),
  38. "})();"
  39. ]);
  40. }
  41. }
  42. module.exports = GlobalRuntimeModule;