All files / packages/tao-utils/src bridge.js

3.03% Statements 1/33
0% Branches 0/21
0% Functions 0/13
3.33% Lines 1/30
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63    2x                                                                                                                        
import { Kernel, AppCtx, INTERCEPT, ASYNC, INLINE } from '@tao.js/core';
 
const NOOP = () => {};
 
function forwardHandler(destination) {
  return (tao, data) => {
    // console.log('bridging::tao', tao);
    if (tao instanceof AppCtx) {
      destination.setAppCtx(tao);
    } else {
      destination.setCtx(tao, data);
    }
  };
}
 
function filteredForwardHandler(destination, filter) {
  const forward = forwardHandler(destination);
  if (!filter) {
    return forward;
  }
  return (tao, data) => {
    if (filter(tao, data)) {
      forward(tao, data);
    }
  };
}
 
function bridge(type, source, destination, filters) {
  if (type !== INTERCEPT && type !== ASYNC && type !== INLINE) {
    return NOOP;
  }
  if (!(source instanceof Kernel) || !(destination instanceof Kernel)) {
    return NOOP;
  }
  const filterFunction =
    typeof filters[0] === 'function' ? filters.shift() : undefined;
  const handler = filteredForwardHandler(destination, filterFunction);
  const attachment = `add${type}Handler`;
  const detachment = `remove${type}Handler`;
  if (!filters.length) {
    source[attachment]({}, handler);
    return () => source[detachment]({}, handler);
  }
  if (Array.isArray(filters[0])) {
    filters = filters[0];
  }
  filters.forEach(trigram => source[attachment](trigram, handler));
  return () =>
    filters.forEach(trigrams => source[detachment](trigrams, handler));
}
 
export function interceptBridge(source, destination, ...filters) {
  return bridge(INTERCEPT, source, destination, filters);
}
 
export function asyncBridge(source, destination, ...filters) {
  return bridge(ASYNC, source, destination, filters);
}
 
export function inlineBridge(source, destination, ...filters) {
  return bridge(INLINE, source, destination, filters);
}