DetachArrayBuffer.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $SyntaxError = GetIntrinsic('%SyntaxError%');
  4. var $TypeError = GetIntrinsic('%TypeError%');
  5. var isArrayBuffer = require('is-array-buffer');
  6. var isSharedArrayBuffer = require('is-shared-array-buffer');
  7. var MessageChannel;
  8. try {
  9. // eslint-disable-next-line global-require
  10. MessageChannel = require('worker_threads').MessageChannel;
  11. } catch (e) { /**/ }
  12. // https://262.ecma-international.org/9.0/#sec-detacharraybuffer
  13. /* globals postMessage */
  14. module.exports = function DetachArrayBuffer(arrayBuffer) {
  15. if (!isArrayBuffer(arrayBuffer) || isSharedArrayBuffer(arrayBuffer)) {
  16. throw new $TypeError('Assertion failed: `arrayBuffer` must be an Object with an [[ArrayBufferData]] internal slot, and not a Shared Array Buffer');
  17. }
  18. // commented out since there's no way to set or access this key
  19. // var key = arguments.length > 1 ? arguments[1] : void undefined;
  20. // if (!SameValue(arrayBuffer[[ArrayBufferDetachKey]], key)) {
  21. // throw new $TypeError('Assertion failed: `key` must be the value of the [[ArrayBufferDetachKey]] internal slot of `arrayBuffer`');
  22. // }
  23. if (typeof structuredClone === 'function') {
  24. structuredClone(arrayBuffer, { transfer: [arrayBuffer] });
  25. } else if (typeof postMessage === 'function') {
  26. postMessage('', '/', [arrayBuffer]); // TODO: see if this might trigger listeners
  27. } else if (MessageChannel) {
  28. (new MessageChannel()).port1.postMessage(null, [arrayBuffer]);
  29. } else {
  30. throw new $SyntaxError('DetachArrayBuffer is not supported in this environment');
  31. }
  32. return null;
  33. };