detach-transferable.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. var global = require('../internals/global');
  3. var tryNodeRequire = require('../internals/try-node-require');
  4. var PROPER_STRUCTURED_CLONE_TRANSFER = require('../internals/structured-clone-proper-transfer');
  5. var structuredClone = global.structuredClone;
  6. var $ArrayBuffer = global.ArrayBuffer;
  7. var $MessageChannel = global.MessageChannel;
  8. var detach = false;
  9. var WorkerThreads, channel, buffer, $detach;
  10. if (PROPER_STRUCTURED_CLONE_TRANSFER) {
  11. detach = function (transferable) {
  12. structuredClone(transferable, { transfer: [transferable] });
  13. };
  14. } else if ($ArrayBuffer) try {
  15. if (!$MessageChannel) {
  16. WorkerThreads = tryNodeRequire('worker_threads');
  17. if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel;
  18. }
  19. if ($MessageChannel) {
  20. channel = new $MessageChannel();
  21. buffer = new $ArrayBuffer(2);
  22. $detach = function (transferable) {
  23. channel.port1.postMessage(null, [transferable]);
  24. };
  25. if (buffer.byteLength === 2) {
  26. $detach(buffer);
  27. if (buffer.byteLength === 0) detach = $detach;
  28. }
  29. }
  30. } catch (error) { /* empty */ }
  31. module.exports = detach;