<commit_before>// @flow
import * as Constants from '../constants/chat'
import * as ChatGen from '../actions/chat-gen'
import {Set, List, Map} from 'immutable'
import {reachabilityReachable} from '../constants/types/flow-types'

const initialState: Constants.State = Constants.makeState()
const initialConversation: Constants.ConversationState = Constants.makeConversationState()

type ConversationsStates = Map<Constants.ConversationIDKey, Constants.ConversationState>
type ConversationUpdateFn = (c: Constants.ConversationState) => Constants.ConversationState
function updateConversation(
  conversationStates: ConversationsStates,
  conversationIDKey: Constants.ConversationIDKey,
  conversationUpdateFn: ConversationUpdateFn
): ConversationsStates {
  return conversationStates.update(conversationIDKey, initialConversation, conversationUpdateFn)
}

function reducer(state: Constants.State = initialState, action: ChatGen.Actions) {
  switch (action.type) {
    case ChatGen.resetStore:
      return Constants.makeState()
    case ChatGen.deleteEntity: {
      const {keyPath, ids} = action.payload
      // $FlowIssue flow can't guarantee the keypath works for all cases
      return state.updateIn(keyPath, map => map.deleteAll(ids))
    }
    case ChatGen.mergeEntity: {
      const {keyPath, entities} = action.payload
      return state.mergeDeepIn(keyPath, entities)
    }
    case ChatGen.replaceEntity: {
      const {keyPath, entities} = action.payload
      return state.mergeIn(keyPath, entities)
    }
    case ChatGen.subtractEntity: {
      const {keyPath, entities} = action.payload
      // $FlowIssue flow can't guarantee the keypath works for all cases
      return state.updateIn(keyPath, set => set.subtract(entities))
    }
    case ChatGen.clearMessages: {
      const {conversationIDKey} = action.payload
      const origConversationState = state.get('conversationStates').get(conversationIDKey)
      if (!origConversationState) {
        console.warn("Attempted to clear conversation state that doesn't exist")
        return state
      }

      const clearedConversationState = initialConversation.merge({
        firstNewMessageID: origConversationState.get('firstNewMessageID'),
      })
      return state.update('conversationStates', conversationStates =>
        conversationStates.set(conversationIDKey, clearedConversationState)
      )
    }
    case ChatGen.setLoaded: {
      const {conversationIDKey, isLoaded} = action.payload
      const newConversationStates = state
        .get('conversationStates')
        .update(conversationIDKey, initialConversation, conversation =>
          conversation.set('isLoaded', isLoaded)
        )

      return state.set('conversationStates', newConversationStates)
    }
    case ChatGen.prependMessages: {
      const {moreToLoad, conversationIDKey} = action.payload
      const newConversationStates = state
        .get('conversationStates')
        .update(conversationIDKey, initialConversation, conversation => {
          return conversation.set('moreToLoad', moreToLoad)
        })

      return state.set('conversationStates', newConversationStates)
    }
    case ChatGen.appendMessages: {
      const {messages: appendMessages, isSelected, conversationIDKey, isAppFocused} = action.payload

      const newConversationStates = state
        .get('conversationStates')
        .update(conversationIDKey, initialConversation, conversation => {
          const firstMessage = appendMessages[0]
          const inConversationFocused = isSelected && isAppFocused
          if (!conversation.get('firstNewMessageID') && !inConversationFocused && firstMessage) {
            // Set first new message if we don't have one set, and are not in
            // the conversation with window focused
            conversation = conversation.set('firstNewMessageID', firstMessage.messageID)
          } else if (inConversationFocused) {
            // Clear new message if we received a new message while in
            // conversation and window is focused
            conversation = conversation.set('firstNewMessageID', null)
          }

          return conversation
        })

      return state.set('conversationStates', newConversationStates)
    }
    case ChatGen.setTypers: {
      const {conversationIDKey, typing} = action.payload
      return state.update('conversationStates', conversationStates =>
        updateConversation(conversationStates, conversationIDKey, conversation =>
          conversation.set('typing', Set(typing))
        )
      )
    }
    case ChatGen.markThreadsStale: {
      const {updates} = action.payload
      const convIDs = updates.map(u => Constants.conversationIDToKey(u.convID))
      return state.update('conversationStates', conversationStates =>
        conversationStates.map((conversationState, conversationIDKey) => {
          if (convIDs.length === 0 || convIDs.includes(conversationIDKey)) {
            return conversationState.set('isStale', true)
          }
          return conversationState
        })
      )
    }
    case ChatGen.inboxSynced: {
      const {convs} = action.payload
      const convIDs = convs.map(u => u.convID)
      return state.update('conversationStates', conversationStates =>
        conversationStates.map((conversationState, conversationIDKey) => {
          if (convIDs.length === 0 || convIDs.includes(conversationIDKey)) {
            return conversationState.set('isStale', true)
          }
          return conversationState
        })
      )
    }
    case ChatGen.updateLatestMessage:
      // Clear new messages id of conversation
      const newConversationStates = state
        .get('conversationStates')
        .update(action.payload.conversationIDKey, initialConversation, conversation =>
          conversation.set('firstNewMessageID', null)
        )
      state = state.set('conversationStates', newConversationStates)
      return state
    case ChatGen.loadingMessages: {
      const {isRequesting, conversationIDKey} = action.payload
      const newConversationStates = state
        .get('conversationStates')
        .update(conversationIDKey, initialConversation, conversation =>
          conversation.set('isRequesting', isRequesting)
        )
      return state.set('conversationStates', newConversationStates)
    }
    case ChatGen.updatedMetadata:
      return state.set('metaData', state.get('metaData').merge(action.payload.updated))
    case ChatGen.updateBrokenTracker:
      const userToBroken = action.payload.userToBroken
      let metaData = state.get('metaData')

      Object.keys(userToBroken).forEach(user => {
        metaData = metaData.update(user, Constants.makeMetaData(), old =>
          old.set('brokenTracker', userToBroken[user])
        )
      })

      return state.set('metaData', metaData)
    case ChatGen.clearRekey: {
      const {conversationIDKey} = action.payload
      return state.set('rekeyInfos', state.get('rekeyInfos').delete(conversationIDKey))
    }
    case ChatGen.updateInboxRekeyOthers: {
      const {conversationIDKey, rekeyers} = action.payload
      return state.set(
        'rekeyInfos',
        state
          .get('rekeyInfos')
          .set(conversationIDKey, Constants.makeRekeyInfo({rekeyParticipants: List(rekeyers)}))
      )
    }
    case ChatGen.updateInboxRekeySelf: {
      const {conversationIDKey} = action.payload
      return state.set(
        'rekeyInfos',
        state.get('rekeyInfos').set(conversationIDKey, Constants.makeRekeyInfo({youCanRekey: true}))
      )
    }
    case ChatGen.addPending: {
      const {participants, temporary} = action.payload
      const sorted = participants.sort()
      const conversationIDKey = Constants.pendingConversationIDKey(sorted.join(','))
      const tempPendingConvIDs = state.tempPendingConversations.filter(v => v).keySeq().toArray()
      return state
        .update('pendingConversations', pendingConversations =>
          // TODO use deleteAll when we update immutable
          pendingConversations
            .filterNot((v, k) => tempPendingConvIDs.includes(k))
            .set(conversationIDKey, List(sorted))
        )
        .update('tempPendingConversations', tempPendingConversations =>
          tempPendingConversations.filter(v => v).set(conversationIDKey, temporary)
        )
    }
    case ChatGen.removeTempPendingConversations: {
      const tempPendingConvIDs = state.tempPendingConversations.filter(v => v).keySeq().toArray()
      return state
        .update('tempPendingConversations', tempPendingConversations => tempPendingConversations.clear())
        .update('pendingConversations', pendingConversations =>
          pendingConversations.filterNot((v, k) => tempPendingConvIDs.includes(k))
        )
    }
    case ChatGen.pendingToRealConversation: {
      const {oldKey} = action.payload
      const oldPending = state.get('pendingConversations')
      if (oldPending.get(oldKey)) {
        return state.set('pendingConversations', oldPending.remove(oldKey))
      } else {
        console.warn("couldn't find pending to upgrade", oldKey)
      }
      break
    }
    case ChatGen.updateFinalizedState: {
      const fs = action.payload.finalizedState
      return state.update('finalizedState', finalizedState => finalizedState.merge(fs))
    }
    case ChatGen.updateSupersedesState: {
      const ss = action.payload.supersedesState
      return state.update('supersedesState', supersedesState => supersedesState.merge(ss))
    }
    case ChatGen.updateSupersededByState: {
      const sbs = action.payload.supersededByState
      return state.update('supersededByState', supersededByState => supersededByState.merge(sbs))
    }
    case ChatGen.showEditor: {
      return state.set('editingMessage', action.payload.message)
    }
    case ChatGen.setPreviousConversation: {
      return state.set('previousConversation', action.payload.conversationIDKey)
    }
    case ChatGen.threadLoadedOffline: {
      const {conversationIDKey} = action.payload
      const newConversationStates = state
        .get('conversationStates')
        .update(conversationIDKey, initialConversation, conversation =>
          conversation.set('loadedOffline', true)
        )
      return state.set('conversationStates', newConversationStates)
    }
    case 'gregor:updateReachability': {
      // reset this when we go online
      if (action.payload.reachability.reachable === reachabilityReachable.yes) {
        const newConversationStates = state
          .get('conversationStates')
          .map(conversation => conversation.set('loadedOffline', false))
        return state.set('conversationStates', newConversationStates)
      }
      break
    }
    case ChatGen.setInboxGlobalUntrustedState: {
      return state.set('inboxGlobalUntrustedState', action.payload.inboxGlobalUntrustedState)
    }
    case ChatGen.setInboxFilter: {
      return state.set('inboxFilter', action.payload.filter)
    }
    case ChatGen.newChat: {
      return state.set('inSearch', true)
    }
    case ChatGen.exitSearch: {
      return state.set('inSearch', false)
    }
    case 'teams:setChannelCreationError': {
      const {payload: {channelCreationError}} = action
      return state.set('channelCreationError', channelCreationError)
    }
    case 'teams:setTeamCreationError': {
      const {payload: {teamCreationError}} = action
      return state.set('teamCreationError', teamCreationError)
    }
    case 'teams:setTeamCreationPending': {
      const {payload: {teamCreationPending}} = action
      return state.set('teamCreationPending', teamCreationPending)
    }
    case 'teams:setTeamJoinError': {
      const {payload: {teamJoinError}} = action
      return state.set('teamJoinError', teamJoinError)
    }
    case 'teams:setTeamJoinSuccess': {
      const {payload: {teamJoinSuccess}} = action
      return state.set('teamJoinSuccess', teamJoinSuccess)
    }
  }

  return state
}

export default reducer
<commit_msg>add reducer case for inbox syncing state (#9636)<commit_after>// @flow
import * as Constants from '../constants/chat'
import * as ChatGen from '../actions/chat-gen'
import {Set, List, Map} from 'immutable'
import {reachabilityReachable} from '../constants/types/flow-types'

const initialState: Constants.State = Constants.makeState()
const initialConversation: Constants.ConversationState = Constants.makeConversationState()

type ConversationsStates = Map<Constants.ConversationIDKey, Constants.ConversationState>
type ConversationUpdateFn = (c: Constants.ConversationState) => Constants.ConversationState
function updateConversation(
  conversationStates: ConversationsStates,
  conversationIDKey: Constants.ConversationIDKey,
  conversationUpdateFn: ConversationUpdateFn
): ConversationsStates {
  return conversationStates.update(conversationIDKey, initialConversation, conversationUpdateFn)
}

function reducer(state: Constants.State = initialState, action: ChatGen.Actions) {
  switch (action.type) {
    case ChatGen.resetStore:
      return Constants.makeState()
    case ChatGen.deleteEntity: {
      const {keyPath, ids} = action.payload
      // $FlowIssue flow can't guarantee the keypath works for all cases
      return state.updateIn(keyPath, map => map.deleteAll(ids))
    }
    case ChatGen.mergeEntity: {
      const {keyPath, entities} = action.payload
      return state.mergeDeepIn(keyPath, entities)
    }
    case ChatGen.replaceEntity: {
      const {keyPath, entities} = action.payload
      return state.mergeIn(keyPath, entities)
    }
    case ChatGen.subtractEntity: {
      const {keyPath, entities} = action.payload
      // $FlowIssue flow can't guarantee the keypath works for all cases
      return state.updateIn(keyPath, set => set.subtract(entities))
    }
    case ChatGen.clearMessages: {
      const {conversationIDKey} = action.payload
      const origConversationState = state.get('conversationStates').get(conversationIDKey)
      if (!origConversationState) {
        console.warn("Attempted to clear conversation state that doesn't exist")
        return state
      }

      const clearedConversationState = initialConversation.merge({
        firstNewMessageID: origConversationState.get('firstNewMessageID'),
      })
      return state.update('conversationStates', conversationStates =>
        conversationStates.set(conversationIDKey, clearedConversationState)
      )
    }
    case ChatGen.setLoaded: {
      const {conversationIDKey, isLoaded} = action.payload
      const newConversationStates = state
        .get('conversationStates')
        .update(conversationIDKey, initialConversation, conversation =>
          conversation.set('isLoaded', isLoaded)
        )

      return state.set('conversationStates', newConversationStates)
    }
    case ChatGen.prependMessages: {
      const {moreToLoad, conversationIDKey} = action.payload
      const newConversationStates = state
        .get('conversationStates')
        .update(conversationIDKey, initialConversation, conversation => {
          return conversation.set('moreToLoad', moreToLoad)
        })

      return state.set('conversationStates', newConversationStates)
    }
    case ChatGen.appendMessages: {
      const {messages: appendMessages, isSelected, conversationIDKey, isAppFocused} = action.payload

      const newConversationStates = state
        .get('conversationStates')
        .update(conversationIDKey, initialConversation, conversation => {
          const firstMessage = appendMessages[0]
          const inConversationFocused = isSelected && isAppFocused
          if (!conversation.get('firstNewMessageID') && !inConversationFocused && firstMessage) {
            // Set first new message if we don't have one set, and are not in
            // the conversation with window focused
            conversation = conversation.set('firstNewMessageID', firstMessage.messageID)
          } else if (inConversationFocused) {
            // Clear new message if we received a new message while in
            // conversation and window is focused
            conversation = conversation.set('firstNewMessageID', null)
          }

          return conversation
        })

      return state.set('conversationStates', newConversationStates)
    }
    case ChatGen.setTypers: {
      const {conversationIDKey, typing} = action.payload
      return state.update('conversationStates', conversationStates =>
        updateConversation(conversationStates, conversationIDKey, conversation =>
          conversation.set('typing', Set(typing))
        )
      )
    }
    case ChatGen.markThreadsStale: {
      const {updates} = action.payload
      const convIDs = updates.map(u => Constants.conversationIDToKey(u.convID))
      return state.update('conversationStates', conversationStates =>
        conversationStates.map((conversationState, conversationIDKey) => {
          if (convIDs.length === 0 || convIDs.includes(conversationIDKey)) {
            return conversationState.set('isStale', true)
          }
          return conversationState
        })
      )
    }
    case ChatGen.inboxSynced: {
      const {convs} = action.payload
      const convIDs = convs.map(u => u.convID)
      return state.update('conversationStates', conversationStates =>
        conversationStates.map((conversationState, conversationIDKey) => {
          if (convIDs.length === 0 || convIDs.includes(conversationIDKey)) {
            return conversationState.set('isStale', true)
          }
          return conversationState
        })
      )
    }
    case ChatGen.updateLatestMessage:
      // Clear new messages id of conversation
      const newConversationStates = state
        .get('conversationStates')
        .update(action.payload.conversationIDKey, initialConversation, conversation =>
          conversation.set('firstNewMessageID', null)
        )
      state = state.set('conversationStates', newConversationStates)
      return state
    case ChatGen.loadingMessages: {
      const {isRequesting, conversationIDKey} = action.payload
      const newConversationStates = state
        .get('conversationStates')
        .update(conversationIDKey, initialConversation, conversation =>
          conversation.set('isRequesting', isRequesting)
        )
      return state.set('conversationStates', newConversationStates)
    }
    case ChatGen.updatedMetadata:
      return state.set('metaData', state.get('metaData').merge(action.payload.updated))
    case ChatGen.updateBrokenTracker:
      const userToBroken = action.payload.userToBroken
      let metaData = state.get('metaData')

      Object.keys(userToBroken).forEach(user => {
        metaData = metaData.update(user, Constants.makeMetaData(), old =>
          old.set('brokenTracker', userToBroken[user])
        )
      })

      return state.set('metaData', metaData)
    case ChatGen.clearRekey: {
      const {conversationIDKey} = action.payload
      return state.set('rekeyInfos', state.get('rekeyInfos').delete(conversationIDKey))
    }
    case ChatGen.updateInboxRekeyOthers: {
      const {conversationIDKey, rekeyers} = action.payload
      return state.set(
        'rekeyInfos',
        state
          .get('rekeyInfos')
          .set(conversationIDKey, Constants.makeRekeyInfo({rekeyParticipants: List(rekeyers)}))
      )
    }
    case ChatGen.updateInboxRekeySelf: {
      const {conversationIDKey} = action.payload
      return state.set(
        'rekeyInfos',
        state.get('rekeyInfos').set(conversationIDKey, Constants.makeRekeyInfo({youCanRekey: true}))
      )
    }
    case ChatGen.addPending: {
      const {participants, temporary} = action.payload
      const sorted = participants.sort()
      const conversationIDKey = Constants.pendingConversationIDKey(sorted.join(','))
      const tempPendingConvIDs = state.tempPendingConversations.filter(v => v).keySeq().toArray()
      return state
        .update('pendingConversations', pendingConversations =>
          // TODO use deleteAll when we update immutable
          pendingConversations
            .filterNot((v, k) => tempPendingConvIDs.includes(k))
            .set(conversationIDKey, List(sorted))
        )
        .update('tempPendingConversations', tempPendingConversations =>
          tempPendingConversations.filter(v => v).set(conversationIDKey, temporary)
        )
    }
    case ChatGen.removeTempPendingConversations: {
      const tempPendingConvIDs = state.tempPendingConversations.filter(v => v).keySeq().toArray()
      return state
        .update('tempPendingConversations', tempPendingConversations => tempPendingConversations.clear())
        .update('pendingConversations', pendingConversations =>
          pendingConversations.filterNot((v, k) => tempPendingConvIDs.includes(k))
        )
    }
    case ChatGen.pendingToRealConversation: {
      const {oldKey} = action.payload
      const oldPending = state.get('pendingConversations')
      if (oldPending.get(oldKey)) {
        return state.set('pendingConversations', oldPending.remove(oldKey))
      } else {
        console.warn("couldn't find pending to upgrade", oldKey)
      }
      break
    }
    case ChatGen.updateFinalizedState: {
      const fs = action.payload.finalizedState
      return state.update('finalizedState', finalizedState => finalizedState.merge(fs))
    }
    case ChatGen.updateSupersedesState: {
      const ss = action.payload.supersedesState
      return state.update('supersedesState', supersedesState => supersedesState.merge(ss))
    }
    case ChatGen.updateSupersededByState: {
      const sbs = action.payload.supersededByState
      return state.update('supersededByState', supersededByState => supersededByState.merge(sbs))
    }
    case ChatGen.showEditor: {
      return state.set('editingMessage', action.payload.message)
    }
    case ChatGen.setPreviousConversation: {
      return state.set('previousConversation', action.payload.conversationIDKey)
    }
    case ChatGen.threadLoadedOffline: {
      const {conversationIDKey} = action.payload
      const newConversationStates = state
        .get('conversationStates')
        .update(conversationIDKey, initialConversation, conversation =>
          conversation.set('loadedOffline', true)
        )
      return state.set('conversationStates', newConversationStates)
    }
    case 'gregor:updateReachability': {
      // reset this when we go online
      if (action.payload.reachability.reachable === reachabilityReachable.yes) {
        const newConversationStates = state
          .get('conversationStates')
          .map(conversation => conversation.set('loadedOffline', false))
        return state.set('conversationStates', newConversationStates)
      }
      break
    }
    case ChatGen.setInboxGlobalUntrustedState: {
      return state.set('inboxGlobalUntrustedState', action.payload.inboxGlobalUntrustedState)
    }
    case ChatGen.setInboxSyncingState: {
      return state.set('inboxSyncingState', action.payload.inboxSyncingState)
    }
    case ChatGen.setInboxFilter: {
      return state.set('inboxFilter', action.payload.filter)
    }
    case ChatGen.newChat: {
      return state.set('inSearch', true)
    }
    case ChatGen.exitSearch: {
      return state.set('inSearch', false)
    }
    case 'teams:setChannelCreationError': {
      const {payload: {channelCreationError}} = action
      return state.set('channelCreationError', channelCreationError)
    }
    case 'teams:setTeamCreationError': {
      const {payload: {teamCreationError}} = action
      return state.set('teamCreationError', teamCreationError)
    }
    case 'teams:setTeamCreationPending': {
      const {payload: {teamCreationPending}} = action
      return state.set('teamCreationPending', teamCreationPending)
    }
    case 'teams:setTeamJoinError': {
      const {payload: {teamJoinError}} = action
      return state.set('teamJoinError', teamJoinError)
    }
    case 'teams:setTeamJoinSuccess': {
      const {payload: {teamJoinSuccess}} = action
      return state.set('teamJoinSuccess', teamJoinSuccess)
    }
  }

  return state
}

export default reducer
<|endoftext|>


<commit_before>// require('dotenv').load();
var alexa = require('alexa-app');

var app = new alexa.app('wolfram');

app.intent('wolfram',
  function(request, response) {
    console.log("Request: %j", request);
    console.log("Saw request '%s'", request.slot('query'));
    var query = request.slot('query');

    console.log("Returning with intent!");
    response.say("End of the road!");
    return true;
});

console.log("exported the handler 6");
exports.handler = app.handler;
<commit_msg>adding in a working pre-filter and requirements<commit_after>require('dotenv').load();

var alexa = require('alexa-app');
var app = new alexa.app('wolfram');
var wolfram = require('wolfram').createClient(process.env.WOLFRAM_APPID);

app.pre = function(request,response,type) {
  console.log("pre-filtering the request");
  if (request.sessionDetails.application.applicationId != process.env.ALEXA_APP_ID) {
    // Fail ungracefully
    response.fail("Invalid applicationId");
  }
  console.log("pre-filtered the request; moving on");
};

app.intent('wolfram',
  function(request, response) {
    console.log("Request: %j", request);
    console.log("Saw request '%s'", request.slot('query'));
    var query = request.slot('query');

    console.log("Returning with intent!");
    response.say("End of the road!");
    return true;
});

console.log("exported the handler 6");
exports.handler = app.handler;
<|endoftext|>


<commit_before>'use strict';

var autils = require('../../AUtils');
var GenericDiffReporterBase = require('../GenericDiffReporterBase');
var shelljs = require('shelljs');

module.exports = GenericDiffReporterBase.create(function () {
  this.name = "P4Merge";

  var isMac = process.platform === 'darwin';
  var app = null;
  if (isMac) {

    try {
      app = shelljs.ls('/Applications/p4merge.app/Contents/Resources/launchp4merge')[0];
    } catch (err) {
      console.error(err);
    }

    try {
      app = app || shelljs.find('/opt/homebrew-cask/Caskroom/p4merge').filter(function (item){
        return item.indexOf('launchp4merge') >= 0;
      })[0];
    } catch (err) {
      console.error(err);
    }
  }

  this.exePath = app || autils.searchForExecutable("Perforce", "p4merge.exe");
});
<commit_msg>found it...<commit_after>'use strict';

var autils = require('../../AUtils');
var GenericDiffReporterBase = require('../GenericDiffReporterBase');
var shelljs = require('shelljs');
var fs = require('fs');

module.exports = GenericDiffReporterBase.create(function () {
  this.name = "P4Merge";

  var isMac = process.platform === 'darwin';
  var app = null;
  if (isMac) {

    try {
      app = shelljs.ls('/Applications/p4merge.app/Contents/Resources/launchp4merge')[0];
    } catch (err) {
      console.error(err);
    }

    try {
      // `shelljs.find` will `process.exit` on error - so test the folder exists first
      if (fs.existsSync('/opt/homebrew-cask/Caskroom/p4merge')) {
        app = app || shelljs.find('/opt/homebrew-cask/Caskroom/p4merge').filter(function (item){
          return item.indexOf('launchp4merge') >= 0;
        })[0];
      }
    } catch (err) {
      //console.error(err);
    }
  }

  this.exePath = app || autils.searchForExecutable("Perforce", "p4merge.exe");
});
<|endoftext|>


<commit_before>// Woodlot custom logging module

'use strict';

var stdoutFormatting        =   require('./stdoutFormatting');
var fileStreamHandler       =   require('./fileStreamHandler');
var utils                   =   require('./utils');
var fireCustomLoggerEvent   =   require('./events').fireCustomLoggerEvent;
var LEVELS                  =   require('./constants').LEVELS;
var customLoggerConfig      =   null;

// Function to generate custom log based on format
function generateCustomLog(format, message, config) {
    var level = config.level;

    switch (format) {
        case 'text':
            return level.toUpperCase() + ' [' + utils.generateCLFTimestamp(new Date()) + ']: ' + '"' + message + '"';

        case 'json':
        default:

            return {
                level: level.toUpperCase(),
                timeStamp: utils.generateCLFTimestamp(new Date()),
                message: message
            };
    }
};

// Function to write log entry to stdout
function logToStdOut(log, format, spacing, config) {
    // Set standard output stream
    var outputStream = process.stdout;

    if (format === 'json') {
        var stringifiedLog = utils.stringifyLog(log, format, spacing),
            colorizedLog = stdoutFormatting.colorizeStdoutFormat(stringifiedLog, 'customLevelJSON');

        outputStream.write(colorizedLog + utils.getFormatSeparator(config));
    } else {
        var colorizedLog = stdoutFormatting.colorizeStdoutFormat(log, 'text')
        outputStream.write(colorizedLog + utils.getFormatSeparator(config));
    }
};

// Custom level log utility
function customLevelLog(level, message) {
    if (!customLoggerConfig) {
        utils.logConfigWarning();
    } else {
        var config = customLoggerConfig;

         // Set default level to 'info'
        config.level = level ? level : 'info';

        var format = utils.getLogFormat(config),
            log = generateCustomLog(format, message, config),
            spacing = utils.getFormatSpacing(config),
            outputStream = process.stdout;

        // Fire woodlot custom logger events
        fireCustomLoggerEvent(level, log);

        // Write to specified file streams
        format === 'text' ? fileStreamHandler(log, config) : fileStreamHandler(utils.stringifyLog(log, format, spacing), config);

        // Write request log to stdout if option is present
        config.logToConsole ? logToStdOut(log, format, spacing, config) : null;
    }
};

// Custom logger main module
var customLogger = {
    // Function to set custom logger config
    config: function(config) {
        if (!config || !config.streams || !config.streams.length) {
            utils.logConfigWarning();
        } else {
            config.logToConsole = ('stdout' in config) ? config.stdout : true;

            customLoggerConfig = config;
        }
    },
    // Custom logging utility level functions - receives a message and logs it out with specified level
    info: function(message) {
        customLevelLog(LEVELS.INFO, message);
    },
    debug: function(message) {
        customLevelLog(LEVELS.DEBUG, message);
    },
    warn: function(message) {
        customLevelLog(LEVELS.WARN, message);
    },
    err: function(message) {
        customLevelLog(LEVELS.ERR, message);
    }
};

module.exports = customLogger;
<commit_msg>Custom logger signature changed to support multiple logger instances<commit_after>// Woodlot custom logging module

'use strict';

var stdoutFormatting        =   require('./stdoutFormatting');
var fileStreamHandler       =   require('./fileStreamHandler');
var utils                   =   require('./utils');
var fireCustomLoggerEvent   =   require('./events').fireCustomLoggerEvent;
var LEVELS                  =   require('./constants').LEVELS;

// Function to generate custom log based on format
function generateCustomLog(format, message, config) {
    var level = config.level;

    switch (format) {
        case 'text':
            return level.toUpperCase() + ' [' + utils.generateCLFTimestamp(new Date()) + ']: ' + '"' + message + '"';

        case 'json':
        default:

            return {
                timeStamp: utils.generateCLFTimestamp(new Date()),
                message: message,
                level: level.toUpperCase()
            };
    }
};

// Function to write log entry to stdout
function logToStdOut(log, format, spacing, config) {
    // Set standard output stream
    var outputStream = process.stdout;

    if (format === 'json') {
        var stringifiedLog = utils.stringifyLog(log, format, spacing),
            colorizedLog = stdoutFormatting.colorizeStdoutFormat(stringifiedLog, 'customLevelJSON');

        outputStream.write(colorizedLog + utils.getFormatSeparator(config));
    } else {
        var colorizedLog = stdoutFormatting.colorizeStdoutFormat(log, 'text')
        outputStream.write(colorizedLog + utils.getFormatSeparator(config));
    }
};

// Custom level log utility
function customLevelLog(config, level, message) {
    if (!config) {
        utils.logConfigWarning();
    } else {
         // Set default level to 'info'
        config.level = level ? level : 'info';

        var format = utils.getLogFormat(config),
            log = generateCustomLog(format, message, config),
            spacing = utils.getFormatSpacing(config),
            outputStream = process.stdout;

        // Fire woodlot custom logger events
        fireCustomLoggerEvent(level, log);

        // Write to specified file streams
        format === 'text' ? fileStreamHandler(log, config) : fileStreamHandler(utils.stringifyLog(log, format, spacing), config);

        // Write request log to stdout if option is present
        config.logToConsole ? logToStdOut(log, format, spacing, config) : null;
    }
};

// Custom logger main module
function customLogger(config) {
    if (!config || !config.streams || !config.streams.length) {
        return utils.logConfigWarning();
    }

    this.config = config;

    this.config.logToConsole = ('stdout' in config) ? config.stdout : true;

    // Custom logging utility level functions - receives a message and logs it out with specified level
    this.info = function(message) {
        customLevelLog(this.config, LEVELS.INFO, message);
    };
    this.debug = function(message) {
        customLevelLog(this.config, LEVELS.DEBUG, message);
    };
    this.warn = function(message) {
        customLevelLog(this.config, LEVELS.WARN, message);
    };
    this.err = function(message) {
        customLevelLog(this.config, LEVELS.ERR, message);
    };
};

module.exports = customLogger;
<|endoftext|>


<commit_before>exports.run = async(client, msg, args) => {
    let messagecount = parseInt(args, 10);
    /*
  Check if msg is higher or lower then the limits
 */
    if (!messagecount) {
        return msg.reply('How many messages?');
    }
    if (messagecount > 100) {
        return msg.reply(`Purge has limits: you cant delete 101 messages per purge`);
    }
    /*
    Actual purge
    */
    let ms;
    if (messagecount === 1) {
        ms = 2;
    } else {
        ms = messagecount;
    }
    msg.channel.fetchMessages({limit: messagecount}).then(async messages => {
        msg.channel.bulkDelete(ms)
    })
        .catch(err => {
            logger.error(err, msg.channel.send('I cant delete msg that are older than a 14 days'));
        })
        .catch(e => logger.error(e));
    setTimeout(function () {
        let promise = msg.channel.send(`Deleted \`${messagecount}\` messages`).then(m => m.delete(1500))
    }, 1500);
};

exports.help = {
    category   : 'util',
    usage      : '[amount:integer]',
    description: 'I will delete the amount of messages you want',
    detail     : 'When using purge the bot delete the amount of requested messages',
    botPerm    : ['MANAGE_MESSAGES', "SEND_MESSAGES"],
    authorPerm : ['MANAGE_MESSAGES'],
    example    : "1",
    alias      : [
        'pur'
    ]
};
<commit_msg>Updated err message<commit_after>exports.run = async(client, msg, args) => {
    let messagecount = parseInt(args, 10);
    /*
  Check if msg is higher or lower then the limits
 */
    if (!messagecount) {
        return msg.reply('How many messages?');
    }
    if (messagecount > 100) {
        return msg.reply(`Purge has a limit of 100 messages a time`);
    }
    /*
    Actual purge
    */
    let ms;
    if (messagecount === 1) {
        ms = 2;
    } else {
        ms = messagecount;
    }
    msg.channel.fetchMessages({limit: messagecount}).then(async messages => {
        msg.channel.bulkDelete(ms)
    })
        .catch(err => {
            logger.error(err, msg.channel.send('I cant delete msg that are older than a 14 days'));
        })
        .catch(e => logger.error(e));
    setTimeout(function () {
        let promise = msg.channel.send(`Deleted \`${messagecount}\` messages`).then(m => m.delete(1500))
    }, 1500);
};

exports.help = {
    category   : 'util',
    usage      : '[amount:integer]',
    description: 'I will delete the amount of messages you want',
    detail     : 'When using purge the bot delete the amount of requested messages',
    botPerm    : ['MANAGE_MESSAGES', "SEND_MESSAGES"],
    authorPerm : ['MANAGE_MESSAGES'],
    example    : "1",
    alias      : [
        'pur'
    ]
};
<|endoftext|>


<commit_before>describe("The JQueryLens", function () {

	beforeEach(function () {
		$('#test-div').remove();
		var sample_lens_html_code = '
'
			+ '

'
			+ '

 '
			+ '

';
		$(sample_lens_html_code).appendTo('body');
		JQueryLens.init({});
	});

	it("cannot change not query its width, height and zoom", function () {
		expect(JQueryLens.setWidth).toBeUndefined();
		expect(JQueryLens.setHeight).toBeUndefined();
		expect(JQueryLens.setZoom).toBeUndefined();
		expect(JQueryLens.width).toBeUndefined();
		expect(JQueryLens.height).toBeUndefined();
		expect(JQueryLens.zoom).toBeUndefined();
	});

	it("has default values for its fields", function () {
		expect(JQueryLens.lens.attr("id")).toBe("lens");
		expect(JQueryLens.thumbnail.attr("id")).toBe("thumbnail");
		expect(JQueryLens.locator.attr("id")).toBe("locator");
	});

	it("can be initialized with values for its fields", function () {
		var anotherDivId = "temp-div";
        var temp_div = '

';
		$(temp_div).appendTo('body');

		JQueryLens.init({
			locator:   anotherDivId,
			thumbnail: anotherDivId,
			lens:  	   anotherDivId
		});

		expect(JQueryLens.locator.attr("id")).toBe(anotherDivId);
		expect(JQueryLens.thumbnail.attr("id")).toBe(anotherDivId);
		expect(JQueryLens.lens.attr("id")).toBe(anotherDivId);

		$('#temp-div').remove();
	});

	it("has locator with same proportion than lens", function () {
		JQueryLens.lens.width(800);
		JQueryLens.lens.height(600);

		JQueryLens.resizeLocator();

		expect(JQueryLens.locator.width() / JQueryLens.locator.height()).toBe(800 / 600);
	});

	it("resizes locator in the proportion the zoom sets when initialized", function () {
		JQueryLens.lens.width(800);
		JQueryLens.lens.height(600);
		JQueryLens.init({zoom: 4});

		expect(JQueryLens.locator.width()).toBe(800 / 4);
		expect(JQueryLens.locator.height()).toBe(600 / 4);
	});

	it("sets thumbnail height according to thumbnail width and the image proportion", function() {
		var image = JQueryLens.image;
		var thumbnail = JQueryLens.thumbnail;

		image.width(1000);
		image.height(500);
		thumbnail.width(200);

		JQueryLens.init({});

		expect(thumbnail.width() / thumbnail.height()).toBe(image.width() / image.height());
	});

	it("sets image position according to locator position in thumbnail", function () {

		var layout = function(scenario) {
			JQueryLens.thumbnail.width(scenario.thumbnailWidth);
			JQueryLens.lens.width(scenario.lensWidth);
			JQueryLens.lens.height(scenario.lensHeight);
			JQueryLens.image.width(scenario.imageWidth);
			JQueryLens.image.height(scenario.imageHeight);
			JQueryLens.init({zoom: scenario.zoom});
			JQueryLens.locator.offset(scenario.locatorPosition);
			JQueryLens.lens.offset(scenario.lensPosition);
		};

		var scenarios = [
			{
				thumbnailWidth: 200,
				lensWidth: 400,
				lensHeight: 200,
				imageWidth: 1000,
				imageHeight: 500,
				zoom: 6,
				lensPosition: {top: 0, left: 0},
				locatorPosition: {top: 10, left: 25},
				expectedImagePosition: {top: -60, left: -150}
			},
			{
				thumbnailWidth: 200,
				lensWidth: 400,
				lensHeight: 200,
				imageWidth: 1000,
				imageHeight: 500,
				zoom: 6,
				lensPosition: {top: 0, left: 0},
				locatorPosition: {top: 0, left: 0},
				expectedImagePosition: {top: 0, left: 0}
			},
			{
				thumbnailWidth:  200,
				lensWidth: 400,
				lensHeight: 200,
				imageWidth: 1000,
				imageHeight: 500,
				zoom: 6,
				lensPosition: {top: 0, left: 0},
				locatorPosition: {top: 50, left: 100},
				expectedImagePosition: {top: -300, left: -600}
			}
		];

		for (var index in scenarios) {
			var scenario = scenarios[index];

			layout(scenario);

			JQueryLens.refreshImageInLens();

			expect(JQueryLens.image.position()).toEqual(scenario.expectedImagePosition);
		}

	});

	it("sets locator position when mouse is inside thumbnail", function() {
		JQueryLens.thumbnail.width(200);
		JQueryLens.thumbnail.offset({top:100,left:50})
		JQueryLens.lens.width(400);
		JQueryLens.lens.height(200);
		JQueryLens.image.width(1000);
		JQueryLens.image.height(500);

		JQueryLens.init({zoom: 4});

		var scenarios = [
			{
				mouse: {x:150, y:150},
				expectedLocatorPosition: {top:125, left:100}
			},
			{
				mouse: {x:150, y:125},
				expectedLocatorPosition: {top:100, left:100}
			},
			{
				mouse: {x:150, y:100},
				expectedLocatorPosition: {top:100, left:100}
			},
			{
				mouse: {x:150, y:50},
				expectedLocatorPosition: {top:100, left:100}
			},
			{
				mouse: {x:150, y:175},
				expectedLocatorPosition: {top:150, left:100}
			},
			{
				mouse: {x:150, y:200},
				expectedLocatorPosition: {top:150, left:100}
			},
			{
				mouse: {x:150, y:250},
				expectedLocatorPosition: {top:150, left:100}
			},
			{
				mouse: {x:100, y:150},
				expectedLocatorPosition: {top:125, left:50}
			},
			{
				mouse: {x:75, y:150},
				expectedLocatorPosition: {top:125, left:50}
			},
			{
				mouse: {x:200, y:150},
				expectedLocatorPosition: {top:125, left:150}
			},
			{
				mouse: {x:250, y:150},
				expectedLocatorPosition: {top:125, left:150}
			}
		];

		for (var index in scenarios) {
			var scenario = scenarios[index];

			JQueryLens.refreshLocatorInThumbnail(scenario.mouse.x, scenario.mouse.y);

			expect(JQueryLens.locator.offset()).toEqual(scenario.expectedLocatorPosition);
		}
	});

	it("moves image in lens when mouse moves in thumbnail", function() {
		JQueryLens.thumbnail.width(400);
		JQueryLens.thumbnail.offset({top:40,left:40})
		JQueryLens.lens.offset({top:40,left:500});
		JQueryLens.lens.width(800);
		JQueryLens.lens.height(600);
		JQueryLens.image.width(1600);
		JQueryLens.image.height(1200);

		JQueryLens.init({zoom: 4});

		var scenarios = [
			{
				mouse: {x:90, y:77.5},
				expectedImagePosition: {top:0, left:0}
			},
			{
				mouse: {x:140, y:115},
				expectedImagePosition: {top:0, left:0}
			}
		];

		for (var index in scenarios) {
			var scenario = scenarios[index];

			JQueryLens.refreshLocatorInThumbnail(scenario.mouse.x, scenario.mouse.y);

			expect(JQueryLens.image.position()).toEqual(scenario.expectedImagePosition);
		}
	});

	it("moves image in lens without being affected by position of lens", function() {
		var mouse = {x:100, y:50};

		JQueryLens.thumbnail.width(200);
		JQueryLens.thumbnail.offset({top:100,left:50})
		JQueryLens.lens.width(400);
		JQueryLens.lens.height(200);
		JQueryLens.image.width(1000);
		JQueryLens.image.height(500);

		JQueryLens.init({zoom: 4});

		var scenario1 = { lensTop: 0,  lensLeft: 0 };
		var scenario2 = { lensTop: 40, lensLeft: 400 };

		JQueryLens.lens.offset({top: scenario1.lensTop, left: scenario1.lensLeft});
		JQueryLens.refreshLocatorInThumbnail(mouse.x, mouse.y);
		var imagePositionScenario1 = JQueryLens.image.position();

		JQueryLens.lens.offset({top: scenario2.lensTop, left: scenario2.lensLeft});
		JQueryLens.refreshLocatorInThumbnail(mouse.x, mouse.y);
		var imagePositionScenario2 = JQueryLens.image.position();

		expect(imagePositionScenario2).toEqual(imagePositionScenario1);
	});

	it("resizes image on lens depending of zoom", function() {
		JQueryLens.thumbnail.width(400);
		JQueryLens.lens.width(800);
		JQueryLens.lens.height(600);
		JQueryLens.image.width(1600);
		JQueryLens.image.height(1200);

		var zoom=6;

		JQueryLens.init({zoom: zoom});

		expect(JQueryLens.image.width()/JQueryLens.thumbnail.width()).toEqual(zoom);
		expect(JQueryLens.image.height()/JQueryLens.thumbnail.height()).toEqual(zoom);
	});
});
<commit_msg>Refactor<commit_after>describe("The JQueryLens", function () {

	beforeEach(function () {
		$('#test-div').remove();
		var sample_lens_html_code = '
'
			+ '

'
			+ '

 '
			+ '

';
		$(sample_lens_html_code).appendTo('body');
		JQueryLens.init({});
	});

	it("cannot change not query its width, height and zoom", function () {
		expect(JQueryLens.setWidth).toBeUndefined();
		expect(JQueryLens.setHeight).toBeUndefined();
		expect(JQueryLens.setZoom).toBeUndefined();
		expect(JQueryLens.width).toBeUndefined();
		expect(JQueryLens.height).toBeUndefined();
		expect(JQueryLens.zoom).toBeUndefined();
	});

	it("has default values for its fields", function () {
		expect(JQueryLens.lens.attr("id")).toBe("lens");
		expect(JQueryLens.thumbnail.attr("id")).toBe("thumbnail");
		expect(JQueryLens.locator.attr("id")).toBe("locator");
	});

	it("can be initialized with values for its fields", function () {
		var anotherDivId = "temp-div";
		var temp_div = $('

');
		temp_div.appendTo('body');

		JQueryLens.init({
			locator:   anotherDivId,
			thumbnail: anotherDivId,
			lens:  	   anotherDivId
		});

		expect(JQueryLens.locator.attr("id")).toBe(anotherDivId);
		expect(JQueryLens.thumbnail.attr("id")).toBe(anotherDivId);
		expect(JQueryLens.lens.attr("id")).toBe(anotherDivId);

		temp_div.remove();
	});

	it("has locator with same proportion than lens", function () {
		JQueryLens.lens.width(800);
		JQueryLens.lens.height(600);

		JQueryLens.resizeLocator();

		expect(JQueryLens.locator.width() / JQueryLens.locator.height()).toBe(800 / 600);
	});

	it("resizes locator in the proportion the zoom sets when initialized", function () {
		JQueryLens.lens.width(800);
		JQueryLens.lens.height(600);
		JQueryLens.init({zoom: 4});

		expect(JQueryLens.locator.width()).toBe(800 / 4);
		expect(JQueryLens.locator.height()).toBe(600 / 4);
	});

	it("sets thumbnail height according to thumbnail width and the image proportion", function() {
		var image = JQueryLens.image;
		var thumbnail = JQueryLens.thumbnail;

		image.width(1000);
		image.height(500);
		thumbnail.width(200);

		JQueryLens.init({});

		expect(thumbnail.width() / thumbnail.height()).toBe(image.width() / image.height());
	});

	it("sets image position according to locator position in thumbnail", function () {

		var layout = function(scenario) {
			JQueryLens.thumbnail.width(scenario.thumbnailWidth);
			JQueryLens.lens.width(scenario.lensWidth);
			JQueryLens.lens.height(scenario.lensHeight);
			JQueryLens.image.width(scenario.imageWidth);
			JQueryLens.image.height(scenario.imageHeight);
			JQueryLens.init({zoom: scenario.zoom});
			JQueryLens.locator.offset(scenario.locatorPosition);
			JQueryLens.lens.offset(scenario.lensPosition);
		};

		var scenarios = [
			{
				thumbnailWidth: 200,
				lensWidth: 400,
				lensHeight: 200,
				imageWidth: 1000,
				imageHeight: 500,
				zoom: 6,
				lensPosition: {top: 0, left: 0},
				locatorPosition: {top: 10, left: 25},
				expectedImagePosition: {top: -60, left: -150}
			},
			{
				thumbnailWidth: 200,
				lensWidth: 400,
				lensHeight: 200,
				imageWidth: 1000,
				imageHeight: 500,
				zoom: 6,
				lensPosition: {top: 0, left: 0},
				locatorPosition: {top: 0, left: 0},
				expectedImagePosition: {top: 0, left: 0}
			},
			{
				thumbnailWidth:  200,
				lensWidth: 400,
				lensHeight: 200,
				imageWidth: 1000,
				imageHeight: 500,
				zoom: 6,
				lensPosition: {top: 0, left: 0},
				locatorPosition: {top: 50, left: 100},
				expectedImagePosition: {top: -300, left: -600}
			}
		];

		for (var index in scenarios) {
			var scenario = scenarios[index];

			layout(scenario);

			JQueryLens.refreshImageInLens();

			expect(JQueryLens.image.position()).toEqual(scenario.expectedImagePosition);
		}

	});

	it("sets locator position when mouse is inside thumbnail", function() {
		JQueryLens.thumbnail.width(200);
		JQueryLens.thumbnail.offset({top:100,left:50})
		JQueryLens.lens.width(400);
		JQueryLens.lens.height(200);
		JQueryLens.image.width(1000);
		JQueryLens.image.height(500);

		JQueryLens.init({zoom: 4});

		var scenarios = [
			{
				mouse: {x:150, y:150},
				expectedLocatorPosition: {top:125, left:100}
			},
			{
				mouse: {x:150, y:125},
				expectedLocatorPosition: {top:100, left:100}
			},
			{
				mouse: {x:150, y:100},
				expectedLocatorPosition: {top:100, left:100}
			},
			{
				mouse: {x:150, y:50},
				expectedLocatorPosition: {top:100, left:100}
			},
			{
				mouse: {x:150, y:175},
				expectedLocatorPosition: {top:150, left:100}
			},
			{
				mouse: {x:150, y:200},
				expectedLocatorPosition: {top:150, left:100}
			},
			{
				mouse: {x:150, y:250},
				expectedLocatorPosition: {top:150, left:100}
			},
			{
				mouse: {x:100, y:150},
				expectedLocatorPosition: {top:125, left:50}
			},
			{
				mouse: {x:75, y:150},
				expectedLocatorPosition: {top:125, left:50}
			},
			{
				mouse: {x:200, y:150},
				expectedLocatorPosition: {top:125, left:150}
			},
			{
				mouse: {x:250, y:150},
				expectedLocatorPosition: {top:125, left:150}
			}
		];

		for (var index in scenarios) {
			var scenario = scenarios[index];

			JQueryLens.refreshLocatorInThumbnail(scenario.mouse.x, scenario.mouse.y);

			expect(JQueryLens.locator.offset()).toEqual(scenario.expectedLocatorPosition);
		}
	});

	it("moves image in lens when mouse moves in thumbnail", function() {
		JQueryLens.thumbnail.width(400);
		JQueryLens.thumbnail.offset({top:40,left:40})
		JQueryLens.lens.offset({top:40,left:500});
		JQueryLens.lens.width(800);
		JQueryLens.lens.height(600);
		JQueryLens.image.width(1600);
		JQueryLens.image.height(1200);

		JQueryLens.init({zoom: 4});

		var scenarios = [
			{
				mouse: {x:90, y:77.5},
				expectedImagePosition: {top:0, left:0}
			},
			{
				mouse: {x:140, y:115},
				expectedImagePosition: {top:0, left:0}
			}
		];

		for (var index in scenarios) {
			var scenario = scenarios[index];

			JQueryLens.refreshLocatorInThumbnail(scenario.mouse.x, scenario.mouse.y);

			expect(JQueryLens.image.position()).toEqual(scenario.expectedImagePosition);
		}
	});

	it("moves image in lens without being affected by position of lens", function() {
		var mouse = {x:100, y:50};

		JQueryLens.thumbnail.width(200);
		JQueryLens.thumbnail.offset({top:100,left:50})
		JQueryLens.lens.width(400);
		JQueryLens.lens.height(200);
		JQueryLens.image.width(1000);
		JQueryLens.image.height(500);

		JQueryLens.init({zoom: 4});

		var scenario1 = { lensTop: 0,  lensLeft: 0 };
		var scenario2 = { lensTop: 40, lensLeft: 400 };

		JQueryLens.lens.offset({top: scenario1.lensTop, left: scenario1.lensLeft});
		JQueryLens.refreshLocatorInThumbnail(mouse.x, mouse.y);
		var imagePositionScenario1 = JQueryLens.image.position();

		JQueryLens.lens.offset({top: scenario2.lensTop, left: scenario2.lensLeft});
		JQueryLens.refreshLocatorInThumbnail(mouse.x, mouse.y);
		var imagePositionScenario2 = JQueryLens.image.position();

		expect(imagePositionScenario2).toEqual(imagePositionScenario1);
	});

	it("resizes image on lens depending of zoom", function() {
		JQueryLens.thumbnail.width(400);
		JQueryLens.lens.width(800);
		JQueryLens.lens.height(600);
		JQueryLens.image.width(1600);
		JQueryLens.image.height(1200);

		var zoom=6;

		JQueryLens.init({zoom: zoom});

		expect(JQueryLens.image.width()/JQueryLens.thumbnail.width()).toEqual(zoom);
		expect(JQueryLens.image.height()/JQueryLens.thumbnail.height()).toEqual(zoom);
	});
});
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')

function fileExists (filepath, options, done = function () {}) {
  if (typeof options === 'function') {
    done = options
    options = {}
  }

  fs.stat(fullPath(filepath, options), (err, stats) => {
    if (err) {
      return err.code === "ENOENT" ?
        done(null, false) :
        done(err)
    }

    done(null, stats.isFile())
  })
}

fileExists.sync = function fileExistsSync (filepath = '', options = {}) {
  try {
    return fs.statSync(fullPath(filepath, options)).isFile()
  }
  catch (e) {
    // Check exception. If ENOENT - no such file or directory ok, file doesn't exist.
    // Otherwise something else went wrong, we don't have rights to access the file, ...
    if (e.code != 'ENOENT') {
      throw e
    }

    return false
  }
}

function fullPath (filepath, options = {}) {
  const root = options.root
  return (root) ? path.join(root, filepath) : filepath
}

module.exports = fileExists
<commit_msg>Update quotes<commit_after>const fs = require('fs')
const path = require('path')

function fileExists (filepath, options, done = function () {}) {
  if (typeof options === 'function') {
    done = options
    options = {}
  }

  fs.stat(fullPath(filepath, options), (err, stats) => {
    if (err) {
      return err.code === 'ENOENT' ?
        done(null, false) :
        done(err)
    }

    done(null, stats.isFile())
  })
}

fileExists.sync = function fileExistsSync (filepath = '', options = {}) {
  try {
    return fs.statSync(fullPath(filepath, options)).isFile()
  }
  catch (e) {
    // Check exception. If ENOENT - no such file or directory ok, file doesn't exist.
    // Otherwise something else went wrong, we don't have rights to access the file, ...
    if (e.code != 'ENOENT') {
      throw e
    }

    return false
  }
}

function fullPath (filepath, options = {}) {
  const root = options.root
  return (root) ? path.join(root, filepath) : filepath
}

module.exports = fileExists
<|endoftext|>


<commit_before>/*
  tbumb. bumps
*/

var bump = ["$bump", "=bump", "dbump", "dlm!bump", "$bump", "!bump", "!!bump", "", "$bump", "=bump", "dbump", "", "$bump", "!bump", "!!bump", "dlm!bump", "$bump", "=bump", "dbump", "", "$bump", "!bump", "!!bump", ""];
var index = 0;
var interval;

module.exports = (self) => {
  self.registerCommand('tbump', function (msg, args) {
	if(interval){
		clearInterval(interval);
		interval = null;
		this.self.createMessage(msg.channel.id, `Stopped bumping`);
		return;
	}
	index = 0;
	this.self.createMessage(msg.channel.id, `Started bumping`);
	interval = setInterval(() => {
		this.log.log(`${bump[index]}`, 'tbump');
		this.self.createMessage(msg.channel.id, `${bump[index]}`);
		index++;
		if(index >= bump.length){
			index = 0;
		}
	}, 1860000);
  });
}
<commit_msg>Delete tbump.js<commit_after><|endoftext|>


<commit_before>var StompParse = require('../lib/stomp_parse').StompParse;
var util = require('util');

describe('When parsing a frame', function() {

  describe('It will need to parse a command from a buffer', function() {
    var stomp_parse;
    var data;

    beforeEach(function () {
      stomp_parse = new StompParse();
      var data_string = 'CONNECTED\nsession-id:test\n\n\0';
      data = Buffer(data_string, encoding='utf8');
    });

    it('should return a string when extracting a command', function() {
      var command = stomp_parse.extract_command(data);
      expect(command).toEqual('CONNECTED');
    });

    it('should return an object when extracting headers', function() {
      var headers = stomp_parse.extract_headers(data);
      expect(typeof(headers)).toBe('object');
    });
  });

  describe('It will need to parse the headers from the remainder of the buffer', function() {
    var stomp_parse;
    var data;

    beforeEach(function () {
      stomp_parse = new StompParse();
      var data_string = 'session-id:test\n\n\0';
      data = Buffer(data_string, encoding='utf8');
    });

    it('should have length of the headers as a string', function() {
      var header_data = stomp_parse.extract_headers(data);
      var expected_header = 'session-id:test';
      expect(header_data.length).toEqual(expected_header.length);
    });

    it('should have a key in the header object', function() {
      var header_data = stomp_parse.extract_headers(data);
      expect('session-id' in header_data.headers).toBeTruthy();
    });

    it('should have a value in the header object', function() {
      var header_data = stomp_parse.extract_headers(data);
      expect(header_data.headers['session-id']).toEqual('test');
    });
  });

  describe('It will need to parse and return a whole frame', function() {
    var stomp_parse;
    var data;

    beforeEach(function () {
      stomp_parse = new StompParse();
      body = 'test body';
      content_length = body.length;
      var data_string = util.format('CONNECTED\nsession-id:test\ncontent-length:%d\n\n%s\0', content_length, body);
      data = Buffer(data_string, encoding='utf8');
    });

    it('should get an object', function() {
      var full_frame = stomp_parse.parse_frame(data);
      expect(typeof(full_frame)).toBe('object');
    });

    it('should return null if argument is not defined', function() {
      var null_frame = stomp_parse.parse_frame();
      expect(null_frame).toBe(null);
    });

    it('should call StompParse.extract_command with a data buffer', function() {
      spyOn(stomp_parse, 'extract_command');
      var full_frame = stomp_parse.parse_frame(data);
      expect(stomp_parse.extract_command).toHaveBeenCalledWith(data);
    });

    it('should call StompParse.extract_headers with a data buffer', function() {
      spyOn(stomp_parse, 'extract_headers');
      var command = stomp_parse.extract_command(data);
      var new_data = data.slice(command.length + 1, data.length);
      var full_frame = stomp_parse.parse_frame(data);
      expect(stomp_parse.extract_headers).toHaveBeenCalledWith(new_data);
    });

    it('should return an object named Frame', function() {
      var full_frame = stomp_parse.parse_frame(data);
      expect(full_frame.constructor.name).toBe('Frame');
    });

    it('should have a body in the data', function() {
      var full_frame = stomp_parse.parse_frame(data);
      expect('body' in full_frame).toBeTruthy();
    });

    it('should have "bytes_message" header if "content-length" specified in the headers', function() {
      var full_frame = stomp_parse.parse_frame(data);
      expect('bytes_message' in full_frame.headers).toBeTruthy();
    });

  });

});
<commit_msg>Fix string (node < v5 doesn't have util.format).<commit_after>var StompParse = require('../lib/stomp_parse').StompParse;

describe('When parsing a frame', function() {

  describe('It will need to parse a command from a buffer', function() {
    var stomp_parse;
    var data;

    beforeEach(function () {
      stomp_parse = new StompParse();
      var data_string = 'CONNECTED\nsession-id:test\n\n\0';
      data = Buffer(data_string, encoding='utf8');
    });

    it('should return a string when extracting a command', function() {
      var command = stomp_parse.extract_command(data);
      expect(command).toEqual('CONNECTED');
    });

    it('should return an object when extracting headers', function() {
      var headers = stomp_parse.extract_headers(data);
      expect(typeof(headers)).toBe('object');
    });
  });

  describe('It will need to parse the headers from the remainder of the buffer', function() {
    var stomp_parse;
    var data;

    beforeEach(function () {
      stomp_parse = new StompParse();
      var data_string = 'session-id:test\n\n\0';
      data = Buffer(data_string, encoding='utf8');
    });

    it('should have length of the headers as a string', function() {
      var header_data = stomp_parse.extract_headers(data);
      var expected_header = 'session-id:test';
      expect(header_data.length).toEqual(expected_header.length);
    });

    it('should have a key in the header object', function() {
      var header_data = stomp_parse.extract_headers(data);
      expect('session-id' in header_data.headers).toBeTruthy();
    });

    it('should have a value in the header object', function() {
      var header_data = stomp_parse.extract_headers(data);
      expect(header_data.headers['session-id']).toEqual('test');
    });
  });

  describe('It will need to parse and return a whole frame', function() {
    var stomp_parse;
    var data;

    beforeEach(function () {
      stomp_parse = new StompParse();
      body = 'test body';
      content_length = body.length;
      var data_string = 'CONNECTED\nsession-id:test\ncontent-length:' + content_length +'\n\n'+ body + '\0';
      data = Buffer(data_string, encoding='utf8');
    });

    it('should get an object', function() {
      var full_frame = stomp_parse.parse_frame(data);
      expect(typeof(full_frame)).toBe('object');
    });

    it('should return null if argument is not defined', function() {
      var null_frame = stomp_parse.parse_frame();
      expect(null_frame).toBe(null);
    });

    it('should call StompParse.extract_command with a data buffer', function() {
      spyOn(stomp_parse, 'extract_command');
      var full_frame = stomp_parse.parse_frame(data);
      expect(stomp_parse.extract_command).toHaveBeenCalledWith(data);
    });

    it('should call StompParse.extract_headers with a data buffer', function() {
      spyOn(stomp_parse, 'extract_headers');
      var command = stomp_parse.extract_command(data);
      var new_data = data.slice(command.length + 1, data.length);
      var full_frame = stomp_parse.parse_frame(data);
      expect(stomp_parse.extract_headers).toHaveBeenCalledWith(new_data);
    });

    it('should return an object named Frame', function() {
      var full_frame = stomp_parse.parse_frame(data);
      expect(full_frame.constructor.name).toBe('Frame');
    });

    it('should have a body in the data', function() {
      var full_frame = stomp_parse.parse_frame(data);
      expect('body' in full_frame).toBeTruthy();
    });

    it('should have "bytes_message" header if "content-length" specified in the headers', function() {
      var full_frame = stomp_parse.parse_frame(data);
      expect('bytes_message' in full_frame.headers).toBeTruthy();
    });

  });

});
<|endoftext|>


<commit_before>'use strict'
var http = require('http')
var fs = require('fs')
var Level = require('level')
var Sublevel = require('level-sublevel/bytewise')
var Blobs = require('multiblob')
var pl = require('pull-level')
var path = require('path')
var MuxRpc = require('muxrpc')
var WS = require('pull-ws-server')
var pull = require('pull-stream')
var JSONDL = require('pull-serializer')
var BlobsHttp = require('./blobs-http')
var mkdirp = require('mkdirp')
var Ecstatic = require('ecstatic')

var Auth = require('./ticket-auth')

var Tiny = require('tiny-route')

var config = require('rc')('eda-grads', {
  path: path.join(process.env.HOME, 'storage/.eda-grads'),
  port: 8000,
})

var merge = require('deep-merge')(function (a, b, k) {
  return b != null ? b : a
})

exports = module.exports = function (config) {

  mkdirp.sync(config.path)

  var db = Sublevel(Level(path.join(config.path, 'db'), {valueEncoding: 'json'}))
  var blobs = Blobs({dir: path.join(config.path, 'blobs'), alg: 'sha256'})
  var auth = Auth(db.sublevel('auth'))

  return {
    put: function (opts, cb) {
      db.get(opts.key, function (err, _value) {
        if(err || !_value) db.put(opts.key, opts.value || {}, cb)
        else {
          db.put(opts.key, merge(_value, opts.value) || {}, cb)
        }
      })
    },
    get: function (key, cb) {
      db.get(key.key || key, cb)
    },
    read: function (opts) {
      console.log(this)
      return pl.read(db)
    },
    blobs: blobs,
    db: db,
    auth: auth,
    whoami: function () {
      return this.id
    }
  }
}

exports.manifest = {
  get: 'async',
  put: 'async',
  read: 'source',
  blobs: {
    get: 'source',
    add: 'sink',
    ls: 'source'
  },
  auth: {
    create: 'async',
    redeem: 'async',
    check: 'async',
    dump: 'source'
  },
  whoami: 'sync'
}

var index = path.join(__dirname, 'static/index.html')

if(!module.parent) {
  if(!process.argv[2]) {
    fs.writeFileSync(
      path.join(__dirname, 'manifest.json'),
      JSON.stringify(exports.manifest, null, 2)
    )

    var api = exports(config)

    var server = http.createServer(require('stack')(

      Ecstatic(path.join(__dirname, 'static')),

      Tiny.get(/^\/redeem\/([0-9a-f]+)/, function (req, res, next) {
        api.auth.redeem(req.params[0], function (err, cookie) {
          if(err) return next(err)
          console.log('code redeemed', cookie)
          res.setHeader('Set-Cookie', cookie)
          res.setHeader('Location', '/')
          res.statusCode = 303
          res.end()
        })
      }),

      //check cookies, and authorize this connection (or not)
      function (req, res, next) {
        api.auth.check(req.headers.cookie, function (err, resource) {
          req.access = resource; next()
        })
      },

//      function (req, res, next) {
//        if(req.method !== 'GET') return next()
//        if(req.url == '/') fs.createReadStream(index).pipe(res)
//        else next()
//      },
//
      //return list of the current access rights. (for debugging)
      Tiny.get(/^\/whoami/, function (req, res, next) {
        res.end(JSON.stringify(req.access)+'\n')
      }),

      BlobsHttp(api.blobs, '/blobs')
    ))
    .listen(process.env.PORT || config.port, function () {
      console.log('listening on:', server.address())
    })

    WS.createServer({server: server}, function (ws) {
      api.auth.check(ws.headers.cookie, function (err, resource) {
        ws.access = resource
        var rpc = MuxRpc(exports.manifest, exports.manifest, JSONDL)
          (api,
            //PERMS.
            function (name, args) {
              if(name[0] !== 'put' || resource === 'admin') return //allowed
              if(name[0] === 'put') {
                if(args[0].key !== resource) {
                  console.log('permission-error', args[0].key, resource)
                  throw new Error('do not have permission to access:'+args[0].key)
                }
              }
              if(name[0] === 'auth' && resource != 'admin')
                throw new Error('only admin may access auth methods')
            },
            resource
          )
        pull(ws, rpc.createStream(), ws)
      })
    })

  }
  else
    require('muxrpcli')
      (process.argv.slice(2), exports.manifest, exports(config))
}

<commit_msg>trying without symlink<commit_after>'use strict'
var http = require('http')
var fs = require('fs')
var Level = require('level')
var Sublevel = require('level-sublevel/bytewise')
var Blobs = require('multiblob')
var pl = require('pull-level')
var path = require('path')
var MuxRpc = require('muxrpc')
var WS = require('pull-ws-server')
var pull = require('pull-stream')
var JSONDL = require('pull-serializer')
var BlobsHttp = require('./blobs-http')
var mkdirp = require('mkdirp')
var Ecstatic = require('ecstatic')

var Auth = require('./ticket-auth')

var Tiny = require('tiny-route')

var config = require('rc')('eda-grads', {
  path: path.join(process.env.HOME, '.eda-grads'),
  port: 8000,
})

var merge = require('deep-merge')(function (a, b, k) {
  return b != null ? b : a
})

exports = module.exports = function (config) {

  mkdirp.sync(config.path)

  var db = Sublevel(Level(path.join(config.path, 'db'), {valueEncoding: 'json'}))
  var blobs = Blobs({dir: path.join(config.path, 'blobs'), alg: 'sha256'})
  var auth = Auth(db.sublevel('auth'))

  return {
    put: function (opts, cb) {
      db.get(opts.key, function (err, _value) {
        if(err || !_value) db.put(opts.key, opts.value || {}, cb)
        else {
          db.put(opts.key, merge(_value, opts.value) || {}, cb)
        }
      })
    },
    get: function (key, cb) {
      db.get(key.key || key, cb)
    },
    read: function (opts) {
      console.log(this)
      return pl.read(db)
    },
    blobs: blobs,
    db: db,
    auth: auth,
    whoami: function () {
      return this.id
    }
  }
}

exports.manifest = {
  get: 'async',
  put: 'async',
  read: 'source',
  blobs: {
    get: 'source',
    add: 'sink',
    ls: 'source'
  },
  auth: {
    create: 'async',
    redeem: 'async',
    check: 'async',
    dump: 'source'
  },
  whoami: 'sync'
}

var index = path.join(__dirname, 'static/index.html')

if(!module.parent) {
  if(!process.argv[2]) {
    fs.writeFileSync(
      path.join(__dirname, 'manifest.json'),
      JSON.stringify(exports.manifest, null, 2)
    )

    var api = exports(config)

    var server = http.createServer(require('stack')(

      Ecstatic(path.join(__dirname, 'static')),

      Tiny.get(/^\/redeem\/([0-9a-f]+)/, function (req, res, next) {
        api.auth.redeem(req.params[0], function (err, cookie) {
          if(err) return next(err)
          console.log('code redeemed', cookie)
          res.setHeader('Set-Cookie', cookie)
          res.setHeader('Location', '/')
          res.statusCode = 303
          res.end()
        })
      }),

      //check cookies, and authorize this connection (or not)
      function (req, res, next) {
        api.auth.check(req.headers.cookie, function (err, resource) {
          req.access = resource; next()
        })
      },

//      function (req, res, next) {
//        if(req.method !== 'GET') return next()
//        if(req.url == '/') fs.createReadStream(index).pipe(res)
//        else next()
//      },
//
      //return list of the current access rights. (for debugging)
      Tiny.get(/^\/whoami/, function (req, res, next) {
        res.end(JSON.stringify(req.access)+'\n')
      }),

      BlobsHttp(api.blobs, '/blobs')
    ))
    .listen(process.env.PORT || config.port, function () {
      console.log('listening on:', server.address())
    })

    WS.createServer({server: server}, function (ws) {
      api.auth.check(ws.headers.cookie, function (err, resource) {
        ws.access = resource
        var rpc = MuxRpc(exports.manifest, exports.manifest, JSONDL)
          (api,
            //PERMS.
            function (name, args) {
              if(name[0] !== 'put' || resource === 'admin') return //allowed
              if(name[0] === 'put') {
                if(args[0].key !== resource) {
                  console.log('permission-error', args[0].key, resource)
                  throw new Error('do not have permission to access:'+args[0].key)
                }
              }
              if(name[0] === 'auth' && resource != 'admin')
                throw new Error('only admin may access auth methods')
            },
            resource
          )
        pull(ws, rpc.createStream(), ws)
      })
    })

  }
  else
    require('muxrpcli')
      (process.argv.slice(2), exports.manifest, exports(config))
}

<|endoftext|>


<commit_before>const decorateEventListener = require('./util/decorateEventListener')
const ensureConfigHasEntry = require('./util/ensureConfigHasEntry')
const ensureConfigHasPlugin = require('./util/ensureConfigHasPlugin')
const findForTarget = require('./util/findForTarget')
const getEntryOutputPathFromStats = require('./util/getEntryOutputPathFromStats')
const getOutputPublicPath = require('./util/getOutputPublicPath')
const moduleExists = require('./util/moduleExists')
const requireDefault = require('./util/requireDefault')
const resolveWith = require('./util/resolveWith')

const {
  Runtime,
  exportContainerRuntime
} = require('./util/container')

const BUNDLE_AVAILABLE_EVENT = 'bundle-available'
const CONTAINER_PROCESS_TITLE = 'udk-ctnr'
const DEV_CONTAINER_CONFIG_NAMES = [
  'udk.container',
  'udkfile',
  'udk.config',
]
const TOP_MODULE_ENTRIES = [
  'source-map-support'
]
const WEBPACK_CONFIG_NAMES = [
  'webpack.config',
  'webpackfile'
]

exportContainerRuntime(module, {
  getConfigFallbackNames () {
    return DEV_CONTAINER_CONFIG_NAMES
  },
  getConfigDefaulter (configPath) {
    const defaulter = Runtime.getConfigDefaulter.call(this, configPath)

    defaulter.set('autoRestart', false)
    defaulter.set('bundleAvailableEvent', BUNDLE_AVAILABLE_EVENT)
    defaulter.set('hmr', 'call', this.parseConfigHMR.bind(this))
    defaulter.set('metafiles', ['package.json'])
    defaulter.set('processTitle', CONTAINER_PROCESS_TITLE)
    defaulter.set('statsOptions', 'call', this.parseConfigStatsOptions.bind(this))
    defaulter.set('topModuleEntries', TOP_MODULE_ENTRIES)
    defaulter.set('webpackConfig', 'call', this.parseConfigWebpackConfig.bind(this))

    defaulter.set('jsonifyCompilerStats', function (stats) {
      return stats.toJson(Object.assign({}, this.statsOptions, this.statsToJsonOptions))
    })

    defaulter.set('printCompilerError', function (err) {
      this.logger && this.logger.error(err)
    })

    defaulter.set('printCompilerStats', function (stats) {
      this.logger && this.logger.info(this.stringifyCompilerStats(stats))
    })

    defaulter.set('stringifyCompilerStats', function (stats) {
      return stats.toString(Object.assign({}, this.statsOptions, this.statsToStringOptions))
    })

    return defaulter
  },
  getWatchpackOptionFiles (container) {
    return Runtime.getWatchpackOptionFiles.call(this, container).concat(
      container.config.webpackConfig || [],
      container.config.metafiles || []
    )
  },
  getWebpackConfig (webpackConfig) {
    if (typeof webpackConfig === 'string') {
      webpackConfig = require(webpackConfig)
    }

    if (Array.isArray(webpackConfig)) {
      webpackConfig = webpackConfig.map((cfg) => {
        if (typeof cfg === 'string') {
          cfg = require(cfg)
        }

        return cfg
      })
    }

    return webpackConfig
  },
  parseConfigHMR (value, config) {
    if (typeof value === 'undefined') {
      value = true
    }

    if (typeof value === 'string') {
      value = {path: value}
    }

    if (value) {
      value = Object.assign({
        hotPollInterval: 1000,
      }, value)

      value.hotMiddleware = Object.assign({
        log: config.logger.info.bind(config.logger),
        path: '/__webpack_hmr'
      }, value.hotMiddleware)

      value.hotMiddlewareClient = Object.assign({}, value.hotMiddlewareClient, {
        path: value.hotMiddleware.path
      })

      value.plugin = Object.assign({}, value.plugin)
    }

    return value
  },
  parseConfigStatsOptions (value, config) {
    if (~['string', 'boolean'].indexOf(typeof value)) {
      return value
    }

    return Object.assign({source: false}, value)
  },
  parseConfigWebpackConfig (value, config) {
    if (!value || typeof value === 'string') {
      value = resolveWith(value, {
        context: config.context,
        fallback: WEBPACK_CONFIG_NAMES
      })
    }

    if (Array.isArray(value)) {
      value = webpackConfig = resolveWith(value, {
        context: config.context
      })
    }

    return value
  },
  prepareWebpackConfig (config, webpackConfig) {
    const nodeConfigs = findForTarget.node(webpackConfig, {many: true})

    const {
      autoRestart,
      // beforeRequire,
      bundleAvailableEvent,
      requestDecorator
    } = config

    ;[].concat(webpackConfig).forEach((obj) => {
      if (obj && !obj.plugins) {
        obj.plugins = []
      }
    })

    nodeConfigs.forEach((nodeConfig) => {
      nodeConfig.plugins.push(function () {
        let bundleMod

        this.plugin('done', (stats) => {
          if (!stats.hasErrors()) {
            if (autoRestart && bundleMod) {
              bundleMod.close && bundleMod.close()
              bundleMod = undefined
            }

            if (!bundleMod) {
              const entryOutputPath = getEntryOutputPathFromStats(stats)

              if (moduleExists(entryOutputPath)) {
                // beforeRequire && beforeRequire(entryOutputPath, stats)

                // Fixture to that babel-polyfill doesn't throw error
                // "only one instance of babel-polyfill is allowed""
                if (global._babelPolyfill) {
                  global._babelPolyfill = false
                }

                bundleMod = requireDefault(entryOutputPath, {cache: false})
                // try {
                //   serverMod = requireES6Module(serverEntry)
                // } catch (e) {
                //   onServerError && onServerError(e)
                // }

                requestDecorator && requestDecorator(bundleMod, stats)

                this.applyPlugins(bundleAvailableEvent, bundleMod, stats)
              }
            }
          }
        })
      })
    })

    this.tryPrepareWebpackStatsInjection(config, webpackConfig)
    this.tryPrepareServeWebAssets(config, webpackConfig)
    this.tryPrepareExtremeHMR(config, webpackConfig)

    config.prepareWebpackConfig && config.prepareWebpackConfig(webpackConfig)
  },
  shutDownContainer (proc, config, event, ...args) {
    config.compilerWatcher && config.compilerWatcher.close()

    Runtime.shutDownContainer.call(this, proc, config, event, ...args)
  },
  shutUpContainer (proc, config) {
    Runtime.shutUpContainer.call(this, proc, config)

    this.debug('get webpack config')

    const webpackConfig = this.getWebpackConfig(config.webpackConfig)

    this.debug('prepare webpack config')

    this.prepareWebpackConfig(config, webpackConfig)

    this.debug('create compiler')

    const compiler = require('./udk')(webpackConfig)

    this.debug('prepare compiler')

    config.prepareCompiler && config.prepareCompiler(compiler)

    config.onCompilerWatchRun && compiler.plugin('watch-run', config.onCompilerWatchRun.bind(config))
    config.onCompilerBeforeCompile && compiler.plugin('before-compile', config.onCompilerBeforeCompile.bind(config))
    config.onCompilerCompile && compiler.plugin('compile', config.onCompilerCompile.bind(config))
    config.onCompilerThisCompilation && compiler.plugin('this-compilation', config.onCompilerThisCompilation.bind(config))
    config.onCompilerCompilation && compiler.plugin('compilation', config.onCompilerCompilation.bind(config))
    config.onCompilerMake && compiler.plugin('make', config.onCompilerMake.bind(config))
    config.onCompilerAfterCompile && compiler.plugin('after-compile', config.onCompilerAfterCompile.bind(config))
    config.onCompilerShouldEmit && compiler.plugin('should-emit', config.onCompilerShouldEmit.bind(config))
    config.onCompilerNeedAdditionalPass && compiler.plugin('need-additional-pass', config.onCompilerNeedAdditionalPass.bind(config))
    config.onCompilerEmit && compiler.plugin('emit', config.onCompilerEmit.bind(config))
    config.onCompilerAfterEmit && compiler.plugin('after-emit', config.onCompilerAfterEmit.bind(config))
    config.onCompilerDone && compiler.plugin('done', config.onCompilerDone.bind(config))
    config.onCompilerFailed && compiler.plugin('failed', config.onCompilerFailed.bind(config))
    config.onCompilerInvalid && compiler.plugin('invalid', config.onCompilerInvalid.bind(config))
    config.onCompilerWatchClose && compiler.plugin('watch-close', config.onCompilerWatchClose.bind(config))

    config.compiler = compiler

    config.compilerWatcher = compiler.watch(this.watchOptions, (err, stats) => {
      this.debug('compiler watching')

      err && config.printCompilerError && config.printCompilerError(err)
      stats && config.printCompilerStats && config.printCompilerStats(stats)

      config.onCompilerWatching && config.onCompilerWatching(err, stats)
    })
  },
  tryPrepareExtremeHMR (config, webpackConfig) {
    if (!config.hmr) {
      return
    }

    const dbug = this.debug

    const {
      autoRestart,
      hmr,
      bundleAvailableEvent,
      topModuleEntries,
    } = config

    const hmrPluginNode = Object.assign({}, hmr.plugin, hmr.pluginNode)
    const hmrPluginWeb = Object.assign({}, hmr.plugin, hmr.pluginWeb)

    const nodeConfigs = findForTarget.node(webpackConfig, {many: true})
    const webConfigs = findForTarget.web(webpackConfig, {many: true})

    ensureConfigHasPlugin(webpackConfig, 'webpack/lib/NoEmitOnErrorsPlugin')

    ensureConfigHasPlugin(webConfigs, 'webpack/lib/HotModuleReplacementPlugin', hmrPluginWeb)

    if (!autoRestart) {
      ensureConfigHasPlugin(nodeConfigs, 'webpack/lib/HotModuleReplacementPlugin', hmrPluginNode)
      ensureConfigHasEntry(nodeConfigs, 'webpack/hot/poll', hmr.hotPollInterval)
    }

    webConfigs.forEach((webConfig) => {
      const {name} = webConfig
      const hotMiddlewareOptions = Object.assign({}, hmr.hotMiddlewareClient, {name})

      ensureConfigHasEntry(webConfig, 'webpack-hot-middleware/client', hotMiddlewareOptions, topModuleEntries)
    })

    nodeConfigs.forEach((nodeConfig) => {
      nodeConfig.plugins.push(function () {
        let hotMiddleware

        this.plugin(bundleAvailableEvent, (nodeBundle) => {
          decorateEventListener('request', nodeBundle, (listener) => {
            dbug('decorate %s with webpack-hot-middleware', nodeConfig.name)

            if (!hotMiddleware) {
              dbug('create webpack-hot-middleware %O', hmr.hotMiddleware)

              hotMiddleware = require('webpack-hot-middleware')(config.compiler, hmr.hotMiddleware)
            }

            return (req, res) => {
              hotMiddleware(req, res, () => listener(req, res))
            }
          })
        })
      })
    })
  },
  tryPrepareServeWebAssets (config, webpackConfig) {
    const dbug = this.debug
    const {bundleAvailableEvent} = config

    const nodeConfigs = findForTarget.node(webpackConfig, {many: true})
    const webConfigs = findForTarget.web(webpackConfig, {many: true})

    nodeConfigs.forEach((nodeConfig) => {
      nodeConfig.plugins.push(function () {
        let serveStatic = []

        this.plugin(bundleAvailableEvent, (nodeBundle) => {
          webConfigs.forEach((webConfig, index) => {
            const publicPath = getOutputPublicPath(webConfig, {startsSlash: true, endsSlash: false})

            decorateEventListener('request', nodeBundle, (listener) => {
              dbug('decorate %s to service %s assets at %o', nodeConfig.name, webConfig.name, publicPath)

              if (!serveStatic[index]) {
                dbug('create serve-static %o', webConfig.output.path)

                serveStatic[index] = require('serve-static')(webConfig.output.path)
              }

              return (req, res) => {
                if (req.url && req.url.startsWith(publicPath)) {
                  const originalUrl = req.url

                  if (originalUrl !== '/') {
                    req.url = originalUrl.substring(publicPath.length)
                  }

                  return serveStatic[index](req, res, () => {
                    req.url = originalUrl

                    listener(req, res)
                  })
                }

                listener(req, res)
              }
            })
          })
        })
      })
    })
  },
  tryPrepareWebpackStatsInjection (config, webpackConfig) {
    const dbug = this.debug
    const {bundleAvailableEvent} = config
    const webpackStats = {}

    const nodeConfigs = findForTarget.node(webpackConfig, {many: true})
    const webConfigs = findForTarget.web(webpackConfig, {many: true})

    webConfigs.forEach((webConfig) => {
      webConfig.plugins.push(function () {
        this.plugin('done', (stats) => {
          dbug('update %s stats', webConfig.name)

          const statsJson = config.jsonifyCompilerStats(stats)

          webpackStats[webConfig.name] = statsJson
        })
      })
    })

    nodeConfigs.forEach((nodeConfig) => {
      nodeConfig.plugins.push(function () {
        this.plugin(bundleAvailableEvent, (nodeBundle) => {
          decorateEventListener('request', nodeBundle, (listener) => {
            dbug('decorate %s to inject webpack stats', nodeConfig.name)

            return (req, res) => {
              dbug('inject webpack stats %o', Object.keys(webpackStats))

              if (config.injectWebpackStats) {
                config.injectWebpackStats(webpackStats, req, res)
              } else {
                res.locals = res.locals || Object.create(null)
                res.locals.webpackStats = Object.assign({}, res.locals.webpackStats, webpackStats)
              }

              listener(req, res)
            }
          })
        })
      })
    })
  }
})
<commit_msg>Dev container: require node bundles in try/catch block<commit_after>const decorateEventListener = require('./util/decorateEventListener')
const ensureConfigHasEntry = require('./util/ensureConfigHasEntry')
const ensureConfigHasPlugin = require('./util/ensureConfigHasPlugin')
const findForTarget = require('./util/findForTarget')
const getEntryOutputPathFromStats = require('./util/getEntryOutputPathFromStats')
const getOutputPublicPath = require('./util/getOutputPublicPath')
const moduleExists = require('./util/moduleExists')
const requireDefault = require('./util/requireDefault')
const resolveWith = require('./util/resolveWith')

const {
  Runtime,
  exportContainerRuntime
} = require('./util/container')

const BUNDLE_AVAILABLE_EVENT = 'bundle-available'
const CONTAINER_PROCESS_TITLE = 'udk-ctnr'
const DEV_CONTAINER_CONFIG_NAMES = [
  'udk.container',
  'udkfile',
  'udk.config',
]
const TOP_MODULE_ENTRIES = [
  'source-map-support'
]
const WEBPACK_CONFIG_NAMES = [
  'webpack.config',
  'webpackfile'
]

exportContainerRuntime(module, {
  getConfigFallbackNames () {
    return DEV_CONTAINER_CONFIG_NAMES
  },
  getConfigDefaulter (configPath) {
    const defaulter = Runtime.getConfigDefaulter.call(this, configPath)

    defaulter.set('autoRestart', false)
    defaulter.set('bundleAvailableEvent', BUNDLE_AVAILABLE_EVENT)
    defaulter.set('hmr', 'call', this.parseConfigHMR.bind(this))
    defaulter.set('metafiles', ['package.json'])
    defaulter.set('processTitle', CONTAINER_PROCESS_TITLE)
    defaulter.set('statsOptions', 'call', this.parseConfigStatsOptions.bind(this))
    defaulter.set('topModuleEntries', TOP_MODULE_ENTRIES)
    defaulter.set('webpackConfig', 'call', this.parseConfigWebpackConfig.bind(this))

    defaulter.set('jsonifyCompilerStats', function (stats) {
      return stats.toJson(Object.assign({}, this.statsOptions, this.statsToJsonOptions))
    })

    defaulter.set('printCompilerError', function (err) {
      this.logger && this.logger.error(err)
    })

    defaulter.set('printCompilerStats', function (stats) {
      this.logger && this.logger.info(this.stringifyCompilerStats(stats))
    })

    defaulter.set('stringifyCompilerStats', function (stats) {
      return stats.toString(Object.assign({}, this.statsOptions, this.statsToStringOptions))
    })

    return defaulter
  },
  getWatchpackOptionFiles (container) {
    return Runtime.getWatchpackOptionFiles.call(this, container).concat(
      container.config.webpackConfig || [],
      container.config.metafiles || []
    )
  },
  getWebpackConfig (webpackConfig) {
    if (typeof webpackConfig === 'string') {
      webpackConfig = require(webpackConfig)
    }

    if (Array.isArray(webpackConfig)) {
      webpackConfig = webpackConfig.map((cfg) => {
        if (typeof cfg === 'string') {
          cfg = require(cfg)
        }

        return cfg
      })
    }

    return webpackConfig
  },
  parseConfigHMR (value, config) {
    if (typeof value === 'undefined') {
      value = true
    }

    if (typeof value === 'string') {
      value = {path: value}
    }

    if (value) {
      value = Object.assign({
        hotPollInterval: 1000,
      }, value)

      value.hotMiddleware = Object.assign({
        log: config.logger.info.bind(config.logger),
        path: '/__webpack_hmr'
      }, value.hotMiddleware)

      value.hotMiddlewareClient = Object.assign({}, value.hotMiddlewareClient, {
        path: value.hotMiddleware.path
      })

      value.plugin = Object.assign({}, value.plugin)
    }

    return value
  },
  parseConfigStatsOptions (value, config) {
    if (~['string', 'boolean'].indexOf(typeof value)) {
      return value
    }

    return Object.assign({source: false}, value)
  },
  parseConfigWebpackConfig (value, config) {
    if (!value || typeof value === 'string') {
      value = resolveWith(value, {
        context: config.context,
        fallback: WEBPACK_CONFIG_NAMES
      })
    }

    if (Array.isArray(value)) {
      value = webpackConfig = resolveWith(value, {
        context: config.context
      })
    }

    return value
  },
  prepareWebpackConfig (config, webpackConfig) {
    const nodeConfigs = findForTarget.node(webpackConfig, {many: true})

    const {
      autoRestart,
      // beforeRequire,
      bundleAvailableEvent,
      requestDecorator
    } = config

    ;[].concat(webpackConfig).forEach((obj) => {
      if (obj && !obj.plugins) {
        obj.plugins = []
      }
    })

    nodeConfigs.forEach((nodeConfig) => {
      nodeConfig.plugins.push(function () {
        let bundleMod

        this.plugin('done', (stats) => {
          if (!stats.hasErrors()) {
            if (autoRestart && bundleMod) {
              bundleMod.close && bundleMod.close()
              bundleMod = undefined
            }

            if (!bundleMod) {
              const entryOutputPath = getEntryOutputPathFromStats(stats)

              if (moduleExists(entryOutputPath)) {
                // beforeRequire && beforeRequire(entryOutputPath, stats)

                // Fixture to that babel-polyfill doesn't throw error
                // "only one instance of babel-polyfill is allowed""
                if (global._babelPolyfill) {
                  global._babelPolyfill = false
                }

                try {
                  bundleMod = requireDefault(entryOutputPath, {cache: false})

                  requestDecorator && requestDecorator(bundleMod, stats)

                  this.applyPlugins(bundleAvailableEvent, bundleMod, stats)
                } catch (e) {
                  process.nextTick(() => config.logger.error(e))
                }
              }
            }
          }
        })
      })
    })

    this.tryPrepareWebpackStatsInjection(config, webpackConfig)
    this.tryPrepareServeWebAssets(config, webpackConfig)
    this.tryPrepareExtremeHMR(config, webpackConfig)

    config.prepareWebpackConfig && config.prepareWebpackConfig(webpackConfig)
  },
  shutDownContainer (proc, config, event, ...args) {
    config.compilerWatcher && config.compilerWatcher.close()

    Runtime.shutDownContainer.call(this, proc, config, event, ...args)
  },
  shutUpContainer (proc, config) {
    Runtime.shutUpContainer.call(this, proc, config)

    this.debug('get webpack config')

    const webpackConfig = this.getWebpackConfig(config.webpackConfig)

    this.debug('prepare webpack config')

    this.prepareWebpackConfig(config, webpackConfig)

    this.debug('create compiler')

    const compiler = require('./udk')(webpackConfig)

    this.debug('prepare compiler')

    config.prepareCompiler && config.prepareCompiler(compiler)

    config.onCompilerWatchRun && compiler.plugin('watch-run', config.onCompilerWatchRun.bind(config))
    config.onCompilerBeforeCompile && compiler.plugin('before-compile', config.onCompilerBeforeCompile.bind(config))
    config.onCompilerCompile && compiler.plugin('compile', config.onCompilerCompile.bind(config))
    config.onCompilerThisCompilation && compiler.plugin('this-compilation', config.onCompilerThisCompilation.bind(config))
    config.onCompilerCompilation && compiler.plugin('compilation', config.onCompilerCompilation.bind(config))
    config.onCompilerMake && compiler.plugin('make', config.onCompilerMake.bind(config))
    config.onCompilerAfterCompile && compiler.plugin('after-compile', config.onCompilerAfterCompile.bind(config))
    config.onCompilerShouldEmit && compiler.plugin('should-emit', config.onCompilerShouldEmit.bind(config))
    config.onCompilerNeedAdditionalPass && compiler.plugin('need-additional-pass', config.onCompilerNeedAdditionalPass.bind(config))
    config.onCompilerEmit && compiler.plugin('emit', config.onCompilerEmit.bind(config))
    config.onCompilerAfterEmit && compiler.plugin('after-emit', config.onCompilerAfterEmit.bind(config))
    config.onCompilerDone && compiler.plugin('done', config.onCompilerDone.bind(config))
    config.onCompilerFailed && compiler.plugin('failed', config.onCompilerFailed.bind(config))
    config.onCompilerInvalid && compiler.plugin('invalid', config.onCompilerInvalid.bind(config))
    config.onCompilerWatchClose && compiler.plugin('watch-close', config.onCompilerWatchClose.bind(config))

    config.compiler = compiler

    config.compilerWatcher = compiler.watch(this.watchOptions, (err, stats) => {
      this.debug('compiler watching')

      err && config.printCompilerError && config.printCompilerError(err)
      stats && config.printCompilerStats && config.printCompilerStats(stats)

      config.onCompilerWatching && config.onCompilerWatching(err, stats)
    })
  },
  tryPrepareExtremeHMR (config, webpackConfig) {
    if (!config.hmr) {
      return
    }

    const dbug = this.debug

    const {
      autoRestart,
      hmr,
      bundleAvailableEvent,
      topModuleEntries,
    } = config

    const hmrPluginNode = Object.assign({}, hmr.plugin, hmr.pluginNode)
    const hmrPluginWeb = Object.assign({}, hmr.plugin, hmr.pluginWeb)

    const nodeConfigs = findForTarget.node(webpackConfig, {many: true})
    const webConfigs = findForTarget.web(webpackConfig, {many: true})

    ensureConfigHasPlugin(webpackConfig, 'webpack/lib/NoEmitOnErrorsPlugin')

    ensureConfigHasPlugin(webConfigs, 'webpack/lib/HotModuleReplacementPlugin', hmrPluginWeb)

    if (!autoRestart) {
      ensureConfigHasPlugin(nodeConfigs, 'webpack/lib/HotModuleReplacementPlugin', hmrPluginNode)
      ensureConfigHasEntry(nodeConfigs, 'webpack/hot/poll', hmr.hotPollInterval)
    }

    webConfigs.forEach((webConfig) => {
      const {name} = webConfig
      const hotMiddlewareOptions = Object.assign({}, hmr.hotMiddlewareClient, {name})

      ensureConfigHasEntry(webConfig, 'webpack-hot-middleware/client', hotMiddlewareOptions, topModuleEntries)
    })

    nodeConfigs.forEach((nodeConfig) => {
      nodeConfig.plugins.push(function () {
        let hotMiddleware

        this.plugin(bundleAvailableEvent, (nodeBundle) => {
          decorateEventListener('request', nodeBundle, (listener) => {
            dbug('decorate %s with webpack-hot-middleware', nodeConfig.name)

            if (!hotMiddleware) {
              dbug('create webpack-hot-middleware %O', hmr.hotMiddleware)

              hotMiddleware = require('webpack-hot-middleware')(config.compiler, hmr.hotMiddleware)
            }

            return (req, res) => {
              hotMiddleware(req, res, () => listener(req, res))
            }
          })
        })
      })
    })
  },
  tryPrepareServeWebAssets (config, webpackConfig) {
    const dbug = this.debug
    const {bundleAvailableEvent} = config

    const nodeConfigs = findForTarget.node(webpackConfig, {many: true})
    const webConfigs = findForTarget.web(webpackConfig, {many: true})

    nodeConfigs.forEach((nodeConfig) => {
      nodeConfig.plugins.push(function () {
        let serveStatic = []

        this.plugin(bundleAvailableEvent, (nodeBundle) => {
          webConfigs.forEach((webConfig, index) => {
            const publicPath = getOutputPublicPath(webConfig, {startsSlash: true, endsSlash: false})

            decorateEventListener('request', nodeBundle, (listener) => {
              dbug('decorate %s to service %s assets at %o', nodeConfig.name, webConfig.name, publicPath)

              if (!serveStatic[index]) {
                dbug('create serve-static %o', webConfig.output.path)

                serveStatic[index] = require('serve-static')(webConfig.output.path)
              }

              return (req, res) => {
                if (req.url && req.url.startsWith(publicPath)) {
                  const originalUrl = req.url

                  if (originalUrl !== '/') {
                    req.url = originalUrl.substring(publicPath.length)
                  }

                  return serveStatic[index](req, res, () => {
                    req.url = originalUrl

                    listener(req, res)
                  })
                }

                listener(req, res)
              }
            })
          })
        })
      })
    })
  },
  tryPrepareWebpackStatsInjection (config, webpackConfig) {
    const dbug = this.debug
    const {bundleAvailableEvent} = config
    const webpackStats = {}

    const nodeConfigs = findForTarget.node(webpackConfig, {many: true})
    const webConfigs = findForTarget.web(webpackConfig, {many: true})

    webConfigs.forEach((webConfig) => {
      webConfig.plugins.push(function () {
        this.plugin('done', (stats) => {
          dbug('update %s stats', webConfig.name)

          const statsJson = config.jsonifyCompilerStats(stats)

          webpackStats[webConfig.name] = statsJson
        })
      })
    })

    nodeConfigs.forEach((nodeConfig) => {
      nodeConfig.plugins.push(function () {
        this.plugin(bundleAvailableEvent, (nodeBundle) => {
          decorateEventListener('request', nodeBundle, (listener) => {
            dbug('decorate %s to inject webpack stats', nodeConfig.name)

            return (req, res) => {
              dbug('inject webpack stats %o', Object.keys(webpackStats))

              if (config.injectWebpackStats) {
                config.injectWebpackStats(webpackStats, req, res)
              } else {
                res.locals = res.locals || Object.create(null)
                res.locals.webpackStats = Object.assign({}, res.locals.webpackStats, webpackStats)
              }

              listener(req, res)
            }
          })
        })
      })
    })
  }
})
<|endoftext|>