<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

module.exports = TChannelOutRequest;

var assert = require('assert');
var EventEmitter = require('./lib/event_emitter');
var stat = require('./stat-tags.js');
var inherits = require('util').inherits;
var parallel = require('run-parallel');
var process = require('process');

var errors = require('./errors');
var States = require('./reqres_states');

function TChannelOutRequest(id, options) {
    /*eslint max-statements: [2, 50], complexity: [2, 25]*/
    var self = this;

    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.responseEvent = self.defineEvent('response');
    self.finishEvent = self.defineEvent('finish');

    // TODO perhaps these ought not be options
    assert(options.channel, 'channel required');
    assert(options.peer, 'peer required');
    assert(id, 'id is required');

    self.retryCount = options.retryCount || 0;
    self.channel = options.channel;
    self.peer = options.peer;
    self.logical = options.logical || false;
    self.parent = options.parent || null;
    self.hasNoParent = options.hasNoParent || false;

    self.remoteAddr = options.remoteAddr || '';
    self.timeout = options.timeout || 0;
    self.tracing = options.tracing || null;
    self.serviceName = options.serviceName || '';
    self.callerName = options.headers && options.headers.cn || '';
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.forwardTrace = options.forwardTrace || false;

    // All self requests have id 0
    self.operations = null;
    self.timeHeapHandle = null;
    self.id = id;
    self.state = States.Initial;
    self.start = 0;
    self.end = 0;
    self.streamed = false;
    self.arg1 = null;
    self.endpoint = '';
    self.span = null;
    self.err = null;
    self.res = null;

    // set for requests created on draining connections
    self.drained = false;
    self.drainReason = '';

    if (options.channel.tracer && !self.forwardTrace) {
        // new span with new ids
        self.setupTracing(options);
    }
}

inherits(TChannelOutRequest, EventEmitter);

TChannelOutRequest.prototype.type = 'tchannel.outgoing-request';

TChannelOutRequest.prototype.setupTracing = function setupTracing(options) {
    var self = this;

    self.span = options.channel.tracer.setupNewSpan({
        outgoing: true,
        parentSpan: options.parent && options.parent.span,
        hasNoParent: options.hasNoParent,
        spanid: null,
        traceid: null,
        parentid: null,
        flags: options.trace ? 1 : 0,
        remoteName: self.remoteAddr,
        serviceName: self.serviceName,
        name: '' // fill this in later
    });

    self.tracing = self.span.getTracing();
};

TChannelOutRequest.prototype._sendCallRequest = function _sendCallRequest(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallRequest'
    });
};

TChannelOutRequest.prototype._sendCallRequestCont = function _sendCallRequestCont(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallRequestCont'
    });
};

TChannelOutRequest.prototype.emitPerAttemptErrorStat =
function emitPerAttemptErrorStat(err) {
    var self = this;

    if (err.isErrorFrame) {
        self.channel.emitFastStat(
            'tchannel.outbound.calls.per-attempt.system-errors',
            'counter',
            1,
            new stat.OutboundCallsSystemErrorsTags(
                self.serviceName,
                self.callerName,
                self.endpoint,
                err.codeName,
                self.retryCount
            )
        );
    } else {
        self.channel.emitFastStat(
            'tchannel.outbound.calls.per-attempt.operational-errors',
            'counter',
            1,
            new stat.OutboundCallsPerAttemptOperationalErrorsTags(
                self.serviceName,
                self.callerName,
                self.endpoint,
                err.type || 'unknown',
                self.retryCounts
            )
        );
    }
};

TChannelOutRequest.prototype.emitPerAttemptResponseStat =
function emitPerAttemptResponseStat(res) {
    var self = this;

    if (!res.ok) {
        self.channel.emitFastStat(
            'tchannel.outbound.calls.per-attempt.app-errors',
            'counter',
            1,
            new stat.OutboundCallsPerAttemptAppErrorsTags(
                self.serviceName,
                self.callerName,
                self.endpoint,
                'unknown',
                self.retryCount
            )
        );
    // Only emit success if peer-to-peer request or relay
    } else if (self.logical === false) {
        self.channel.emitFastStat(
            'tchannel.outbound.calls.success',
            'counter',
            1,
            new stat.OutboundCallsSuccessTags(
                self.serviceName,
                self.callerName,
                self.endpoint
            )
        );
    }
};

TChannelOutRequest.prototype.emitPerAttemptLatency =
function emitPerAttemptLatency() {
    var self = this;

    var latency = self.end - self.start;

    self.channel.emitFastStat(
        'tchannel.outbound.calls.per-attempt-latency',
        'timing',
        latency,
        new stat.OutboundCallsPerAttemptLatencyTags(
            self.serviceName,
            self.callerName,
            self.endpoint,
            self.remoteAddr,
            self.retryCount
        )
    );
};

TChannelOutRequest.prototype.emitError = function emitError(err) {
    var self = this;

    if (self.end) {
        self.channel.logger.warn('Unexpected error after end for OutRequest', {
            serviceName: self.serviceName,
            endpoint: self.endpoint,
            socketRemoteAddr: self.remoteAddr,
            callerName: self.callerName,
            oldError: self.err,
            oldResponse: !!self.res,
            error: err
        });
    } else {
        self.end = self.channel.timers.now();
    }

    self.err = err;
    self.emitPerAttemptLatency();
    self.emitPerAttemptErrorStat(err);

    self.peer.invalidateScore('outreq.emitError');

    self.errorEvent.emit(self, err);
};

TChannelOutRequest.prototype.extendLogInfo = function extendLogInfo(info) {
    var self = this;

    info.outRequestId = self.id;
    info.outRequestType = self.type;
    info.outRequestState = States.describe(self.state);
    info.outRequestRemoteAddr = self.remoteAddr;
    info.serviceName = self.serviceName;
    info.outRequestErr = self.err;

    if (self.endpoint !== null) {
        info.outRequestArg1 = self.endpoint;
    } else {
        info.outRequestArg1 = String(self.arg1);
    }

    return info;
};

TChannelOutRequest.prototype.emitResponse = function emitResponse(res) {
    var self = this;

    self.peer.invalidateScore('outreq.emitResponse');

    if (self.end) {
        self.channel.logger.warn('Unexpected response after end for OutRequest', {
            serviceName: self.serviceName,
            endpoint: self.endpoint,
            socketRemoteAddr: self.remoteAddr,
            callerName: self.callerName,
            oldError: self.err,
            oldResponse: !!self.res
        });
    } else {
        self.end = self.channel.timers.now();
    }

    self.res = res;
    self.res.span = self.span;

    self.emitPerAttemptLatency();
    self.emitPerAttemptResponseStat(res);

    self.responseEvent.emit(self, res);
};

TChannelOutRequest.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;

    if (self.drained) {
        self.emitError(errors.RequestDrained({
            reason: self.drainReason
        }));
        return;
    }

    switch (self.state) {
        case States.Initial:
            self.sendCallRequestFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallRequestContFrame(parts, isLast);
            break;
        case States.Done:
            // TODO: could probably happen normally, like say if a
            // streaming request is cancelled
            self.emitError(errors.RequestFrameState({
                attempted: 'arg parts',
                state: 'Done'
            }));
            break;
        case States.Error:
            // TODO: log warn
            break;
        default:
            // TODO: log warn
            break;
    }
};

TChannelOutRequest.prototype.sendCallRequestFrame = function sendCallRequestFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.start = self.channel.timers.now();
            if (self.span) {
                self.span.annotate('cs');
            }
            self._sendCallRequest(args, isLast);
            if (isLast) {
                self.state = States.Done;
            } else {
                self.state = States.Streaming;
            }
            break;
        case States.Streaming:
            self.emitError(errors.RequestFrameState({
                attempted: 'call request',
                state: 'Streaming'
            }));
            break;
        case States.Done:
            self.emitError(errors.RequestAlreadyDone({
                attempted: 'call request'
            }));
            break;
        default:
            // TODO: log warn
            break;
    }
};

TChannelOutRequest.prototype.sendCallRequestContFrame = function sendCallRequestContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.emitError(errors.RequestFrameState({
                attempted: 'call request continuation',
                state: 'Initial'
            }));
            break;
        case States.Streaming:
            self._sendCallRequestCont(args, isLast);
            if (isLast) {
                self.state = States.Done;
            }
            break;
        case States.Done:
            self.emitError(errors.RequestAlreadyDone({
                attempted: 'call request continuation'
            }));
            break;
        default:
            // TODO: log warn
            break;
    }
};

TChannelOutRequest.prototype.sendArg1 = function sendArg1(arg1) {
    var self = this;

    if (self.drained) {
        self.emitError(errors.RequestDrained({
            reason: self.drainReason
        }));
        return self;
    }

    self.arg1 = arg1;
    self.endpoint = String(arg1);
    if (self.span) {
        self.span.name = self.endpoint;
    }

    return self;
};

TChannelOutRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;

    if (callback) {
        self.hookupCallback(callback);
    }

    if (self.drained) {
        self.emitError(errors.RequestDrained({
            reason: self.drainReason
        }));
        return self;
    }

    self.sendArg1(arg1);

    if (self.span) {
        self.span.annotateBinary('as', self.headers.as);
        self.span.annotateBinary('cn', self.callerName);
    }

    if (self.logical === false && self.retryCount === 0) {
        self.emitOutboundCallsSent();
    }

    self.sendCallRequestFrame([arg1, arg2, arg3], true);
    self.finishEvent.emit(self);
    return self;
};

TChannelOutRequest.prototype.emitOutboundCallsSent =
function emitOutboundCallsSent() {
    var self = this;

    self.channel.emitFastStat(
        'tchannel.outbound.calls.sent',
        'counter',
        1,
        new stat.OutboundCallsSentTags(
            self.serviceName,
            self.callerName,
            self.endpoint
        )
    );
};

TChannelOutRequest.prototype.hookupStreamCallback =
function hookupStreamCallback(callback) {
    var self = this;
    var called = false;

    self.errorEvent.on(onError);
    self.responseEvent.on(onResponse);

    function onError(err) {
        if (called) {
            return;
        }
        called = true;
        callback(err, null, null);
    }

    function onResponse(res) {
        if (called) {
            return;
        }
        called = true;
        callback(null, self, res);
    }

    return self;
};

TChannelOutRequest.prototype.hookupCallback =
function hookupCallback(callback) {
    var self = this;

    if (callback.canStream) {
        return self.hookupStreamCallback(callback);
    }
    var called = false;

    self.errorEvent.on(onError);
    self.responseEvent.on(onResponse);

    function onError(err) {
        if (called) {
            return;
        }
        called = true;
        callback(err, null, null);
    }

    function onResponse(res) {
        if (called) {
            return;
        }
        called = true;
        if (!res.streamed) {
            callback(null, res, res.arg2, res.arg3);
            return;
        }
        parallel({
            arg2: res.arg2.onValueReady,
            arg3: res.arg3.onValueReady
        }, compatCall);
        function compatCall(err, args) {
            callback(err, res, args.arg2, args.arg3);
        }
    }

    return self;
};

TChannelOutRequest.prototype.onTimeout = function onTimeout(now) {
    var self = this;
    var timeoutError;

    if (self.err) {
        self.channel.logger.warn('unexpected onTimeout for errored out request', {
            serviceName: self.serviceName,
            endpoint: self.endpoint,
            socketRemoteAddr: self.remoteAddr,
            callerName: self.callerName,

            oldError: self.err,
            oldResponse: !!self.res,

            time: now
        });
    }

    if (!self.res || self.res.state === States.Initial) {
        timeoutError = errors.RequestTimeoutError({
            id: self.id,
            start: self.start,
            elapsed: now - self.start,
            logical: self.logical,
            timeout: self.timeout,
            remoteAddr: self.remoteAddr
        });
        if (self.operations) {
            self.operations.checkLastTimeoutTime(now);
            self.operations.popOutReq(self.id);
        }

        process.nextTick(deferOutReqTimeoutErrorEmit);
    } else if (self.operations) {
        self.operations.checkLastTimeoutTime(now);
        self.operations.popOutReq(self.id);
    }

    function deferOutReqTimeoutErrorEmit() {
        self.emitError(timeoutError);
    }
};
<commit_msg>out_req: only mark end on last call response frame<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

module.exports = TChannelOutRequest;

var assert = require('assert');
var EventEmitter = require('./lib/event_emitter');
var stat = require('./stat-tags.js');
var inherits = require('util').inherits;
var parallel = require('run-parallel');
var process = require('process');

var errors = require('./errors');
var States = require('./reqres_states');

function TChannelOutRequest(id, options) {
    /*eslint max-statements: [2, 50], complexity: [2, 25]*/
    var self = this;

    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.responseEvent = self.defineEvent('response');
    self.finishEvent = self.defineEvent('finish');

    // TODO perhaps these ought not be options
    assert(options.channel, 'channel required');
    assert(options.peer, 'peer required');
    assert(id, 'id is required');

    self.retryCount = options.retryCount || 0;
    self.channel = options.channel;
    self.peer = options.peer;
    self.logical = options.logical || false;
    self.parent = options.parent || null;
    self.hasNoParent = options.hasNoParent || false;

    self.remoteAddr = options.remoteAddr || '';
    self.timeout = options.timeout || 0;
    self.tracing = options.tracing || null;
    self.serviceName = options.serviceName || '';
    self.callerName = options.headers && options.headers.cn || '';
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.forwardTrace = options.forwardTrace || false;

    // All self requests have id 0
    self.operations = null;
    self.timeHeapHandle = null;
    self.id = id;
    self.state = States.Initial;
    self.start = 0;
    self.end = 0;
    self.streamed = false;
    self.arg1 = null;
    self.endpoint = '';
    self.span = null;
    self.err = null;
    self.res = null;

    // set for requests created on draining connections
    self.drained = false;
    self.drainReason = '';

    if (options.channel.tracer && !self.forwardTrace) {
        // new span with new ids
        self.setupTracing(options);
    }
}

inherits(TChannelOutRequest, EventEmitter);

TChannelOutRequest.prototype.type = 'tchannel.outgoing-request';

TChannelOutRequest.prototype.setupTracing = function setupTracing(options) {
    var self = this;

    self.span = options.channel.tracer.setupNewSpan({
        outgoing: true,
        parentSpan: options.parent && options.parent.span,
        hasNoParent: options.hasNoParent,
        spanid: null,
        traceid: null,
        parentid: null,
        flags: options.trace ? 1 : 0,
        remoteName: self.remoteAddr,
        serviceName: self.serviceName,
        name: '' // fill this in later
    });

    self.tracing = self.span.getTracing();
};

TChannelOutRequest.prototype._sendCallRequest = function _sendCallRequest(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallRequest'
    });
};

TChannelOutRequest.prototype._sendCallRequestCont = function _sendCallRequestCont(args, isLast) {
    var self = this;
    throw errors.UnimplementedMethod({
        className: self.constructor.name,
        methodName: '_sendCallRequestCont'
    });
};

TChannelOutRequest.prototype.emitPerAttemptErrorStat =
function emitPerAttemptErrorStat(err) {
    var self = this;

    if (err.isErrorFrame) {
        self.channel.emitFastStat(
            'tchannel.outbound.calls.per-attempt.system-errors',
            'counter',
            1,
            new stat.OutboundCallsSystemErrorsTags(
                self.serviceName,
                self.callerName,
                self.endpoint,
                err.codeName,
                self.retryCount
            )
        );
    } else {
        self.channel.emitFastStat(
            'tchannel.outbound.calls.per-attempt.operational-errors',
            'counter',
            1,
            new stat.OutboundCallsPerAttemptOperationalErrorsTags(
                self.serviceName,
                self.callerName,
                self.endpoint,
                err.type || 'unknown',
                self.retryCounts
            )
        );
    }
};

TChannelOutRequest.prototype.emitPerAttemptResponseStat =
function emitPerAttemptResponseStat(res) {
    var self = this;

    if (!res.ok) {
        self.channel.emitFastStat(
            'tchannel.outbound.calls.per-attempt.app-errors',
            'counter',
            1,
            new stat.OutboundCallsPerAttemptAppErrorsTags(
                self.serviceName,
                self.callerName,
                self.endpoint,
                'unknown',
                self.retryCount
            )
        );
    // Only emit success if peer-to-peer request or relay
    } else if (self.logical === false) {
        self.channel.emitFastStat(
            'tchannel.outbound.calls.success',
            'counter',
            1,
            new stat.OutboundCallsSuccessTags(
                self.serviceName,
                self.callerName,
                self.endpoint
            )
        );
    }
};

TChannelOutRequest.prototype.emitPerAttemptLatency =
function emitPerAttemptLatency() {
    var self = this;

    var latency = self.end - self.start;

    self.channel.emitFastStat(
        'tchannel.outbound.calls.per-attempt-latency',
        'timing',
        latency,
        new stat.OutboundCallsPerAttemptLatencyTags(
            self.serviceName,
            self.callerName,
            self.endpoint,
            self.remoteAddr,
            self.retryCount
        )
    );
};

TChannelOutRequest.prototype.emitError = function emitError(err) {
    var self = this;

    if (self.end) {
        self.channel.logger.warn('Unexpected error after end for OutRequest', {
            serviceName: self.serviceName,
            endpoint: self.endpoint,
            socketRemoteAddr: self.remoteAddr,
            callerName: self.callerName,
            oldError: self.err,
            oldResponse: !!self.res,
            error: err
        });
    } else {
        self.end = self.channel.timers.now();
    }

    self.err = err;
    self.emitPerAttemptLatency();
    self.emitPerAttemptErrorStat(err);

    self.peer.invalidateScore('outreq.emitError');

    self.errorEvent.emit(self, err);
};

TChannelOutRequest.prototype.extendLogInfo = function extendLogInfo(info) {
    var self = this;

    info.outRequestId = self.id;
    info.outRequestType = self.type;
    info.outRequestState = States.describe(self.state);
    info.outRequestRemoteAddr = self.remoteAddr;
    info.serviceName = self.serviceName;
    info.outRequestErr = self.err;

    if (self.endpoint !== null) {
        info.outRequestArg1 = self.endpoint;
    } else {
        info.outRequestArg1 = String(self.arg1);
    }

    return info;
};

TChannelOutRequest.prototype.emitResponse = function emitResponse(res) {
    var self = this;

    self.res = res;
    self.res.span = self.span;

    if (!self.res.streamed) {
        self.markEnd();
    } else {
        self.res.finishEvent.on(onFinished);
    }

    self.responseEvent.emit(self, res);

    function onFinished() {
        self.markEnd();
    }
};

TChannelOutRequest.prototype.markEnd = function markEnd() {
    var self = this;

    self.peer.invalidateScore('outreq.emitResponse');

    if (self.end) {
        self.channel.logger.warn('Unexpected response after end for OutRequest', {
            serviceName: self.serviceName,
            endpoint: self.endpoint,
            socketRemoteAddr: self.remoteAddr,
            callerName: self.callerName,
            oldError: self.err,
            oldResponse: !!self.res
        });
    } else {
        self.end = self.channel.timers.now();
    }

    self.emitPerAttemptLatency();
    self.emitPerAttemptResponseStat(self.res);
};

TChannelOutRequest.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;

    if (self.drained) {
        self.emitError(errors.RequestDrained({
            reason: self.drainReason
        }));
        return;
    }

    switch (self.state) {
        case States.Initial:
            self.sendCallRequestFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallRequestContFrame(parts, isLast);
            break;
        case States.Done:
            // TODO: could probably happen normally, like say if a
            // streaming request is cancelled
            self.emitError(errors.RequestFrameState({
                attempted: 'arg parts',
                state: 'Done'
            }));
            break;
        case States.Error:
            // TODO: log warn
            break;
        default:
            // TODO: log warn
            break;
    }
};

TChannelOutRequest.prototype.sendCallRequestFrame = function sendCallRequestFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.start = self.channel.timers.now();
            if (self.span) {
                self.span.annotate('cs');
            }
            self._sendCallRequest(args, isLast);
            if (isLast) {
                self.state = States.Done;
            } else {
                self.state = States.Streaming;
            }
            break;
        case States.Streaming:
            self.emitError(errors.RequestFrameState({
                attempted: 'call request',
                state: 'Streaming'
            }));
            break;
        case States.Done:
            self.emitError(errors.RequestAlreadyDone({
                attempted: 'call request'
            }));
            break;
        default:
            // TODO: log warn
            break;
    }
};

TChannelOutRequest.prototype.sendCallRequestContFrame = function sendCallRequestContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.emitError(errors.RequestFrameState({
                attempted: 'call request continuation',
                state: 'Initial'
            }));
            break;
        case States.Streaming:
            self._sendCallRequestCont(args, isLast);
            if (isLast) {
                self.state = States.Done;
            }
            break;
        case States.Done:
            self.emitError(errors.RequestAlreadyDone({
                attempted: 'call request continuation'
            }));
            break;
        default:
            // TODO: log warn
            break;
    }
};

TChannelOutRequest.prototype.sendArg1 = function sendArg1(arg1) {
    var self = this;

    if (self.drained) {
        self.emitError(errors.RequestDrained({
            reason: self.drainReason
        }));
        return self;
    }

    self.arg1 = arg1;
    self.endpoint = String(arg1);
    if (self.span) {
        self.span.name = self.endpoint;
    }

    return self;
};

TChannelOutRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;

    if (callback) {
        self.hookupCallback(callback);
    }

    if (self.drained) {
        self.emitError(errors.RequestDrained({
            reason: self.drainReason
        }));
        return self;
    }

    self.sendArg1(arg1);

    if (self.span) {
        self.span.annotateBinary('as', self.headers.as);
        self.span.annotateBinary('cn', self.callerName);
    }

    if (self.logical === false && self.retryCount === 0) {
        self.emitOutboundCallsSent();
    }

    self.sendCallRequestFrame([arg1, arg2, arg3], true);
    self.finishEvent.emit(self);
    return self;
};

TChannelOutRequest.prototype.emitOutboundCallsSent =
function emitOutboundCallsSent() {
    var self = this;

    self.channel.emitFastStat(
        'tchannel.outbound.calls.sent',
        'counter',
        1,
        new stat.OutboundCallsSentTags(
            self.serviceName,
            self.callerName,
            self.endpoint
        )
    );
};

TChannelOutRequest.prototype.hookupStreamCallback =
function hookupStreamCallback(callback) {
    var self = this;
    var called = false;

    self.errorEvent.on(onError);
    self.responseEvent.on(onResponse);

    function onError(err) {
        if (called) {
            return;
        }
        called = true;
        callback(err, null, null);
    }

    function onResponse(res) {
        if (called) {
            return;
        }
        called = true;
        callback(null, self, res);
    }

    return self;
};

TChannelOutRequest.prototype.hookupCallback =
function hookupCallback(callback) {
    var self = this;

    if (callback.canStream) {
        return self.hookupStreamCallback(callback);
    }
    var called = false;

    self.errorEvent.on(onError);
    self.responseEvent.on(onResponse);

    function onError(err) {
        if (called) {
            return;
        }
        called = true;
        callback(err, null, null);
    }

    function onResponse(res) {
        if (called) {
            return;
        }
        called = true;
        if (!res.streamed) {
            callback(null, res, res.arg2, res.arg3);
            return;
        }
        parallel({
            arg2: res.arg2.onValueReady,
            arg3: res.arg3.onValueReady
        }, compatCall);
        function compatCall(err, args) {
            callback(err, res, args.arg2, args.arg3);
        }
    }

    return self;
};

TChannelOutRequest.prototype.onTimeout = function onTimeout(now) {
    var self = this;
    var timeoutError;

    if (self.err) {
        self.channel.logger.warn('unexpected onTimeout for errored out request', {
            serviceName: self.serviceName,
            endpoint: self.endpoint,
            socketRemoteAddr: self.remoteAddr,
            callerName: self.callerName,

            oldError: self.err,
            oldResponse: !!self.res,

            time: now
        });
    }

    if (!self.res || self.res.state === States.Initial) {
        timeoutError = errors.RequestTimeoutError({
            id: self.id,
            start: self.start,
            elapsed: now - self.start,
            logical: self.logical,
            timeout: self.timeout,
            remoteAddr: self.remoteAddr
        });
        if (self.operations) {
            self.operations.checkLastTimeoutTime(now);
            self.operations.popOutReq(self.id);
        }

        process.nextTick(deferOutReqTimeoutErrorEmit);
    } else if (self.operations) {
        self.operations.checkLastTimeoutTime(now);
        self.operations.popOutReq(self.id);
    }

    function deferOutReqTimeoutErrorEmit() {
        self.emitError(timeoutError);
    }
};
<|endoftext|>


<commit_before>/* SnackbarJS - MIT LICENSE (https://github.com/FezVrasta/snackbarjs/blob/master/LICENSE.md) */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function( $ ){

    $(document).ready(function() {
        $("body").append("
");
    });

    function isset(variable) {
        if (typeof variable !== "undefined" && variable !== null) {
            return true;
        } else {
            return false;
        }
    }

    //events (publish subscribe) pattern [aka Event Emitter]
    var events = {
      events: {},
      on: function (eventName, fn) {
        this.events[eventName] = this.events[eventName] || [];
        this.events[eventName].push(fn);
      },
      off: function(eventName, fn) {
        if (this.events[eventName]) {
          for (var i = 0; i < this.events[eventName].length; i++) {
            if (this.events[eventName][i] === fn) {
              this.events[eventName].splice(i, 1);
              break;
            }
          }
        }
      },
      emit: function (eventName, data) {
        if (this.events[eventName]) {
          this.events[eventName].forEach(function(fn) {
            fn(data);
          });
        }
      }
    };

    $(document)
    .on("click", "[data-toggle=snackbar]", function() {
        $(this).snackbar("toggle");
    })
    .on("click", "#snackbar-container .snackbar", function() {
        $(this).snackbar("hide");
    });

    $.snackbar = function(options) {

        if (isset(options) && options === Object(options)) {
            var $snackbar;

			var snackbarNew = false;

            if (!isset(options.id)) {
                options.id = "snackbar" + Date.now();
                $snackbar = $("
").attr("id", options.id).attr("class", "snackbar");
				snackbarNew = true;
            } else {
                if ($("#" + options.id).length) {
					$snackbar = $("#" + options.id);
				} else {
					$snackbar = $("
").attr("id", "" + options.id).attr("class", "snackbar");
					snackbarNew = true;
				}
            }

            var snackbarStatus = $snackbar.hasClass("snackbar-opened");

            if (isset(options.style)) {
				if (snackbarStatus) {
					$snackbar.attr("class", "snackbar snackbar-opened " + options.style);
                } else {
					$snackbar.attr("class", "snackbar " + options.style);
                }
				$snackbar.attr("data-style", options.style);
            } else {
                if (snackbarStatus) {
					$snackbar.attr("class", "snackbar snackbar-opened");
                } else {
					$snackbar.attr("class", "snackbar");
                }
            }

            options.htmlAllowed = isset(options.htmlAllowed) ? options.htmlAllowed : false;

            options.timeout = (isset(options.timeout)) ? options.timeout : 3000;
			$snackbar.attr("data-timeout", options.timeout);

            options.content = (options.htmlAllowed) ? options.content : $("
" + options.content + "
").text();

            if (isset(options.onClose)) events.on(options.id, options.onClose);

			if (isset(options.htmlAllowed)) {
				$snackbar.attr("data-html-allowed", options.htmlAllowed);
			}

            if (isset(options.content)) {
                if ($snackbar.find(".snackbar-content").length) {
                    $snackbar.find(".snackbar-content").html(options.content);
                } else {
                    $snackbar.prepend("" + options.content + "");
                }
				$snackbar.attr("data-content", options.content);
            }

            if (snackbarNew) {
                $snackbar.appendTo("#snackbar-container");
            } else {
                $snackbar.insertAfter("#snackbar-container .snackbar:last-child");
            }

            // Show or hide item
            if (isset(options.action) && options.action == "toggle") {
                if (snackbarStatus) {
                    options.action = "hide";
                } else {
                    options.action = "show";
                }
            }

            var animationId1 = Date.now();
            $snackbar.data("animationId1", animationId1);
            setTimeout(function() {
                if ($snackbar.data("animationId1") === animationId1) {
                    if (!isset(options.action) || options.action == "show") {
                        $snackbar.addClass("snackbar-opened");
                    } else if (isset(options.action) && options.action == "hide") {
                        $snackbar.removeClass("snackbar-opened");
                        events.emit(options.id);
                        events.off(options.id);
                    }
                }
            }, 50);

            // Set timer for item autohide
            var animationId2 = Date.now();
            $snackbar.data("animationId2", animationId2);

            if (options.timeout !== 0) {
                setTimeout(function() {
                    if ($snackbar.data("animationId2") === animationId2) {
                        $snackbar.removeClass("snackbar-opened");
                        events.emit(options.id);
                        events.off(options.id);
                    }
                }, options.timeout);
            }

            return $snackbar;

        } else {
            return false;
        }
    };

    $.fn.snackbar = function(action) {
        if (typeof action==='undefined'){
            return;
        }
        var options = {};

        if (!this.hasClass("snackbar")) {

            if (!isset(action) || action === "show" || action === "hide" || action == "toggle") {
                options = {
                    content: $(this).attr("data-content"),
                    style: $(this).attr("data-style"),
                    timeout: $(this).attr("data-timeout"),
                    htmlAllowed: $(this).attr("data-html-allowed")
                };
            }

            if (isset(action)) {
                options.id = this.attr("data-snackbar-id");

                if(action === "show" || action === "hide" || action == "toggle") {
                    options.action = action;
                }
            }

            var $snackbar = $.snackbar(options);
            this.attr("data-snackbar-id", $snackbar.attr("id"));

            return $snackbar;

        } else {

            options = {
					id: this.attr("id"),
                    content: $(this).attr("data-content"),
                    style: $(this).attr("data-style"),
                    timeout: parseInt($(this).attr("data-timeout")),
                    htmlAllowed: $(this).attr("data-html-allowed")
                };
            if(action === "show" || action === "hide" || action == "toggle") {
                options.action = action;
            }
            return $.snackbar(options);
        }

    };
}));
<commit_msg>Bug fix con Event Emitter<commit_after>/* SnackbarJS - MIT LICENSE (https://github.com/FezVrasta/snackbarjs/blob/master/LICENSE.md) */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function( $ ){

    $(document).ready(function() {
        $("body").append("
");
    });

    function isset(variable) {
        if (typeof variable !== "undefined" && variable !== null) {
            return true;
        } else {
            return false;
        }
    }

    //events (publish subscribe) pattern [aka Event Emitter]
    var events = {
      events: {},
      on: function (eventName, fn) {
        this.events[eventName] = this.events[eventName] || [];
        this.events[eventName].push(fn);
      },
      off: function(eventName) {
        if (this.events[eventName]) {
          delete this.events[eventName];
        }
      },
      emit: function (eventName, data) {
        if (this.events[eventName]) {
          this.events[eventName].forEach(function(fn) {
            fn(data);
          });
        }
      }
    };

    $(document)
    .on("click", "[data-toggle=snackbar]", function() {
        $(this).snackbar("toggle");
    })
    .on("click", "#snackbar-container .snackbar", function() {
        $(this).snackbar("hide");
    });

    $.snackbar = function(options) {

        if (isset(options) && options === Object(options)) {
            var $snackbar;

			var snackbarNew = false;

            if (!isset(options.id)) {
                options.id = "snackbar" + Date.now();
                $snackbar = $("
").attr("id", options.id).attr("class", "snackbar");
				snackbarNew = true;
            } else {
                if ($("#" + options.id).length) {
					$snackbar = $("#" + options.id);
				} else {
					$snackbar = $("
").attr("id", "" + options.id).attr("class", "snackbar");
					snackbarNew = true;
				}
            }

            var snackbarStatus = $snackbar.hasClass("snackbar-opened");

            if (isset(options.style)) {
				if (snackbarStatus) {
					$snackbar.attr("class", "snackbar snackbar-opened " + options.style);
                } else {
					$snackbar.attr("class", "snackbar " + options.style);
                }
				$snackbar.attr("data-style", options.style);
            } else {
                if (snackbarStatus) {
					$snackbar.attr("class", "snackbar snackbar-opened");
                } else {
					$snackbar.attr("class", "snackbar");
                }
            }

            options.htmlAllowed = isset(options.htmlAllowed) ? options.htmlAllowed : false;

            options.timeout = (isset(options.timeout)) ? options.timeout : 3000;
			$snackbar.attr("data-timeout", options.timeout);

            options.content = (options.htmlAllowed) ? options.content : $("
" + options.content + "
").text();

            if (isset(options.onClose)) events.on(options.id, options.onClose);

			if (isset(options.htmlAllowed)) {
				$snackbar.attr("data-html-allowed", options.htmlAllowed);
			}

            if (isset(options.content)) {
                if ($snackbar.find(".snackbar-content").length) {
                    $snackbar.find(".snackbar-content").html(options.content);
                } else {
                    $snackbar.prepend("" + options.content + "");
                }
				$snackbar.attr("data-content", options.content);
            }

            if (snackbarNew) {
                $snackbar.appendTo("#snackbar-container");
            } else {
                $snackbar.insertAfter("#snackbar-container .snackbar:last-child");
            }

            // Show or hide item
            if (isset(options.action) && options.action == "toggle") {
                if (snackbarStatus) {
                    options.action = "hide";
                } else {
                    options.action = "show";
                }
            }

            var animationId1 = Date.now();
            $snackbar.data("animationId1", animationId1);
            setTimeout(function() {
                if ($snackbar.data("animationId1") === animationId1) {
                    if (!isset(options.action) || options.action == "show") {
                        $snackbar.addClass("snackbar-opened");
                    } else if (isset(options.action) && options.action == "hide") {
                        $snackbar.removeClass("snackbar-opened");
                        events.emit(options.id);
                        events.off(options.id);
                    }
                }
            }, 50);

            // Set timer for item autohide
            var animationId2 = Date.now();
            $snackbar.data("animationId2", animationId2);

            if (options.timeout !== 0) {
                setTimeout(function() {
                    if ($snackbar.data("animationId2") === animationId2) {
                        $snackbar.removeClass("snackbar-opened");
                        events.emit(options.id);
                        events.off(options.id);
                    }
                }, options.timeout);
            }

            return $snackbar;

        } else {
            return false;
        }
    };

    $.fn.snackbar = function(action) {
        if (typeof action==='undefined'){
            return;
        }
        var options = {};

        if (!this.hasClass("snackbar")) {

            if (!isset(action) || action === "show" || action === "hide" || action == "toggle") {
                options = {
                    content: $(this).attr("data-content"),
                    style: $(this).attr("data-style"),
                    timeout: $(this).attr("data-timeout"),
                    htmlAllowed: $(this).attr("data-html-allowed")
                };
            }

            if (isset(action)) {
                options.id = this.attr("data-snackbar-id");

                if(action === "show" || action === "hide" || action == "toggle") {
                    options.action = action;
                }
            }

            var $snackbar = $.snackbar(options);
            this.attr("data-snackbar-id", $snackbar.attr("id"));

            return $snackbar;

        } else {

            options = {
					id: this.attr("id"),
                    content: $(this).attr("data-content"),
                    style: $(this).attr("data-style"),
                    timeout: parseInt($(this).attr("data-timeout")),
                    htmlAllowed: $(this).attr("data-html-allowed")
                };
            if(action === "show" || action === "hide" || action == "toggle") {
                options.action = action;
            }
            return $.snackbar(options);
        }

    };
}));
<|endoftext|>


<commit_before>var fs = require('fs'),
  ejs = require('ejs');

function titlefy(fileName) {
  // Eww, gross. I'm so bad.
  var string = fileName.substring(0, 1).toUpperCase() + fileName.substring(1);
  return string.replace(/-([a-z])/ig, function (all, letter) {
      return ' ' + letter.toUpperCase();
  }).replace(/ Of /, ' of ').replace(/ And /, ' and ').replace(/ The /, ' the ')
    .replace(/ Or /, ' or ').replace(/ For /, ' for ').replace(/ To /, ' to ')
    .replace(/ At /, ' at ').replace(/ In /, ' in ').replace(/ A /, ' a ')
    .replace(/ With /, ' with ').replace(/ But /, ' but ');
}

function renderBlogs(uncanny) {
  fs.readFile(uncanny.source + 'blogs/layout.ejs', 'utf8', function (err, template) {
    if (err) { throw err; }
    uncanny.uncanny.blogs.forEach(function (blog) {
      var blogPage = ejs.render(template, {
        filename: uncanny.source + 'blogs/layout.ejs',
        uncanny: uncanny.uncanny,
        blog: blog
      });

      fs.writeFile(uncanny.target + 'blogs/' + blog.name + '.html', blogPage, function (err) {
        if (err) { throw err; }
      });
    });
  });
}

function rebuildUncanny(uncanny, callback) {
  ['blogs', 'scripts', 'images', 'styles', 'templates'].forEach(function (directory) {
    uncanny.uncanny[directory] = [];

    if (directory == 'blogs') {
      fs.readdir(uncanny.source + directory, function (err, files) {
        if (err) { throw err; }
        files.forEach(function (file) {
          var blogDate = file.match(uncanny.blogDateExtract);
          if (blogDate) {
            var blogName = file.replace(uncanny.blogDateRegEx, '').substring(1).replace(/\.md$/, '');
            var blogContent = fs.readFileSync(uncanny.target + 'blogs/' + blogName + '.htm', 'utf8');

            var blogObject = {
              "year": blogDate[1],
              "month": blogDate[2],
              "day": blogDate[3],
              "name": blogName,
              "title": titlefy(blogName),
              "target": "/blogs/" + blogName + ".html",
              "content": blogContent,
              "source": file
            };

            uncanny.uncanny.blogs.push(blogObject);
          }
        });
        uncanny.uncanny.blogs = uncanny.uncanny.blogs.reverse();
        renderBlogs(uncanny);
      });
    } else {
      fs.readdir(uncanny.target + directory, function (err, files) {
        if (err) { throw err; }
        files.forEach(function (file) {
          uncanny.uncanny[directory].push(file);
        });
      });
    }
  });
  callback && callback();
}

function recompile(uncanny, directory, callback) {
  fs.readdir(uncanny.source + directory, function (err, files) {
    if (err) { throw err; }

    files.forEach(function (file) {
      var targetFile = uncanny.source + directory + (directory !== '' ? '/' + file : file);
      fs.stat(targetFile, function (err, stats) {
        if (!stats.isDirectory()) {
          uncanny.directories[directory].recompile(file);
        }
      });
    });

    callback && callback(directory);

  });
}

function bootstrap(uncanny, callback) {
  uncanny.customDirs.concat(['blogs', 'scripts', 'styles', 'images', 'templates']).forEach(function (directory) {
    if (!fs.existsSync(uncanny.source + directory)) { fs.mkdirSync(uncanny.source + directory); }
    if (!fs.existsSync(uncanny.target + directory)) { fs.mkdirSync(uncanny.target + directory); }
  });

  callback && callback();
}

function fixBlogName(uncanny, blogName) {
  var blogDate = new Date(),
    month = ('0' + (blogDate.getUTCMonth() + 1)).slice(-2),
    day = ('0' + blogDate.getUTCDate()).slice(-2),
    year = blogDate.getUTCFullYear(),
    newBlogName = [year, month, day, blogName].join('-');
  fs.rename(uncanny.source + 'blogs/' + blogName, uncanny.source + 'blogs/' + newBlogName);
}

exports.fixBlogName = fixBlogName;
exports.rebuildUncanny = rebuildUncanny;
exports.bootstrap = bootstrap;
exports.recompile = recompile;
<commit_msg>remove extra dashes<commit_after>var fs = require('fs'),
  ejs = require('ejs');

function titlefy(fileName) {
  // Eww, gross. I'm so bad.
  var string = fileName.substring(0, 1).toUpperCase() + fileName.substring(1);
  return string.replace(/-([a-z])/ig, function (all, letter) {
      return ' ' + letter.toUpperCase();
  }).replace(/ Of /, ' of ').replace(/ And /, ' and ').replace(/ The /, ' the ')
    .replace(/ Or /, ' or ').replace(/ For /, ' for ').replace(/ To /, ' to ')
    .replace(/ At /, ' at ').replace(/ In /, ' in ').replace(/ A /, ' a ')
    .replace(/ With /, ' with ').replace(/ But /, ' but ').replace(/-/, '');
}

function renderBlogs(uncanny) {
  fs.readFile(uncanny.source + 'blogs/layout.ejs', 'utf8', function (err, template) {
    if (err) { throw err; }
    uncanny.uncanny.blogs.forEach(function (blog) {
      var blogPage = ejs.render(template, {
        filename: uncanny.source + 'blogs/layout.ejs',
        uncanny: uncanny.uncanny,
        blog: blog
      });

      fs.writeFile(uncanny.target + 'blogs/' + blog.name + '.html', blogPage, function (err) {
        if (err) { throw err; }
      });
    });
  });
}

function rebuildUncanny(uncanny, callback) {
  ['blogs', 'scripts', 'images', 'styles', 'templates'].forEach(function (directory) {
    uncanny.uncanny[directory] = [];

    if (directory == 'blogs') {
      fs.readdir(uncanny.source + directory, function (err, files) {
        if (err) { throw err; }
        files.forEach(function (file) {
          var blogDate = file.match(uncanny.blogDateExtract);
          if (blogDate) {
            var blogName = file.replace(uncanny.blogDateRegEx, '').substring(1).replace(/\.md$/, '');
            var blogContent = fs.readFileSync(uncanny.target + 'blogs/' + blogName + '.htm', 'utf8');

            var blogObject = {
              "year": blogDate[1],
              "month": blogDate[2],
              "day": blogDate[3],
              "name": blogName,
              "title": titlefy(blogName),
              "target": "/blogs/" + blogName + ".html",
              "content": blogContent,
              "source": file
            };

            uncanny.uncanny.blogs.push(blogObject);
          }
        });
        uncanny.uncanny.blogs = uncanny.uncanny.blogs.reverse();
        renderBlogs(uncanny);
      });
    } else {
      fs.readdir(uncanny.target + directory, function (err, files) {
        if (err) { throw err; }
        files.forEach(function (file) {
          uncanny.uncanny[directory].push(file);
        });
      });
    }
  });
  callback && callback();
}

function recompile(uncanny, directory, callback) {
  fs.readdir(uncanny.source + directory, function (err, files) {
    if (err) { throw err; }

    files.forEach(function (file) {
      var targetFile = uncanny.source + directory + (directory !== '' ? '/' + file : file);
      fs.stat(targetFile, function (err, stats) {
        if (!stats.isDirectory()) {
          uncanny.directories[directory].recompile(file);
        }
      });
    });

    callback && callback(directory);

  });
}

function bootstrap(uncanny, callback) {
  uncanny.customDirs.concat(['blogs', 'scripts', 'styles', 'images', 'templates']).forEach(function (directory) {
    if (!fs.existsSync(uncanny.source + directory)) { fs.mkdirSync(uncanny.source + directory); }
    if (!fs.existsSync(uncanny.target + directory)) { fs.mkdirSync(uncanny.target + directory); }
  });

  callback && callback();
}

function fixBlogName(uncanny, blogName) {
  var blogDate = new Date(),
    month = ('0' + (blogDate.getUTCMonth() + 1)).slice(-2),
    day = ('0' + blogDate.getUTCDate()).slice(-2),
    year = blogDate.getUTCFullYear(),
    newBlogName = [year, month, day, blogName].join('-');
  fs.rename(uncanny.source + 'blogs/' + blogName, uncanny.source + 'blogs/' + newBlogName);
}

exports.fixBlogName = fixBlogName;
exports.rebuildUncanny = rebuildUncanny;
exports.bootstrap = bootstrap;
exports.recompile = recompile;
<|endoftext|>


<commit_before>var RUNTIME_PACKAGE = require('../package.json'),

    /**
     * List of postman packages to include while generating dependency object
     *
     * @const
     * @type {String[]}
     */
    PACKAGES_TO_CONSIDER = {
        'chai-postman': true,
        'postman-collection': true,
        'postman-request': true,
        'postman-sandbox': true,
        'uniscope': true,
        'uvm': true
    },

    /**
     * Generate object containing version and dependencies of Runtime or given module.
     *
     * @param {String} [moduleName] - Module name
     * @param {Boolean} [deepDependencies=true] - Do depth dependencies traversal or stop at root
     * @param {Object} [moduleData={}] - Object to store module data
     * @returns {Object}
     *
     * @example
Returned Object Structure

     * var runtime = require('postman-runtime');
     * runtime.version();
     * {
     *     version: '7.6.1',
     *     dependencies: {
     *         'postman-collection' : {
     *             version: '3.4.2',
     *             dependencies: {
     *                 'postman-request': {
     *                     version: '2.88.1-postman.5'
     *                 }
     *             }
     *         },
     *         'postman-request': {
     *             version: '2.88.1-postman.5'
     *         }
     *     }
     * }
     */
    getVersionData = function (moduleName, deepDependencies, moduleData) {
        // Set default values of function arguments if not given
        !moduleData && (moduleData = {});
        // Include nested dependencies in moduleData object only if deepDependencies=true.
        // Return only direct dependencies of module if deepDependencies=false.
        (deepDependencies === undefined) && (deepDependencies = true);

        var key,
            version,

            // Runtime's package.json is considered by default
            packageJson = RUNTIME_PACKAGE;

        // bail out if either dependency not in PACKAGES_TO_CONSIDER
        // or not Runtime's dependency
        if (
            moduleName &&
            !(
                PACKAGES_TO_CONSIDER[moduleName] &&
                (
                    packageJson.dependencies.hasOwnProperty(moduleName) ||
                    packageJson.devDependencies.hasOwnProperty(moduleName)
                )
            )
        ) {
            return;
        }

        // if module name is given in function argument, consider that module's package.json instead of default
        if (moduleName) {
            // eslint-disable-next-line security/detect-non-literal-require
            packageJson = require('../node_modules/' + moduleName + '/package.json');
        }

        // set version of dependency given as function argument or Runtime
        moduleData.version = packageJson.version;
        moduleData.dependencies = {};

        for (key in PACKAGES_TO_CONSIDER) {
            // if key is normal dependency
            if (packageJson.dependencies.hasOwnProperty(key)) {
                version = packageJson.dependencies[key];
            }
            // else if key is devDependency
            else if (packageJson.devDependencies.hasOwnProperty(key)) {
                version = packageJson.devDependencies[key];
            }
            // skip if key is not listed as dependency in packageJson
            else {
                continue;
            }

            // include dependency in module data
            moduleData.dependencies[key] = {
                version: version,
                dependencies: {}
            };

            // recursive call to include deep-dependency
            if (!moduleName && deepDependencies) {
                getVersionData(key, deepDependencies, moduleData.dependencies[key]);
            }

            // delete if no deep-dependency found
            if (Object.keys(moduleData.dependencies[key].dependencies).length === 0) {
                delete moduleData.dependencies[key].dependencies;
            }
        }

        return moduleData;
    };

module.exports = getVersionData;
<commit_msg>Added comment explaining getVersionData() function argument<commit_after>var RUNTIME_PACKAGE = require('../package.json'),

    /**
     * List of postman packages to include while generating dependency object
     *
     * @const
     * @type {String[]}
     */
    PACKAGES_TO_CONSIDER = {
        'chai-postman': true,
        'postman-collection': true,
        'postman-request': true,
        'postman-sandbox': true,
        'uniscope': true,
        'uvm': true
    },

    /**
     * Generate object containing version and dependencies of Runtime or given module.
     *
     * @param {String} [moduleName] - Module name
     * @param {Boolean} [deepDependencies=true] - Do depth dependencies traversal or stop at root
     * @param {Object} [moduleData={}] - Object to store module data
     * @returns {Object}
     *
     * @example
Returned Object Structure

     * var runtime = require('postman-runtime');
     * runtime.version();
     * {
     *     version: '7.6.1',
     *     dependencies: {
     *         'postman-collection' : {
     *             version: '3.4.2',
     *             dependencies: {
     *                 'postman-request': {
     *                     version: '2.88.1-postman.5'
     *                 }
     *             }
     *         },
     *         'postman-request': {
     *             version: '2.88.1-postman.5'
     *         }
     *     }
     * }
     */
    getVersionData = function (moduleName, deepDependencies, moduleData) {
        // Set default values of function arguments if not given

        // Argument moduleData is undefined if function is called directly.
        // Otherwise moduleData will contain object if called recursively.
        !moduleData && (moduleData = {});
        // Include nested dependencies in moduleData object only if deepDependencies=true.
        // Return only direct dependencies of module if deepDependencies=false.
        (deepDependencies === undefined) && (deepDependencies = true);

        var key,
            version,

            // Runtime's package.json is considered by default
            packageJson = RUNTIME_PACKAGE;

        // bail out if either dependency not in PACKAGES_TO_CONSIDER
        // or not Runtime's dependency
        if (
            moduleName &&
            !(
                PACKAGES_TO_CONSIDER[moduleName] &&
                (
                    packageJson.dependencies.hasOwnProperty(moduleName) ||
                    packageJson.devDependencies.hasOwnProperty(moduleName)
                )
            )
        ) {
            return;
        }

        // if module name is given in function argument, consider that module's package.json instead of default
        if (moduleName) {
            // eslint-disable-next-line security/detect-non-literal-require
            packageJson = require('../node_modules/' + moduleName + '/package.json');
        }

        // set version of dependency given as function argument or Runtime
        moduleData.version = packageJson.version;
        moduleData.dependencies = {};

        for (key in PACKAGES_TO_CONSIDER) {
            // if key is normal dependency
            if (packageJson.dependencies.hasOwnProperty(key)) {
                version = packageJson.dependencies[key];
            }
            // else if key is devDependency
            else if (packageJson.devDependencies.hasOwnProperty(key)) {
                version = packageJson.devDependencies[key];
            }
            // skip if key is not listed as dependency in packageJson
            else {
                continue;
            }

            // include dependency in module data
            moduleData.dependencies[key] = {
                version: version,
                dependencies: {}
            };

            // recursive call to include deep-dependency
            if (!moduleName && deepDependencies) {
                getVersionData(key, deepDependencies, moduleData.dependencies[key]);
            }

            // delete if no deep-dependency found
            if (Object.keys(moduleData.dependencies[key].dependencies).length === 0) {
                delete moduleData.dependencies[key].dependencies;
            }
        }

        return moduleData;
    };

module.exports = getVersionData;
<|endoftext|>


<commit_before>/*
 jQuery UI Sortable plugin wrapper

 @param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
 */
angular.module('ui.sortable', [])
  .value('uiSortableConfig',{})
  .directive('uiSortable', [
    'uiSortableConfig', '$timeout', '$log',
    function(uiSortableConfig, $timeout, $log) {
      return {
        require: '?ngModel',
        scope: {
          ngModel: '=',
          uiSortable: '='
        },
        link: function(scope, element, attrs, ngModel) {
          var savedNodes;

          function combineCallbacks(first,second){
            if(second && (typeof second === 'function')) {
              return function() {
                first.apply(this, arguments);
                second.apply(this, arguments);
              };
            }
            return first;
          }

          function getSortableWidgetInstance(element) {
            // this is a fix to support jquery-ui prior to v1.11.x
            // otherwise we should be using `element.sortable('instance')`
            var data = element.data('ui-sortable');
            if (data && typeof data === 'object' && data.widgetFullName === 'ui-sortable') {
              return data;
            }
            return null;
          }

          function hasSortingHelper (element, ui) {
            var helperOption = element.sortable('option','helper');
            return helperOption === 'clone' || (typeof helperOption === 'function' && ui.item.sortable.isCustomHelperUsed());
          }

          // thanks jquery-ui
          function isFloating (item) {
            return (/left|right/).test(item.css('float')) || (/inline|table-cell/).test(item.css('display'));
          }

          function getElementScope(elementScopes, element) {
            var result = null;
            for (var i = 0; i < elementScopes.length; i++) {
              var x = elementScopes[i];
              if (x.element[0] === element[0]) {
                result = x.scope;
                break;
              }
            }
            return result;
          }

          function afterStop(e, ui) {
            ui.item.sortable._destroy();
          }

          var opts = {};

          // directive specific options
          var directiveOpts = {
            'ui-floating': undefined
          };

          var callbacks = {
            receive: null,
            remove:null,
            start:null,
            stop:null,
            update:null
          };

          var wrappers = {
            helper: null
          };

          angular.extend(opts, directiveOpts, uiSortableConfig, scope.uiSortable);

          if (!angular.element.fn || !angular.element.fn.jquery) {
            $log.error('ui.sortable: jQuery should be included before AngularJS!');
            return;
          }

          if (ngModel) {

            // When we add or remove elements, we need the sortable to 'refresh'
            // so it can find the new/removed elements.
            scope.$watch('ngModel.length', function() {
              // Timeout to let ng-repeat modify the DOM
              $timeout(function() {
                // ensure that the jquery-ui-sortable widget instance
                // is still bound to the directive's element
                if (!!getSortableWidgetInstance(element)) {
                  element.sortable('refresh');
                }
              }, 0, false);
            });

            callbacks.start = function(e, ui) {
              if (opts['ui-floating'] === 'auto') {
                // since the drag has started, the element will be
                // absolutely positioned, so we check its siblings
                var siblings = ui.item.siblings();
                var sortableWidgetInstance = getSortableWidgetInstance(angular.element(e.target));
                sortableWidgetInstance.floating = isFloating(siblings);
              }

              // Save the starting position of dragged item
              ui.item.sortable = {
                model: ngModel.$modelValue[ui.item.index()],
                index: ui.item.index(),
                source: ui.item.parent(),
                sourceModel: ngModel.$modelValue,
                cancel: function () {
                  ui.item.sortable._isCanceled = true;
                },
                isCanceled: function () {
                  return ui.item.sortable._isCanceled;
                },
                isCustomHelperUsed: function () {
                  return !!ui.item.sortable._isCustomHelperUsed;
                },
                _isCanceled: false,
                _isCustomHelperUsed: ui.item.sortable._isCustomHelperUsed,
                _destroy: function () {
                  angular.forEach(ui.item.sortable, function(value, key) {
                    ui.item.sortable[key] = undefined;
                  });
                }
              };
            };

            callbacks.activate = function(e, ui) {
              // We need to make a copy of the current element's contents so
              // we can restore it after sortable has messed it up.
              // This is inside activate (instead of start) in order to save
              // both lists when dragging between connected lists.
              savedNodes = element.contents();

              // If this list has a placeholder (the connected lists won't),
              // don't inlcude it in saved nodes.
              var placeholder = element.sortable('option','placeholder');

              // placeholder.element will be a function if the placeholder, has
              // been created (placeholder will be an object).  If it hasn't
              // been created, either placeholder will be false if no
              // placeholder class was given or placeholder.element will be
              // undefined if a class was given (placeholder will be a string)
              if (placeholder && placeholder.element && typeof placeholder.element === 'function') {
                var phElement = placeholder.element();
                // workaround for jquery ui 1.9.x,
                // not returning jquery collection
                phElement = angular.element(phElement);

                // exact match with the placeholder's class attribute to handle
                // the case that multiple connected sortables exist and
                // the placehoilder option equals the class of sortable items
                var excludes = element.find('[class="' + phElement.attr('class') + '"]:not([ng-repeat], [data-ng-repeat])');

                savedNodes = savedNodes.not(excludes);
              }

              // save the directive's scope so that it is accessible from ui.item.sortable
              var connectedSortables = ui.item.sortable._connectedSortables || [];

              connectedSortables.push({
                element: element,
                scope: scope
              });

              ui.item.sortable._connectedSortables = connectedSortables;
            };

            callbacks.update = function(e, ui) {
              // Save current drop position but only if this is not a second
              // update that happens when moving between lists because then
              // the value will be overwritten with the old value
              if(!ui.item.sortable.received) {
                ui.item.sortable.dropindex = ui.item.index();
                var droptarget = ui.item.parent();
                ui.item.sortable.droptarget = droptarget;

                var droptargetScope = getElementScope(ui.item.sortable._connectedSortables, droptarget);
                ui.item.sortable.droptargetModel = droptargetScope.ngModel;

                // Cancel the sort (let ng-repeat do the sort for us)
                // Don't cancel if this is the received list because it has
                // already been canceled in the other list, and trying to cancel
                // here will mess up the DOM.
                element.sortable('cancel');
              }

              // Put the nodes back exactly the way they started (this is very
              // important because ng-repeat uses comment elements to delineate
              // the start and stop of repeat sections and sortable doesn't
              // respect their order (even if we cancel, the order of the
              // comments are still messed up).
              if (hasSortingHelper(element, ui) && !ui.item.sortable.received &&
                  element.sortable( 'option', 'appendTo' ) === 'parent') {
                // restore all the savedNodes except .ui-sortable-helper element
                // (which is placed last). That way it will be garbage collected.
                savedNodes = savedNodes.not(savedNodes.last());
              }
              savedNodes.appendTo(element);

              // If this is the target connected list then
              // it's safe to clear the restored nodes since:
              // update is currently running and
              // stop is not called for the target list.
              if(ui.item.sortable.received) {
                savedNodes = null;
              }

              // If received is true (an item was dropped in from another list)
              // then we add the new item to this list otherwise wait until the
              // stop event where we will know if it was a sort or item was
              // moved here from another list
              if(ui.item.sortable.received && !ui.item.sortable.isCanceled()) {
                scope.$apply(function () {
                  ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0,
                                             ui.item.sortable.moved);
                });
              }
            };

            callbacks.stop = function(e, ui) {
              // If the received flag hasn't be set on the item, this is a
              // normal sort, if dropindex is set, the item was moved, so move
              // the items in the list.
              if(!ui.item.sortable.received &&
                 ('dropindex' in ui.item.sortable) &&
                 !ui.item.sortable.isCanceled()) {

                scope.$apply(function () {
                  ngModel.$modelValue.splice(
                    ui.item.sortable.dropindex, 0,
                    ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]);
                });
              } else {
                // if the item was not moved, then restore the elements
                // so that the ngRepeat's comment are correct.
                if ((!('dropindex' in ui.item.sortable) || ui.item.sortable.isCanceled()) &&
                    !hasSortingHelper(element, ui)) {
                  savedNodes.appendTo(element);
                }
              }

              // It's now safe to clear the savedNodes
              // since stop is the last callback.
              savedNodes = null;
            };

            callbacks.receive = function(e, ui) {
              // An item was dropped here from another list, set a flag on the
              // item.
              ui.item.sortable.received = true;
            };

            callbacks.remove = function(e, ui) {
              // Workaround for a problem observed in nested connected lists.
              // There should be an 'update' event before 'remove' when moving
              // elements. If the event did not fire, cancel sorting.
              if (!('dropindex' in ui.item.sortable)) {
                element.sortable('cancel');
                ui.item.sortable.cancel();
              }

              // Remove the item from this list's model and copy data into item,
              // so the next list can retrive it
              if (!ui.item.sortable.isCanceled()) {
                scope.$apply(function () {
                  ui.item.sortable.moved = ngModel.$modelValue.splice(
                    ui.item.sortable.index, 1)[0];
                });
              }
            };

            wrappers.helper = function (inner) {
              if (inner && typeof inner === 'function') {
                return function (e, item) {
                  var innerResult = inner.apply(this, arguments);
                  item.sortable._isCustomHelperUsed = item !== innerResult;
                  return innerResult;
                };
              }
              return inner;
            };

            scope.$watchCollection('uiSortable', function(newVal /*, oldVal*/) {
              // ensure that the jquery-ui-sortable widget instance
              // is still bound to the directive's element
              var sortableWidgetInstance = getSortableWidgetInstance(element);
              if (!!sortableWidgetInstance) {
                angular.forEach(newVal, function(value, key) {
                  // if it's a custom option of the directive,
                  // handle it approprietly
                  if (key in directiveOpts) {
                    if (key === 'ui-floating' && (value === false || value === true)) {
                      sortableWidgetInstance.floating = value;
                    }

                    opts[key] = value;
                    return;
                  }

                  if (callbacks[key]) {
                    if( key === 'stop' ){
                      // call apply after stop
                      value = combineCallbacks(
                        value, function() { scope.$apply(); });

                      value = combineCallbacks(value, afterStop);
                    }
                    // wrap the callback
                    value = combineCallbacks(callbacks[key], value);
                  } else if (wrappers[key]) {
                    value = wrappers[key](value);
                  }

                  opts[key] = value;
                  element.sortable('option', key, value);
                });
              }
            }, true);

            angular.forEach(callbacks, function(value, key) {
              opts[key] = combineCallbacks(value, opts[key]);
              if( key === 'stop' ){
                opts[key] = combineCallbacks(opts[key], afterStop);
              }
            });

          } else {
            $log.info('ui.sortable: ngModel not provided!', element);
          }

          // Create sortable
          element.sortable(opts);
        }
      };
    }
  ]);
<commit_msg>fix(sortable): use $watchCollection to track ngModel changes<commit_after>/*
 jQuery UI Sortable plugin wrapper

 @param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
 */
angular.module('ui.sortable', [])
  .value('uiSortableConfig',{})
  .directive('uiSortable', [
    'uiSortableConfig', '$timeout', '$log',
    function(uiSortableConfig, $timeout, $log) {
      return {
        require: '?ngModel',
        scope: {
          ngModel: '=',
          uiSortable: '='
        },
        link: function(scope, element, attrs, ngModel) {
          var savedNodes;

          function combineCallbacks(first,second){
            if(second && (typeof second === 'function')) {
              return function() {
                first.apply(this, arguments);
                second.apply(this, arguments);
              };
            }
            return first;
          }

          function getSortableWidgetInstance(element) {
            // this is a fix to support jquery-ui prior to v1.11.x
            // otherwise we should be using `element.sortable('instance')`
            var data = element.data('ui-sortable');
            if (data && typeof data === 'object' && data.widgetFullName === 'ui-sortable') {
              return data;
            }
            return null;
          }

          function hasSortingHelper (element, ui) {
            var helperOption = element.sortable('option','helper');
            return helperOption === 'clone' || (typeof helperOption === 'function' && ui.item.sortable.isCustomHelperUsed());
          }

          // thanks jquery-ui
          function isFloating (item) {
            return (/left|right/).test(item.css('float')) || (/inline|table-cell/).test(item.css('display'));
          }

          function getElementScope(elementScopes, element) {
            var result = null;
            for (var i = 0; i < elementScopes.length; i++) {
              var x = elementScopes[i];
              if (x.element[0] === element[0]) {
                result = x.scope;
                break;
              }
            }
            return result;
          }

          function afterStop(e, ui) {
            ui.item.sortable._destroy();
          }

          var opts = {};

          // directive specific options
          var directiveOpts = {
            'ui-floating': undefined
          };

          var callbacks = {
            receive: null,
            remove:null,
            start:null,
            stop:null,
            update:null
          };

          var wrappers = {
            helper: null
          };

          angular.extend(opts, directiveOpts, uiSortableConfig, scope.uiSortable);

          if (!angular.element.fn || !angular.element.fn.jquery) {
            $log.error('ui.sortable: jQuery should be included before AngularJS!');
            return;
          }

          if (ngModel) {

            // When we add or remove elements, we need the sortable to 'refresh'
            // so it can find the new/removed elements.
            scope.$watchCollection('ngModel', function() {
              // Timeout to let ng-repeat modify the DOM
              $timeout(function() {
                // ensure that the jquery-ui-sortable widget instance
                // is still bound to the directive's element
                if (!!getSortableWidgetInstance(element)) {
                  element.sortable('refresh');
                }
              }, 0, false);
            });

            callbacks.start = function(e, ui) {
              if (opts['ui-floating'] === 'auto') {
                // since the drag has started, the element will be
                // absolutely positioned, so we check its siblings
                var siblings = ui.item.siblings();
                var sortableWidgetInstance = getSortableWidgetInstance(angular.element(e.target));
                sortableWidgetInstance.floating = isFloating(siblings);
              }

              // Save the starting position of dragged item
              ui.item.sortable = {
                model: ngModel.$modelValue[ui.item.index()],
                index: ui.item.index(),
                source: ui.item.parent(),
                sourceModel: ngModel.$modelValue,
                cancel: function () {
                  ui.item.sortable._isCanceled = true;
                },
                isCanceled: function () {
                  return ui.item.sortable._isCanceled;
                },
                isCustomHelperUsed: function () {
                  return !!ui.item.sortable._isCustomHelperUsed;
                },
                _isCanceled: false,
                _isCustomHelperUsed: ui.item.sortable._isCustomHelperUsed,
                _destroy: function () {
                  angular.forEach(ui.item.sortable, function(value, key) {
                    ui.item.sortable[key] = undefined;
                  });
                }
              };
            };

            callbacks.activate = function(e, ui) {
              // We need to make a copy of the current element's contents so
              // we can restore it after sortable has messed it up.
              // This is inside activate (instead of start) in order to save
              // both lists when dragging between connected lists.
              savedNodes = element.contents();

              // If this list has a placeholder (the connected lists won't),
              // don't inlcude it in saved nodes.
              var placeholder = element.sortable('option','placeholder');

              // placeholder.element will be a function if the placeholder, has
              // been created (placeholder will be an object).  If it hasn't
              // been created, either placeholder will be false if no
              // placeholder class was given or placeholder.element will be
              // undefined if a class was given (placeholder will be a string)
              if (placeholder && placeholder.element && typeof placeholder.element === 'function') {
                var phElement = placeholder.element();
                // workaround for jquery ui 1.9.x,
                // not returning jquery collection
                phElement = angular.element(phElement);

                // exact match with the placeholder's class attribute to handle
                // the case that multiple connected sortables exist and
                // the placehoilder option equals the class of sortable items
                var excludes = element.find('[class="' + phElement.attr('class') + '"]:not([ng-repeat], [data-ng-repeat])');

                savedNodes = savedNodes.not(excludes);
              }

              // save the directive's scope so that it is accessible from ui.item.sortable
              var connectedSortables = ui.item.sortable._connectedSortables || [];

              connectedSortables.push({
                element: element,
                scope: scope
              });

              ui.item.sortable._connectedSortables = connectedSortables;
            };

            callbacks.update = function(e, ui) {
              // Save current drop position but only if this is not a second
              // update that happens when moving between lists because then
              // the value will be overwritten with the old value
              if(!ui.item.sortable.received) {
                ui.item.sortable.dropindex = ui.item.index();
                var droptarget = ui.item.parent();
                ui.item.sortable.droptarget = droptarget;

                var droptargetScope = getElementScope(ui.item.sortable._connectedSortables, droptarget);
                ui.item.sortable.droptargetModel = droptargetScope.ngModel;

                // Cancel the sort (let ng-repeat do the sort for us)
                // Don't cancel if this is the received list because it has
                // already been canceled in the other list, and trying to cancel
                // here will mess up the DOM.
                element.sortable('cancel');
              }

              // Put the nodes back exactly the way they started (this is very
              // important because ng-repeat uses comment elements to delineate
              // the start and stop of repeat sections and sortable doesn't
              // respect their order (even if we cancel, the order of the
              // comments are still messed up).
              if (hasSortingHelper(element, ui) && !ui.item.sortable.received &&
                  element.sortable( 'option', 'appendTo' ) === 'parent') {
                // restore all the savedNodes except .ui-sortable-helper element
                // (which is placed last). That way it will be garbage collected.
                savedNodes = savedNodes.not(savedNodes.last());
              }
              savedNodes.appendTo(element);

              // If this is the target connected list then
              // it's safe to clear the restored nodes since:
              // update is currently running and
              // stop is not called for the target list.
              if(ui.item.sortable.received) {
                savedNodes = null;
              }

              // If received is true (an item was dropped in from another list)
              // then we add the new item to this list otherwise wait until the
              // stop event where we will know if it was a sort or item was
              // moved here from another list
              if(ui.item.sortable.received && !ui.item.sortable.isCanceled()) {
                scope.$apply(function () {
                  ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0,
                                             ui.item.sortable.moved);
                });
              }
            };

            callbacks.stop = function(e, ui) {
              // If the received flag hasn't be set on the item, this is a
              // normal sort, if dropindex is set, the item was moved, so move
              // the items in the list.
              if(!ui.item.sortable.received &&
                 ('dropindex' in ui.item.sortable) &&
                 !ui.item.sortable.isCanceled()) {

                scope.$apply(function () {
                  ngModel.$modelValue.splice(
                    ui.item.sortable.dropindex, 0,
                    ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]);
                });
              } else {
                // if the item was not moved, then restore the elements
                // so that the ngRepeat's comment are correct.
                if ((!('dropindex' in ui.item.sortable) || ui.item.sortable.isCanceled()) &&
                    !hasSortingHelper(element, ui)) {
                  savedNodes.appendTo(element);
                }
              }

              // It's now safe to clear the savedNodes
              // since stop is the last callback.
              savedNodes = null;
            };

            callbacks.receive = function(e, ui) {
              // An item was dropped here from another list, set a flag on the
              // item.
              ui.item.sortable.received = true;
            };

            callbacks.remove = function(e, ui) {
              // Workaround for a problem observed in nested connected lists.
              // There should be an 'update' event before 'remove' when moving
              // elements. If the event did not fire, cancel sorting.
              if (!('dropindex' in ui.item.sortable)) {
                element.sortable('cancel');
                ui.item.sortable.cancel();
              }

              // Remove the item from this list's model and copy data into item,
              // so the next list can retrive it
              if (!ui.item.sortable.isCanceled()) {
                scope.$apply(function () {
                  ui.item.sortable.moved = ngModel.$modelValue.splice(
                    ui.item.sortable.index, 1)[0];
                });
              }
            };

            wrappers.helper = function (inner) {
              if (inner && typeof inner === 'function') {
                return function (e, item) {
                  var innerResult = inner.apply(this, arguments);
                  item.sortable._isCustomHelperUsed = item !== innerResult;
                  return innerResult;
                };
              }
              return inner;
            };

            scope.$watchCollection('uiSortable', function(newVal /*, oldVal*/) {
              // ensure that the jquery-ui-sortable widget instance
              // is still bound to the directive's element
              var sortableWidgetInstance = getSortableWidgetInstance(element);
              if (!!sortableWidgetInstance) {
                angular.forEach(newVal, function(value, key) {
                  // if it's a custom option of the directive,
                  // handle it approprietly
                  if (key in directiveOpts) {
                    if (key === 'ui-floating' && (value === false || value === true)) {
                      sortableWidgetInstance.floating = value;
                    }

                    opts[key] = value;
                    return;
                  }

                  if (callbacks[key]) {
                    if( key === 'stop' ){
                      // call apply after stop
                      value = combineCallbacks(
                        value, function() { scope.$apply(); });

                      value = combineCallbacks(value, afterStop);
                    }
                    // wrap the callback
                    value = combineCallbacks(callbacks[key], value);
                  } else if (wrappers[key]) {
                    value = wrappers[key](value);
                  }

                  opts[key] = value;
                  element.sortable('option', key, value);
                });
              }
            }, true);

            angular.forEach(callbacks, function(value, key) {
              opts[key] = combineCallbacks(value, opts[key]);
              if( key === 'stop' ){
                opts[key] = combineCallbacks(opts[key], afterStop);
              }
            });

          } else {
            $log.info('ui.sortable: ngModel not provided!', element);
          }

          // Create sortable
          element.sortable(opts);
        }
      };
    }
  ]);
<|endoftext|>


<commit_before>import path from "path";

import { unified } from "unified";
import remarkParse from "remark-parse";
import { visit, SKIP, CONTINUE } from "unist-util-visit";
import { readSync } from "to-vfile";

const remarkImport = () => {
    // TODO: this may need to be configurable some day
    const parser = unified().use(remarkParse);

    const plugin = (tree, file) => {
        // Need history length to resolve files, if it doesn't exist we bail
        if(!file.history.length) {
            return tree;
        }

        const parse = /^@import (?:"|'|“)?(?<name>[^'"”]*)(?:"|'|”)?(?:\n|$)/;
        const { dir } = path.parse(file.history[file.history.length - 1]);

        visit(tree, { type : "text" }, (node, index, parent) => {
            if(!node.value.startsWith("@import")) {
                return SKIP;
            }

            const matched = node.value.match(parse);

            if(!matched) {
                return SKIP;
            }

            const { name } = matched.groups;

            const target = path.resolve(dir, name);

            const md = readSync(target);

            const ast = parser.parse(md);
            const root = parser.runSync(ast);

            for(const i in root) {
                parent[i] = root[i];
            }

            return CONTINUE;
        });

        return tree;
    };

    parser.use(() => plugin);

    return plugin;
};

export default remarkImport;
<commit_msg>feat(www): notifier for imported .md files<commit_after>import path from "path";

import { unified } from "unified";
import remarkParse from "remark-parse";
import { visit, SKIP, CONTINUE } from "unist-util-visit";
import { readSync } from "to-vfile";

const remarkImport = (options = false) => {
    // TODO: this may need to be configurable some day
    const parser = unified().use(remarkParse);

    const { imported } = options;

    const plugin = (tree, file) => {
        // Need history length to resolve files, if it doesn't exist we bail
        if(!file.history.length) {
            return tree;
        }

        const parse = /^@import (?:"|'|“)?(?<name>[^'"”]*)(?:"|'|”)?(?:\n|$)/;
        const { dir } = path.parse(file.history[file.history.length - 1]);

        visit(tree, { type : "text" }, (node, index, parent) => {
            if(!node.value.startsWith("@import")) {
                return SKIP;
            }

            const matched = node.value.match(parse);

            if(!matched) {
                return SKIP;
            }

            const { name } = matched.groups;

            const target = path.resolve(dir, name);

            if(imported) {
                imported(target);
            }

            const md = readSync(target);

            const ast = parser.parse(md);
            const root = parser.runSync(ast);

            for(const i in root) {
                parent[i] = root[i];
            }

            return CONTINUE;
        });

        return tree;
    };

    parser.use(() => plugin);

    return plugin;
};

export default remarkImport;
<|endoftext|>


<commit_before>/**
 * Adds dependency watching to the core fs.watchFile implementation.
 */
var fs = require('fs');

var watchedFiles = {};

function notifyWatch(filename, type, sourceChange) {
    var watchInfo = watchedFiles[filename];
    if (watchInfo) {
        watchInfo.callbacks.forEach(function(callback) {
          callback(type, filename, sourceChange);
        });
        watchInfo.parents.forEach(function(parent) {
          notifyWatch(parent, type, sourceChange);
        });
    }
}

function watchFile(filename, callback, parent) {
    var watchInfo = {
        callbacks: [],
        parents: []
    };
    if (callback) {
        watchInfo.callbacks.push(callback);
    }
    if (parent) {
        watchInfo.parents.push(parent);
    }
    watchedFiles[filename.virtual || filename] = watchInfo;

    if (!filename.virtual) {
      watchInfo.watch = fs.watch(filename, function(type) {
        notifyWatch(filename, type, filename);
      });
    }
}

exports.watchFile = function(filename, dependencies, callback) {
    var watch = watchedFiles[filename.virtual || filename];
    if (!watch) {
        // Create a watch on this and all others
        watchFile(filename, callback);
    } else {
        if (~~watch.callbacks.indexOf(callback)) {
            watch.callbacks.push(callback);
        }
    }

    filename = filename.virtual || filename;

    dependencies.forEach(function(depend) {
        var watch = watchedFiles[depend];
        if (!watch) {
            watchFile(depend, undefined, filename);
        } else {
            if (~~watch.parents.indexOf(filename)) {
                watch.parents.push(filename);
            }
        }
    });
};

exports.unwatchAll = function() {
    for (var name in watchedFiles) {
        if (watchedFiles[name].watch) {
          watchedFiles[name].watch.close();
        }
        delete watchedFiles[name];
    }
};
<commit_msg>Add limited EMFILE retry to watcher watch op<commit_after>/**
 * Adds dependency watching to the core fs.watchFile implementation.
 */
var fs = require('fs');

var watchedFiles = {};

function notifyWatch(filename, type, sourceChange) {
    var watchInfo = watchedFiles[filename];
    if (watchInfo) {
        watchInfo.callbacks.forEach(function(callback) {
          callback(type, filename, sourceChange);
        });
        watchInfo.parents.forEach(function(parent) {
          notifyWatch(parent, type, sourceChange);
        });
    }
}

function watchFile(filename, callback, parent) {
    var watchInfo = {
        callbacks: [],
        parents: []
    };
    if (callback) {
        watchInfo.callbacks.push(callback);
    }
    if (parent) {
        watchInfo.parents.push(parent);
    }
    watchedFiles[filename.virtual || filename] = watchInfo;

    if (!filename.virtual) {
      var hasRetried;

      (function watch() {
        try {
          watchInfo.watch = fs.watch(filename, function(type) {
            notifyWatch(filename, type, filename);
          });
        } catch (err) {
          if (!hasRetried && err.code === 'EMFILE') {
            hasRetried = true;
            setTimeout(watch, 500);
          } else {
            throw err;
          }
        }
      })();
    }
}

exports.watchFile = function(filename, dependencies, callback) {
    var watch = watchedFiles[filename.virtual || filename];
    if (!watch) {
        // Create a watch on this and all others
        watchFile(filename, callback);
    } else {
        if (~~watch.callbacks.indexOf(callback)) {
            watch.callbacks.push(callback);
        }
    }

    filename = filename.virtual || filename;

    dependencies.forEach(function(depend) {
        var watch = watchedFiles[depend];
        if (!watch) {
            watchFile(depend, undefined, filename);
        } else {
            if (~~watch.parents.indexOf(filename)) {
                watch.parents.push(filename);
            }
        }
    });
};

exports.unwatchAll = function() {
    for (var name in watchedFiles) {
        if (watchedFiles[name].watch) {
          watchedFiles[name].watch.close();
        }
        delete watchedFiles[name];
    }
};
<|endoftext|>