<commit_before>/*global module:true */

module.exports = function( grunt ) {
  'use strict';
  //
  // Grunt configuration:
  //
  // https://github.com/cowboy/grunt/blob/master/docs/getting_started.md
  //
  grunt.initConfig({

    buildConfig : {
        temp : "./temp",
        jekyllStageConfig : "_config.stage.yml",
        jekyllProdConfig : "_config.prod.yml",
        jekyllGHConfig : "_config.gh.yml"
    },

    jshint: {
        app : {
            files: {
                src: [
                    'Gruntfile.js',
                    '../app/scripts/*.js',
                    '../app/scripts/models/**/*.js',
                    '../app/scripts/views/**/*.js'
                ]
            },
            options: {
                curly: true,
                eqeqeq: true,
                immed: true,
                latedef: true,
                newcap: true,
                noarg: true,
                sub: true,
                undef: true,
                boss: true,
                eqnull: true,
                browser: true,
                unused: true,

                globals: {
                    jQuery: true,
                    define: true,
                    require: true,
                    Modernizr: true,
                    escape: true,
                    tenantName: true //fix this in models/account.js
                }
            }
        },

        test: {
          options: {
            unused : false,
            expr : true,
            es5 : true,
            globals: {
                jQuery: true,
                define: true,
                require: true,
                Modernizr: true,
                describe: true,
                it: true,
                expect: true,
                sinon: true,
                afterEach: true,
                beforeEach: true
            }
          },
          files: {
            src: ['../test/spec/**/*.js']
          }
        }
    },

    copy: {

        temp: {
            files: [{expand: true, cwd: '../app/', src: ['**'], dest: '<%= buildConfig.temp %>'}]
        },

        gh_stage: {
            files: [
                // scripts

                {expand: true, cwd: '../app/scripts/', src: ['**'], dest: '../target/dist/gh/scripts/'},

                // styles

                {expand: true, cwd: '../app/styles/', src : '*.css', dest: '../target/dist/gh/styles/'},

                // images

                {expand: true, cwd: '../app/images/', src: ['**'], dest: '../target/dist/gh/images/'},

                // fonts

                {expand: true, cwd: '../app/fonts/', src: ['**'], dest: '../target/dist/gh/fonts/'},

                // pages

                {expand: true, cwd: '../app/_site/', src: ['*.html','**/*.html','*.xml'], dest: '../target/dist/gh/'},

                // templates

                {expand: true, cwd: '../app/templates/', src: ['*.html'], dest: '../target/dist/gh/templates/'},

                // robots.txt

                {expand: true, cwd: '../app/_site/', src: ['*.txt'], dest: '../target/dist/gh/'}
            ]
        },

        stage: {
            files: [
                // scripts

                {expand: true, cwd: '../app/scripts/', src: ['**'], dest: '../target/dist/stage/scripts/'},

                // factory scripts

                {expand: true, cwd: '../app/factory/', src: ['**'], dest: '../target/dist/stage/factory/'},

                // factory styles

                {expand: true, cwd: '../app/factory/', src : '*.css', dest: '../target/dist/stage/factory/'},

                // styles

                {expand: true, cwd: '../app/styles/', src : '*.css', dest: '../target/dist/stage/styles/'},

                // images

                {expand: true, cwd: '../app/images/', src: ['**'], dest: '../target/dist/stage/images/'},

                // fonts

                {expand: true, cwd: '../app/fonts/', src: ['**'], dest: '../target/dist/stage/fonts/'},

                // pages

                {expand: true, cwd: '../app/_site/', src: ['*.html','**/*.html','*.xml'], dest: '../target/dist/stage/'},

                // templates

                {expand: true, cwd: '../app/templates/', src: ['*.html'], dest: '../target/dist/stage/templates/'},

                // robots.txt

                {expand: true, cwd: '../app/_site/', src: ['*.txt'], dest: '../target/dist/stage/'}

            ]
        },

        prod: {
            files: [
                // scripts

                {
                    expand: true,
                    cwd: '../dist/scripts/',
                    src: ['vendor/modernizr*.js','*.amd-app.js'],
                    dest: '../target/dist/prod/scripts/'
                },

                // factory scripts

                {
                    expand: true,
                    cwd: '../dist/factory/',
                    src: '*.js',
                    dest: '../target/dist/prod/factory/'
                },

                // factory styles

                {
                    expand: true,
                    cwd: '../dist/factory/',
                    src : '*.css',
                    dest: '../target/dist/prod/factory/'
                },

                // styles

                {
                    expand: true,
                    cwd: '../dist/styles/',
                    src : '*.css',
                    dest: '../target/dist/prod/styles/'
                },

                // images

                {
                    expand: true,
                    cwd: '../dist/images/',
                    src: ['**'],
                    dest: '../target/dist/prod/images/'
                },

                // fonts

                {
                    expand: true,
                    cwd: '../dist/fonts/',
                    src: ['**'],
                    dest: '../target/dist/prod/fonts/'
                },

                // pages

                {
                    expand: true,
                    cwd: '../dist/_site/',
                    src: ['*.html','**/*.html','*.xml'],
                    dest: '../target/dist/prod/'
                },

                // robots.txt

                {expand: true, cwd: '../app/_site/', src: ['*.txt'], dest: '../target/dist/prod/'}
            ]
        }
    },

    shell : {

        init : {
            command: 'rm -rf dist',
            options: {
                stdout: true,
                failOnError: true
            }
        },

        jekyll_stage_config : {
            command: 'cp <%= buildConfig.jekyllStageConfig %> <%= buildConfig.temp %>/_config.yml',
            options: {
                stdout: true,
                failOnError: true
            }
        },

        jekyll_gh_config : {
            command: 'cp <%= buildConfig.jekyllGHConfig %> <%= buildConfig.temp %>/_config.yml',
            options: {
                stdout: true,
                failOnError: true
            }
        },

        jekyll_prod_config : {
            command: 'cp <%= buildConfig.jekyllProdConfig %> <%= buildConfig.temp %>/_config.yml',
            options: {
                stdout: true,
                failOnError: true
            }
        },

        jekyll : {
            command: 'jekyll',
            options: {
                stdout: true,
                failOnError: true,
                execOptions: {
                    cwd: '<%= buildConfig.temp %>'
                }
            }
        },

        yeoman : {
            command: 'yeoman build',
            options: {
                stdout: true,
                failOnError: true,
                execOptions: {
                    cwd: '../',
                    maxBuffer: 1024000
                }
            }
        },

        clean_dist : {
            command: 'rm -rf ../dist && rm -rf ../temp && rm -rf <%= buildConfig.temp %>',
            options: {
                stdout: true,
                failOnError: true,
                execOptions: {
                    cwd: './'
                }
            }
        }
    }

  });

  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.registerTask('build',
        [
            //check code quality before building
            'jshint:test', 'jshint:app',

            // get rid of the previous dist jazz
            'shell:init',

            // copy all application files to the temporary folder
            'copy:temp',

            // ------------------ Github pages STAGING

            // copy staging _config.yml to the temporary folder
            'shell:jekyll_gh_config',

            // run jekyll build for github staging
            'shell:jekyll',

            // run yeoman build on top of staging Jekyll build
            'shell:yeoman',

            // copy staging build output
            'copy:gh_stage',

            // ------------------ STAGING

            // copy staging _config.yml to the temporary folder
            'shell:jekyll_stage_config',

            // run jekyll build for staging
            'shell:jekyll',

            // run yeoman build on top of staging Jekyll build
            'shell:yeoman',

            // copy staging build output
            'copy:stage',

            // ------------------ PRODUCTION

            // copy staging _config.yml to the temporary folder
            'shell:jekyll_prod_config',

            // run jekyll build for production
            'shell:jekyll',

            // run yeoman build on top of production Jekyll build
            'shell:yeoman',

            // copy production goodness
            'copy:prod',

            // clean up
            'shell:clean_dist'
        ]
    );
};
<commit_msg>CLDIDE copy factory resources to prod<commit_after>/*global module:true */

module.exports = function( grunt ) {
  'use strict';
  //
  // Grunt configuration:
  //
  // https://github.com/cowboy/grunt/blob/master/docs/getting_started.md
  //
  grunt.initConfig({

    buildConfig : {
        temp : "./temp",
        jekyllStageConfig : "_config.stage.yml",
        jekyllProdConfig : "_config.prod.yml",
        jekyllGHConfig : "_config.gh.yml"
    },

    jshint: {
        app : {
            files: {
                src: [
                    'Gruntfile.js',
                    '../app/scripts/*.js',
                    '../app/scripts/models/**/*.js',
                    '../app/scripts/views/**/*.js'
                ]
            },
            options: {
                curly: true,
                eqeqeq: true,
                immed: true,
                latedef: true,
                newcap: true,
                noarg: true,
                sub: true,
                undef: true,
                boss: true,
                eqnull: true,
                browser: true,
                unused: true,

                globals: {
                    jQuery: true,
                    define: true,
                    require: true,
                    Modernizr: true,
                    escape: true,
                    tenantName: true //fix this in models/account.js
                }
            }
        },

        test: {
          options: {
            unused : false,
            expr : true,
            es5 : true,
            globals: {
                jQuery: true,
                define: true,
                require: true,
                Modernizr: true,
                describe: true,
                it: true,
                expect: true,
                sinon: true,
                afterEach: true,
                beforeEach: true
            }
          },
          files: {
            src: ['../test/spec/**/*.js']
          }
        }
    },

    copy: {

        temp: {
            files: [{expand: true, cwd: '../app/', src: ['**'], dest: '<%= buildConfig.temp %>'}]
        },

        gh_stage: {
            files: [
                // scripts

                {expand: true, cwd: '../app/scripts/', src: ['**'], dest: '../target/dist/gh/scripts/'},

                // styles

                {expand: true, cwd: '../app/styles/', src : '*.css', dest: '../target/dist/gh/styles/'},

                // images

                {expand: true, cwd: '../app/images/', src: ['**'], dest: '../target/dist/gh/images/'},

                // fonts

                {expand: true, cwd: '../app/fonts/', src: ['**'], dest: '../target/dist/gh/fonts/'},

                // pages

                {expand: true, cwd: '../app/_site/', src: ['*.html','**/*.html','*.xml'], dest: '../target/dist/gh/'},

                // templates

                {expand: true, cwd: '../app/templates/', src: ['*.html'], dest: '../target/dist/gh/templates/'},

                // robots.txt

                {expand: true, cwd: '../app/_site/', src: ['*.txt'], dest: '../target/dist/gh/'}
            ]
        },

        stage: {
            files: [
                // scripts

                {expand: true, cwd: '../app/scripts/', src: ['**'], dest: '../target/dist/stage/scripts/'},

                // factory folder

                {expand: true, cwd: '../app/factory/', src: ['**'], dest: '../target/dist/stage/factory/'},

                // styles

                {expand: true, cwd: '../app/styles/', src : '*.css', dest: '../target/dist/stage/styles/'},

                // images

                {expand: true, cwd: '../app/images/', src: ['**'], dest: '../target/dist/stage/images/'},

                // fonts

                {expand: true, cwd: '../app/fonts/', src: ['**'], dest: '../target/dist/stage/fonts/'},

                // pages

                {expand: true, cwd: '../app/_site/', src: ['*.html','**/*.html','*.xml'], dest: '../target/dist/stage/'},

                // templates

                {expand: true, cwd: '../app/templates/', src: ['*.html'], dest: '../target/dist/stage/templates/'},

                // robots.txt

                {expand: true, cwd: '../app/_site/', src: ['*.txt'], dest: '../target/dist/stage/'}

            ]
        },

        prod: {
            files: [
                // scripts

                {
                    expand: true,
                    cwd: '../dist/scripts/',
                    src: ['vendor/modernizr*.js','*.amd-app.js'],
                    dest: '../target/dist/prod/scripts/'
                },

                // factory folder

                {
                    expand: true,
                    cwd: '../dist/factory/',
                    src: ['**'],
                    dest: '../target/dist/prod/factory/'
                },

                // styles

                {
                    expand: true,
                    cwd: '../dist/styles/',
                    src : '*.css',
                    dest: '../target/dist/prod/styles/'
                },

                // images

                {
                    expand: true,
                    cwd: '../dist/images/',
                    src: ['**'],
                    dest: '../target/dist/prod/images/'
                },

                // fonts

                {
                    expand: true,
                    cwd: '../dist/fonts/',
                    src: ['**'],
                    dest: '../target/dist/prod/fonts/'
                },

                // pages

                {
                    expand: true,
                    cwd: '../dist/_site/',
                    src: ['*.html','**/*.html','*.xml'],
                    dest: '../target/dist/prod/'
                },

                // robots.txt

                {expand: true, cwd: '../app/_site/', src: ['*.txt'], dest: '../target/dist/prod/'}
            ]
        }
    },

    shell : {

        init : {
            command: 'rm -rf dist',
            options: {
                stdout: true,
                failOnError: true
            }
        },

        jekyll_stage_config : {
            command: 'cp <%= buildConfig.jekyllStageConfig %> <%= buildConfig.temp %>/_config.yml',
            options: {
                stdout: true,
                failOnError: true
            }
        },

        jekyll_gh_config : {
            command: 'cp <%= buildConfig.jekyllGHConfig %> <%= buildConfig.temp %>/_config.yml',
            options: {
                stdout: true,
                failOnError: true
            }
        },

        jekyll_prod_config : {
            command: 'cp <%= buildConfig.jekyllProdConfig %> <%= buildConfig.temp %>/_config.yml',
            options: {
                stdout: true,
                failOnError: true
            }
        },

        jekyll : {
            command: 'jekyll',
            options: {
                stdout: true,
                failOnError: true,
                execOptions: {
                    cwd: '<%= buildConfig.temp %>'
                }
            }
        },

        yeoman : {
            command: 'yeoman build',
            options: {
                stdout: true,
                failOnError: true,
                execOptions: {
                    cwd: '../',
                    maxBuffer: 1024000
                }
            }
        },

        clean_dist : {
            command: 'rm -rf ../dist && rm -rf ../temp && rm -rf <%= buildConfig.temp %>',
            options: {
                stdout: true,
                failOnError: true,
                execOptions: {
                    cwd: './'
                }
            }
        }
    }

  });

  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.registerTask('build',
        [
            //check code quality before building
            'jshint:test', 'jshint:app',

            // get rid of the previous dist jazz
            'shell:init',

            // copy all application files to the temporary folder
            'copy:temp',

            // ------------------ Github pages STAGING

            // copy staging _config.yml to the temporary folder
            'shell:jekyll_gh_config',

            // run jekyll build for github staging
            'shell:jekyll',

            // run yeoman build on top of staging Jekyll build
            'shell:yeoman',

            // copy staging build output
            'copy:gh_stage',

            // ------------------ STAGING

            // copy staging _config.yml to the temporary folder
            'shell:jekyll_stage_config',

            // run jekyll build for staging
            'shell:jekyll',

            // run yeoman build on top of staging Jekyll build
            'shell:yeoman',

            // copy staging build output
            'copy:stage',

            // ------------------ PRODUCTION

            // copy staging _config.yml to the temporary folder
            'shell:jekyll_prod_config',

            // run jekyll build for production
            'shell:jekyll',

            // run yeoman build on top of production Jekyll build
            'shell:yeoman',

            // copy production goodness
            'copy:prod',

            // clean up
            'shell:clean_dist'
        ]
    );
};
<|endoftext|>


<commit_before>Tinytest.add("lodash - Exists", function(test) {
	test.notEqual(typeof lodash, 'undefined', "Expected lodash to not be undefined");
});
<commit_msg>Add test to check that _ and lodash are equal<commit_after>Tinytest.add("lodash - Exists", function(test) {
	test.notEqual(typeof lodash, 'undefined', "Expected lodash to not be undefined");
});

Tinytest.add("lodash - lodash equals _", function(test) {
	test.equal(lodash, _, "Expected lodash to be equal to _");
});
<|endoftext|>


<commit_before>/* -*- coding: utf-8 -*- vim: set ts=2 sw=2 expandtab
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Copyright (C) 2002-2012  TechGame Networks, LLC.
~
~ This library is free software; you can redistribute it
~ and/or modify it under the terms of the MIT style License as
~ found in the LICENSE file included with this distribution.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For futures and promises {then:, resolve:, reject:} must always be fully bound closures.
*/

"use strict";

exports.Promise = Promise
function Promise(then) { if (then!==undefined) this.then = then }
Promise.api = {
    always: function(always) { return this.then(always, always) },
    done: function(success) { return this.then(success, undefined) },
    fail: function(failure) { return this.then(undefined, failure) },
    thenCall: function(callback) { // chain to node-style callback(err, ans)
        return this.then(callback.bind(this,null), callback.bind(this)) },
    timeout: function(ms) { return Promise.timeout(this, ms) },
    thenLog: function(opt) { return thenLog(this, opt) }
}
Promise.prototype = Object.create(Promise.api,
    {promise: {get: function(){return this}}
    ,state: {get: function(){return this.then.state}}
    })

exports.isPromise = Promise.isPromise = isPromise
function isPromise(tgt) {
    return (tgt!==undefined) && (tgt.then!==undefined) }

exports.asPromise = Promise.wrap = asPromise
function asPromise(tgt) {
    return isPromise(tgt) ? tgt : Future.resolved(tgt).promise }

exports.when = Promise.when = when
function when(tgt, success, failure) {
    if (success!==undefined || failure!==undefined)
        return asPromise(tgt).then(success, failure)
    else return asPromise(tgt) }

var slice = Array.prototype.slice

exports.Future = Future
function Future(then, resolve, reject) {
    this.promise = new Promise(then)
    if (resolve !== undefined)
        this.resolve = resolve
    if (reject !== undefined)
        this.reject = reject
}
Future.prototype = Object.create(Promise.api,
    {then: {get: function(){return this.promise.then}}
    ,state: {get: function(){return this.promise.state}}
    ,callback: {get: function(){ var self=this; // lazy-bind node-style callback
      return function(err, ans){
          return err ? self.reject(err)
            : self.resolve.apply(self, slice.call(arguments, 1)); }}}
    })
Future.prototype.resolve = function(result) { }
Future.prototype.reject = function(error) { }

exports.isFuture = Future.isFuture = isFuture
function isFuture(tgt) {
    return (tgt!==undefined) &&
         ( (typeof tgt.resolve==='function')
        || (typeof tgt.reject ==='function')) }

//~ Future: thenable, deferred, resolved and rejected ~~~~~~~
exports.thenable = Future.thenable = thenable
function thenable(thisArg, success, failure, inner) {
    if (typeof success === "object") {
        if (failure===undefined)
            failure = success.failure || success.reject || success.fail
        success = success.success || success.resolve || success.done
    }
    if (success===undefined && failure===undefined)
        return Future.deferred(thisArg)
    else return new Future(then, resolve, reject)

    function argsAsArray(args) {
        return args instanceof Array ? args : [args] }
    function then(success, failure) {
        if (inner===undefined)
            inner = Future.deferred(thisArg)
        return inner.then(success, failure) }
    function resolve() {
        then.state = true
        var resultVec = arguments,
            next = (inner!==undefined) ? inner : Future.absentTail
        if (success!==undefined)
            try {
                var res = success.apply(thisArg, resultVec)
                if (res!==undefined)
                    resultVec = argsAsArray(res)
            } catch (err) {
                success = failure = undefined
                inner = Future.rejected(err, thisArg)
                return next.reject(err)
            }
        else if (failure===undefined) return
        success = failure = undefined
        inner = Future.resolved(resultVec, thisArg, true)
        return next.resolve.apply(next, resultVec) }
    function reject() {
        then.state = false
        var errorVec = arguments,
            next = (inner!==undefined) ? inner : Future.absentTail
        if (failure!==undefined)
            try {
                var res = failure.apply(thisArg, errorVec)
                if (res!==undefined)
                    errorVec = argsAsArray(res)
            } catch (err) { errorVec = [err] }
        else if (success===undefined) return;
        success = failure = undefined
        inner = Future.rejected(errorVec, thisArg, true)
        return next.reject.apply(next, errorVec) } }

Future.absentTail = {resolve: function() {}, reject: function() {}}
Future.onActionError = function(error, thisArg) { console.error(error) }

exports.deferred = Future.deferred = deferred
function deferred(thisArg) {
    var actions=[], inner
    return new Future(then, resolve, reject)
    function then(success, failure) {
        if (inner!==undefined)
            return inner.then(success, failure)
        var ans = Future.thenable(thisArg, success, failure)
        actions.push(ans)
        return ans.promise }
    function resolve() {
        then.state = true
        if (actions===undefined) return;
        var resultVec = arguments
        inner = Future.resolved(resultVec, thisArg, true)
        for (var i=0; i<actions.length; i++) {
            var ea = actions[i].resolve
            if (ea===undefined) continue
            try { ea.apply(thisArg, resultVec)
            } catch (err) { Future.onActionError(err, thisArg) }
        } actions = undefined }
    function reject() {
        then.state = false
        if (actions===undefined) return
        var errorVec = arguments
        inner = Future.rejected(errorVec, thisArg, true)
        for (var i=0; i<actions.length; i++) {
            var ea = actions[i].reject
            if (ea===undefined) continue
            try { ea.apply(thisArg, errorVec)
            } catch (err) { Future.onActionError(err, thisArg) }
        } actions = undefined }
}

exports.resolved = Future.resolved = resolved
function resolved(result, thisArg, inVecForm) {
    if (!inVecForm) result = [result]
    else result = slice.call(result, 0)
    then.state = true
    return new Future(then)
    function then(success, failure) {
        var ans = thenable(thisArg, success, failure)
        return ans.resolve.apply(ans, result), ans.promise }}

exports.rejected = Future.rejected = rejected
function rejected(error, thisArg, inVecForm) {
    if (!inVecForm) error = [error]
    else error = slice.call(error, 0)
    then.state = false
    return new Future(then)
    function then(success, failure) {
        var ans = thenable(thisArg, success, failure)
        return ans.reject.apply(ans, error), ans.promise }}

//~ Utility Futures: invert, delay and timeout ~~~~~~~~~~~~~~
exports.inverted = Future.inverted = inverted
function inverted(tgt) {
    if (tgt===undefined) tgt = deferred()
    return new Future(tgt.then, tgt.reject, tgt.resolve) }

exports.delay = Future.delay = Promise.delay = delay
function delay(ms, bReject) {
    var res=deferred(),
        tid=setTimeout(bReject?res.reject:res.resolve, ms)
    res.always(function() {clearTimeout(tid)})
    return res }
exports.timeout = Future.timeout = Promise.timeout = timeout
function timeout(target, ms, bReject) {
    var res = delay(ms, (bReject!=undefined?bReject:true))
    when(target, res)
    return res }

exports.thenLog = thenLog
function thenLog(target, opt) {
    if (!opt) opt = {}
    var log = opt.log || console.log,
        s = opt.success || 'success',
        f = opt.failure || 'failure'

    if (!opt.showArgs && opt.showArgs!==undefined)
        target.then(function(){log(s)}, function(){log(f)})
    else target.then(
        function(){log(s+': ', slice.call(arguments, 0).join(', '))},
        function(){log(f+': ', slice.call(arguments, 0).join(', '))})
    return target /* don't chain for logging */ }

//~ Compositions: any, all, every, first ~~~~~~~~~~~~~~~~~~~~
function forEachPromise(anArray, thisArg, resolveFirst, rejectFirst, rejectAll) {
    var n=0, future=deferred(thisArg), linchpin={
        push: function(ea) {
            if (isPromise(ea)) {
                ++n; ea.then(linchpin)
            } else if (resolveFirst)
                future.resolve(anArray)
            return ea },
        resolve: function() {
            if (resolveFirst || (--n < 1))
                future.resolve(anArray) },
        reject: function() {
            if (rejectFirst || (--n < 1))
                future.reject(anArray)
            if (rejectAll)
                future.resolve = future.reject } }

    ;[].forEach.call(anArray, linchpin.push)
    if (n<1) future.resolve(n)
    return future }

exports.every = Future.every = Promise.every = every
function every(anArray, thisArg) {
    return forEachPromise(anArray, thisArg, false, false, true) }
exports.all = Future.all = Promise.all = all
function all(anArray, thisArg) {
    return forEachPromise(anArray, thisArg, false, true) }
exports.first = Future.first = Promise.first = first
function first(anArray, thisArg) {
    return forEachPromise(anArray, thisArg, true, true) }
exports.any = Future.any = Promise.any = any
function any(anArray, thisArg) {
    return forEachPromise(anArray, thisArg, true, false) }

<commit_msg>Changed indent to 2 spaces<commit_after>/* -*- coding: utf-8 -*- vim: ts=2 sw=2 expandtab
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Copyright (C) 2002-2012  TechGame Networks, LLC.
~
~ This library is free software; you can redistribute it
~ and/or modify it under the terms of the MIT style License as
~ found in the LICENSE file included with this distribution.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For futures and promises {then:, resolve:, reject:} must always be fully bound closures.
*/

"use strict";

exports.Promise = Promise
function Promise(then) { if (then!==undefined) this.then = then }
Promise.api = {
  always: function(always) { return this.then(always, always) },
  done: function(success) { return this.then(success, undefined) },
  fail: function(failure) { return this.then(undefined, failure) },
  thenCall: function(callback) { // chain to node-style callback(err, ans)
    return this.then(callback.bind(this,null), callback.bind(this)) },
  timeout: function(ms) { return Promise.timeout(this, ms) },
  thenLog: function(opt) { return thenLog(this, opt) }
}
Promise.prototype = Object.create(Promise.api,
  {promise: {get: function(){return this}}
  ,state: {get: function(){return this.then.state}}
  })

exports.isPromise = Promise.isPromise = isPromise
function isPromise(tgt) {
  return (tgt!==undefined) && (tgt.then!==undefined) }

exports.asPromise = Promise.wrap = asPromise
function asPromise(tgt) {
  return isPromise(tgt) ? tgt : Future.resolved(tgt).promise }

exports.when = Promise.when = when
function when(tgt, success, failure) {
  if (success!==undefined || failure!==undefined)
    return asPromise(tgt).then(success, failure)
  else return asPromise(tgt) }

var slice = Array.prototype.slice

exports.Future = Future
function Future(then, resolve, reject) {
  this.promise = new Promise(then)
  if (resolve !== undefined)
    this.resolve = resolve
  if (reject !== undefined)
    this.reject = reject
}
Future.prototype = Object.create(Promise.api,
  {then: {get: function(){return this.promise.then}}
  ,state: {get: function(){return this.promise.state}}
  ,callback: {get: function(){ var self=this; // lazy-bind node-style callback
    return function(err, ans){
      return err ? self.reject(err)
        : self.resolve.apply(self, slice.call(arguments, 1)); }}}
  })
Future.prototype.resolve = function(result) { }
Future.prototype.reject = function(error) { }

exports.isFuture = Future.isFuture = isFuture
function isFuture(tgt) {
  return (tgt!==undefined) && (isFunction(tgt.resolve) || isFunction(tgt.reject))}
function isFunction(a) { return 'function'===typeof a }

//~ Future: thenable, deferred, resolved and rejected ~~~~~~~
exports.thenable = Future.thenable = thenable
function thenable(thisArg, success, failure, inner) {
  if (typeof success === "object") {
    if (failure===undefined)
      failure = success.failure || success.reject || success.fail
    success = success.success || success.resolve || success.done
  }
  if (success===undefined && failure===undefined)
    return Future.deferred(thisArg)
  else return new Future(then, resolve, reject)

  function argsAsArray(args) {
    return args instanceof Array ? args : [args] }
  function then(success, failure) {
    if (inner===undefined)
      inner = Future.deferred(thisArg)
    return inner.then(success, failure) }
  function resolve() {
    then.state = true
    var resultVec = arguments,
        next = (inner!==undefined) ? inner : Future.absentTail
    if (success!==undefined)
      try {
        var res = success.apply(thisArg, resultVec)
        if (res!==undefined)
          resultVec = argsAsArray(res)
      } catch (err) {
        success = failure = undefined
        inner = Future.rejected(err, thisArg)
        return next.reject(err)
      }
    else if (failure===undefined) return
    success = failure = undefined
    inner = Future.resolved(resultVec, thisArg, true)
    return next.resolve.apply(next, resultVec) }
  function reject() {
    then.state = false
    var errorVec = arguments,
        next = (inner!==undefined) ? inner : Future.absentTail
    if (failure!==undefined)
      try {
        var res = failure.apply(thisArg, errorVec)
        if (res!==undefined)
          errorVec = argsAsArray(res)
      } catch (err) { errorVec = [err] }
    else if (success===undefined) return;
    success = failure = undefined
    inner = Future.rejected(errorVec, thisArg, true)
    return next.reject.apply(next, errorVec) } }

Future.absentTail = {resolve: function() {}, reject: function() {}}
Future.onActionError = function(error, thisArg) { console.error(error) }

exports.deferred = Future.deferred = deferred
function deferred(thisArg) {
  var actions=[], inner
  return new Future(then, resolve, reject)
  function then(success, failure) {
    if (inner!==undefined)
      return inner.then(success, failure)
    var ans = Future.thenable(thisArg, success, failure)
    actions.push(ans)
    return ans.promise }
  function resolve() {
    then.state = true
    if (actions===undefined) return;
    var resultVec = arguments
    inner = Future.resolved(resultVec, thisArg, true)
    for (var i=0; i<actions.length; i++) {
      var ea = actions[i].resolve
      if (ea===undefined) continue
      try { ea.apply(thisArg, resultVec)
      } catch (err) { Future.onActionError(err, thisArg) }
    } actions = undefined }
  function reject() {
    then.state = false
    if (actions===undefined) return
    var errorVec = arguments
    inner = Future.rejected(errorVec, thisArg, true)
    for (var i=0; i<actions.length; i++) {
      var ea = actions[i].reject
      if (ea===undefined) continue
      try { ea.apply(thisArg, errorVec)
      } catch (err) { Future.onActionError(err, thisArg) }
    } actions = undefined }
}

exports.resolved = Future.resolved = resolved
function resolved(result, thisArg, inVecForm) {
  if (!inVecForm) result = [result]
  else result = slice.call(result, 0)
  then.state = true
  return new Future(then)
  function then(success, failure) {
    var ans = thenable(thisArg, success, failure)
    return ans.resolve.apply(ans, result), ans.promise }}

exports.rejected = Future.rejected = rejected
function rejected(error, thisArg, inVecForm) {
  if (!inVecForm) error = [error]
  else error = slice.call(error, 0)
  then.state = false
  return new Future(then)
  function then(success, failure) {
    var ans = thenable(thisArg, success, failure)
    return ans.reject.apply(ans, error), ans.promise }}

//~ Utility Futures: invert, delay and timeout ~~~~~~~~~~~~~~
exports.inverted = Future.inverted = inverted
function inverted(tgt) {
  if (tgt===undefined) tgt = deferred()
  return new Future(tgt.then, tgt.reject, tgt.resolve) }

exports.delay = Future.delay = Promise.delay = delay
function delay(ms, bReject) {
  var res=deferred(),
      tid=setTimeout(bReject?res.reject:res.resolve, ms)
  res.always(function() {clearTimeout(tid)})
  return res }
exports.timeout = Future.timeout = Promise.timeout = timeout
function timeout(target, ms, bReject) {
  var res = delay(ms, (bReject!=undefined?bReject:true))
  when(target, res)
  return res }

exports.thenLog = thenLog
function thenLog(target, opt) {
  if (!opt) opt = {}
  var log = opt.log || console.log,
      s = opt.success || 'success',
      f = opt.failure || 'failure'

  if (!opt.showArgs && opt.showArgs!==undefined)
    target.then(function(){log(s)}, function(){log(f)})
  else target.then(
    function(){log(s+': ', slice.call(arguments, 0).join(', '))},
    function(){log(f+': ', slice.call(arguments, 0).join(', '))})
  return target /* don't chain for logging */ }

//~ Compositions: any, all, every, first ~~~~~~~~~~~~~~~~~~~~
function forEachPromise(anArray, thisArg, resolveFirst, rejectFirst, rejectAll) {
  var n=0, future=deferred(thisArg), linchpin={
    push: function(ea) {
      if (isPromise(ea)) {
        ++n; ea.then(linchpin)
      } else if (resolveFirst)
        future.resolve(anArray)
      return ea },
    resolve: function() {
      if (resolveFirst || (--n < 1))
        future.resolve(anArray) },
    reject: function() {
      if (rejectFirst || (--n < 1))
        future.reject(anArray)
      if (rejectAll)
        future.resolve = future.reject } }

  ;[].forEach.call(anArray, linchpin.push)
  if (n<1) future.resolve(n)
  return future }

exports.every = Future.every = Promise.every = every
function every(anArray, thisArg) {
  return forEachPromise(anArray, thisArg, false, false, true) }
exports.all = Future.all = Promise.all = all
function all(anArray, thisArg) {
  return forEachPromise(anArray, thisArg, false, true) }
exports.first = Future.first = Promise.first = first
function first(anArray, thisArg) {
  return forEachPromise(anArray, thisArg, true, true) }
exports.any = Future.any = Promise.any = any
function any(anArray, thisArg) {
  return forEachPromise(anArray, thisArg, true, false) }

<|endoftext|>


<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import path from 'path';
import gaze from 'gaze';
import Promise from 'bluebird';
import fs from './lib/fs';
import pkg from '../package.json';
/**
 * Copies static files such as robots.txt, favicon.ico to the
 * output (build) folder.
 */
async function copy({ watch } = {}) {
  const ncp = Promise.promisify(require('ncp'));

  await Promise.all([
    ncp('src/public', 'build/public'),
    ncp('src/content', 'build/content'),
    ncp('package.json', 'build/package.json'),
    ncp('.env.prod', 'build/.env'),
    ncp('database.js', 'build/database.js'),
    ncp('.sequelizerc', 'build/.sequelizerc'),
    ncp('db', 'build/db'),
    ncp('cert', 'build/cert')
  ]);

  await fs.writeFile('./build/package.json', JSON.stringify({
    private: true,
    engines: pkg.engines,
    dependencies: pkg.dependencies,
    scripts: {
      start: 'node server.js',
    },
  }, null, 2));

  if (watch) {
    const watcher = await new Promise((resolve, reject) => {
      gaze('src/content/**/*.*', (err, val) => err ? reject(err) : resolve(val));
    });
    watcher.on('changed', async (file) => {
      const relPath = file.substr(path.join(__dirname, '../src/content/').length);
      await ncp(`src/content/${relPath}`, `build/content/${relPath}`);
    });
  }
}

export default copy;
<commit_msg>Fixes #614<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import path from 'path';
import gaze from 'gaze';
import Promise from 'bluebird';
import fs from './lib/fs';
import pkg from '../package.json';
/**
 * Copies static files such as robots.txt, favicon.ico to the
 * output (build) folder.
 */
async function copy({ watch } = {}) {
  const ncp = Promise.promisify(require('ncp'));

  await Promise.all([
    ncp('src/public', 'build/public'),
    ncp('src/content', 'build/content'),
    ncp('package.json', 'build/package.json'),
    ncp('.env.prod', 'build/.env'),
    ncp('database.js', 'build/database.js'),
    ncp('.sequelizerc', 'build/.sequelizerc'),
    ncp('db', 'build/db'),
    ncp('cert', 'build/cert')
  ]);

  await fs.writeFile('./build/package.json', JSON.stringify({
    private: true,
    engines: pkg.engines,
    dependencies: pkg.dependencies,
    scripts: {
      start: 'node server.js',
    },
  }, null, 2));

  if (watch) {
    const watcher = await new Promise((resolve, reject) => {
      gaze('src/content/**/*.*', (err, val) => err ? reject(err) : resolve(val));
    });
    const cp = async (file) => {
      const relPath = file.substr(path.join(__dirname, '../src/content/').length);
      await ncp(`src/content/${relPath}`, `build/content/${relPath}`);
    }
    watcher.on('changed', cp);
    watcher.on('added',   cp);
  }
}

export default copy;
<|endoftext|>


<commit_before>import Vue from 'vue/dist/vue.js';
import './vue-plugins';

// components
import PageContainer from './PageContainer.vue';
import Sidebar from './Sidebar.vue';
import { ProfileDialog } from './components/profile_dialog';

// helpers
import './hub_call';
import EventEmitter from './event_emitter';

frappe.provide('hub');
frappe.provide('erpnext.hub');

$.extend(erpnext.hub, EventEmitter.prototype);

erpnext.hub.Marketplace = class Marketplace {
	constructor({ parent }) {
		this.$parent = $(parent);
		this.page = parent.page;

		frappe.model.with_doc('Marketplace Settings').then(doc => {
			hub.settings = doc;
			const is_registered = hub.settings.registered;
			const is_registered_seller = hub.settings.company_email === frappe.session.user;
			this.setup_header();
			this.make_sidebar();
			this.make_body();
			this.setup_events();
			this.refresh();
			if (!is_registered && !is_registered_seller && frappe.user_roles.includes('System Manager')) {
				this.page.set_primary_action('Become a Seller', this.show_register_dialog.bind(this))
			}
		});
	}

	setup_header() {
		this.page.set_title(__('Marketplace'));
	}

	setup_events() {
		this.$parent.on('click', '[data-route]', (e) => {
			const $target = $(e.currentTarget);
			const route = $target.data().route;
			frappe.set_route(route);
		});

		// generic action handler
		this.$parent.on('click', '[data-action]', e => {
			const $target = $(e.currentTarget);
			const action = $target.data().action;

			if (action && this[action]) {
				this[action].apply(this, $target);
			}
		})
	}

	make_sidebar() {
		this.$sidebar = this.$parent.find('.layout-side-section').addClass('hidden-xs');

		new Vue({
			el: $('
').appendTo(this.$sidebar)[0],
			render: h => h(Sidebar)
		});
	}

	make_body() {
		this.$body = this.$parent.find('.layout-main-section');
		this.$page_container = $('
').appendTo(this.$body);

		new Vue({
			el: '.hub-page-container',
			render: h => h(PageContainer)
		});

		erpnext.hub.on('seller-registered', () => {
			this.page.clear_primary_action()
			frappe.model.with_doc('Marketplace Settings').then((doc)=> {
				hub.settings = doc;
			});
		});
	}

	refresh() {

	}

	show_register_dialog() {
		this.register_dialog = ProfileDialog(
			__('Become a Seller'),
			{
				label: __('Register'),
				on_submit: this.register_seller.bind(this)
			}
		);

		this.register_dialog.show();
	}

	register_seller(form_values) {
		frappe.call({
		    method: 'erpnext.hub_node.doctype.hub_settings.hub_settings.register_seller',
		    args: form_values
		}).then(() => {
			this.register_dialog.hide();
			frappe.set_route('marketplace', 'publish');

		    erpnext.hub.trigger('seller-registered');
		});
	}

}
<commit_msg>[fix] hub_settings -> marketplace_settings in call<commit_after>import Vue from 'vue/dist/vue.js';
import './vue-plugins';

// components
import PageContainer from './PageContainer.vue';
import Sidebar from './Sidebar.vue';
import { ProfileDialog } from './components/profile_dialog';

// helpers
import './hub_call';
import EventEmitter from './event_emitter';

frappe.provide('hub');
frappe.provide('erpnext.hub');

$.extend(erpnext.hub, EventEmitter.prototype);

erpnext.hub.Marketplace = class Marketplace {
	constructor({ parent }) {
		this.$parent = $(parent);
		this.page = parent.page;

		frappe.model.with_doc('Marketplace Settings').then(doc => {
			hub.settings = doc;
			const is_registered = hub.settings.registered;
			const is_registered_seller = hub.settings.company_email === frappe.session.user;
			this.setup_header();
			this.make_sidebar();
			this.make_body();
			this.setup_events();
			this.refresh();
			if (!is_registered && !is_registered_seller && frappe.user_roles.includes('System Manager')) {
				this.page.set_primary_action('Become a Seller', this.show_register_dialog.bind(this))
			}
		});
	}

	setup_header() {
		this.page.set_title(__('Marketplace'));
	}

	setup_events() {
		this.$parent.on('click', '[data-route]', (e) => {
			const $target = $(e.currentTarget);
			const route = $target.data().route;
			frappe.set_route(route);
		});

		// generic action handler
		this.$parent.on('click', '[data-action]', e => {
			const $target = $(e.currentTarget);
			const action = $target.data().action;

			if (action && this[action]) {
				this[action].apply(this, $target);
			}
		})
	}

	make_sidebar() {
		this.$sidebar = this.$parent.find('.layout-side-section').addClass('hidden-xs');

		new Vue({
			el: $('
').appendTo(this.$sidebar)[0],
			render: h => h(Sidebar)
		});
	}

	make_body() {
		this.$body = this.$parent.find('.layout-main-section');
		this.$page_container = $('
').appendTo(this.$body);

		new Vue({
			el: '.hub-page-container',
			render: h => h(PageContainer)
		});

		erpnext.hub.on('seller-registered', () => {
			this.page.clear_primary_action()
			frappe.model.with_doc('Marketplace Settings').then((doc)=> {
				hub.settings = doc;
			});
		});
	}

	refresh() {

	}

	show_register_dialog() {
		this.register_dialog = ProfileDialog(
			__('Become a Seller'),
			{
				label: __('Register'),
				on_submit: this.register_seller.bind(this)
			}
		);

		this.register_dialog.show();
	}

	register_seller(form_values) {
		frappe.call({
		    method: 'erpnext.hub_node.doctype.marketplace_settings.marketplace_settings.register_seller',
		    args: form_values
		}).then(() => {
			this.register_dialog.hide();
			frappe.set_route('marketplace', 'publish');

		    erpnext.hub.trigger('seller-registered');
		});
	}

}
<|endoftext|>


<commit_before>var five = require("johnny-five"),
    Edison = require("edison-io"),
    board = new five.Board({
        io: new Edison()
    }),
    express = require("express"),
    app = express(),
    server = app.listen(3000);

app.use(express.static('public'));

board.on("ready", function() {
  var rightServo = new five.Servo.Continuous(5),
      leftServo = new five.Servo.Continuous(6),
      led = new five.Led(13),
      piezo = new five.Piezo(12),
      la_cucaracha = '- - C C - C C - C C - F F F F - A A A A - -';

  // Add to REPL
  this.repl.inject({
    led: led,
    rightServo: rightServo,
    leftServo: leftServo,
    piezo: piezo
  });

  app.post('/forward', function(sReq, sRes){
    led.blink();

    rightServo.cw(1);
    leftServo.ccw(1);

    sRes.end();
  });

  app.post('/backward', function(sReq, sRes){
    led.blink();

    rightServo.ccw(1);
    leftServo.cw(1);

    sRes.end();
  });

  app.post('/right', function(sReq, sRes){
    led.blink();

    rightServo.ccw(0.5);
    leftServo.ccw(0.5);

    sRes.end();
  });

  app.post('/left', function(sReq, sRes){
    led.blink();

    rightServo.cw(0.5);
    leftServo.cw(0.5);

    sRes.end();
  });

  app.post('/stop', function(sReq, sRes){
    led.blink();

    rightServo.cw(0);
    leftServo.cw(0);

    sRes.end();
  });

  app.post('/honk', function(sReq, sRes){
    led.blink();

    piezo.play({
        // song is composed by a string of notes
        // a default beat is set, and the default octave is used
        // any invalid note is read as "no note"
        song: la_cucaracha + la_cucaracha,
        beats: 1 / 8,
        tempo: 100
    });

    sRes.end();
  });
});<commit_msg>change buzzer pin<commit_after>var five = require("johnny-five"),
    Edison = require("edison-io"),
    board = new five.Board({
        io: new Edison()
    }),
    express = require("express"),
    app = express(),
    server = app.listen(3000);

app.use(express.static('public'));

board.on("ready", function() {
  var rightServo = new five.Servo.Continuous(5),
      leftServo = new five.Servo.Continuous(6),
      led = new five.Led(13),
      piezo = new five.Piezo(3),
      la_cucaracha = '- - C C - C C - C C - F F F F - A A A A - -';

  // Add to REPL
  this.repl.inject({
    led: led,
    rightServo: rightServo,
    leftServo: leftServo,
    piezo: piezo
  });

  app.post('/forward', function(sReq, sRes){
    led.blink();

    rightServo.cw(1);
    leftServo.ccw(1);

    sRes.end();
  });

  app.post('/backward', function(sReq, sRes){
    led.blink();

    rightServo.ccw(1);
    leftServo.cw(1);

    sRes.end();
  });

  app.post('/right', function(sReq, sRes){
    led.blink();

    rightServo.ccw(0.5);
    leftServo.ccw(0.5);

    sRes.end();
  });

  app.post('/left', function(sReq, sRes){
    led.blink();

    rightServo.cw(0.5);
    leftServo.cw(0.5);

    sRes.end();
  });

  app.post('/stop', function(sReq, sRes){
    led.blink();

    rightServo.cw(0);
    leftServo.cw(0);

    sRes.end();
  });

  app.post('/honk', function(sReq, sRes){
    led.blink();

    piezo.play({
        // song is composed by a string of notes
        // a default beat is set, and the default octave is used
        // any invalid note is read as "no note"
        song: la_cucaracha + la_cucaracha,
        beats: 1 / 8,
        tempo: 100
    });

    sRes.end();
  });
});<|endoftext|>


<commit_before>define([], function () {
  'use strict';

  class Modal { // eslint-disable-line
    constructor(modalTrigger, config) {
      this.config = config
      this.setListeners(modalTrigger);
    }

    trap(e, modal) {
      if (e.which == 27) {
        this.closeModal(modal);
      }
      if (e.which == 9) {
        let currentFocus = document.activeElement,
            totalOfFocusable = modal.focusableChildren.length,
            focusedIndex = modal.focusableChildren.indexOf(currentFocus);
        if (e.shiftKey) {
          if (focusedIndex === 0) {
            e.preventDefault();
            modal.focusableChildren[totalOfFocusable - 1].focus();
          }
        }
        else {
          if (focusedIndex == totalOfFocusable - 1) {
            e.preventDefault();
            modal.focusableChildren[0].focus();
          }
        }
      }
    }

    modalOpenMq(modal) {
      modal.el.setAttribute('aria-hidden', false);
      modal.trigger.setAttribute('aria-expanded', true);
    }

    closeOpenMq(modal) {
      modal.el.setAttribute('aria-hidden', true);
      modal.trigger.setAttribute('aria-expanded', false);
    }

    openModal(modal) {
      modal.focused = document.activeElement;
      modal.el.setAttribute('aria-hidden', false);
      modal.trigger.setAttribute('aria-expanded', true);
      modal.el.classList.add(modal.activeClass);
      modal.focusableChildren = Array.from(modal.el.querySelectorAll(modal.focusable));
      modal.focusableChildren[0].focus();
      modal.el.addEventListener('keydown', (e) => {
        this.trap(e, modal);
      });
    }

    closeModal(modal) {
      modal.el.setAttribute('aria-hidden', true);
      modal.trigger.setAttribute('aria-expanded', false);
      modal.el.classList.remove(modal.activeClass);
      modal.focused.focus();
    }
    setListeners(modalTrigger) {
      const modal = {};
      modal.trigger = modalTrigger,
      modal.el = document.querySelector(`.modal[data-modal=${modal.trigger.dataset.modalTrigger}]`),
      modal.content     = modal.el.querySelector('.modal__content'),
      modal.closeButton = modal.el.querySelector('.modal__close-button'),
      modal.activeClass = 'modal--active',
      modal.focusable   = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), object, embed, *[tabindex], *[contenteditable]',
      modal.focused     = '';
      modal.trigger.addEventListener('click',
        () => this.openModal(modal)
      );
      // clicking on button (x) closes the modal
      if (modal.closeButton) {
        modal.closeButton.addEventListener('click',
          () => this.closeModal(modal)
        );
      }

      // clicking anywhere outside of the modal closes the modal
      window.addEventListener('click', (e) => {
        if (e.target === modal.el
          && modal.el.classList.contains(modal.activeClass)
          && !modal.content.contains(e.target)
        ) {
          this.closeModal(modal)
        }
      });
      // escape key closes the modal
      window.addEventListener('keydown', (e) => {
        if (e.which === 27
          && modal.el.classList.contains(modal.activeClass)
        ) {
          this.closeModal(modal)
        }
      });

      if (this.config && this.config.mqOpen) {
        const mqOpenBreakpoint = window.matchMedia(this.config.mqOpen);
        if (mqOpenBreakpoint.matches) {
          this.modalOpenMq(modal)
        }
        window.addEventListener('resize', (e) => {
          if (mqOpenBreakpoint.matches) {
            this.modalOpenMq(modal);
          } else {
            this.closeOpenMq(modal);
          }
        })
      }
    }
  }

  return function (config, element) {
    new Modal(element, config);
  };
});
<commit_msg>#80758 - Fix query selector error<commit_after>define([], function () {
  'use strict';

  class Modal { // eslint-disable-line
    constructor(modalTrigger, config) {
      this.config = config
      this.setListeners(modalTrigger);
    }

    trap(e, modal) {
      if (e.which == 27) {
        this.closeModal(modal);
      }
      if (e.which == 9) {
        let currentFocus = document.activeElement,
            totalOfFocusable = modal.focusableChildren.length,
            focusedIndex = modal.focusableChildren.indexOf(currentFocus);
        if (e.shiftKey) {
          if (focusedIndex === 0) {
            e.preventDefault();
            modal.focusableChildren[totalOfFocusable - 1].focus();
          }
        }
        else {
          if (focusedIndex == totalOfFocusable - 1) {
            e.preventDefault();
            modal.focusableChildren[0].focus();
          }
        }
      }
    }

    modalOpenMq(modal) {
      modal.el.setAttribute('aria-hidden', false);
      modal.trigger.setAttribute('aria-expanded', true);
    }

    closeOpenMq(modal) {
      modal.el.setAttribute('aria-hidden', true);
      modal.trigger.setAttribute('aria-expanded', false);
    }

    openModal(modal) {
      modal.focused = document.activeElement;
      modal.el.setAttribute('aria-hidden', false);
      modal.trigger.setAttribute('aria-expanded', true);
      modal.el.classList.add(modal.activeClass);
      modal.focusableChildren = Array.from(modal.el.querySelectorAll(modal.focusable));
      modal.focusableChildren[0].focus();
      modal.el.addEventListener('keydown', (e) => {
        this.trap(e, modal);
      });
    }

    closeModal(modal) {
      modal.el.setAttribute('aria-hidden', true);
      modal.trigger.setAttribute('aria-expanded', false);
      modal.el.classList.remove(modal.activeClass);
      modal.focused.focus();
    }
    setListeners(modalTrigger) {
      const modal = {};
      modal.trigger = modalTrigger,
      modal.el = document.querySelector(`.modal[data-modal='${modal.trigger.dataset.modalTrigger}']`),
      modal.content     = modal.el.querySelector('.modal__content'),
      modal.closeButton = modal.el.querySelector('.modal__close-button'),
      modal.activeClass = 'modal--active',
      modal.focusable   = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), object, embed, *[tabindex], *[contenteditable]',
      modal.focused     = '';
      modal.trigger.addEventListener('click',
        () => this.openModal(modal)
      );
      // clicking on button (x) closes the modal
      if (modal.closeButton) {
        modal.closeButton.addEventListener('click',
          () => this.closeModal(modal)
        );
      }

      // clicking anywhere outside of the modal closes the modal
      window.addEventListener('click', (e) => {
        if (e.target === modal.el
          && modal.el.classList.contains(modal.activeClass)
          && !modal.content.contains(e.target)
        ) {
          this.closeModal(modal)
        }
      });
      // escape key closes the modal
      window.addEventListener('keydown', (e) => {
        if (e.which === 27
          && modal.el.classList.contains(modal.activeClass)
        ) {
          this.closeModal(modal)
        }
      });

      if (this.config && this.config.mqOpen) {
        const mqOpenBreakpoint = window.matchMedia(this.config.mqOpen);
        if (mqOpenBreakpoint.matches) {
          this.modalOpenMq(modal)
        }
        window.addEventListener('resize', (e) => {
          if (mqOpenBreakpoint.matches) {
            this.modalOpenMq(modal);
          } else {
            this.closeOpenMq(modal);
          }
        })
      }
    }
  }

  return function (config, element) {
    new Modal(element, config);
  };
});
<|endoftext|>


<commit_before>"use strict"

const gpio = require("./index");

exports.activate = (scope, state, args, data, stream, next) => {
    console.log('GPIO.activate:', args);
    gpio.activate(args.gpio);
    next(null, data, stream);
};

exports.deactivate = (scope, state, args, data, stream, next) => {
    console.log('GPIO.deactivate:', args);
    gpio.deactivate(args.gpio);
    next(null, data, stream);
};

exports.read = (scope, state, args, data, stream, next) => {
    console.log('GPIO.read:', args);
    next(null, data, gpio.read(args.gpio));
};

exports.write = (scope, state, args, data, stream, next) => {
    console.log('GPIO.write:', args);
    stream.pipe(gpio.write(args.gpio));
    next(null, data, stream);
};
<commit_msg>pass direction arg<commit_after>"use strict"

const gpio = require("./index");

exports.activate = (scope, state, args, data, stream, next) => {
    console.log('GPIO.activate:', args);
    gpio.activate(args.gpio, args.direction || "out");
    next(null, data, stream);
};

exports.deactivate = (scope, state, args, data, stream, next) => {
    console.log('GPIO.deactivate:', args);
    gpio.deactivate(args.gpio);
    next(null, data, stream);
};

exports.read = (scope, state, args, data, stream, next) => {
    console.log('GPIO.read:', args);
    next(null, data, gpio.read(args.gpio));
};

exports.write = (scope, state, args, data, stream, next) => {
    console.log('GPIO.write:', args);
    stream.pipe(gpio.write(args.gpio));
    next(null, data, stream);
};
<|endoftext|>


<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';

var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var parallel = require('run-parallel');

var InArgStream = require('./argstream').InArgStream;
var OutArgStream = require('./argstream').OutArgStream;

var emptyBuffer = Buffer(0);

var States = Object.create(null);
States.Initial = 0;
States.Streaming = 1;
States.Done = 2;
States.Error = 3;

function TChannelIncomingRequest(id, options) {
    if (!(this instanceof TChannelIncomingRequest)) {
        return new TChannelIncomingRequest(id, options);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || null;
    self.service = options.service || '';
    self.remoteAddr = null;
    self.headers = options.headers || {};
    self.checksum = options.checksum || null;
    if (options.streamed) {
        self.streamed = true;
        self._argstream = InArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    } else {
        self.streamed = false;
        self._argstream = null;
        self.arg1 = emptyBuffer;
        self.arg2 = emptyBuffer;
        self.arg3 = emptyBuffer;
    }
    self.on('finish', function onFinish() {
        self.state = States.Done;
    });
}

inherits(TChannelIncomingRequest, EventEmitter);

TChannelIncomingRequest.prototype.handleFrame = function handleFrame(parts) {
    var self = this;
    if (self.streamed) {
        self._argstream.handleFrame(parts);
    } else {
        if (!parts) return;
        if (parts.length !== 3 ||
                self.state !== States.Initial) throw new Error('not implemented');
        self.arg1 = parts[0] || emptyBuffer;
        self.arg2 = parts[1] || emptyBuffer;
        self.arg3 = parts[2] || emptyBuffer;
    }
};

TChannelIncomingRequest.prototype.finish = function finish() {
    var self = this;
    if (self.state === States.Done) {
        throw new Error('request already done'); // TODO: typed error
    } else {
        self.state = States.Done;
    }
};

function TChannelIncomingResponse(id, options) {
    if (!(this instanceof TChannelIncomingResponse)) {
        return new TChannelIncomingResponse(id, options);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.checksum = options.checksum || null;
    self.ok = self.code === 0; // TODO: probably okay, but a bit jank
    if (options.streamed) {
        self.streamed = true;
        self._argstream = InArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    } else {
        self.streamed = false;
        self._argstream = null;
        self.arg1 = emptyBuffer;
        self.arg2 = emptyBuffer;
        self.arg3 = emptyBuffer;
    }
    self.on('finish', function onFinish() {
        self.state = States.Done;
    });
}

inherits(TChannelIncomingResponse, EventEmitter);

TChannelIncomingResponse.prototype.handleFrame = function handleFrame(parts) {
    var self = this;
    if (self.streamed) {
        self._argstream.handleFrame(parts);
    } else {
        if (!parts) return;
        if (parts.length !== 3 ||
                self.state !== States.Initial) throw new Error('not implemented');
        self.arg1 = parts[0] || emptyBuffer;
        self.arg2 = parts[1] || emptyBuffer;
        self.arg3 = parts[2] || emptyBuffer;
    }
};

TChannelIncomingResponse.prototype.finish = function finish() {
    var self = this;
    if (self.state === States.Done) {
        throw new Error('response already done'); // TODO: typed error
    } else {
        self.state = States.Done;
    }
};

function TChannelOutgoingRequest(id, options) {
    if (!(this instanceof TChannelOutgoingRequest)) {
        return new TChannelOutgoingRequest(id, options);
    }
    options = options || {};
    if (!options.sendFrame) {
        throw new Error('missing sendFrame');
    }
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || null;
    self.service = options.service || '';
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.sendFrame = options.sendFrame;
    if (options.streamed) {
        self.streamed = true;
        self._argstream = OutArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('frame', function onFrame(parts, isLast) {
            self.sendParts(parts, isLast);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    } else {
        self.streamed = false;
        self._argstream = null;
        self.arg1 = null;
        self.arg2 = null;
        self.arg3 = null;
    }
}

inherits(TChannelOutgoingRequest, EventEmitter);

TChannelOutgoingRequest.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    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 canceled
            throw new Error('got frame in done state'); // TODO: typed error
        case States.Error:
            // TODO: log warn
            break;
    }
};

TChannelOutgoingRequest.prototype.sendCallRequestFrame = function sendCallRequestFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendFrame.callRequest(args, isLast);
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            throw new Error('first request frame already sent'); // TODO: typed error
        case States.Done:
            throw new Error('request already done'); // TODO: typed error
    }
};

TChannelOutgoingRequest.prototype.sendCallRequestContFrame = function sendCallRequestContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            throw new Error('first request frame not sent'); // TODO: typed error
        case States.Streaming:
            self.sendFrame.callRequestCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
            throw new Error('request already done'); // TODO: typed error
    }
};

TChannelOutgoingRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    if (callback) self.hookupCallback(callback);
    if (self.streamed) {
        self.arg1.end(arg1);
        self.arg2.end(arg2);
        self.arg3.end(arg3);
    } else {
        self.sendCallRequestFrame([
            arg1 ? Buffer(arg1) : emptyBuffer,
            arg2 ? Buffer(arg2) : emptyBuffer,
            arg3 ? Buffer(arg3) : emptyBuffer
        ], true);
        self.emit('finish');
    }
    return self;
};

TChannelOutgoingRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    self.once('error', onError);
    self.once('response', onResponse);
    function onError(err) {
        self.removeListener('response', onResponse);
        callback(err, null);
    }

    function onResponse(res) {
        self.removeListener('error', onError);
        if (callback.canStream) {
            callback(null, res);
        } else if (res.streamed) {
            parallel({
                arg2: res.arg2.onValueReady,
                arg3: res.arg3.onValueReady
            }, compatCall);
        } else {
            compatCall(null, res);
        }

        function compatCall(err, args) {
            callback(err, res, args.arg2, args.arg3);
        }
    }
    return self;
};

function TChannelOutgoingResponse(id, options) {
    if (!(this instanceof TChannelOutgoingResponse)) {
        return new TChannelOutgoingResponse(id, options);
    }
    options = options || {};
    if (!options.sendFrame) {
        throw new Error('missing sendFrame');
    }
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.tracing = options.tracing || null;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.ok = self.code === 0;
    self.sendFrame = options.sendFrame;
    if (options.streamed) {
        self.streamed = true;
        self._argstream = OutArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('frame', function onFrame(parts, isLast) {
            self.sendParts(parts, isLast);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    } else {
        self.streamed = false;
        self._argstream = null;
        self.arg1 = null;
        self.arg2 = null;
        self.arg3 = null;
    }
}

inherits(TChannelOutgoingResponse, EventEmitter);

TChannelOutgoingResponse.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendCallResponseFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallResponseContFrame(parts, isLast);
            break;
        case States.Done:
            throw new Error('got frame in done state'); // TODO: typed error
        case States.Error:
            // TODO: log warn
            break;
    }
};

TChannelOutgoingResponse.prototype.sendCallResponseFrame = function sendCallResponseFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendFrame.callResponse(args, isLast);
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            throw new Error('first response frame already sent'); // TODO: typed error
        case States.Done:
        case States.Error:
            throw new Error('response already done'); // TODO: typed error
    }
};

TChannelOutgoingResponse.prototype.sendCallResponseContFrame = function sendCallResponseContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            throw new Error('first response frame not sent'); // TODO: typed error
        case States.Streaming:
            self.sendFrame.callResponseCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
        case States.Error:
            throw new Error('response already done'); // TODO: typed error
    }
};

TChannelOutgoingResponse.prototype.sendError = function sendError(codeString, message) {
    var self = this;
    if (self.state === States.Done || self.state === States.Error) {
        throw new Error('response already done'); // TODO: typed error
    } else {
        self.state = States.Error;
        if (self.streamed) {
            // TODO: we could decide to flush any parts in a (first?) call res frame
            self._argstream.finished = true;
            self.arg1.end();
            self.arg2.end();
            self.arg3.end();
        }
        self.sendFrame.error(codeString, message);
    }
};

TChannelOutgoingResponse.prototype.setOk = function setOk(ok) {
    var self = this;
    if (self.state !== States.Initial) {
        throw new Error('response already started'); // TODO typed error
    }
    self.ok = ok;
    self.code = ok ? 0 : 1; // TODO: too coupled to v2 specifics?
    if (self.streamed) {
        self.arg1.end();
    }
};

TChannelOutgoingResponse.prototype.sendOk = function sendOk(res1, res2) {
    var self = this;
    self.setOk(true);
    if (self.streamed) {
        self.arg2.end(res1);
        self.arg3.end(res2);
    } else {
        self.sendCallResponseFrame([
            self.arg1 || emptyBuffer,
            res1 ? Buffer(res1) : emptyBuffer,
            res2 ? Buffer(res2) : emptyBuffer
        ], true);
        self.emit('finish');
    }
};

TChannelOutgoingResponse.prototype.sendNotOk = function sendNotOk(res1, res2) {
    var self = this;
    self.setOk(false);
    if (self.streamed) {
        self.arg2.end(res1);
        self.arg3.end(res2);
    } else {
        self.sendCallResponseFrame([
            self.arg1 || emptyBuffer,
            res1 ? Buffer(res1) : emptyBuffer,
            res2 ? Buffer(res2) : emptyBuffer
        ], true);
        self.emit('finish');
    }
};

module.exports.States = States;
module.exports.IncomingRequest = TChannelIncomingRequest;
module.exports.IncomingResponse = TChannelIncomingResponse;
module.exports.OutgoingRequest = TChannelOutgoingRequest;
module.exports.OutgoingResponse = TChannelOutgoingResponse;
<commit_msg>TChannelOutgoingResponse: factor out send<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';

var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var parallel = require('run-parallel');

var InArgStream = require('./argstream').InArgStream;
var OutArgStream = require('./argstream').OutArgStream;

var emptyBuffer = Buffer(0);

var States = Object.create(null);
States.Initial = 0;
States.Streaming = 1;
States.Done = 2;
States.Error = 3;

function TChannelIncomingRequest(id, options) {
    if (!(this instanceof TChannelIncomingRequest)) {
        return new TChannelIncomingRequest(id, options);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || null;
    self.service = options.service || '';
    self.remoteAddr = null;
    self.headers = options.headers || {};
    self.checksum = options.checksum || null;
    if (options.streamed) {
        self.streamed = true;
        self._argstream = InArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    } else {
        self.streamed = false;
        self._argstream = null;
        self.arg1 = emptyBuffer;
        self.arg2 = emptyBuffer;
        self.arg3 = emptyBuffer;
    }
    self.on('finish', function onFinish() {
        self.state = States.Done;
    });
}

inherits(TChannelIncomingRequest, EventEmitter);

TChannelIncomingRequest.prototype.handleFrame = function handleFrame(parts) {
    var self = this;
    if (self.streamed) {
        self._argstream.handleFrame(parts);
    } else {
        if (!parts) return;
        if (parts.length !== 3 ||
                self.state !== States.Initial) throw new Error('not implemented');
        self.arg1 = parts[0] || emptyBuffer;
        self.arg2 = parts[1] || emptyBuffer;
        self.arg3 = parts[2] || emptyBuffer;
    }
};

TChannelIncomingRequest.prototype.finish = function finish() {
    var self = this;
    if (self.state === States.Done) {
        throw new Error('request already done'); // TODO: typed error
    } else {
        self.state = States.Done;
    }
};

function TChannelIncomingResponse(id, options) {
    if (!(this instanceof TChannelIncomingResponse)) {
        return new TChannelIncomingResponse(id, options);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.checksum = options.checksum || null;
    self.ok = self.code === 0; // TODO: probably okay, but a bit jank
    if (options.streamed) {
        self.streamed = true;
        self._argstream = InArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    } else {
        self.streamed = false;
        self._argstream = null;
        self.arg1 = emptyBuffer;
        self.arg2 = emptyBuffer;
        self.arg3 = emptyBuffer;
    }
    self.on('finish', function onFinish() {
        self.state = States.Done;
    });
}

inherits(TChannelIncomingResponse, EventEmitter);

TChannelIncomingResponse.prototype.handleFrame = function handleFrame(parts) {
    var self = this;
    if (self.streamed) {
        self._argstream.handleFrame(parts);
    } else {
        if (!parts) return;
        if (parts.length !== 3 ||
                self.state !== States.Initial) throw new Error('not implemented');
        self.arg1 = parts[0] || emptyBuffer;
        self.arg2 = parts[1] || emptyBuffer;
        self.arg3 = parts[2] || emptyBuffer;
    }
};

TChannelIncomingResponse.prototype.finish = function finish() {
    var self = this;
    if (self.state === States.Done) {
        throw new Error('response already done'); // TODO: typed error
    } else {
        self.state = States.Done;
    }
};

function TChannelOutgoingRequest(id, options) {
    if (!(this instanceof TChannelOutgoingRequest)) {
        return new TChannelOutgoingRequest(id, options);
    }
    options = options || {};
    if (!options.sendFrame) {
        throw new Error('missing sendFrame');
    }
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || null;
    self.service = options.service || '';
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.sendFrame = options.sendFrame;
    if (options.streamed) {
        self.streamed = true;
        self._argstream = OutArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('frame', function onFrame(parts, isLast) {
            self.sendParts(parts, isLast);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    } else {
        self.streamed = false;
        self._argstream = null;
        self.arg1 = null;
        self.arg2 = null;
        self.arg3 = null;
    }
}

inherits(TChannelOutgoingRequest, EventEmitter);

TChannelOutgoingRequest.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    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 canceled
            throw new Error('got frame in done state'); // TODO: typed error
        case States.Error:
            // TODO: log warn
            break;
    }
};

TChannelOutgoingRequest.prototype.sendCallRequestFrame = function sendCallRequestFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendFrame.callRequest(args, isLast);
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            throw new Error('first request frame already sent'); // TODO: typed error
        case States.Done:
            throw new Error('request already done'); // TODO: typed error
    }
};

TChannelOutgoingRequest.prototype.sendCallRequestContFrame = function sendCallRequestContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            throw new Error('first request frame not sent'); // TODO: typed error
        case States.Streaming:
            self.sendFrame.callRequestCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
            throw new Error('request already done'); // TODO: typed error
    }
};

TChannelOutgoingRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    if (callback) self.hookupCallback(callback);
    if (self.streamed) {
        self.arg1.end(arg1);
        self.arg2.end(arg2);
        self.arg3.end(arg3);
    } else {
        self.sendCallRequestFrame([
            arg1 ? Buffer(arg1) : emptyBuffer,
            arg2 ? Buffer(arg2) : emptyBuffer,
            arg3 ? Buffer(arg3) : emptyBuffer
        ], true);
        self.emit('finish');
    }
    return self;
};

TChannelOutgoingRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    self.once('error', onError);
    self.once('response', onResponse);
    function onError(err) {
        self.removeListener('response', onResponse);
        callback(err, null);
    }

    function onResponse(res) {
        self.removeListener('error', onError);
        if (callback.canStream) {
            callback(null, res);
        } else if (res.streamed) {
            parallel({
                arg2: res.arg2.onValueReady,
                arg3: res.arg3.onValueReady
            }, compatCall);
        } else {
            compatCall(null, res);
        }

        function compatCall(err, args) {
            callback(err, res, args.arg2, args.arg3);
        }
    }
    return self;
};

function TChannelOutgoingResponse(id, options) {
    if (!(this instanceof TChannelOutgoingResponse)) {
        return new TChannelOutgoingResponse(id, options);
    }
    options = options || {};
    if (!options.sendFrame) {
        throw new Error('missing sendFrame');
    }
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.tracing = options.tracing || null;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.ok = self.code === 0;
    self.sendFrame = options.sendFrame;
    if (options.streamed) {
        self.streamed = true;
        self._argstream = OutArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('frame', function onFrame(parts, isLast) {
            self.sendParts(parts, isLast);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    } else {
        self.streamed = false;
        self._argstream = null;
        self.arg1 = null;
        self.arg2 = null;
        self.arg3 = null;
    }
}

inherits(TChannelOutgoingResponse, EventEmitter);

TChannelOutgoingResponse.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendCallResponseFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallResponseContFrame(parts, isLast);
            break;
        case States.Done:
            throw new Error('got frame in done state'); // TODO: typed error
        case States.Error:
            // TODO: log warn
            break;
    }
};

TChannelOutgoingResponse.prototype.sendCallResponseFrame = function sendCallResponseFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendFrame.callResponse(args, isLast);
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            throw new Error('first response frame already sent'); // TODO: typed error
        case States.Done:
        case States.Error:
            throw new Error('response already done'); // TODO: typed error
    }
};

TChannelOutgoingResponse.prototype.sendCallResponseContFrame = function sendCallResponseContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            throw new Error('first response frame not sent'); // TODO: typed error
        case States.Streaming:
            self.sendFrame.callResponseCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
        case States.Error:
            throw new Error('response already done'); // TODO: typed error
    }
};

TChannelOutgoingResponse.prototype.sendError = function sendError(codeString, message) {
    var self = this;
    if (self.state === States.Done || self.state === States.Error) {
        throw new Error('response already done'); // TODO: typed error
    } else {
        self.state = States.Error;
        if (self.streamed) {
            // TODO: we could decide to flush any parts in a (first?) call res frame
            self._argstream.finished = true;
            self.arg1.end();
            self.arg2.end();
            self.arg3.end();
        }
        self.sendFrame.error(codeString, message);
    }
};

TChannelOutgoingResponse.prototype.setOk = function setOk(ok) {
    var self = this;
    if (self.state !== States.Initial) {
        throw new Error('response already started'); // TODO typed error
    }
    self.ok = ok;
    self.code = ok ? 0 : 1; // TODO: too coupled to v2 specifics?
    if (self.streamed) {
        self.arg1.end();
    }
};

TChannelOutgoingResponse.prototype.sendOk = function sendOk(res1, res2) {
    var self = this;
    self.setOk(true);
    self.send(res1, res2);
};

TChannelOutgoingResponse.prototype.sendNotOk = function sendNotOk(res1, res2) {
    var self = this;
    self.setOk(false);
    self.send(res1, res2);
};

TChannelOutgoingResponse.prototype.send = function send(res1, res2) {
    var self = this;
    if (self.streamed) {
        self.arg2.end(res1);
        self.arg3.end(res2);
    } else {
        self.sendCallResponseFrame([
            self.arg1 || emptyBuffer,
            res1 ? Buffer(res1) : emptyBuffer,
            res2 ? Buffer(res2) : emptyBuffer
        ], true);
        self.emit('finish');
    }
};

module.exports.States = States;
module.exports.IncomingRequest = TChannelIncomingRequest;
module.exports.IncomingResponse = TChannelIncomingResponse;
module.exports.OutgoingRequest = TChannelOutgoingRequest;
module.exports.OutgoingResponse = TChannelOutgoingResponse;
<|endoftext|>