withCancel.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.withCancel = exports.getAsyncIterableWithCancel = exports.getAsyncIteratorWithCancel = void 0;
  4. const memoize_js_1 = require("./memoize.js");
  5. async function defaultAsyncIteratorReturn(value) {
  6. return { value, done: true };
  7. }
  8. const proxyMethodFactory = (0, memoize_js_1.memoize2)(function proxyMethodFactory(target, targetMethod) {
  9. return function proxyMethod(...args) {
  10. return Reflect.apply(targetMethod, target, args);
  11. };
  12. });
  13. function getAsyncIteratorWithCancel(asyncIterator, onCancel) {
  14. return new Proxy(asyncIterator, {
  15. has(asyncIterator, prop) {
  16. if (prop === 'return') {
  17. return true;
  18. }
  19. return Reflect.has(asyncIterator, prop);
  20. },
  21. get(asyncIterator, prop, receiver) {
  22. const existingPropValue = Reflect.get(asyncIterator, prop, receiver);
  23. if (prop === 'return') {
  24. const existingReturn = existingPropValue || defaultAsyncIteratorReturn;
  25. return async function returnWithCancel(value) {
  26. const returnValue = await onCancel(value);
  27. return Reflect.apply(existingReturn, asyncIterator, [returnValue]);
  28. };
  29. }
  30. else if (typeof existingPropValue === 'function') {
  31. return proxyMethodFactory(asyncIterator, existingPropValue);
  32. }
  33. return existingPropValue;
  34. },
  35. });
  36. }
  37. exports.getAsyncIteratorWithCancel = getAsyncIteratorWithCancel;
  38. function getAsyncIterableWithCancel(asyncIterable, onCancel) {
  39. return new Proxy(asyncIterable, {
  40. get(asyncIterable, prop, receiver) {
  41. const existingPropValue = Reflect.get(asyncIterable, prop, receiver);
  42. if (Symbol.asyncIterator === prop) {
  43. return function asyncIteratorFactory() {
  44. const asyncIterator = Reflect.apply(existingPropValue, asyncIterable, []);
  45. return getAsyncIteratorWithCancel(asyncIterator, onCancel);
  46. };
  47. }
  48. else if (typeof existingPropValue === 'function') {
  49. return proxyMethodFactory(asyncIterable, existingPropValue);
  50. }
  51. return existingPropValue;
  52. },
  53. });
  54. }
  55. exports.getAsyncIterableWithCancel = getAsyncIterableWithCancel;
  56. exports.withCancel = getAsyncIterableWithCancel;