inline-createSuper-helpers.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = addCreateSuperHelper;
  6. var _core = require("@babel/core");
  7. const helperIDs = new WeakMap();
  8. function addCreateSuperHelper(file) {
  9. if (helperIDs.has(file)) {
  10. return (_core.types.cloneNode || _core.types.clone)(helperIDs.get(file));
  11. }
  12. try {
  13. return file.addHelper("createSuper");
  14. } catch (_unused) {}
  15. const id = file.scope.generateUidIdentifier("createSuper");
  16. helperIDs.set(file, id);
  17. const fn = helper({
  18. CREATE_SUPER: id,
  19. GET_PROTOTYPE_OF: file.addHelper("getPrototypeOf"),
  20. POSSIBLE_CONSTRUCTOR_RETURN: file.addHelper("possibleConstructorReturn")
  21. });
  22. file.path.unshiftContainer("body", [fn]);
  23. file.scope.registerDeclaration(file.path.get("body.0"));
  24. return _core.types.cloneNode(id);
  25. }
  26. const helper = _core.template.statement`
  27. function CREATE_SUPER(Derived) {
  28. function isNativeReflectConstruct() {
  29. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  30. // core-js@3
  31. if (Reflect.construct.sham) return false;
  32. // Proxy can't be polyfilled. Every browser implemented
  33. // proxies before or at the same time as Reflect.construct,
  34. // so if they support Proxy they also support Reflect.construct.
  35. if (typeof Proxy === "function") return true;
  36. // Since Reflect.construct can't be properly polyfilled, some
  37. // implementations (e.g. core-js@2) don't set the correct internal slots.
  38. // Those polyfills don't allow us to subclass built-ins, so we need to
  39. // use our fallback implementation.
  40. try {
  41. // If the internal slots aren't set, this throws an error similar to
  42. // TypeError: this is not a Date object.
  43. Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));
  44. return true;
  45. } catch (e) {
  46. return false;
  47. }
  48. }
  49. return function () {
  50. var Super = GET_PROTOTYPE_OF(Derived), result;
  51. if (isNativeReflectConstruct()) {
  52. // NOTE: This doesn't work if this.__proto__.constructor has been modified.
  53. var NewTarget = GET_PROTOTYPE_OF(this).constructor;
  54. result = Reflect.construct(Super, arguments, NewTarget);
  55. } else {
  56. result = Super.apply(this, arguments);
  57. }
  58. return POSSIBLE_CONSTRUCTOR_RETURN(this, result);
  59. }
  60. }
  61. `;