DetachArrayBuffer.js 1.5 KB

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