index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. /** @typedef {`$${import('.').InternalSlot}`} SaltedInternalSlot */
  3. /** @typedef {{ [k in SaltedInternalSlot]?: unknown }} SlotsObject */
  4. var hasOwn = require('hasown');
  5. /** @type {import('side-channel').Channel<object, SlotsObject>} */
  6. var channel = require('side-channel')();
  7. var $TypeError = require('es-errors/type');
  8. /** @type {import('.')} */
  9. var SLOT = {
  10. assert: function (O, slot) {
  11. if (!O || (typeof O !== 'object' && typeof O !== 'function')) {
  12. throw new $TypeError('`O` is not an object');
  13. }
  14. if (typeof slot !== 'string') {
  15. throw new $TypeError('`slot` must be a string');
  16. }
  17. channel.assert(O);
  18. if (!SLOT.has(O, slot)) {
  19. throw new $TypeError('`' + slot + '` is not present on `O`');
  20. }
  21. },
  22. get: function (O, slot) {
  23. if (!O || (typeof O !== 'object' && typeof O !== 'function')) {
  24. throw new $TypeError('`O` is not an object');
  25. }
  26. if (typeof slot !== 'string') {
  27. throw new $TypeError('`slot` must be a string');
  28. }
  29. var slots = channel.get(O);
  30. // eslint-disable-next-line no-extra-parens
  31. return slots && slots[/** @type {SaltedInternalSlot} */ ('$' + slot)];
  32. },
  33. has: function (O, slot) {
  34. if (!O || (typeof O !== 'object' && typeof O !== 'function')) {
  35. throw new $TypeError('`O` is not an object');
  36. }
  37. if (typeof slot !== 'string') {
  38. throw new $TypeError('`slot` must be a string');
  39. }
  40. var slots = channel.get(O);
  41. // eslint-disable-next-line no-extra-parens
  42. return !!slots && hasOwn(slots, /** @type {SaltedInternalSlot} */ ('$' + slot));
  43. },
  44. set: function (O, slot, V) {
  45. if (!O || (typeof O !== 'object' && typeof O !== 'function')) {
  46. throw new $TypeError('`O` is not an object');
  47. }
  48. if (typeof slot !== 'string') {
  49. throw new $TypeError('`slot` must be a string');
  50. }
  51. var slots = channel.get(O);
  52. if (!slots) {
  53. slots = {};
  54. channel.set(O, slots);
  55. }
  56. // eslint-disable-next-line no-extra-parens
  57. slots[/** @type {SaltedInternalSlot} */ ('$' + slot)] = V;
  58. }
  59. };
  60. if (Object.freeze) {
  61. Object.freeze(SLOT);
  62. }
  63. module.exports = SLOT;