DetachArrayBuffer.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. var $SyntaxError = require('es-errors/syntax');
  3. var $TypeError = require('es-errors/type');
  4. var IsDetachedBuffer = require('./IsDetachedBuffer');
  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 (!IsDetachedBuffer(arrayBuffer)) { // node v21.0.0+ throws when you structuredClone a detached buffer
  24. if (typeof structuredClone === 'function') {
  25. structuredClone(arrayBuffer, { transfer: [arrayBuffer] });
  26. } else if (typeof postMessage === 'function') {
  27. postMessage('', '/', [arrayBuffer]); // TODO: see if this might trigger listeners
  28. } else if (MessageChannel) {
  29. (new MessageChannel()).port1.postMessage(null, [arrayBuffer]);
  30. } else {
  31. throw new $SyntaxError('DetachArrayBuffer is not supported in this environment');
  32. }
  33. }
  34. return null;
  35. };