SetIntegrityLevel.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $SyntaxError = require('es-errors/syntax');
  4. var $TypeError = require('es-errors/type');
  5. var $preventExtensions = GetIntrinsic('%Object.preventExtensions%', true);
  6. var $gOPD = require('gopd');
  7. var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%', true);
  8. var forEach = require('../helpers/forEach');
  9. var DefinePropertyOrThrow = require('./DefinePropertyOrThrow');
  10. var IsAccessorDescriptor = require('./IsAccessorDescriptor');
  11. var ToPropertyDescriptor = require('./ToPropertyDescriptor');
  12. var Type = require('./Type');
  13. // https://262.ecma-international.org/6.0/#sec-setintegritylevel
  14. module.exports = function SetIntegrityLevel(O, level) {
  15. if (Type(O) !== 'Object') {
  16. throw new $TypeError('Assertion failed: Type(O) is not Object');
  17. }
  18. if (level !== 'sealed' && level !== 'frozen') {
  19. throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`');
  20. }
  21. if (!$preventExtensions) {
  22. throw new $SyntaxError('SetIntegrityLevel requires native `Object.preventExtensions` support');
  23. }
  24. var status = $preventExtensions(O);
  25. if (!status) {
  26. return false;
  27. }
  28. if (!$gOPN) {
  29. throw new $SyntaxError('SetIntegrityLevel requires native `Object.getOwnPropertyNames` support');
  30. }
  31. var theKeys = $gOPN(O);
  32. if (level === 'sealed') {
  33. forEach(theKeys, function (k) {
  34. DefinePropertyOrThrow(O, k, { configurable: false });
  35. });
  36. } else if (level === 'frozen') {
  37. forEach(theKeys, function (k) {
  38. var currentDesc = $gOPD(O, k);
  39. if (typeof currentDesc !== 'undefined') {
  40. var desc;
  41. if (IsAccessorDescriptor(ToPropertyDescriptor(currentDesc))) {
  42. desc = { configurable: false };
  43. } else {
  44. desc = { configurable: false, writable: false };
  45. }
  46. DefinePropertyOrThrow(O, k, desc);
  47. }
  48. });
  49. }
  50. return true;
  51. };