<commit_before>import xs from 'xstream';

function pausable (pause$) {
  return function (stream) {
    return pause$
      .map(paused => stream.filter(() => paused))
      .flatten();
  };
}

function disposeAllStreams (streams) {
  keys(streams).forEach(key => {
    const value = streams[key];

    delete streams[key];

    value && value.dispose && value.dispose();
  });
}

function makeDispose ({streams}, originalDispose, context) {
  return function dispose () {
    originalDispose.bind(context)();
    disposeAllStreams(streams);
  };
}

function onDispose (observable, disposeHandler) {
  const oldDispose = observable.dispose.bind(observable);

  observable.dispose = () => {
    disposeHandler();
    oldDispose();
  };

  return observable;
}

function record ({streams, addLogEntry, pause$}, streamToRecord, identifier) {
  const stream = streamToRecord.compose(pausable(pause$.startWith(true))).map(event => {
    if (typeof event.subscribe === 'function') {
      const eventStream = event.debug((innerEvent) => {
        addLogEntry({event: xs.of(innerEvent), time: new Date(), identifier, stream});
      });

      eventStream.request = event.request;

      return eventStream;
    }

    addLogEntry({event, time: new Date(), identifier, stream}); // TODO - stream is undefined and unused

    return event;
  });

  streams[identifier] = stream;

  return stream.debug(() => {});
}

function recordObservableSource ({streams, addLogEntry, pause$}, source) {
  const source$ = source.compose(pausable(pause$.startWith(true))).debug(event => {
    if (typeof event.subscribe === 'function') {
      const loggedEvent$ = event.do(response => {
        addLogEntry({
          event: Object.assign(
            Observable.just(response),
            event
          ),
          time: new Date(),
          identifier: ':root'
        });
      });

      loggedEvent$.request = event.request;

      source$.shamefullySendNext(loggedEvent$);
    } else {
      addLogEntry({event, time: new Date(), identifier: ':root'});

      return event;
    }
  });

  streams[':root'] = source$;

  return source$;
}

function wrapSourceFunction ({streams, addLogEntry, pause$}, name, f, context, scope = []) {
  return function newSource (...args) {
    const newScope = scope.concat(args);

    const returnValue = f.bind(context, ...args)();

    if (name.indexOf('isolate') !== -1 || typeof returnValue !== 'object') {
      return returnValue;
    }

    if (typeof returnValue.addListener !== 'function') {
      return wrapSource({streams, addLogEntry, pause$}, returnValue, newScope);
    }

    const identifier = newScope.join('/');

    return record({streams, addLogEntry, pause$}, returnValue, identifier);
  };
}

function keys (obj) {
  const _keys = [];

  for (let prop in obj) {
    _keys.push(prop);
  }

  return _keys;
}

function wrapSource ({streams, addLogEntry, pause$}, source, scope = []) {
  const returnValue = {};

  keys(source).forEach(key => {
    const value = source[key];

    if (key === 'dispose') {
      returnValue[key] = makeDispose({streams}, value, source);
    } else if (typeof value === 'function') {
      returnValue[key] = wrapSourceFunction({streams, addLogEntry, pause$}, key, value, returnValue, scope);
    } else {
      returnValue[key] = value;
    }
  });

  return returnValue;
}

const shittyListener = {
  next: () => {},
  error: () => {},
  complete: () => {}
};

const log = (label) => ({
  error: () => {},
  complete: () => {}
});

const subscribe = (f) => ({
  next: f,
  error: () => {},
  complete: () => {}
});

function createLog$() {
  const logEntry$ = xs.create();
  const logEntryReducer$ = logEntry$.map(entry => (log) => log.concat(entry));

  const logReplace$ = xs.create();
  const logReplaceReducer$ = logReplace$.map(newLog => (log) => newLog);

  const logReducer$ = xs.merge(
    logEntryReducer$,
    logReplaceReducer$
  )

  const log$ = logReducer$
    .fold((log, reducer) => reducer(log), [])

  function addLogEntry (entry) {
    logEntry$.shamefullySendNext(entry);
  }

  function replaceLog (newLog) {
    logReplace$.shamefullySendNext(newLog);
  }

  return {log$, addLogEntry, replaceLog};
}

export default function restartable (driver, opts = {}) {
  const {log$, addLogEntry, replaceLog} = createLog$();
  // TODO - dispose log subscription
  log$.addListener(shittyListener);

  const streams = {};

  const pauseSinksWhileReplaying = opts.pauseSinksWhileReplaying === undefined ? true : opts.pauseSinksWhileReplaying;
  const pause$ = (opts.pause$ || xs.empty()).startWith(true);
  const replayOnlyLastSink = opts.replayOnlyLastSink || false;

  let replaying;
  const lastSinkEvent$ = xs.createWithMemory();
  const finishedReplay$ = xs.create();

  function restartableDriver (sink$, streamAdapter) {
    const filteredSink$ = xs.create();

    if (sink$) {
      if (replaying && replayOnlyLastSink)  {
        lastSinkEvent$.map(lastEvent => finishedReplay$.mapTo(lastEvent)).flatten().take(1).addListener(subscribe((event) => {
          filteredSink$.shamefullySendNext(event);
        }));
      }

      if (pauseSinksWhileReplaying) {
        sink$.compose(pausable(pause$)).filter(() => !replaying).addListener({
          next: (ev) => filteredSink$.shamefullySendNext(ev),
          error: (err) => console.error(err),
          complete: () => {}
        });
      } else {
        sink$.compose(pausable(pause$)).addListener(subscribe((ev) => filteredSink$.shamefullySendNext(ev)));
      }
    }

    lastSinkEvent$.imitate(sink$);

    const source = driver(filteredSink$, streamAdapter);

    let returnValue;

    if (source === undefined || source === null) {
      return source;
    } else if (typeof source.addListener === 'function') {
      returnValue = recordObservableSource({streams, addLogEntry, pause$}, source);
    } else {
      returnValue = wrapSource({streams, addLogEntry, pause$}, source);
    }

    const oldReturnValueDispose = returnValue.dispose;

    returnValue.dispose = function () {
      oldReturnValueDispose && oldReturnValueDispose.bind(returnValue)();
      sink$ && sink$.dispose && sink$.dispose();

      disposeAllStreams(streams);
    }

    returnValue.log$ = log$;

    return returnValue;
  }

  function replayable (driver) {
    driver.onPreReplay = function () {
      replaying = true;
    };

    driver.replayLog = function (scheduler, newLog$, timeToResetTo = null) {
      let logToReplaceWith;

      newLog$.take(1).addListener({
        next: newLog => {
          logToReplaceWith = newLog;

          function scheduleEvent (historicEvent) {
            scheduler.scheduleAbsolute({}, historicEvent.time, () => {
              if (streams[historicEvent.identifier]) {
                streams[historicEvent.identifier].shamefullySendNext(historicEvent.event);
              } else {
                console.error('Missing replay stream ', historicEvent.identifier)
              }
            });
          }

          newLog.filter(event => timeToResetTo === null || event.time <= timeToResetTo).forEach(scheduleEvent);
        },

        error: (err) => {
          console.error(err);
        },

        complete: () => {
          replaceLog(logToReplaceWith);
        }
      })
    };

    driver.onPostReplay = function () {
      replaying = false;
      finishedReplay$.shamefullySendNext();
    };

    return restartableDriver;
  }

  return replayable(restartableDriver);
}
<commit_msg>Refactor<commit_after>import xs from 'xstream';

function pausable (pause$) {
  return function (stream) {
    return pause$
      .map(paused => stream.filter(() => paused))
      .flatten();
  };
}

function disposeAllStreams (streams) {
  keys(streams).forEach(key => {
    const value = streams[key];

    delete streams[key];

    value && value.dispose && value.dispose();
  });
}

function makeDispose ({streams}, originalDispose, context) {
  return function dispose () {
    originalDispose.bind(context)();
    disposeAllStreams(streams);
  };
}

function onDispose (observable, disposeHandler) {
  const oldDispose = observable.dispose.bind(observable);

  observable.dispose = () => {
    disposeHandler();
    oldDispose();
  };

  return observable;
}

function record ({streams, addLogEntry, pause$}, streamToRecord, identifier) {
  const stream = streamToRecord.compose(pausable(pause$.startWith(true))).map(event => {
    if (typeof event.subscribe === 'function') {
      const eventStream = event.debug((innerEvent) => {
        addLogEntry({event: xs.of(innerEvent), time: new Date(), identifier, stream});
      });

      eventStream.request = event.request;

      return eventStream;
    }

    addLogEntry({event, time: new Date(), identifier, stream}); // TODO - stream is undefined and unused

    return event;
  });

  streams[identifier] = stream;

  return stream.debug(() => {});
}

function recordObservableSource ({streams, addLogEntry, pause$}, source) {
  const source$ = source.compose(pausable(pause$.startWith(true))).debug(event => {
    if (typeof event.subscribe === 'function') {
      const loggedEvent$ = event.do(response => {
        addLogEntry({
          event: Object.assign(
            Observable.just(response),
            event
          ),
          time: new Date(),
          identifier: ':root'
        });
      });

      loggedEvent$.request = event.request;

      source$.shamefullySendNext(loggedEvent$);
    } else {
      addLogEntry({event, time: new Date(), identifier: ':root'});

      return event;
    }
  });

  streams[':root'] = source$;

  return source$;
}

function wrapSourceFunction ({streams, addLogEntry, pause$}, name, f, context, scope = []) {
  return function newSource (...args) {
    const newScope = scope.concat(args);

    const returnValue = f.bind(context, ...args)();

    if (name.indexOf('isolate') !== -1 || typeof returnValue !== 'object') {
      return returnValue;
    }

    if (typeof returnValue.addListener !== 'function') {
      return wrapSource({streams, addLogEntry, pause$}, returnValue, newScope);
    }

    const identifier = newScope.join('/');

    return record({streams, addLogEntry, pause$}, returnValue, identifier);
  };
}

function keys (obj) {
  const _keys = [];

  for (let prop in obj) {
    _keys.push(prop);
  }

  return _keys;
}

function wrapSource ({streams, addLogEntry, pause$}, source, scope = []) {
  const returnValue = {};

  keys(source).forEach(key => {
    const value = source[key];

    if (key === 'dispose') {
      returnValue[key] = makeDispose({streams}, value, source);
    } else if (typeof value === 'function') {
      returnValue[key] = wrapSourceFunction({streams, addLogEntry, pause$}, key, value, returnValue, scope);
    } else {
      returnValue[key] = value;
    }
  });

  return returnValue;
}

const shittyListener = {
  next: () => {},
  error: () => {},
  complete: () => {}
};

const log = (label) => ({
  error: () => {},
  complete: () => {}
});

const subscribe = (f) => ({
  next: f,
  error: () => {},
  complete: () => {}
});

function createLog$() {
  const logEntry$ = xs.create();
  const logEntryReducer$ = logEntry$.map(entry => (log) => log.concat(entry));

  const logReplace$ = xs.create();
  const logReplaceReducer$ = logReplace$.map(newLog => (log) => newLog);

  const logReducer$ = xs.merge(
    logEntryReducer$,
    logReplaceReducer$
  )

  const log$ = logReducer$
    .fold((log, reducer) => reducer(log), [])

  function addLogEntry (entry) {
    logEntry$.shamefullySendNext(entry);
  }

  function replaceLog (newLog) {
    logReplace$.shamefullySendNext(newLog);
  }

  return {log$, addLogEntry, replaceLog};
}

export default function restartable (driver, opts = {}) {
  const {log$, addLogEntry, replaceLog} = createLog$();
  // TODO - dispose log subscription
  log$.addListener(shittyListener);

  const streams = {};

  const pauseSinksWhileReplaying = opts.pauseSinksWhileReplaying === undefined ? true : opts.pauseSinksWhileReplaying;
  const pause$ = (opts.pause$ || xs.empty()).startWith(true);
  const replayOnlyLastSink = opts.replayOnlyLastSink || false;

  let replaying;
  const isReplaying = () => replaying;
  const setReplaying = (newReplaying) => replaying = newReplaying;
  const finishedReplay$ = xs.create();

  function restartableDriver (sink$, streamAdapter) {
    const filteredSink$ = xs.create();
    const lastSinkEvent$ = xs.createWithMemory();

    if (sink$) {
      if (isReplaying() && replayOnlyLastSink)  {
        lastSinkEvent$.map(lastEvent => finishedReplay$.mapTo(lastEvent)).flatten().take(1).addListener(subscribe((event) => {
          filteredSink$.shamefullySendNext(event);
        }));
      }

      if (pauseSinksWhileReplaying) {
        sink$.compose(pausable(pause$)).filter(() => !isReplaying()).addListener({
          next: (ev) => filteredSink$.shamefullySendNext(ev),
          error: (err) => console.error(err),
          complete: () => {}
        });
      } else {
        sink$.compose(pausable(pause$)).addListener(subscribe((ev) => filteredSink$.shamefullySendNext(ev)));
      }
    }

    lastSinkEvent$.imitate(sink$);

    const source = driver(filteredSink$, streamAdapter);

    let returnValue;

    if (source === undefined || source === null) {
      return source;
    } else if (typeof source.addListener === 'function') {
      returnValue = recordObservableSource({streams, addLogEntry, pause$}, source);
    } else {
      returnValue = wrapSource({streams, addLogEntry, pause$}, source);
    }

    const oldReturnValueDispose = returnValue.dispose;

    returnValue.dispose = function () {
      oldReturnValueDispose && oldReturnValueDispose.bind(returnValue)();
      sink$ && sink$.dispose && sink$.dispose();

      disposeAllStreams(streams);
    }

    returnValue.log$ = log$;

    return returnValue;
  }

  function replayable (driver) {
    driver.onPreReplay = function () {
      setReplaying(true);
    };

    driver.replayLog = function (scheduler, newLog$, timeToResetTo = null) {
      let logToReplaceWith;

      newLog$.take(1).addListener({
        next: newLog => {
          logToReplaceWith = newLog;

          function scheduleEvent (historicEvent) {
            scheduler.scheduleAbsolute({}, historicEvent.time, () => {
              if (streams[historicEvent.identifier]) {
                streams[historicEvent.identifier].shamefullySendNext(historicEvent.event);
              } else {
                console.error('Missing replay stream ', historicEvent.identifier)
              }
            });
          }

          newLog.filter(event => timeToResetTo === null || event.time <= timeToResetTo).forEach(scheduleEvent);
        },

        error: (err) => {
          console.error(err);
        },

        complete: () => {
          replaceLog(logToReplaceWith);
        }
      })
    };

    driver.onPostReplay = function () {
      setReplaying(false);
      finishedReplay$.shamefullySendNext();
    };

    return driver;
  }

  return replayable(restartableDriver);
}
<|endoftext|>


<commit_before>import { delay, eventChannel } from 'redux-saga';
import { fork, take, call, put } from 'redux-saga/effects';

export const FETCHED_JOBS = 'FETCHED_JOBS';
export const FETCHED_JOB = 'FETCHED_JOB';
export const WATCH_JOB = 'WATCH_JOB';
export const UNWATCH_JOB = 'UNWATCH_JOB';

export const FETCHED_NODES = 'FETCHED_NODES';
export const FETCHED_NODE = 'FETCHED_NODE';
export const FETCH_NODE = 'FETCH_NODE';
export const WATCH_NODE = 'WATCH_NODE';
export const UNWATCH_NODE = 'UNWATCH_NODE';

export const FETCHED_EVALS = 'FETCHED_EVALS';
export const FETCHED_EVAL = 'FETCHED_EVAL';
export const WATCH_EVAL = 'WATCH_EVAL';
export const UNWATCH_EVAL = 'UNWATCH_EVAL';

export const FETCHED_ALLOCS = 'FETCHED_ALLOCS';
export const FETCHED_ALLOC = 'FETCHED_ALLOC';
export const WATCH_ALLOC = 'WATCH_ALLOC';
export const UNWATCH_ALLOC = 'UNWATCH_ALLOC';

export const FETCH_DIR = 'FETCH_DIR'
export const FETCHED_DIR = 'FETCHED_DIR'

export const WATCH_FILE = 'WATCH_FILE'
export const UNWATCH_FILE = 'UNWATCH_FILE'
export const FETCHED_FILE = 'FETCHED_FILE'

function subscribe(socket) {
    return eventChannel(emit => {
        socket.onmessage = (event) => {
            const data = JSON.parse(event.data)
            emit({
                type: data.Type,
                payload: data.Payload
            })
        }
        return () => {};
    });
}

function* read(socket) {
    const channel = yield call(subscribe, socket);
    while (true) {
         let action = yield take(channel);
         yield put(action);
    }
}

function* write(socket) {
    while (true) {
        const action = yield take([
            WATCH_JOB,
            UNWATCH_JOB,
            WATCH_ALLOC,
            UNWATCH_ALLOC,
            WATCH_EVAL,
            UNWATCH_EVAL,
            WATCH_NODE,
            UNWATCH_NODE,
            FETCH_NODE,
            FETCH_DIR,
            WATCH_FILE,
            UNWATCH_FILE,
        ]);
        socket.send(JSON.stringify(action))
    }
}

function* transport(socket) {
    yield fork(read, socket);
    yield fork(write, socket);
}

function connect() {
    const socket = new WebSocket(`ws://${location.host}/ws`)

    const resolver = (resolve, reject) => {
        const timeout = setTimeout(() => {
            reject("Unable to connect to the backend...");
        }, 2000)

        socket.onopen = () => {
            console.log("Connected to the backend.")
            resolve(socket)
            clearTimeout(timeout)
        }
    }

    return new Promise(resolver.bind(socket))
}

function* events() {
    while (true) {
        try {
            const socket = yield call(connect)
            yield call(transport, socket)
        } catch(e) {
            console.log(e)
        }
        yield delay(5000)
    }
}

export default function* eventSaga() {
    yield fork(events)
}
<commit_msg>deduce websocket protocol from page protocol<commit_after>import { delay, eventChannel } from 'redux-saga';
import { fork, take, call, put } from 'redux-saga/effects';

export const FETCHED_JOBS = 'FETCHED_JOBS';
export const FETCHED_JOB = 'FETCHED_JOB';
export const WATCH_JOB = 'WATCH_JOB';
export const UNWATCH_JOB = 'UNWATCH_JOB';

export const FETCHED_NODES = 'FETCHED_NODES';
export const FETCHED_NODE = 'FETCHED_NODE';
export const FETCH_NODE = 'FETCH_NODE';
export const WATCH_NODE = 'WATCH_NODE';
export const UNWATCH_NODE = 'UNWATCH_NODE';

export const FETCHED_EVALS = 'FETCHED_EVALS';
export const FETCHED_EVAL = 'FETCHED_EVAL';
export const WATCH_EVAL = 'WATCH_EVAL';
export const UNWATCH_EVAL = 'UNWATCH_EVAL';

export const FETCHED_ALLOCS = 'FETCHED_ALLOCS';
export const FETCHED_ALLOC = 'FETCHED_ALLOC';
export const WATCH_ALLOC = 'WATCH_ALLOC';
export const UNWATCH_ALLOC = 'UNWATCH_ALLOC';

export const FETCH_DIR = 'FETCH_DIR'
export const FETCHED_DIR = 'FETCHED_DIR'

export const WATCH_FILE = 'WATCH_FILE'
export const UNWATCH_FILE = 'UNWATCH_FILE'
export const FETCHED_FILE = 'FETCHED_FILE'

function subscribe(socket) {
    return eventChannel(emit => {
        socket.onmessage = (event) => {
            const data = JSON.parse(event.data)
            emit({
                type: data.Type,
                payload: data.Payload
            })
        }
        return () => {};
    });
}

function* read(socket) {
    const channel = yield call(subscribe, socket);
    while (true) {
         let action = yield take(channel);
         yield put(action);
    }
}

function* write(socket) {
    while (true) {
        const action = yield take([
            WATCH_JOB,
            UNWATCH_JOB,
            WATCH_ALLOC,
            UNWATCH_ALLOC,
            WATCH_EVAL,
            UNWATCH_EVAL,
            WATCH_NODE,
            UNWATCH_NODE,
            FETCH_NODE,
            FETCH_DIR,
            WATCH_FILE,
            UNWATCH_FILE,
        ]);
        socket.send(JSON.stringify(action))
    }
}

function* transport(socket) {
    yield fork(read, socket);
    yield fork(write, socket);
}

function connect() {
    const protocol = location.protocol === "https:" ? "wss:" : "ws:";
    const socket = new WebSocket(`${protocol}//${location.host}/ws`);

    const resolver = (resolve, reject) => {
        const timeout = setTimeout(() => {
            reject("Unable to connect to the backend...");
        }, 2000)

        socket.onopen = () => {
            console.log("Connected to the backend.")
            resolve(socket)
            clearTimeout(timeout)
        }
    }

    return new Promise(resolver.bind(socket))
}

function* events() {
    while (true) {
        try {
            const socket = yield call(connect)
            yield call(transport, socket)
        } catch(e) {
            console.log(e)
        }
        yield delay(5000)
    }
}

export default function* eventSaga() {
    yield fork(events)
}
<|endoftext|>


<commit_before>import autoprefixer from 'autoprefixer';
import cloneDeep from 'lodash/cloneDeep';
import isEmpty from 'lodash/isEmpty';
import isString from 'lodash/isString';
import isUndefined from 'lodash/isUndefined';
import path from 'path';
import postcss from 'postcss';
import reqwest from 'reqwest';
import url from 'url';

import CssUrlRewriter from 'css-url-rewriter-ex';

import resolvePath from './resolve-path';

function injectStyle(css, address) {
  if (url) {
    const style = document.querySelector(`style[data-url="${address}"]`);
    if (style) {
      style.remove();
    }
  }

  const style = document.createElement('style');
  style.type = 'text/css';

  if (url) {
    style.setAttribute('data-url', url);
  }

  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }

  const head = document.head || document.getElementsByTagName('head')[0];
  head.appendChild(style);
}

const importSass = new Promise(async (resolve) => {
  if (window.Worker) {
    const Sass = await System.import('sass.js/dist/sass', __moduleName);
    const worker = await System.normalize('sass.js/dist/sass.worker', __moduleName);
    resolve(new Sass(worker));
  } else {
    const Sass = await System.import('sass.js/dist/sass.sync', __moduleName);
    resolve(Sass);
  }
});

async function sassImporter(request, done) {
  let resolved;
  let content;
  try {
    // Currently only supporting scss imports due to
    // https://github.com/sass/libsass/issues/1695
    resolved = await resolvePath(request);
    const partialPath = resolved.replace(/\/([^/]*)$/, '/_$1');
    const resp = await reqwest(partialPath);
    // In Cordova Apps the response is the raw XMLHttpRequest
    content = resp.responseText ? resp.responseText : resp;
  } catch (e) {
    try {
      const resp = await reqwest(resolved);
      content = resp.responseText ? resp.responseText : resp;
    } catch (er) {
      done();
      return;
    }
  }
  done({ content, path: resolved });
}

// intercept file loading requests (@import directive) from libsass
importSass.then(sass => {
  sass.importer(sassImporter);
});

async function compile(scss, styleUrl) {
  // compile module
  const content = scss.content;
  const responseText = content.responseText;
  if (isString(content) && isEmpty(content) ||
      !isUndefined(responseText) && isEmpty(responseText)) {
    return '';
  }
  const sass = await importSass;
  let { status, text, formatted } = await new Promise(res => {  // eslint-disable-line
    sass.compile(content, scss.options, res);
  });
  if (status !== 0) {
    throw formatted;
  }

  // rewrite urls and copy assets if enabled
  const pluginOptions = System.sassPluginOptions || {};
  if (pluginOptions.rewriteUrl) {
    const urlRewriter = new CssUrlRewriter({ root: System.baseURL });
    text = urlRewriter.rewrite(styleUrl, text);
  }

  // apply autoprefixer if enabled
  if (pluginOptions.autoprefixer) {
    const autoprefixerOptions = pluginOptions.autoprefixer instanceof Object
      ? pluginOptions.autoprefixer
      : undefined;
    const { css } = await postcss([autoprefixer(autoprefixerOptions)]).process(text);
    text = css;
  }

  // inject module and remove old module
  injectStyle(text, styleUrl);

  // return an empty module in the module pipeline itself
  return '';
}

export default async function sassInject(load) {
  const pluginOptions = System.sassPluginOptions || {};
  let basePath = path.dirname(url.parse(load.address).pathname);
  if (basePath !== '/') {
    basePath += '/';
  }
  const urlBase = basePath;
  const indentedSyntax = load.address.endsWith('.sass');
  let options = {};
  if (pluginOptions.sassOptions) {
    options = cloneDeep(pluginOptions.sassOptions);
  }
  options.indentedSyntax = indentedSyntax;
  options.importer = { urlBase };
  // load initial scss file
  const resp = await reqwest(load.address);
  // In Cordova Apps the response is the raw XMLHttpRequest
  const scss = {
    content: resp.responseText ? resp.responseText : resp,
    options,
  };
  return compile(scss, load.address);
}
<commit_msg>fix wrong variable name<commit_after>import autoprefixer from 'autoprefixer';
import cloneDeep from 'lodash/cloneDeep';
import isEmpty from 'lodash/isEmpty';
import isString from 'lodash/isString';
import isUndefined from 'lodash/isUndefined';
import path from 'path';
import postcss from 'postcss';
import reqwest from 'reqwest';
import url from 'url';

import CssUrlRewriter from 'css-url-rewriter-ex';

import resolvePath from './resolve-path';

function injectStyle(css, address) {
  if (address) {
    const style = document.querySelector(`style[data-url="${address}"]`);
    if (style) {
      style.remove();
    }
  }

  const style = document.createElement('style');
  style.type = 'text/css';

  if (address) {
    style.setAttribute('data-url', address);
  }

  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }

  const head = document.head || document.getElementsByTagName('head')[0];
  head.appendChild(style);
}

const importSass = new Promise(async (resolve) => {
  if (window.Worker) {
    const Sass = await System.import('sass.js/dist/sass', __moduleName);
    const worker = await System.normalize('sass.js/dist/sass.worker', __moduleName);
    resolve(new Sass(worker));
  } else {
    const Sass = await System.import('sass.js/dist/sass.sync', __moduleName);
    resolve(Sass);
  }
});

async function sassImporter(request, done) {
  let resolved;
  let content;
  try {
    // Currently only supporting scss imports due to
    // https://github.com/sass/libsass/issues/1695
    resolved = await resolvePath(request);
    const partialPath = resolved.replace(/\/([^/]*)$/, '/_$1');
    const resp = await reqwest(partialPath);
    // In Cordova Apps the response is the raw XMLHttpRequest
    content = resp.responseText ? resp.responseText : resp;
  } catch (e) {
    try {
      const resp = await reqwest(resolved);
      content = resp.responseText ? resp.responseText : resp;
    } catch (er) {
      done();
      return;
    }
  }
  done({ content, path: resolved });
}

// intercept file loading requests (@import directive) from libsass
importSass.then(sass => {
  sass.importer(sassImporter);
});

async function compile(scss, styleUrl) {
  // compile module
  const content = scss.content;
  const responseText = content.responseText;
  if (isString(content) && isEmpty(content) ||
      !isUndefined(responseText) && isEmpty(responseText)) {
    return '';
  }
  const sass = await importSass;
  let { status, text, formatted } = await new Promise(res => {  // eslint-disable-line
    sass.compile(content, scss.options, res);
  });
  if (status !== 0) {
    throw formatted;
  }

  // rewrite urls and copy assets if enabled
  const pluginOptions = System.sassPluginOptions || {};
  if (pluginOptions.rewriteUrl) {
    const urlRewriter = new CssUrlRewriter({ root: System.baseURL });
    text = urlRewriter.rewrite(styleUrl, text);
  }

  // apply autoprefixer if enabled
  if (pluginOptions.autoprefixer) {
    const autoprefixerOptions = pluginOptions.autoprefixer instanceof Object
      ? pluginOptions.autoprefixer
      : undefined;
    const { css } = await postcss([autoprefixer(autoprefixerOptions)]).process(text);
    text = css;
  }

  // inject module and remove old module
  injectStyle(text, styleUrl);

  // return an empty module in the module pipeline itself
  return '';
}

export default async function sassInject(load) {
  const pluginOptions = System.sassPluginOptions || {};
  let basePath = path.dirname(url.parse(load.address).pathname);
  if (basePath !== '/') {
    basePath += '/';
  }
  const urlBase = basePath;
  const indentedSyntax = load.address.endsWith('.sass');
  let options = {};
  if (pluginOptions.sassOptions) {
    options = cloneDeep(pluginOptions.sassOptions);
  }
  options.indentedSyntax = indentedSyntax;
  options.importer = { urlBase };
  // load initial scss file
  const resp = await reqwest(load.address);
  // In Cordova Apps the response is the raw XMLHttpRequest
  const scss = {
    content: resp.responseText ? resp.responseText : resp,
    options,
  };
  return compile(scss, load.address);
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var Ref = require('./Ref');

// Helper function. Source: http://stackoverflow.com/questions/1007981
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
    var fnStr = func.toString().replace(STRIP_COMMENTS, '');
    var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
    if (result === null) {
        result = [];
    }
    return result;
}

var schemaUtils = {

    getResourcesInfo: function getResourcesInfo(schema) {
        var resourcesInfo = {};

        function copyAndAppend(array, element) {
            var newArray = _.clone(array);
            newArray.push(element);
            return newArray;
        }

        function addResource(subSchema, path, inCollections) {
            console.assert(_.filter(path, _.matches('{}')).length === inCollections.length);
            var type = schemaUtils.determineType(subSchema);
            var newResourceInfo = {
                type: type,
                inCollections: inCollections,
                args: _.map(inCollections, function (collectionName) {
                    return collectionName + 'Ids (a list of integers)';
                }),
                returnType: _.map(inCollections, _.constant('list')).concat({
                    'collection': 'list',
                    'object': 'object',
                    'reference': 'integer',
                }[type]),
            };
            if (type === 'object') {
                newResourceInfo.primitives = _.filter(_.keys(subSchema), function(fieldName) {
                    return schemaUtils.determineType(subSchema[fieldName]) === 'primitive';
                });
            } else if (type === 'collection') {
                newResourceInfo.collectionOf = schemaUtils.determineType(subSchema[0]);
                newResourceInfo.args.push('criteria (object)');
            } else if (type === 'reference') {
                newResourceInfo.referenceTo = subSchema.ref;
            }
            resourcesInfo[path.join('.')] = newResourceInfo;
        }

        function traverse(subSchema, path, inCollections) {
            switch (schemaUtils.determineType(subSchema)) {
                case 'collection':
                    addResource(subSchema, path, inCollections);
                    if (!(subSchema[0] instanceof Ref)) {
                        // We provide endpoints for objects (but not refs) inside the collection.
                        traverse(
                            subSchema[0],
                            copyAndAppend(path, '{}'),
                            copyAndAppend(inCollections, _.last(path))
                        );
                    }
                    return;
                case 'reference':
                    addResource(subSchema, path, inCollections);
                    return;
                case 'object':
                    if (path.length) { // No endpoint for the root object.
                        addResource(subSchema, path, inCollections);
                    }
                    _.each(subSchema, function(value, key) {
                        traverse(value, copyAndAppend(path, key), inCollections);
                    });
                    return;
            }
        }

        traverse(schema, [], []);

        return resourcesInfo;
    },

    formatNestedType: function formatNestedType (types) {
        return _.reduceRight(types, function (accumulatedType, newOuterType) {
            if (_.contains(['list', 'array', 'collection'], newOuterType)) {
                accumulatedType = accumulatedType.replace(/(?= )|$/, 's'); // plural form
            }
            return newOuterType + ' of ' + accumulatedType;
        });
    },

    checkResourceHandlers: function checkResourceHandlers(schema, resourceHandlers) {
        var problems = [];
        var resourcesInfo = schemaUtils.getResourcesInfo(schema);

        _.each(resourcesInfo, function (resource, ref) {
            var missingOrInvalid;
            if (!_.has(resourceHandlers, ref)) {
                missingOrInvalid = 'Missing';
            } else if (getParamNames(resourceHandlers[ref]).length !== resource.args.length) {
                missingOrInvalid = 'Invalid';
            }
            if (missingOrInvalid) {
                problems.push(
                    missingOrInvalid + ' handler for ' + ref + '. ' +
                    'It should accept arguments: ' + resource.args.join(', ') + ' and return a ' +
                    schemaUtils.formatNestedType(['Promise'].concat(resource.returnType))
                );
            }
        });
        var unknownHandlers = _.difference(_.functions(resourceHandlers), _.keys(resourcesInfo));
        _.each(unknownHandlers, function (unknownHandler) {
            problems.push('Unexpected handler for: ' + unknownHandler);
        });
        return problems;
    },

    checkResourceResult: function checkResourceResult(resourceName, handlerInfo, args, result) {
        var subResult = result;

        var expectedSubResultId;
        var problemMessage = null;
        _.each(handlerInfo.inCollections, function (collectionName, collectionIndex) {
            var subArg = args[collectionIndex];
            console.assert(_.isArray(subArg), 'Invalid args');

            if (!_.isArray(subResult)) {
                problemMessage = ('Expected sub-result to be an array of length ' + subArg.length +
                        ', but got ' + JSON.stringify(subResult));
                return false; // Stop iteration.
            } else if (subResult.length !== subArg.length) {
                problemMessage = ('Wrong item count in sub-result; expected ' + subArg.length +
                        ', but got ' + subResult.length + ' (Hint: if some requested key is ' +
                        'invalid, the handler should return null in this place)');
                return false; // Stop iteration.
            }

            for (var i=0; i<subResult.length; i++) {
                if (subResult[i] != null) {
                    subResult = subResult[i];
                    expectedSubResultId = subArg[i];
                    break;
                }
                if (i === subResult.length - 1) {
                    console.warn('Got no result from ' + resourceName + ' for args: ' +
                            args.join(', ') + ' (received: ' + JSON.stringify(result) + ')');
                    subResult = null;
                    return false;
                }
            }
        });
        if (problemMessage) {
            return [problemMessage];
        }

        if (subResult == null) {
            return []; // No result is also a valid result.
        }

        if (handlerInfo.type === 'reference' && !_.isNumber(subResult)) {
            problemMessage = 'reference (integer) expected';
        }
        if (handlerInfo.type === 'object' && (!_.isObject(subResult) || _.isArray(subResult))) {
            problemMessage = 'object expected';
        }
        if (handlerInfo.type === 'collection' && !_.isArray(subResult)) {
            problemMessage = 'list (array) expected';
        }
        if (problemMessage) {
            var nestedType = _.map(handlerInfo.inCollections, _.constant('list'));
            nestedType.push(problemMessage);
            return ['Wrong result type: ' + schemaUtils.formatNestedType(nestedType) +
                    ', got: ' + JSON.stringify(result)];
        }

        var problems = [];
        if (handlerInfo.type === 'object') {
            if (!expectedSubResultId || subResult.id && subResult.id != expectedSubResultId) { // jshint ignore:line
                problems.push('object with id=' + expectedSubResultId + ' expected, got ' + subResult.id);
            }
            _.each(_.keys(subResult), function (fieldName) {
                if (fieldName !== 'id' && !_.contains(handlerInfo.primitives, fieldName)) {
                    problems.push('Unexpected field ' + fieldName);
                } else if (_.isUndefined(subResult[fieldName])) {
                    problems.push('Got undefined for ' + fieldName);
                } else if (schemaUtils.determineType(subResult[fieldName]) !== 'primitive') {
                    problems.push('Expected primitive value for ' + fieldName);
                }
            });
            _.each(handlerInfo.primitives, function (fieldName) {
                if (fieldName !== 'id' && !_.has(subResult, fieldName)) {
                    problems.push('Field ' + fieldName + ' not found');
                }
            });
        }
        return problems;
    },

    determineType: function determineType(schemaObj) {
        if (_.isArray(schemaObj)) {
            if (!schemaObj[0] || determineType(schemaObj[0]) === 'primitive') {
                return 'primitive';
            }
            return 'collection';
        } else if (schemaObj instanceof Ref) {
            return 'reference';
        } else if (_.isObject(schemaObj)) {
            if (schemaObj instanceof Date) {
                return 'primitive';
            }
            console.assert(_.isPlainObject(schemaObj));
            return 'object';
        } else {
            console.assert(!_.isUndefined(schemaObj));
            return 'primitive';
        }
    },

    descendInSchema: function descendInSchema(schema, subSchema, key) {
        switch (schemaUtils.determineType(subSchema)) {
            case 'collection':
                return subSchema[0]; // NOTE: we ignore the key.
            case 'reference':
                return schemaUtils.descendInSchema(schema, subSchema.get(schema)[0], key);
            case 'object':
                return subSchema[key];
            default:
                throw 'descendInSchema: Cannot descend to "' + key + '" key in primitive value';
        }
    },

    getTypeDeep: function getTypeDeep(schema, ref) {
        var path = ref.split('.');
        var subSchema = schema;
        _.each(path, function(key) {
            subSchema = schemaUtils.descendInSchema(schema, subSchema, key);
            if (subSchema == null) {
                throw 'getTypeDeep: Invalid ref: ' + ref;
            }
        });
        return schemaUtils.determineType(subSchema);
    },

    getRefFromStore: function getRefFromStore(schema, store, ref) {
        var path = ref.split('.');
        var subSchema = schema;
        var subStore = store;
        for (var pathIndex = 0; pathIndex < path.length; pathIndex++) {
            // Going one level down in the schema tree.
            var key = path[pathIndex];
            subSchema = schemaUtils.descendInSchema(schema, subSchema, key);
            subStore = subStore[key]; // TODO support multiple refs and stars
            if (subStore == null) {
                return null;
            }
            if (schemaUtils.determineType(subSchema) === 'reference') {
                console.assert(_.isNumber(subStore) || _.isString(subStore));
                var newRef = _.flatten([
                    subSchema.ref, subStore, _.slice(path, pathIndex+1)
                ]).join('.');
                return getRefFromStore(schema, store, newRef);
            }
        }
        return subStore;
    },

    filterRefs: function filterRefs(schema, refs) {
        console.assert(_.isArray(refs), 'filterRefs: ref array expected');
        var refsMap = {};
        function refUp(ref) {
            return _.dropRight(ref.split('.')).join('.'); // UGLY
        }
        _.each(refs, function (ref) {
            var type = schemaUtils.getTypeDeep(schema, ref);
            if (type === 'primitive') {
                refsMap[refUp(ref)] = true;
            } else if (type === 'object' || type === 'reference') {
                refsMap[ref] = true;
            }
        });
        return _.keys(refsMap);
    }
};

module.exports = schemaUtils;
<commit_msg>Ids are not treated specially anymore in the result validation.<commit_after>'use strict';

var _ = require('lodash');
var Ref = require('./Ref');

// Helper function. Source: http://stackoverflow.com/questions/1007981
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
    var fnStr = func.toString().replace(STRIP_COMMENTS, '');
    var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
    if (result === null) {
        result = [];
    }
    return result;
}

var schemaUtils = {

    getResourcesInfo: function getResourcesInfo(schema) {
        var resourcesInfo = {};

        function copyAndAppend(array, element) {
            var newArray = _.clone(array);
            newArray.push(element);
            return newArray;
        }

        function addResource(subSchema, path, inCollections) {
            console.assert(_.filter(path, _.matches('{}')).length === inCollections.length);
            var type = schemaUtils.determineType(subSchema);
            var newResourceInfo = {
                type: type,
                inCollections: inCollections,
                args: _.map(inCollections, function (collectionName) {
                    return collectionName + 'Ids (a list of integers)';
                }),
                returnType: _.map(inCollections, _.constant('list')).concat({
                    'collection': 'list',
                    'object': 'object',
                    'reference': 'integer',
                }[type]),
            };
            if (type === 'object') {
                newResourceInfo.primitives = _.filter(_.keys(subSchema), function(fieldName) {
                    return schemaUtils.determineType(subSchema[fieldName]) === 'primitive';
                });
            } else if (type === 'collection') {
                newResourceInfo.collectionOf = schemaUtils.determineType(subSchema[0]);
                newResourceInfo.args.push('criteria (object)');
            } else if (type === 'reference') {
                newResourceInfo.referenceTo = subSchema.ref;
            }
            resourcesInfo[path.join('.')] = newResourceInfo;
        }

        function traverse(subSchema, path, inCollections) {
            switch (schemaUtils.determineType(subSchema)) {
                case 'collection':
                    addResource(subSchema, path, inCollections);
                    if (!(subSchema[0] instanceof Ref)) {
                        // We provide endpoints for objects (but not refs) inside the collection.
                        traverse(
                            subSchema[0],
                            copyAndAppend(path, '{}'),
                            copyAndAppend(inCollections, _.last(path))
                        );
                    }
                    return;
                case 'reference':
                    addResource(subSchema, path, inCollections);
                    return;
                case 'object':
                    if (path.length) { // No endpoint for the root object.
                        addResource(subSchema, path, inCollections);
                    }
                    _.each(subSchema, function(value, key) {
                        traverse(value, copyAndAppend(path, key), inCollections);
                    });
                    return;
            }
        }

        traverse(schema, [], []);

        return resourcesInfo;
    },

    formatNestedType: function formatNestedType (types) {
        return _.reduceRight(types, function (accumulatedType, newOuterType) {
            if (_.contains(['list', 'array', 'collection'], newOuterType)) {
                accumulatedType = accumulatedType.replace(/(?= )|$/, 's'); // plural form
            }
            return newOuterType + ' of ' + accumulatedType;
        });
    },

    checkResourceHandlers: function checkResourceHandlers(schema, resourceHandlers) {
        var problems = [];
        var resourcesInfo = schemaUtils.getResourcesInfo(schema);

        _.each(resourcesInfo, function (resource, ref) {
            var missingOrInvalid;
            if (!_.has(resourceHandlers, ref)) {
                missingOrInvalid = 'Missing';
            } else if (getParamNames(resourceHandlers[ref]).length !== resource.args.length) {
                missingOrInvalid = 'Invalid';
            }
            if (missingOrInvalid) {
                problems.push(
                    missingOrInvalid + ' handler for ' + ref + '. ' +
                    'It should accept arguments: ' + resource.args.join(', ') + ' and return a ' +
                    schemaUtils.formatNestedType(['Promise'].concat(resource.returnType))
                );
            }
        });
        var unknownHandlers = _.difference(_.functions(resourceHandlers), _.keys(resourcesInfo));
        _.each(unknownHandlers, function (unknownHandler) {
            problems.push('Unexpected handler for: ' + unknownHandler);
        });
        return problems;
    },

    checkResourceResult: function checkResourceResult(resourceName, handlerInfo, args, result) {
        var subResult = result;

        var expectedSubResultId;
        var problemMessage = null;
        _.each(handlerInfo.inCollections, function (collectionName, collectionIndex) {
            var subArg = args[collectionIndex];
            console.assert(_.isArray(subArg), 'Invalid args');

            if (!_.isArray(subResult)) {
                problemMessage = ('Expected sub-result to be an array of length ' + subArg.length +
                        ', but got ' + JSON.stringify(subResult));
                return false; // Stop iteration.
            } else if (subResult.length !== subArg.length) {
                problemMessage = ('Wrong item count in sub-result; expected ' + subArg.length +
                        ', but got ' + subResult.length + ' (Hint: if some requested key is ' +
                        'invalid, the handler should return null in this place)');
                return false; // Stop iteration.
            }

            for (var i=0; i<subResult.length; i++) {
                if (subResult[i] != null) {
                    subResult = subResult[i];
                    expectedSubResultId = subArg[i];
                    break;
                }
                if (i === subResult.length - 1) {
                    console.warn('Got no result from ' + resourceName + ' for args: ' +
                            args.join(', ') + ' (received: ' + JSON.stringify(result) + ')');
                    subResult = null;
                    return false;
                }
            }
        });
        if (problemMessage) {
            return [problemMessage];
        }

        if (subResult == null) {
            return []; // No result is also a valid result.
        }

        if (handlerInfo.type === 'reference' && !_.isNumber(subResult)) {
            problemMessage = 'reference (integer) expected';
        }
        if (handlerInfo.type === 'object' && (!_.isObject(subResult) || _.isArray(subResult))) {
            problemMessage = 'object expected';
        }
        if (handlerInfo.type === 'collection' && !_.isArray(subResult)) {
            problemMessage = 'list (array) expected';
        }
        if (problemMessage) {
            var nestedType = _.map(handlerInfo.inCollections, _.constant('list'));
            nestedType.push(problemMessage);
            return ['Wrong result type: ' + schemaUtils.formatNestedType(nestedType) +
                    ', got: ' + JSON.stringify(result)];
        }

        var problems = [];
        if (handlerInfo.type === 'object') {
            if (!expectedSubResultId || subResult.id && subResult.id != expectedSubResultId) { // jshint ignore:line
                problems.push('object with id=' + expectedSubResultId + ' expected, got ' + subResult.id);
            }
            _.each(_.keys(subResult), function (fieldName) {
                if (!_.contains(handlerInfo.primitives, fieldName)) {
                    problems.push('Unexpected field ' + fieldName);
                } else if (_.isUndefined(subResult[fieldName])) {
                    problems.push('Got undefined for ' + fieldName);
                } else if (schemaUtils.determineType(subResult[fieldName]) !== 'primitive') {
                    problems.push('Expected primitive value for ' + fieldName);
                }
            });
            _.each(handlerInfo.primitives, function (fieldName) {
                if (!_.has(subResult, fieldName)) {
                    problems.push('Field ' + fieldName + ' not found');
                }
            });
        }
        return problems;
    },

    determineType: function determineType(schemaObj) {
        if (_.isArray(schemaObj)) {
            if (!schemaObj[0] || determineType(schemaObj[0]) === 'primitive') {
                return 'primitive';
            }
            return 'collection';
        } else if (schemaObj instanceof Ref) {
            return 'reference';
        } else if (_.isObject(schemaObj)) {
            if (schemaObj instanceof Date) {
                return 'primitive';
            }
            console.assert(_.isPlainObject(schemaObj));
            return 'object';
        } else {
            console.assert(!_.isUndefined(schemaObj));
            return 'primitive';
        }
    },

    descendInSchema: function descendInSchema(schema, subSchema, key) {
        switch (schemaUtils.determineType(subSchema)) {
            case 'collection':
                return subSchema[0]; // NOTE: we ignore the key.
            case 'reference':
                return schemaUtils.descendInSchema(schema, subSchema.get(schema)[0], key);
            case 'object':
                return subSchema[key];
            default:
                throw 'descendInSchema: Cannot descend to "' + key + '" key in primitive value';
        }
    },

    getTypeDeep: function getTypeDeep(schema, ref) {
        var path = ref.split('.');
        var subSchema = schema;
        _.each(path, function(key) {
            subSchema = schemaUtils.descendInSchema(schema, subSchema, key);
            if (subSchema == null) {
                throw 'getTypeDeep: Invalid ref: ' + ref;
            }
        });
        return schemaUtils.determineType(subSchema);
    },

    getRefFromStore: function getRefFromStore(schema, store, ref) {
        var path = ref.split('.');
        var subSchema = schema;
        var subStore = store;
        for (var pathIndex = 0; pathIndex < path.length; pathIndex++) {
            // Going one level down in the schema tree.
            var key = path[pathIndex];
            subSchema = schemaUtils.descendInSchema(schema, subSchema, key);
            subStore = subStore[key]; // TODO support multiple refs and stars
            if (subStore == null) {
                return null;
            }
            if (schemaUtils.determineType(subSchema) === 'reference') {
                console.assert(_.isNumber(subStore) || _.isString(subStore));
                var newRef = _.flatten([
                    subSchema.ref, subStore, _.slice(path, pathIndex+1)
                ]).join('.');
                return getRefFromStore(schema, store, newRef);
            }
        }
        return subStore;
    },

    filterRefs: function filterRefs(schema, refs) {
        console.assert(_.isArray(refs), 'filterRefs: ref array expected');
        var refsMap = {};
        function refUp(ref) {
            return _.dropRight(ref.split('.')).join('.'); // UGLY
        }
        _.each(refs, function (ref) {
            var type = schemaUtils.getTypeDeep(schema, ref);
            if (type === 'primitive') {
                refsMap[refUp(ref)] = true;
            } else if (type === 'object' || type === 'reference') {
                refsMap[ref] = true;
            }
        });
        return _.keys(refsMap);
    }
};

module.exports = schemaUtils;
<|endoftext|>


<commit_before>(function(jsenvy) {
	/**
	 }
	 * Scope Creep
	 * ===
	 * A fun way to creep on people's scope. Lets you:
	 * - Update a scope to see the scope difference
	 * - View the current contents of the scope, in case you forgot what you're creeping on
	 */
	jsenvy.ScopeCreep = function(victim, ignores) {
		var properties = [],
			methods = [];

		ignores = ignores || {properties: [], methods: []};

		//a setter for the scope properties and methods
		function setScope(scope) {
			if (typeof scope !== "object") {
				scope = enumerateScope();
			}

			properties = scope.properties;
			methods = scope.methods;
		}

		//an updater for the scope that returns the difference
		function update() {
			var diff = getScopeDiff();
			setScope(diff.scope);
			return diff;
		}

		//the actually scope dissection
		function enumerateScope() {
			var properties = [],
				methods = [],
				thingsToIgnore = ["length", "__CommandLineAPI"];

			var scope = Object.getOwnPropertyNames(victim);
			for (var i = 0; i < scope.length; i++) {
				var prop = scope[i];
				if (thingsToIgnore.indexOf(prop) >= 0) continue;
				if (typeof window[prop] === "function") {
					methods.push(prop);
				} else {
					properties.push(prop);
				}
			}

			return {
				properties: properties,
				methods: methods
			};
		}

		//retrieve the scope diff without setting the scope
		function getScopeDiff() {
			var newScope = enumerateScope();

			var propertyDiff = arrayDiff(ignores.properties, arrayDiff(properties, newScope.properties)),
				methodDiff = arrayDiff(ignores.methods, arrayDiff(methods, newScope.methods));

			return {
				properties: propertyDiff,
				methods: methodDiff,
				scope: newScope
			};
		}

		function arrayDiff(array1, array2) {
			var difference = [];

			array2.forEach(function(item) {
				if (array1.indexOf(item) === -1) {
					difference.push(item);
				}
			});

			return difference;
		}

		setScope();
		return {
			update: update,
			peek: getScopeDiff,
			get: enumerateScope
		}
	};
})(jsenvy);<commit_msg>optimizing scope creep<commit_after>(function(jsenvy) {
	/**
	 }
	 * Scope Creep
	 * ===
	 * A fun way to creep on people's scope. Lets you:
	 * - Update a scope to see the scope difference
	 * - View the current contents of the scope, in case you forgot what you're creeping on
	 */
	jsenvy.ScopeCreep = function(victim, ignores) {
		var properties = [],
			methods = [];

		ignores = ignores || {properties: [], methods: []};

		//a setter for the scope properties and methods
		function setScope(scope) {
			if (typeof scope !== "object") {
				scope = enumerateScope();
			}

			properties = scope.properties;
			methods = scope.methods;
		}

		//an updater for the scope that returns the difference
		function update() {
			var diff = getScopeDiff();
			setScope(diff.scope);
			return diff;
		}

		//the actually scope dissection
		function enumerateScope() {
			var properties = [],
				methods = [],
				thingsToIgnore = ["length", "__CommandLineAPI"];

			for(var key in victim) {
				if (thingsToIgnore.indexOf(key) === -1) {
					if (typeof victim[key] === 'function') {
						methods.push(key);
					} else {
						properties.push(key);
					}
				}
			}

			return {
				properties: properties,
				methods: methods
			};
		}

		//retrieve the scope diff without setting the scope
		function getScopeDiff() {
			var newScope = enumerateScope();

			var propertyDiff = arrayDiff(ignores.properties, arrayDiff(properties, newScope.properties)),
				methodDiff = arrayDiff(ignores.methods, arrayDiff(methods, newScope.methods));

			return {
				properties: propertyDiff,
				methods: methodDiff,
				scope: newScope
			};
		}

		function arrayDiff(array1, array2) {
			var difference = [];

			array2.forEach(function(item) {
				if (array1.indexOf(item) === -1) {
					difference.push(item);
				}
			});

			return difference;
		}

		setScope();
		return {
			update: update,
			peek: getScopeDiff,
			get: enumerateScope
		}
	};
})(jsenvy);<|endoftext|>


<commit_before>/**
 * Created by Dana Zhang on 10/6/2014.
 */

// Metrics Questions/assumptions
// Priority
// threshold and objective can be undefined
// what's weightNeg and weightPos
// category = true ?
// testbench is the name of the testbench from which value will be computed
// unit conversion?
// functions are all linear?  do they have a fixed format? score = A x (threshold - value)/(objective - threshold) + B perhaps?

// how to use: node score.js requirement_json_file, testbench1_of_design1_file, testbench2_of_design1_file, ...
// e.g. node score.js TopLevelRequirementGroup.json WalkieTalkieManufacturing.json WalkieTalkiePerformance.json WalkieTalkieStaticMeasurements.json

var CHILDREN = "children";
var NAME = "name";

// used as key
var METRIC_NAME = "metricName";
var TESTBENCH = "testBench";
var DELIM = "+";
// used as key

// rqmt associated constants
var THRESH = "threshold";
var OBJECTIVE = "objective";
var FUNCTION = "function";
var UNIT = "unit";
var KPP = "KPP";
var WEIGHT_POS = "weightPos";
var PRIORITY = "Priority";

// design associated constants
var DESIGN_TB = "TestBench";
var METRICS = "Metrics";
var VALUE = "Value";
var METRIC_UNIT = "Unit";

// round to 1/ROUND decimal places
var ROUND = 1000;

// enumeration functions
var LINEAR = "Linear";
var EXPONETIAL = "Exponential";
var LOGRITHMIC = "Logrithmic";

/**
 * score design file against requirement file
 */
var score = function (requirementObj, testbenchObjArray) {
    var subResult,
        metricsTable,
        result;

    metricsTable = processDesigns(testbenchObjArray);
    subResult = processRqmt(requirementObj, metricsTable);
    result = generateOutput(subResult);
    return result;
};

/**
 * process all input design files by calling getMetricsFromDesign()
 * @param testbenchObjArray
 */
var processDesigns = function (testbenchObjArray) {
    var i,
        metricsTable = {},
        _getMetricsFromDesign;

    /**
     * Store all metrics from design files to a lookup table,
     * as the rmqt tree is traversed, rqmts are compared
     * against each entry in the look up table
     * @param design
     * @private
     */
    _getMetricsFromDesign = function (design) {
        var testbench = design[DESIGN_TB],
            metrics = design[METRICS],
            j,
            metric,
            key,
            metricValue;

        for (j = 0; j < metrics.length; j += 1) {
            metric = metrics[j];
            key = testbench + DELIM + metric["Name"];
            metricValue = {
                Value: metric[VALUE],
                unit: metric[METRIC_UNIT],
                KPP: metric[KPP]
            };
            metricsTable[key] = metricValue;
        }
    };

    for (i = 0; i < testbenchObjArray.length; i += 1) {
        _getMetricsFromDesign(testbenchObjArray[i]);
    }

    return metricsTable;
};

/**
 * store all requirements along with the original hierarchy in a dictionary
 * key is unique name of metric
 * value is information needed to calculate the score for each metric along with parentNode
 * @param requirementObj
 * @param metricsTable
 */

var processRqmt = function (requirementObj, metricsTable) {
    var _processNode,
        result;

    _processNode = function (node) {
        var children,
            child,
            i,
            subNode,
            subScore;

        if (node.hasOwnProperty(CHILDREN)) {
            // if node is not leaf
            children = node[CHILDREN];
            for (i = 0; i < children.length; i += 1) {
                child = children[i];
                // keep going until we reach leaf
                if (!node.score) {
                    node.score = 0;
                }

                subNode = _processNode(child);
                subScore = subNode.hasOwnProperty("result") ? subNode.result.score : subNode.score;
                if (subScore === 0) {
                    node.pass = false;
                }
                node.score = node.pass === false ? 0 : node.score + subScore;
            }
        } else {
            // if node is leaf - a requirement, evaluate it
            node.result = evaluateRqmt(node, metricsTable);
        }
        return node;
    };

    result = _processNode(requirementObj);

    return result;
};

var evaluateRqmt = function (rqmtNode, metricsTable) {
    var key = rqmtNode[TESTBENCH] + DELIM + rqmtNode[METRIC_NAME],
        metricNode = metricsTable[key],
        result = {
            score: 0,
            type: ""
        };

    if (metricNode) {
        // if requirement has a matching metric in the design file
        result = evaluate(rqmtNode, metricNode);

    } else {
        result.type = "no data";
    }

    return result;
};

/**
 * Strictly linear function, assuming score is 0.1 at Threshold
 * @param reqNode
 * @param metricNode
 */
var evaluate = function (reqNode, metricNode) {
    var weight = reqNode[WEIGHT_POS],
        func = reqNode[FUNCTION],
        T = reqNode[THRESH],
        O = reqNode[OBJECTIVE],
        factor = convertUnit(metricNode[UNIT], reqNode[UNIT]), // todo: apply unit conversion if necessary
        adjusted_metric = metricNode[VALUE] === null ? null : metricNode[VALUE] * factor,
        score,
        type,
        resultNode,
        _scoreLinear,
        _scoreExp,
        _scoreLog; // fn

    _scoreLinear = function (val) {
        var A = 0.9 / (O - T), // todo: handle the divideZero case
            B = 1 - A * O;

        score = (val * A + B); // weighted score
        type = "meet threshold";
    };

    _scoreExp = function (val) {
        var A = 0.9 / (Math.exp(T) - Math.exp(O)),
            B = 1 - A * Math.exp(T);

        score = (A * Math.exp(val) + B);
        type = "meet threshold";
    };

    _scoreLog = function (val) {
        var A = 0.9 / (Math.log(O / T)),
            B = 1 - A * Math.log(O);

        score = (A * Math.log(val) + B);
        type = "meet threshold";
    };

    if (reqNode[KPP] && metricNode[KPP] === false) {
        score = 0;
        type = "violated kpp";
    } else {
        if (adjusted_metric === null) {
            score = 0;
            type = "no data";
        } else if (T <= O && adjusted_metric < T || T > O && adjusted_metric > T) {
            score = 0;
            type = "does not meet threshold";
        } else if (T <= O && adjusted_metric >= O || T > O && adjusted_metric <= O) {
            score = 1;
            type = "meet objective";
        } else if (func === "" || func === LINEAR) {
            _scoreLinear(adjusted_metric);
        } else if (func === EXPONETIAL) {
            _scoreExp(adjusted_metric);
        } else if (func === LOGRITHMIC) {
            _scoreLog(adjusted_metric);
        }
    }

    resultNode = {
        score: Math.round(score * weight * ROUND) / ROUND,
        type: type
    };
    return resultNode;
};

/**
 * a recursive function to generate the final result output
 * @param node - node to start with
 * @returns {{}}
 */
var generateOutput = function (node) {
    var children,
        i,
        child,
        result = {};

    if (node.hasOwnProperty(CHILDREN)) {

        result.name = node[NAME];
        result.Priority = node[PRIORITY];
        result.pass = node.pass !== false;
        result.score = Math.round(node.score * ROUND) / ROUND;

        children = node[CHILDREN];
        result.children = [];
        for (i = 0; i < children.length; i += 1) {
            child = children[i];
            result.children.push(generateOutput(child));
        }
    } else {
        result = {
            testBench: node[TESTBENCH],
            name: node[METRIC_NAME],
            Priority: node[PRIORITY],
            pass: node.result.score !== 0,
            score: Math.round(node.result.score * ROUND) / ROUND,
            type: node.result.type
        }
    }
    return result;
};

/**
 *
 * @param unit
 * @returns a factor of design metricValue
 * @param target
 */
var convertUnit = function (unit, target) {
    var factor = 1;
    if (unit.toLowerCase() === target.toLowerCase()) {
        factor = 1;
    } else {
        // todo: change factor to unit conversion result
    }
    return factor;
};

module.exports = score;<commit_msg>Fixed typo<commit_after>/**
 * Created by Dana Zhang on 10/6/2014.
 */

// Metrics Questions/assumptions
// Priority
// threshold and objective can be undefined
// what's weightNeg and weightPos
// category = true ?
// testbench is the name of the testbench from which value will be computed
// unit conversion?
// functions are all linear?  do they have a fixed format? score = A x (threshold - value)/(objective - threshold) + B perhaps?

// how to use: node score.js requirement_json_file, testbench1_of_design1_file, testbench2_of_design1_file, ...
// e.g. node score.js TopLevelRequirementGroup.json WalkieTalkieManufacturing.json WalkieTalkiePerformance.json WalkieTalkieStaticMeasurements.json

var CHILDREN = "children";
var NAME = "name";

// used as key
var METRIC_NAME = "metricName";
var TESTBENCH = "testBench";
var DELIM = "+";
// used as key

// rqmt associated constants
var THRESH = "threshold";
var OBJECTIVE = "objective";
var FUNCTION = "function";
var UNIT = "unit";
var KPP = "KPP";
var WEIGHT_POS = "weightPos";
var PRIORITY = "Priority";

// design associated constants
var DESIGN_TB = "TestBench";
var METRICS = "Metrics";
var VALUE = "Value";
var METRIC_UNIT = "Unit";

// round to 1/ROUND decimal places
var ROUND = 1000;

// enumeration functions
var LINEAR = "Linear";
var EXPONETIAL = "Exponential";
var LOGARITHMIC = "Logarithmic";

/**
 * score design file against requirement file
 */
var score = function (requirementObj, testbenchObjArray) {
    var subResult,
        metricsTable,
        result;

    metricsTable = processDesigns(testbenchObjArray);
    subResult = processRqmt(requirementObj, metricsTable);
    result = generateOutput(subResult);
    return result;
};

/**
 * process all input design files by calling getMetricsFromDesign()
 * @param testbenchObjArray
 */
var processDesigns = function (testbenchObjArray) {
    var i,
        metricsTable = {},
        _getMetricsFromDesign;

    /**
     * Store all metrics from design files to a lookup table,
     * as the rmqt tree is traversed, rqmts are compared
     * against each entry in the look up table
     * @param design
     * @private
     */
    _getMetricsFromDesign = function (design) {
        var testbench = design[DESIGN_TB],
            metrics = design[METRICS],
            j,
            metric,
            key,
            metricValue;

        for (j = 0; j < metrics.length; j += 1) {
            metric = metrics[j];
            key = testbench + DELIM + metric["Name"];
            metricValue = {
                Value: metric[VALUE],
                unit: metric[METRIC_UNIT],
                KPP: metric[KPP]
            };
            metricsTable[key] = metricValue;
        }
    };

    for (i = 0; i < testbenchObjArray.length; i += 1) {
        _getMetricsFromDesign(testbenchObjArray[i]);
    }

    return metricsTable;
};

/**
 * store all requirements along with the original hierarchy in a dictionary
 * key is unique name of metric
 * value is information needed to calculate the score for each metric along with parentNode
 * @param requirementObj
 * @param metricsTable
 */

var processRqmt = function (requirementObj, metricsTable) {
    var _processNode,
        result;

    _processNode = function (node) {
        var children,
            child,
            i,
            subNode,
            subScore;

        if (node.hasOwnProperty(CHILDREN)) {
            // if node is not leaf
            children = node[CHILDREN];
            for (i = 0; i < children.length; i += 1) {
                child = children[i];
                // keep going until we reach leaf
                if (!node.score) {
                    node.score = 0;
                }

                subNode = _processNode(child);
                subScore = subNode.hasOwnProperty("result") ? subNode.result.score : subNode.score;
                if (subScore === 0) {
                    node.pass = false;
                }
                node.score = node.pass === false ? 0 : node.score + subScore;
            }
        } else {
            // if node is leaf - a requirement, evaluate it
            node.result = evaluateRqmt(node, metricsTable);
        }
        return node;
    };

    result = _processNode(requirementObj);

    return result;
};

var evaluateRqmt = function (rqmtNode, metricsTable) {
    var key = rqmtNode[TESTBENCH] + DELIM + rqmtNode[METRIC_NAME],
        metricNode = metricsTable[key],
        result = {
            score: 0,
            type: ""
        };

    if (metricNode) {
        // if requirement has a matching metric in the design file
        result = evaluate(rqmtNode, metricNode);

    } else {
        result.type = "no data";
    }

    return result;
};

/**
 * Strictly linear function, assuming score is 0.1 at Threshold
 * @param reqNode
 * @param metricNode
 */
var evaluate = function (reqNode, metricNode) {
    var weight = reqNode[WEIGHT_POS],
        func = reqNode[FUNCTION],
        T = reqNode[THRESH],
        O = reqNode[OBJECTIVE],
        factor = convertUnit(metricNode[UNIT], reqNode[UNIT]), // todo: apply unit conversion if necessary
        adjusted_metric = metricNode[VALUE] === null ? null : metricNode[VALUE] * factor,
        score,
        type,
        resultNode,
        _scoreLinear,
        _scoreExp,
        _scoreLog; // fn

    _scoreLinear = function (val) {
        var A = 0.9 / (O - T), // todo: handle the divideZero case
            B = 1 - A * O;

        score = (val * A + B); // weighted score
        type = "meet threshold";
    };

    _scoreExp = function (val) {
        var A = 0.9 / (Math.exp(T) - Math.exp(O)),
            B = 1 - A * Math.exp(T);

        score = (A * Math.exp(val) + B);
        type = "meet threshold";
    };

    _scoreLog = function (val) {
        var A = 0.9 / (Math.log(O / T)),
            B = 1 - A * Math.log(O);

        score = (A * Math.log(val) + B);
        type = "meet threshold";
    };

    if (reqNode[KPP] && metricNode[KPP] === false) {
        score = 0;
        type = "violated kpp";
    } else {
        if (adjusted_metric === null) {
            score = 0;
            type = "no data";
        } else if (T <= O && adjusted_metric < T || T > O && adjusted_metric > T) {
            score = 0;
            type = "does not meet threshold";
        } else if (T <= O && adjusted_metric >= O || T > O && adjusted_metric <= O) {
            score = 1;
            type = "meet objective";
        } else if (func === "" || func === LINEAR) {
            _scoreLinear(adjusted_metric);
        } else if (func === EXPONETIAL) {
            _scoreExp(adjusted_metric);
        } else if (func === LOGARITHMIC) {
            _scoreLog(adjusted_metric);
        }
    }

    resultNode = {
        score: Math.round(score * weight * ROUND) / ROUND,
        type: type
    };
    return resultNode;
};

/**
 * a recursive function to generate the final result output
 * @param node - node to start with
 * @returns {{}}
 */
var generateOutput = function (node) {
    var children,
        i,
        child,
        result = {};

    if (node.hasOwnProperty(CHILDREN)) {

        result.name = node[NAME];
        result.Priority = node[PRIORITY];
        result.pass = node.pass !== false;
        result.score = Math.round(node.score * ROUND) / ROUND;

        children = node[CHILDREN];
        result.children = [];
        for (i = 0; i < children.length; i += 1) {
            child = children[i];
            result.children.push(generateOutput(child));
        }
    } else {
        result = {
            testBench: node[TESTBENCH],
            name: node[METRIC_NAME],
            Priority: node[PRIORITY],
            pass: node.result.score !== 0,
            score: Math.round(node.result.score * ROUND) / ROUND,
            type: node.result.type
        }
    }
    return result;
};

/**
 *
 * @param unit
 * @returns a factor of design metricValue
 * @param target
 */
var convertUnit = function (unit, target) {
    var factor = 1;
    if (unit.toLowerCase() === target.toLowerCase()) {
        factor = 1;
    } else {
        // todo: change factor to unit conversion result
    }
    return factor;
};

module.exports = score;<|endoftext|>


<commit_before>var http = require('http').createServer(handler);
var io = require('socket.io').listen(http);
var util = require('util');
var locations = {};

var credentials = require('./credentials.js');

console.log(credentials.credentials.consumer_key);
 var keys = {
        "consumer_key" : credentials.credentials.consumer_key
      , "consumer_secret" : credentials.credentials.consumer_secret
      , "access_token_key" : credentials.credentials.access_token_key
      , "access_token_secret" : credentials.credentials.access_token_secret
    };

var tu = require('tuiter')(keys);
//tu.filter({locations: [{lat: 41.1, long: -71.7},{lat: 42.8, long: -70}]}, function(stream){
//
//  // New tweet
//  stream.on("tweet", function(data){
//    console.log(data.text);
//    console.log(data.entities);
//    console.log(data.coordinates);
//    console.log(data.place.full_name);
//    console.log(data.place.bounding_box.coordinates);
//
//    if(data.coordinates && data.coordinates.coordinates){
//      io.sockets.emit("update", {
//          coordinates: data.coordinates.coordinates
//        , screen_name: data.user.screen_name
//        , text: data.text
//        , profile_image_url: data.user.profile_image_url
//        , media_url: data.entities.media
//      });
//    } else if(data.place){
//      var place = data.place.bounding_box.coordinates[0][0];
//       io.sockets.emit("update", {
//          coordinates: place
//        , screen_name: data.user.screen_name
//        , text: data.text
//        , profile_image_url: data.user.profile_image_url
//        , media_url: data.entities.media
//      });
//    }
//  });
//
//  stream.on("delete", function(data){
//    console.log("delete");
//    //I don't care about deleted tweets
//  });
//
//  // Log errors
//  stream.on("error", function(error){
//    // handle errors
//    console.log("error:"+error);
//  });
//
//});

tu.filter({locations: [{lat: 36, long: -123},{lat: 38, long: -122}]}, function(stream){

	  // New tweet
	  stream.on("tweet", function(data){
	    console.log(data.text);
	    console.log(data.entities);
	    console.log(data.coordinates);
	    console.log(data.place.full_name);
	    console.log(data.place.bounding_box.coordinates);

	    if(data.coordinates && data.coordinates.coordinates){
	      io.sockets.emit("update", {
	          coordinates: data.coordinates.coordinates
	        , screen_name: data.user.screen_name
	        , text: data.text
	        , profile_image_url: data.user.profile_image_url
	        , media_url: data.entities.media
	      });
	    } else if(data.place){
	      var place = data.place.bounding_box.coordinates[0][0];
	       io.sockets.emit("update", {
	          coordinates: place
	        , screen_name: data.user.screen_name
	        , text: data.text
	        , profile_image_url: data.user.profile_image_url
	        , media_url: data.entities.media
	      });
	    }
	  });

	  stream.on("delete", function(data){
	    console.log("delete");
	    //I don't care about deleted tweets
	  });

	  // Log errors
	  stream.on("error", function(error){
	    // handle errors
	    console.log("error:"+error);
	  });

	});

function handler(req, res) {
//	fs.readFile('index.html', function(err, data) {
//		res.writeHead(200, {
//			'Content-Type' : 'text/html'
//		});
//		res.end(data);
//	});
//        res.send(200);
};

io.sockets.on('connection', function(socket) {
	console.log("Someone connected");

	socket.on('subscribe', function(location) {
		if (socket.location === undefined) {
			socket.leave(socket.location);
		}

		socket.location = location;
		locations[location] = location;
		socket.join(location);
	});
});

http.listen(8081, function() {
	console.log('%s listening at %s', http.name, http.url);
});
<commit_msg>Updating the server filter.<commit_after>var http = require('http').createServer(handler);
var io = require('socket.io').listen(http);
var util = require('util');
var locations = {};

var credentials = require('./credentials.js');

console.log(credentials.credentials.consumer_key);
 var keys = {
        "consumer_key" : credentials.credentials.consumer_key
      , "consumer_secret" : credentials.credentials.consumer_secret
      , "access_token_key" : credentials.credentials.access_token_key
      , "access_token_secret" : credentials.credentials.access_token_secret
    };

var tu = require('tuiter')(keys);
//tu.filter({locations: [{lat: 41.1, long: -71.7},{lat: 42.8, long: -70}]}, function(stream){
//
//  // New tweet
//  stream.on("tweet", function(data){
//    console.log(data.text);
//    console.log(data.entities);
//    console.log(data.coordinates);
//    console.log(data.place.full_name);
//    console.log(data.place.bounding_box.coordinates);
//
//    if(data.coordinates && data.coordinates.coordinates){
//      io.sockets.emit("update", {
//          coordinates: data.coordinates.coordinates
//        , screen_name: data.user.screen_name
//        , text: data.text
//        , profile_image_url: data.user.profile_image_url
//        , media_url: data.entities.media
//      });
//    } else if(data.place){
//      var place = data.place.bounding_box.coordinates[0][0];
//       io.sockets.emit("update", {
//          coordinates: place
//        , screen_name: data.user.screen_name
//        , text: data.text
//        , profile_image_url: data.user.profile_image_url
//        , media_url: data.entities.media
//      });
//    }
//  });
//
//  stream.on("delete", function(data){
//    console.log("delete");
//    //I don't care about deleted tweets
//  });
//
//  // Log errors
//  stream.on("error", function(error){
//    // handle errors
//    console.log("error:"+error);
//  });
//
//});

tu.filter({locations: [{lat: 36, long: -123},{lat: 38, long: -122},{lat: 41.1, long: -71.7},{lat: 42.8, long: -70}]}, function(stream){

	  // New tweet
	  stream.on("tweet", function(data){
	    console.log(data.text);
	    console.log(data.entities);
	    console.log(data.coordinates);
	    console.log(data.place.full_name);
	    console.log(data.place.bounding_box.coordinates);

	    if(data.coordinates && data.coordinates.coordinates){
	      io.sockets.emit("update", {
	          coordinates: data.coordinates.coordinates
	        , screen_name: data.user.screen_name
	        , text: data.text
	        , profile_image_url: data.user.profile_image_url
	        , media_url: data.entities.media
	      });
	    } else if(data.place){
	      var place = data.place.bounding_box.coordinates[0][0];
	       io.sockets.emit("update", {
	          coordinates: place
	        , screen_name: data.user.screen_name
	        , text: data.text
	        , profile_image_url: data.user.profile_image_url
	        , media_url: data.entities.media
	      });
	    }
	  });

	  stream.on("delete", function(data){
	    console.log("delete");
	    //I don't care about deleted tweets
	  });

	  // Log errors
	  stream.on("error", function(error){
	    // handle errors
	    console.log("error:"+error);
	  });

	});

function handler(req, res) {
//	fs.readFile('index.html', function(err, data) {
//		res.writeHead(200, {
//			'Content-Type' : 'text/html'
//		});
//		res.end(data);
//	});
//        res.send(200);
};

io.sockets.on('connection', function(socket) {
	console.log("Someone connected");

	socket.on('subscribe', function(location) {
		if (socket.location === undefined) {
			socket.leave(socket.location);
		}

		socket.location = location;
		locations[location] = location;
		socket.join(location);
	});
});

http.listen(8081, function() {
	console.log('%s listening at %s', http.name, http.url);
});
<|endoftext|>


<commit_before>import R from 'ramda';
import Promise from 'bluebird';
import chalk from 'chalk';
import webpackBuilder from './webpack-builder';
import webpackConfig from './webpack-config';
import { formatEntryPaths, trimRootModulePath } from './paths';
import log from '../shared/log';

/**
 * Calculates the size of the JS bundles.
 * @param {Object} options:
 *
 *           --entry:  Required. The entry path(s).
 *
 *           --prod:   Flag indicating if the JS should be built for production (smaller).
 *                     Default: false.
 *
 *           --silent: Flag indicating if log output should be suppressed.
 *                     Default: false.
 *
 * @return {Promise}.
 */
export default (options = {}) => new Promise((resolve, reject) => {
  (async () => {
    // Setup initial conditions.
    const { entry, prod, silent } = options;
    const isProduction = prod || false;
    log.silent = silent || false;

    // Initial message.
    let msg;
    msg = 'Calculating size of javascript files';
    msg = isProduction ? `${ msg }(production)` : msg;
    msg += '...\n';
    log.info(chalk.grey(msg));

    // Prepare the Webpack configuration.
    const config = webpackConfig({
      entry: formatEntryPaths(entry),
      outputFile: 'specs.js',
      isProduction,
    });

    // Build the JS.
    let stats;
    try {
      stats = await webpackBuilder(config);
    } catch (err) {
      reject(err);
    }

    // Write output.
    log.info(chalk.green('Code Size:'));
    log.info(chalk.grey(' - minified:   '), isProduction);
    log.info(chalk.grey(' - build time: '), stats.buildTime.secs, 'secs');
    log.info();

    const logModule = (key, title, data) => {
      // General information.
      log.info('', chalk.blue(title));
      log.info(
        chalk.grey('   - size:     '),
        data.size.display, chalk.grey('=>'),
        chalk.magenta(data.zipped.display), chalk.grey('zipped')
      );

      // List modules/paths.
      const modules = config.entry[key].map(item => trimRootModulePath(item));
      log.info(chalk.grey('   - modules:  '), modules[0] || chalk.magenta('None.'));
      R.takeLast(modules.length - 1, modules).forEach(item => {
        log.info(chalk.grey('               '), item);
      });

      log.info();
    };
    logModule('app', 'specs', stats.modules.app);
    logModule('vendor', 'vendor', stats.modules.vendor);

    // Finish up.
    log.silent = false;
    resolve(stats);
  })();
});
<commit_msg>Tweak log text.<commit_after>import R from 'ramda';
import Promise from 'bluebird';
import chalk from 'chalk';
import webpackBuilder from './webpack-builder';
import webpackConfig from './webpack-config';
import { formatEntryPaths, trimRootModulePath } from './paths';
import log from '../shared/log';

/**
 * Calculates the size of the JS bundles.
 * @param {Object} options:
 *
 *           --entry:  Required. The entry path(s).
 *
 *           --prod:   Flag indicating if the JS should be built for production (smaller).
 *                     Default: false.
 *
 *           --silent: Flag indicating if log output should be suppressed.
 *                     Default: false.
 *
 * @return {Promise}.
 */
export default (options = {}) => new Promise((resolve, reject) => {
  (async () => {
    // Setup initial conditions.
    const { entry, prod, silent } = options;
    const isProduction = prod || false;
    log.silent = silent || false;

    // Initial message.
    let msg;
    msg = 'Bundling and calculating size of javascript files';
    msg = isProduction ? `${ msg }(production)` : msg;
    msg += '...\n';
    log.info(chalk.grey(msg));

    // Prepare the Webpack configuration.
    const config = webpackConfig({
      entry: formatEntryPaths(entry),
      outputFile: 'specs.js',
      isProduction,
    });

    // Build the JS.
    let stats;
    try {
      stats = await webpackBuilder(config);
    } catch (err) {
      reject(err);
    }

    // Write output.
    log.info(chalk.green('Code Size:'));
    log.info(chalk.grey(' - minified:   '), isProduction);
    log.info(chalk.grey(' - build time: '), stats.buildTime.secs, 'secs');
    log.info();

    const logModule = (key, title, data) => {
      // General information.
      log.info('', chalk.blue(title));
      log.info(
        chalk.grey('   - size:     '),
        data.size.display, chalk.grey('=>'),
        chalk.magenta(data.zipped.display), chalk.grey('zipped')
      );

      // List modules/paths.
      const modules = config.entry[key].map(item => trimRootModulePath(item));
      log.info(chalk.grey('   - modules:  '), modules[0] || chalk.magenta('None.'));
      R.takeLast(modules.length - 1, modules).forEach(item => {
        log.info(chalk.grey('               '), item);
      });

      log.info();
    };
    logModule('app', 'specs', stats.modules.app);
    logModule('vendor', 'vendor', stats.modules.vendor);

    // Finish up.
    log.silent = false;
    resolve(stats);
  })();
});
<|endoftext|>


<commit_before>/* jslint node: true */
'use strict';

var ERRORS = {
  'abort': 0,
  'alert': 1,
  'crit': 2,
  'error': 3,
  'warn': 4
};

var _ = require('lodash');
var B = require('backdash');

var env = require('./env');
var vmFile = require('../viewmodels/file');
var vmNavigator = require('../viewmodels/navigator');
var session = require('../models/session');

var bus = _.extend({}, B.Events);
var stdout = _.extend({}, B.Events);

// convert the global context to an event emitter
//      NOTE: only the subscription mechanism is exposed
global.agilemd.on = stdout.on;

// apply previously created handlers; capture last init command
_.each(global.agilemd._q, function (cmd) {
  if (cmd[0] === 'on') {
    stdout.on(cmd[1][0], cmd[1][1], cmd[1][2] || global);
  }
});

// replay recorded events once other components are ready;
//      also, convert queue api into direct api function calls
function init () {
  var cmdInit;
  var cmdOpen;

  // once auth received, play last recorded open event
  session.on('change:token', function (model) {
    global.agilemd.open = function (type, id) {
      if (type === 'module') {
        vmNavigator.transition({
          moduleId: id
        });
      }
      else {
        vmFile.transition({
          entityId: id
        });
      }
    };

    // replay the last open command; once again filter through events
    //      to handle accumlation while auth was taking place
    cmdOpen = _.findLast(global.agilemd._q, function (cmd) {
      return cmd[0] === 'open';
    });

    if (cmdOpen) {
      global.agilemd.open.apply(null, cmdOpen[1]);
    } else {
      // set an known unknown state; default the app into viewing the
      //      first module to which the token provides access
      vmNavigator.transition({
        moduleId: -1
      });
    }

    // clean up queue parameters
    global.agilemd._q = [];
  });

  // expose open as public api; open events are still enqueued until
  //      auth completes
  global.agilemd.open = function () {
    global.agilemd._q.push([
      'open',
      Array.prototype.slice.call(arguments)
    ]);
  };

  // if available, replay the most recent init command;
  // expose init as public api
  cmdInit = _.findLast(global.agilemd._q, function (cmd) {
    return cmd[0] === 'init';
  });

  if (cmdInit) {
    var rawInit = (cmdInit[1] && cmdInit[1].length) ? cmdInit[1][0] : {};

    // check for navigation config
    if (rawInit.disableNavigation) {
      vmNavigator.set('isDisabled', rawInit.disableNavigation);
      delete rawInit.disableNavigation;
    }

    // check for open wihin config and proxy into open commands
    if (rawInit.file) {
      global.agilemd.open('file', rawInit.file);
      delete rawInit.file;
    }
    else if (rawInit.module) {
      global.agilemd.open('module', rawInit.module);
      delete rawInit.module;
    }

    session.authenticate.apply(null, cmdInit[1]);
  }

  global.agilemd.init = session.authenticate;
}

// emit relevant auth events
session.on('change:token', function (model) {
  stdout.trigger('auth', {
    clientId: model.get('clientId'),
    ownerId: model.get('ownerId')
  });
});

// outbound messages bound to view model changes
vmNavigator.on('change', function (vm) {
  var changed = vm.changedAttributes();

  if (changed.path && changed.path.length) {
    var currentFolder = changed.path[changed.path.length - 1];

    stdout.trigger('openFolder', {
      moduleId: vm.get('moduleId'),
      folderId: currentFolder._id,
      folderTitle: currentFolder.title
    });
  }

  if (changed.title) {
    stdout.trigger('openModule', {
      moduleId: vm.get('moduleId'),
      moduleTitle: changed.title
    });
  }
});

vmFile.on('change:title', function (vm, title) {
  if (!title) return;

  stdout.trigger('openFile', {
    fileId: vm.get('entityId'),
    fileTitle: title,
    fileType: vm.get('type')
  });
});

// export errors that proxy into the exposed api
_.each(ERRORS, function (code, key) {
  module.exports[key] = bus[key] = function (msg) {
    stdout.trigger('error', {
      code: code,
      message: msg
    });
  };
});

module.exports.init = init;
module.exports.on = bus.on;
module.exports.trigger = bus.trigger;
<commit_msg>rel #1; refactoring prepwork<commit_after>/* jslint node: true */
'use strict';

var ERRORS = {
  'abort': 0,
  'alert': 1,
  'crit': 2,
  'error': 3,
  'warn': 4
};

var _ = require('lodash');
var B = require('backdash');

var env = require('./env');
var vmFile = require('../viewmodels/file');
var vmNavigator = require('../viewmodels/navigator');
var session = require('../models/session');

var bus = _.extend({}, B.Events);
var stdout = _.extend({}, B.Events);

// convert the global context to an event emitter
//      NOTE: only the subscription mechanism is exposed
global.agilemd.on = stdout.on;

// apply previously created handlers; capture last init command
_.each(global.agilemd._q, function (cmd) {
  if (cmd[0] === 'on') {
    stdout.on(cmd[1][0], cmd[1][1], cmd[1][2] || global);
  }
});

// replay recorded events once other components are ready;
//      also, convert queue api into direct api function calls
function init () {
  var cmdInit;
  var cmdOpen;

  // once auth received, play last recorded open event
  session.on('change:token', function (model) {
    global.agilemd.open = function (type, id) {
      if (type === 'module') {
        vmNavigator.transition({
          moduleId: id
        });
      }
      else {
        vmFile.transition({
          entityId: id
        });
      }
    };

    // replay the last open command; once again filter through events
    //      to handle accumlation while auth was taking place
    cmdOpen = _.findLast(global.agilemd._q, function (cmd) {
      return cmd[0] === 'open';
    });

    if (cmdOpen) {
      global.agilemd.open.apply(null, cmdOpen[1]);
    } else {
      // set an known unknown state; default the app into viewing the
      //      first module to which the token provides access
      vmNavigator.transition({
        moduleId: -1
      });
    }

    // clean up queue parameters
    global.agilemd._q = [];
  });

  // expose open as public api; open events are still enqueued until
  //      auth completes
  global.agilemd.open = function () {
    global.agilemd._q.push([
      'open',
      Array.prototype.slice.call(arguments)
    ]);
  };

  // if available, replay the most recent init command;
  // expose init as public api
  cmdInit = _.findLast(global.agilemd._q, function (cmd) {
    return cmd[0] === 'init';
  });

  if (cmdInit) {
    var rawInit = (cmdInit[1] && cmdInit[1].length) ? cmdInit[1][0] : {};

    // check for navigation config
    if (rawInit.disableNavigation) {
      vmNavigator.set('isDisabled', rawInit.disableNavigation);
      delete rawInit.disableNavigation;
    }

    // check for open wihin config and proxy into open commands
    if (rawInit.file) {
      global.agilemd.open('file', rawInit.file);
      delete rawInit.file;
    }
    else if (rawInit.module) {
      global.agilemd.open('module', rawInit.module);
      delete rawInit.module;
    }

    session.authenticate.apply(null, cmdInit[1]);
  }

  global.agilemd.init = session.authenticate;
}

// emit relevant auth events
session.on('change:token', function (model) {
  stdout.trigger('auth', {
    clientId: model.get('clientId'),
    ownerId: model.get('ownerId')
  });
});

// outbound messages bound to view model changes
vmNavigator.on('change', function (vm) {
  var changed = vm.changedAttributes();

  if (changed.path && changed.path.length) {
    var currentFolder = changed.path[changed.path.length - 1];

    stdout.trigger('openFolder', {
      moduleId: vm.get('moduleId'),
      folderId: currentFolder._id,
      folderTitle: currentFolder.title
    });
  }

  if (changed.title) {
    stdout.trigger('openModule', {
      moduleId: vm.get('moduleId'),
      moduleTitle: changed.title
    });
  }
});

vmFile.on('change', function (vm) {
  var changed = vm.changedAttributes();

  if (changed.title) {
    stdout.trigger('openFile', {
      fileId: vm.get('entityId'),
      fileTitle: changed.title,
      fileType: vm.get('type')
    });
  }
});

// export errors that proxy into the exposed api
_.each(ERRORS, function (code, key) {
  module.exports[key] = bus[key] = function (msg) {
    stdout.trigger('error', {
      code: code,
      message: msg
    });
  };
});

module.exports.init = init;
module.exports.on = bus.on;
module.exports.trigger = bus.trigger;
<|endoftext|>