<commit_before>
(function( window, $ ) {
  var $window, $doc;

  $window = $(window);
  $doc = $( document.documentElement );

  window.componentNamespace = window.componentNamespace || window;

  Function.prototype.bind = function( context ) {
    var self = this;

    return function() {
      self.apply( context, arguments );
    };
  };

  var Tau = window.componentNamespace.Tau = function( element ) {
    var startIndex;

    this.element = element;
    this.$element = $( element );
    this.$initial = this.$element.find("img");
    this.startIndex = parseInt( this.$initial.attr("data-start") || "0", 10 );

    this.createImages();

    // TODO all of this should probably wait until the images load
    this.goto( this.startIndex );
    this.autoRotate();
    this.bind();
  };

  Tau.autoRotateDelay = 64;
  Tau.verticalScrollRatio = 4;

  Tau.prototype.change = function( delta ) {
    this.goto( this.index + delta );
  };

  Tau.prototype.goto = function( index ) {
    var $next;

    // deal with negative indices properly
    if( index < 0 ) {
      index = this.$images.length + index;
    }

    // make sure we stay within the bounds of our image set, record the new value
    this.index = index % this.$images.length;

    $next = this.$images.eq( this.index );

    if( !$next[0].tauImageLoaded ) {
      return;
    }

    if( this.$current ) {
      this.$current.removeClass( "focused" );
    }

    // record the current focused image and make it visible
    this.$current = $next;
    this.$current.addClass( "focused" );
  };

  // TODO transplant the attributes from the initial image
  Tau.prototype.createImages = function() {
    var src, frames, $new;

    src = this.$initial.attr( "data-src-template" );
    frames = parseInt( this.$initial.attr( "data-frames" ), 10 );

    for( var i = 2; i <= frames; i++) {
      $new = $( "" );
      this.$element.append( $new );

      // record when each image has loaded
      $new.bind( "load", function() {
        this.tauImageLoaded = true;
      });
    }

    this.$images = this.$element.find( "img" );
  };

  Tau.prototype.bind = function() {
    $doc.bind( "mouseup touchend", this.release.bind(this) );
    this.$element.bind( "mousedown touchstart", this.track.bind(this) );
  };

  Tau.prototype.autoRotate = function() {
    this.autoInterval = setInterval(function() {
      this.change( 1 );
    }.bind(this), Tau.autoRotateDelay);
  };

  Tau.prototype.stopAutoRotate = function() {
    clearInterval( this.autoInterval );
  };

  Tau.prototype.track = function( event ) {
    var point;

    // prevent dragging behavior for mousedown
    if( event.type === "mousedown"  ){
      event.preventDefault();
    }

    if( this.tracking ) {
      return;
    }

    this.tracking = true;

    this.cursorGrab();

    // calculate/store how many pixels makes for an image switch
    this.rotateThreshold = $doc[0].clientWidth / this.$images.length;

    // record the x for threshold calculations
    point = this.getPoint( event );
    this.downX = point.x;
    this.downY = point.y;
    this.downIndex = this.index;

    $doc.bind( "mousemove", this.rotate.bind(this) );
    $doc.bind( "touchmove", this.rotate.bind(this) );
  };

  Tau.prototype.release = function( event ) {
    this.cursorRelease();
    $doc.unbind( "mousemove", this.rotate.bind(this) );
    $doc.unbind( "touchmove", this.rotate.bind(this) );
    this.tracking = false;
  };

  Tau.prototype.cursorGrab = function() {
    $doc.addClass( "grabbing" );
    this.$element.addClass( "grabbing" );
  };

  Tau.prototype.cursorRelease = function() {
    $doc.removeClass( "grabbing" );
    this.$element.removeClass( "grabbing" );
  };

  Tau.prototype.getPoint = function( event ) {
    var touch = event.touches || (event.originalEvent && event.originalEvent.touches);

    if( touch ){
      return {
        x: touch[0].pageX,
        y: touch[0].pageY
      };
    }

    return {
      x: event.pageX,
      y: event.pageY
    };
  };

  Tau.prototype.rotate = function( event ) {
    var deltaX, deltaY, point;

    point = this.getPoint( event );
    deltaX = point.x - this.downX;
    deltaY = point.y - this.downY;

    // if the movement on the Y dominates X then skip and allow scroll
    if( Math.abs(deltaY) / Math.abs(deltaX) >= Tau.verticalScrollRatio ) {
      return;
    }

    // NOTE works better on mousedown, here allows autorotate to continue on scroll
    this.stopAutoRotate();

    // NOTE to reverse the spin direction add the delta/thresh to the downIndex
    // NOTE it might be better to prevent anyway for slow drags across the image
    if( Math.abs(deltaX) >= this.rotateThreshold ) {
      event.preventDefault();
      this.goto( this.downIndex - Math.round(deltaX / this.rotateThreshold) );
    }
  };
})(this, jQuery);
<commit_msg>simplify goto a bit, add some comments<commit_after>
(function( window, $ ) {
  var $window, $doc;

  $window = $(window);
  $doc = $( document.documentElement );

  window.componentNamespace = window.componentNamespace || window;

  Function.prototype.bind = function( context ) {
    var self = this;

    return function() {
      self.apply( context, arguments );
    };
  };

  var Tau = window.componentNamespace.Tau = function( element ) {
    var startIndex;

    this.element = element;
    this.$element = $( element );
    this.$initial = this.$element.find("img");
    this.startIndex = parseInt( this.$initial.attr("data-start") || "0", 10 );

    this.createImages();

    // TODO all of this should probably wait until the images load
    this.goto( this.startIndex );
    this.autoRotate();
    this.bind();
  };

  Tau.autoRotateDelay = 64;
  Tau.verticalScrollRatio = 4;

  Tau.prototype.change = function( delta ) {
    this.goto( this.index + delta );
  };

  Tau.prototype.goto = function( index ) {
    var $next;

    // stay within the bounds of the array
    this.index = (this.$images.length + index) % this.$images.length;

    // set the next image that's going to be shown/focused
    $next = this.$images.eq( this.index );

    // skip this action if the desired image isn't loaded yet
    // TODO do something fancier here instead of just throwing up hands
    if( !$next[0].tauImageLoaded ) {
      return;
    }

    // hide the old focused image
    if( this.$current ) {
      this.$current.removeClass( "focused" );
    }

    // record the current focused image and make it visible
    this.$current = $next;

    // show the new focused image
    this.$current.addClass( "focused" );
  };

  // TODO transplant the attributes from the initial image
  Tau.prototype.createImages = function() {
    var src, frames, $new;

    src = this.$initial.attr( "data-src-template" );
    frames = parseInt( this.$initial.attr( "data-frames" ), 10 );

    for( var i = 2; i <= frames; i++) {
      $new = $( "" );
      this.$element.append( $new );

      // record when each image has loaded
      $new.bind( "load", function() {
        this.tauImageLoaded = true;
      });
    }

    this.$images = this.$element.find( "img" );
  };

  Tau.prototype.bind = function() {
    $doc.bind( "mouseup touchend", this.release.bind(this) );
    this.$element.bind( "mousedown touchstart", this.track.bind(this) );
  };

  Tau.prototype.autoRotate = function() {
    this.autoInterval = setInterval(function() {
      this.change( 1 );
    }.bind(this), Tau.autoRotateDelay);
  };

  Tau.prototype.stopAutoRotate = function() {
    clearInterval( this.autoInterval );
  };

  Tau.prototype.track = function( event ) {
    var point;

    // prevent dragging behavior for mousedown
    if( event.type === "mousedown"  ){
      event.preventDefault();
    }

    if( this.tracking ) {
      return;
    }

    this.tracking = true;

    this.cursorGrab();

    // calculate/store how many pixels makes for an image switch
    this.rotateThreshold = $doc[0].clientWidth / this.$images.length;

    // record the x for threshold calculations
    point = this.getPoint( event );
    this.downX = point.x;
    this.downY = point.y;
    this.downIndex = this.index;

    $doc.bind( "mousemove", this.rotate.bind(this) );
    $doc.bind( "touchmove", this.rotate.bind(this) );
  };

  Tau.prototype.release = function( event ) {
    this.cursorRelease();
    $doc.unbind( "mousemove", this.rotate.bind(this) );
    $doc.unbind( "touchmove", this.rotate.bind(this) );
    this.tracking = false;
  };

  Tau.prototype.cursorGrab = function() {
    $doc.addClass( "grabbing" );
    this.$element.addClass( "grabbing" );
  };

  Tau.prototype.cursorRelease = function() {
    $doc.removeClass( "grabbing" );
    this.$element.removeClass( "grabbing" );
  };

  Tau.prototype.getPoint = function( event ) {
    var touch = event.touches || (event.originalEvent && event.originalEvent.touches);

    if( touch ){
      return {
        x: touch[0].pageX,
        y: touch[0].pageY
      };
    }

    return {
      x: event.pageX,
      y: event.pageY
    };
  };

  Tau.prototype.rotate = function( event ) {
    var deltaX, deltaY, point;

    point = this.getPoint( event );
    deltaX = point.x - this.downX;
    deltaY = point.y - this.downY;

    // if the movement on the Y dominates X then skip and allow scroll
    if( Math.abs(deltaY) / Math.abs(deltaX) >= Tau.verticalScrollRatio ) {
      return;
    }

    // NOTE works better on mousedown, here allows autorotate to continue on scroll though
    this.stopAutoRotate();

    // NOTE to reverse the spin direction add the delta/thresh to the downIndex
    // NOTE it might be better to prevent anyway for slow drags across the image
    if( Math.abs(deltaX) >= this.rotateThreshold ) {
      event.preventDefault();
      this.goto( this.downIndex - Math.round(deltaX / this.rotateThreshold) );
    }
  };
})(this, jQuery);
<|endoftext|>


<commit_before>import {createSpecBuilderClass} from './helpers';

import {RepositoryBuilder} from './repository';
import {UserBuilder} from './user';
import {createConnectionBuilderClass} from './connection';

const CommentBuilder = createSpecBuilderClass('PullRequestReviewCommentBuilder', {
  __typename: {default: 'PullRequestReviewComment'},
  id: {default: 0},
  path: {default: 'first.txt'},
  position: {default: 0, nullable: true},
  author: {linked: UserBuilder},
  url: {default: 'https://github.com/atom/github/pull/1829/files#r242224689'},
  createdAt: {default: '2018-12-27T17:51:17Z'},
  bodyHTML: {default: 'Lorem ipsum dolor sit amet, te urbanitas appellantur est.'},
  replyTo: {default: null, nullable: true},
  isMinimized: {default: false},
});

const CommentConnectionBuilder = createConnectionBuilderClass('PullRequestReviewCommentConnectionBuilder', CommentBuilder);

const ReviewThreadBuilder = createSpecBuilderClass('ReviewThreadBuilder', {
  __typename: {default: 'PullRequestReviewThread'},
  id: {default: 0},
  isResolved: {default: false},
  comments: {linked: CommentConnectionBuilder},
});

const ReviewBuilder = createSpecBuilderClass('PullRequestReviewBuilder', {
  __typename: {default: 'PullRequestReview'},
  id: {default: 0},
  submittedAt: {default: '2018-12-28T20:40:55Z'},
  body: {default: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit'},
  state: {default: 'COMMENTED'},
  author: {linked: UserBuilder},
  comments: {linked: CommentConnectionBuilder},
});

const PullRequestBuilder = createSpecBuilderClass('PullRequestBuilder', {
  number: {default: 123},
  headRefName: {default: 'head-ref'},
  url: {default: 'https://github.com/aaa/bbb/pull/1'},
  repository: {linked: RepositoryBuilder},
  headRepository: {linked: RepositoryBuilder, nullable: true},
  reviews: {linked: createConnectionBuilderClass('ReviewConnection', ReviewBuilder)},
  reviewThreads: {linked: createConnectionBuilderClass('ReviewThreadConnection', ReviewThreadBuilder)},
});

export function reviewThreadBuilder(...nodes) {
  return new ReviewThreadBuilder(nodes);
}

export function pullRequestBuilder(...nodes) {
  return new PullRequestBuilder(nodes);
}
<commit_msg>Generate unique IDs automatically by default<commit_after>import {createSpecBuilderClass} from './helpers';

import {RepositoryBuilder} from './repository';
import {UserBuilder} from './user';
import {createConnectionBuilderClass} from './connection';
import {nextID} from '../id-sequence';

const CommentBuilder = createSpecBuilderClass('PullRequestReviewCommentBuilder', {
  __typename: {default: 'PullRequestReviewComment'},
  id: {default: nextID},
  path: {default: 'first.txt'},
  position: {default: 0, nullable: true},
  author: {linked: UserBuilder},
  url: {default: 'https://github.com/atom/github/pull/1829/files#r242224689'},
  createdAt: {default: '2018-12-27T17:51:17Z'},
  bodyHTML: {default: 'Lorem ipsum dolor sit amet, te urbanitas appellantur est.'},
  replyTo: {default: null, nullable: true},
  isMinimized: {default: false},
});

const CommentConnectionBuilder = createConnectionBuilderClass('PullRequestReviewCommentConnectionBuilder', CommentBuilder);

const ReviewThreadBuilder = createSpecBuilderClass('ReviewThreadBuilder', {
  __typename: {default: 'PullRequestReviewThread'},
  id: {default: nextID},
  isResolved: {default: false},
  comments: {linked: CommentConnectionBuilder},
});

const ReviewBuilder = createSpecBuilderClass('PullRequestReviewBuilder', {
  __typename: {default: 'PullRequestReview'},
  id: {default: nextID},
  submittedAt: {default: '2018-12-28T20:40:55Z'},
  body: {default: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit'},
  state: {default: 'COMMENTED'},
  author: {linked: UserBuilder},
  comments: {linked: CommentConnectionBuilder},
});

const PullRequestBuilder = createSpecBuilderClass('PullRequestBuilder', {
  number: {default: 123},
  headRefName: {default: 'head-ref'},
  url: {default: 'https://github.com/aaa/bbb/pull/1'},
  repository: {linked: RepositoryBuilder},
  headRepository: {linked: RepositoryBuilder, nullable: true},
  reviews: {linked: createConnectionBuilderClass('ReviewConnection', ReviewBuilder)},
  reviewThreads: {linked: createConnectionBuilderClass('ReviewThreadConnection', ReviewThreadBuilder)},
});

export function reviewThreadBuilder(...nodes) {
  return new ReviewThreadBuilder(nodes);
}

export function pullRequestBuilder(...nodes) {
  return new PullRequestBuilder(nodes);
}
<|endoftext|>


<commit_before>/*
 *  PekeUpload 2.0 - jQuery plugin
 *  written by Pedro Molina
 *  http://www.pekebyte.com/
 *
 *  Copyright (c) 2015 Pedro Molina (http://pekebyte.com)
 *  Dual licensed under the MIT (MIT-LICENSE.txt)
 *  and GPL (GPL-LICENSE.txt) licenses.
 *
 *  Built for jQuery library
 *  http://jquery.com
 *
 */
(function($) {
    $.fn.pekeUpload = function(options) {
        // default configuration properties
        var defaults = {
            dragMode: false,
            dragText: "Drag and Drop your files here",
            bootstrap: false,
            btnText: "Browse files...",
            allowedExtensions: "",
            invalidExtError: "Invalid File Type",
            maxSize: 0,
            sizeError: "Size of the file is greather than allowed",
            showPreview: true,
            showFilename: true,
            showPercent: true,
            showErrorAlerts: true,
            errorOnResponse: "There has been an error uploading your file",
            onSubmit: false,
            url: "upload.php",
            data: null,
            limit: 0,
            limitError: "You have reached the limit of files that you can upload",
            onFileError: function(file, error) {},
            onFileSuccess: function(file, data) {}
        };
        var options = $.extend(defaults, options);
        var pekeUpload = {
            obj: $(this),
            files: [],
            uparea: null,
            container: null,
            uploadedfiles: 0,
            hasErrors: false,
            init: function() {
                this.replacehtml();
                this.uparea.on("click", function() {
                    pekeUpload.selectfiles();
                });
                ///Handle events when drag
                if (options.dragMode) {
                    this.handledragevents();
                }
                this.handlebuttonevents();
                //Dismiss all warnings
                $(document).on("click", ".pkwrncl", function() {
                    $(this).parent("div").remove();
                });
                //Bind event if is on Submit
                if (options.onSubmit) {
                    this.handleFormSubmission();
                }
            },
            replacehtml: function() {
                var html = null;
                switch (options.dragMode) {
                  case true:
                    switch (options.bootstrap) {
                      case true:
                        html = '

' + options.dragText + "

";
                        break;

                      case false:
                        html = '

' + options.dragText + "

";
                        break;
                    }
                    break;

                  case false:
                    switch (options.bootstrap) {
                      case true:
                        html = '  ' + options.btnText + "";
                        break;

                      case false:
                        html = '' + options.btnText + "";
                        break;
                    }
                    break;
                }
                this.obj.hide();
                this.uparea = $(html).insertAfter(this.obj);
                this.container = $('

').insertAfter(this.uparea);
            },
            selectfiles: function() {
                this.obj.click();
            },
            handlebuttonevents: function() {
                $(document).on("change", this.obj, function() {
                    pekeUpload.checkFile(pekeUpload.obj[0].files[0]);
                });
            },
            handledragevents: function() {
                $(document).on("dragenter", function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                });
                $(document).on("dragover", function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                });
                $(document).on("drop", function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                });
                this.uparea.on("dragenter", function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                    $(this).css("border", "2px solid #0B85A1");
                });
                this.uparea.on("dragover", function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                });
                this.uparea.on("drop", function(e) {
                    $(this).css("border", "2px dotted #0B85A1");
                    e.preventDefault();
                    var files = e.originalEvent.dataTransfer.files;
                    for (var i = 0; i < files.length; i++) {
                        pekeUpload.checkFile(files[i]);
                    }
                });
            },
            checkFile: function(file) {
                error = this.validateFile(file);
                if (error) {
                    if (options.showErrorAlerts) {
                        this.addWarning(error);
                    }
                    this.hasErrors = true;
                    options.onFileError(file, error);
                } else {
                    this.files.push(file);
                    if (this.files.length > options.limit && options.limit > 0) {
                        this.files.splice(this.files.length - 1, 1);
                        if (options.showErrorAlerts) {
                            this.addWarning(options.limitError, this.obj);
                        }
                        this.hasErrors = true;
                        options.onFileError(file, error);
                    } else {
                        this.addRow(file);
                        if (options.onSubmit == false) {
                            this.upload(file, this.files.length - 1);
                        }
                    }
                }
            },
            addWarning: function(error, c) {
                var html = null;
                switch (options.bootstrap) {
                  case true:
                    html = '
<button type="button" class="close pkwrncl" data-dismiss="alert">×</button> ' + error + "
";
                    break;

                  case false:
                    html = '
<button type="button" class="close pkwrncl" data-dismiss="alert">×</button> ' + error + "
";
                    break;
                }
                if (!c) {
                    this.container.append(html);
                } else {
                    $(html).insertBefore(c);
                }
            },
            validateFile: function(file) {
                if (!this.checkExtension(file)) {
                    return options.invalidExtError;
                }
                if (!this.checkSize(file)) {
                    return options.sizeError;
                }
                return null;
            },
            checkExtension: function(file) {
                if (options.allowedExtensions == "") {
                    return true;
                }
                var ext = file.name.split(".").pop().toLowerCase();
                var allowed = options.allowedExtensions.split("|");
                if ($.inArray(ext, allowed) == -1) {
                    return false;
                } else {
                    return true;
                }
            },
            checkSize: function(file) {
                if (options.maxSize == 0) {
                    return true;
                }
                if (file.size > options.maxSize) {
                    return false;
                } else {
                    return true;
                }
            },
            addRow: function(file) {
                var i = this.files.length - 1;
                switch (options.bootstrap) {
                  case true:
                    var newRow = $('

').appendTo(this.container);
                    if (options.showPreview) {
                        var prev = $('

').appendTo(newRow);
                        this.previewFile(prev, file);
                    }
                    var finfo = $('

').appendTo(newRow);
                    if (options.showFilename) {
                        finfo.append('
' + file.name + "
");
                    }
                    var progress = $('

').appendTo(finfo);
                    if (options.showPercent) {
                        progress.find("div.progress-bar").text("0%");
                    }
                    break;

                  case false:
                    var newRow = $('

').appendTo(this.container);
                    if (options.showPreview) {
                        var prev = $('

').appendTo(newRow);
                        this.previewFile(prev, file);
                    }
                    var finfo = $('

').appendTo(newRow);
                    if (options.showFilename) {
                        finfo.append('
' + file.name + "
");
                    }
                    var progress = $('

').appendTo(finfo);
                    if (options.showPercent) {
                        progress.find("div.bar-pekeupload").text("0%");
                    }
                    break;
                }
            },
            previewFile: function(container, file) {
                var type = file.type.split("/")[0];
                switch (type) {
                  case "image":
                    var fileUrl = window.URL.createObjectURL(file);
                    var prev = $('').appendTo(container);
                    break;

                  case "video":
                    var fileUrl = window.URL.createObjectURL(file);
                    var prev = $('<video src="' + fileUrl + '" width="100%" controls></video>').appendTo(container);
                    break;

                  case "audio":
                    var fileUrl = window.URL.createObjectURL(file);
                    var prev = $('<audio src="' + fileUrl + '" width="100%" controls></audio>').appendTo(container);
                    break;

                  default:
                    if (options.bootstrap) {
                        var prev = $('').appendTo(container);
                    } else {
                        var prev = $('

').appendTo(container);
                    }
                    break;
                }
            },
            upload: function(file, pos) {
                var formData = new FormData();
                formData.append(this.obj.attr("name"), file);
                for (var key in options.data) {
                    formData.append(key, options.data[key]);
                }
                $.ajax({
                    url: options.url,
                    type: "POST",
                    data: formData,
                    dataType: "json",
                    success: function(data) {
                        if (data == 1 || data.success == 1) {
                            pekeUpload.files[pos] = null;
                            $('div.row[rel="' + pos + '"]').find(".pkuppbr").css("width", "100%");
                            options.onFileSuccess(file, data);
                        } else {
                            pekeUpload.files.splice(pos, 1);
                            var err = null;
                            if (error in json) {
                                err = null;
                            } else {
                                err = options.errorOnResponse;
                            }
                            if (options.showErrorAlerts) {
                                pekeUpload.addWarning(err, $('div.row[rel="' + pos + '"]'));
                            }
                            $('div.row[rel="' + pos + '"]').remove();
                            pekeUpload.hasErrors = true;
                            options.onFileError(file, err);
                        }
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        pekeUpload.files.splice(pos, 1);
                        if (options.showErrorAlerts) {
                            pekeUpload.addWarning(thrownError, $('div.pkrw[rel="' + pos + '"]'));
                        }
                        pekeUpload.hasErrors = true;
                        options.onFileError(file, thrownError);
                        $('div.pkrw[rel="' + pos + '"]').remove();
                    },
                    xhr: function() {
                        myXhr = $.ajaxSettings.xhr();
                        if (myXhr.upload) {
                            myXhr.upload.addEventListener("progress", function(e) {
                                pekeUpload.handleProgress(e, pos);
                            }, false);
                        }
                        return myXhr;
                    },
                    complete: function() {
                        if (options.onSubmit) {
                            pekeUpload.uploadedfiles++;
                            if (pekeUpload.uploadedfiles == pekeUpload.files.length && pekeUpload.hasErrors == false) {
                                pekeUpload.obj.remove();
                                pekeUpload.obj.parent("form").submit();
                            }
                        }
                    },
                    cache: false,
                    contentType: false,
                    processData: false
                });
            },
            handleProgress: function(e, pos) {
                if (e.lengthComputable) {
                    var total = e.total;
                    var loaded = e.loaded;
                    var percent = Number((e.loaded * 100 / e.total).toFixed(2));
                    var progressbar = $('div.pkrw[rel="' + pos + '"]').find(".pkuppbr");
                    progressbar.css("width", percent + "%");
                    if (options.showPercent) {
                        progressbar.text(percent + "%");
                    }
                }
            },
            handleFormSubmission: function() {
                var form = this.obj.parent("form");
                form.submit(function() {
                    pekeUpload.hasErrors = false;
                    pekeUpload.uploadedfiles = 0;
                    for (var i = 0; i < pekeUpload.files.length; i++) {
                        if (pekeUpload.files[i]) {
                            pekeUpload.upload(pekeUpload.files[i], i);
                        } else {
                            pekeUpload.uploadedfiles++;
                            if (pekeUpload.uploadedfiles == pekeUpload.files.length && pekeUpload.hasErrors == false) {
                                pekeUpload.obj.remove();
                                return true;
                            }
                        }
                    }
                    return false;
                });
            }
        };
        pekeUpload.init();
    };
})(jQuery);<commit_msg>Option to delete file from queue<commit_after>/*
 *  PekeUpload 2.0 - jQuery plugin
 *  written by Pedro Molina
 *  http://www.pekebyte.com/
 *
 *  Copyright (c) 2015 Pedro Molina (http://pekebyte.com)
 *  Dual licensed under the MIT (MIT-LICENSE.txt)
 *  and GPL (GPL-LICENSE.txt) licenses.
 *
 *  Built for jQuery library
 *  http://jquery.com
 *
 */
(function($) {
    $.fn.pekeUpload = function(options) {
        // default configuration properties
        var defaults = {
            dragMode: false,
            dragText: "Drag and Drop your files here",
            bootstrap: false,
            btnText: "Browse files...",
            allowedExtensions: "",
            invalidExtError: "Invalid File Type",
            maxSize: 0,
            sizeError: "Size of the file is greather than allowed",
            showPreview: true,
            showFilename: true,
            showPercent: true,
            showErrorAlerts: true,
            errorOnResponse: "There has been an error uploading your file",
            onSubmit: false,
            url: "upload.php",
            data: null,
            limit: 0,
            limitError: "You have reached the limit of files that you can upload",
            delfiletext: "Remove from queue",
            onFileError: function(file, error) {},
            onFileSuccess: function(file, data) {}
        };
        var options = $.extend(defaults, options);
        var pekeUpload = {
            obj: $(this),
            files: [],
            uparea: null,
            container: null,
            uploadedfiles: 0,
            hasErrors: false,
            init: function() {
                this.replacehtml();
                this.uparea.on("click", function() {
                    pekeUpload.selectfiles();
                });
                ///Handle events when drag
                if (options.dragMode) {
                    this.handledragevents();
                }
                this.handlebuttonevents();
                //Dismiss all warnings
                $(document).on("click", ".pkwrncl", function() {
                    $(this).parent("div").remove();
                });
                //Bind event if is on Submit
                if (options.onSubmit) {
                    this.handleFormSubmission();
                }
            },
            replacehtml: function() {
                var html = null;
                switch (options.dragMode) {
                  case true:
                    switch (options.bootstrap) {
                      case true:
                        html = '

' + options.dragText + "

";
                        break;

                      case false:
                        html = '

' + options.dragText + "

";
                        break;
                    }
                    break;

                  case false:
                    switch (options.bootstrap) {
                      case true:
                        html = '  ' + options.btnText + "";
                        break;

                      case false:
                        html = '' + options.btnText + "";
                        break;
                    }
                    break;
                }
                this.obj.hide();
                this.uparea = $(html).insertAfter(this.obj);
                this.container = $('

').insertAfter(this.uparea);
            },
            selectfiles: function() {
                this.obj.click();
            },
            handlebuttonevents: function() {
                $(document).on("change", this.obj, function() {
                    pekeUpload.checkFile(pekeUpload.obj[0].files[0]);
                });
                $(document).on('click','.pkdel',function(){
                    var parent = $(this).parent('div').parent('div');
                    pekeUpload.delAndRearrange(parent);
                });
            },
            handledragevents: function() {
                $(document).on("dragenter", function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                });
                $(document).on("dragover", function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                });
                $(document).on("drop", function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                });
                this.uparea.on("dragenter", function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                    $(this).css("border", "2px solid #0B85A1");
                });
                this.uparea.on("dragover", function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                });
                this.uparea.on("drop", function(e) {
                    $(this).css("border", "2px dotted #0B85A1");
                    e.preventDefault();
                    var files = e.originalEvent.dataTransfer.files;
                    for (var i = 0; i < files.length; i++) {
                        pekeUpload.checkFile(files[i]);
                    }
                });
            },
            checkFile: function(file) {
                error = this.validateFile(file);
                if (error) {
                    if (options.showErrorAlerts) {
                        this.addWarning(error);
                    }
                    this.hasErrors = true;
                    options.onFileError(file, error);
                } else {
                    this.files.push(file);
                    if (this.files.length > options.limit && options.limit > 0) {
                        this.files.splice(this.files.length - 1, 1);
                        if (options.showErrorAlerts) {
                            this.addWarning(options.limitError, this.obj);
                        }
                        this.hasErrors = true;
                        options.onFileError(file, error);
                    } else {
                        this.addRow(file);
                        if (options.onSubmit == false) {
                            this.upload(file, this.files.length - 1);
                        }
                    }
                }
            },
            addWarning: function(error, c) {
                var html = null;
                switch (options.bootstrap) {
                  case true:
                    html = '
<button type="button" class="close pkwrncl" data-dismiss="alert">×</button> ' + error + "
";
                    break;

                  case false:
                    html = '
<button type="button" class="close pkwrncl" data-dismiss="alert">×</button> ' + error + "
";
                    break;
                }
                if (!c) {
                    this.container.append(html);
                } else {
                    $(html).insertBefore(c);
                }
            },
            validateFile: function(file) {
                if (!this.checkExtension(file)) {
                    return options.invalidExtError;
                }
                if (!this.checkSize(file)) {
                    return options.sizeError;
                }
                return null;
            },
            checkExtension: function(file) {
                if (options.allowedExtensions == "") {
                    return true;
                }
                var ext = file.name.split(".").pop().toLowerCase();
                var allowed = options.allowedExtensions.split("|");
                if ($.inArray(ext, allowed) == -1) {
                    return false;
                } else {
                    return true;
                }
            },
            checkSize: function(file) {
                if (options.maxSize == 0) {
                    return true;
                }
                if (file.size > options.maxSize) {
                    return false;
                } else {
                    return true;
                }
            },
            addRow: function(file) {
                var i = this.files.length - 1;
                switch (options.bootstrap) {
                  case true:
                    var newRow = $('

').appendTo(this.container);
                    if (options.showPreview) {
                        var prev = $('

').appendTo(newRow);
                        this.previewFile(prev, file);
                    }
                    var finfo = $('

').appendTo(newRow);
                    if (options.showFilename) {
                        finfo.append('
' + file.name + "
");
                    }
                    if (options.notAjax == false){
                        var progress = $('

').appendTo(finfo);
                        if (options.showPercent) {
                            progress.find("div.progress-bar").text("0%");
                        }
                    }
                    var dismiss = $('

').appendTo(newRow);
                    $(''+options.delfiletext+'').appendTo(dismiss);
                    break;

                  case false:
                    var newRow = $('

').appendTo(this.container);
                    if (options.showPreview) {
                        var prev = $('

').appendTo(newRow);
                        this.previewFile(prev, file);
                    }
                    var finfo = $('

').appendTo(newRow);
                    if (options.showFilename) {
                        finfo.append('
' + file.name + "
");
                    }
                    if (options.notAjax == false){
                        var progress = $('

').appendTo(finfo);
                        if (options.showPercent) {
                            progress.find("div.bar-pekeupload").text("0%");
                        }
                    }
                    var dismiss = $('

').appendTo(newRow);
                    $(''+options.delfiletext+'').appendTo(dismiss);
                    break;
                }
            },
            previewFile: function(container, file) {
                var type = file.type.split("/")[0];
                switch (type) {
                  case "image":
                    var fileUrl = window.URL.createObjectURL(file);
                    var prev = $('').appendTo(container);
                    break;

                  case "video":
                    var fileUrl = window.URL.createObjectURL(file);
                    var prev = $('<video src="' + fileUrl + '" width="100%" controls></video>').appendTo(container);
                    break;

                  case "audio":
                    var fileUrl = window.URL.createObjectURL(file);
                    var prev = $('<audio src="' + fileUrl + '" width="100%" controls></audio>').appendTo(container);
                    break;

                  default:
                    if (options.bootstrap) {
                        var prev = $('').appendTo(container);
                    } else {
                        var prev = $('

').appendTo(container);
                    }
                    break;
                }
            },
            upload: function(file, pos) {
                var formData = new FormData();
                formData.append(this.obj.attr("name"), file);
                for (var key in options.data) {
                    formData.append(key, options.data[key]);
                }
                $.ajax({
                    url: options.url,
                    type: "POST",
                    data: formData,
                    dataType: "json",
                    success: function(data) {
                        if (data == 1 || data.success == 1) {
                            pekeUpload.files[pos] = null;
                            $('div.row[rel="' + pos + '"]').find(".pkuppbr").css("width", "100%");
                            options.onFileSuccess(file, data);
                        } else {
                            pekeUpload.files.splice(pos, 1);
                            var err = null;
                            if (error in json) {
                                err = null;
                            } else {
                                err = options.errorOnResponse;
                            }
                            if (options.showErrorAlerts) {
                                pekeUpload.addWarning(err, $('div.row[rel="' + pos + '"]'));
                            }
                            $('div.row[rel="' + pos + '"]').remove();
                            pekeUpload.hasErrors = true;
                            options.onFileError(file, err);
                        }
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        pekeUpload.files.splice(pos, 1);
                        if (options.showErrorAlerts) {
                            pekeUpload.addWarning(thrownError, $('div.pkrw[rel="' + pos + '"]'));
                        }
                        pekeUpload.hasErrors = true;
                        options.onFileError(file, thrownError);
                        $('div.pkrw[rel="' + pos + '"]').remove();
                    },
                    xhr: function() {
                        myXhr = $.ajaxSettings.xhr();
                        if (myXhr.upload) {
                            myXhr.upload.addEventListener("progress", function(e) {
                                pekeUpload.handleProgress(e, pos);
                            }, false);
                        }
                        return myXhr;
                    },
                    complete: function() {
                        if (options.onSubmit) {
                            pekeUpload.uploadedfiles++;
                            if (pekeUpload.uploadedfiles == pekeUpload.files.length && pekeUpload.hasErrors == false) {
                                pekeUpload.obj.remove();
                                pekeUpload.obj.parent("form").submit();
                            }
                        }
                    },
                    cache: false,
                    contentType: false,
                    processData: false
                });
            },
            handleProgress: function(e, pos) {
                if (e.lengthComputable) {
                    var total = e.total;
                    var loaded = e.loaded;
                    var percent = Number((e.loaded * 100 / e.total).toFixed(2));
                    var progressbar = $('div.pkrw[rel="' + pos + '"]').find(".pkuppbr");
                    progressbar.css("width", percent + "%");
                    if (options.showPercent) {
                        progressbar.text(percent + "%");
                    }
                }
            },
            handleFormSubmission: function() {
                var form = this.obj.parent("form");
                form.submit(function() {
                    pekeUpload.hasErrors = false;
                    pekeUpload.uploadedfiles = 0;
                    for (var i = 0; i < pekeUpload.files.length; i++) {
                        if (pekeUpload.files[i]) {
                            pekeUpload.upload(pekeUpload.files[i], i);
                        } else {
                            pekeUpload.uploadedfiles++;
                            if (pekeUpload.uploadedfiles == pekeUpload.files.length && pekeUpload.hasErrors == false) {
                                pekeUpload.obj.remove();
                                return true;
                            }
                        }
                    }
                    return false;
                });
            },
            ,
            delAndRearrange: function(parent){
                var id = parent.attr('rel');
                pekeUpload.files.splice(parseInt(id), 1);
                parent.remove();
                pekeUpload.container.find('div.pkrw').each(function(index){
                    $(this).attr('rel',index);
                });
            }
        };
        pekeUpload.init();
    };
})(jQuery);<|endoftext|>


<commit_before>class DiscordEventListener {
    constructor(client, server, channelName) {
        this.client      = client;
        this.server      = server;
        this.channelName = channelName;
    }

    listen() {
        this.channel = this.server.channels.get('name', this.channelName);
        if (this.channel === null || this.channel === undefined) {
            return this.client.createChannel(this.server, this.channelName, 'text', (error, channel) => {
                if (error) {
                    return console.log(`Could not create channel in ${this.server.name}: ${this.channelName}`);
                }

                this.addListeners();
            });
        }

        this.addListeners();
    }

    addListeners() {
        this.client.on('ready', client => this.logEvent('Bot is ready'));

        this.client.on('channelCreated', this.onChannel.bind(this, 'created'));
        this.client.on('channelDeleted', this.onChannel.bind(this, 'deleted'));
        this.client.on('channelUpdated', this.onChannel.bind(this, 'updated'));

        this.client.on('serverNewMember', this.onServerUser.bind(this, 'new'));
        this.client.on('serverMemberRemoved', this.onServerUser.bind(this, 'removed'));

        this.client.on('userBanned', this.onUser.bind(this, 'ban'));
        this.client.on('userUnbanned', this.onUser.bind(this, 'unban'));

        this.client.on('voiceJoin', this.onVoice.bind(this, 'voice_join'));
        this.client.on('voiceLeave', this.onVoice.bind(this, 'voice_leave'));

        this.client.on('presence', this.onUserPresence.bind(this));
    }

    logEvent(message) {
        this.client.sendMessage(this.channel, message);
    }

    onChannel(type, channel, updatedChannel) {
        if (channel.server === undefined) {
            return;
        }

        if (channel.server.id !== this.server.id) {
            return;
        }

        if (type !== 'updated') {
            return this.logEvent(`Channel ${type}: **${channel.name}**`);
        }

        if (channel.name !== updatedChannel.name) {
            this.logEvent(`Channel name changed: **${channel.name}** -> **${updatedChannel.name}**`);
        }
    }

    onServerUser(type, server, user) {
        if (server.id !== this.server.id) {
            return;
        }

        this.logEvent(`**${user.username}** has ${type === 'new' ? 'joined' : 'left'} the server.`);
    }

    onUser(type, user, server) {
        if (server.id !== this.server.id) {
            return;
        }

        this.logEvent(`**${user.username}** has been ${type}ned`);
    }

    onVoice(type, channel, user) {
        if (channel.server.id !== this.server.id) {
            return;
        }

        this.logEvent(
            `**${user.username}** has ${type === 'voice_join' ? 'joined' : 'left'} the voice channel:  **${channel.name}**.`
        );
    }

    /**
     * @todo Add the users game to the list of games they play
     *
     * @param old
     * @param newUser
     */
    onUserPresence(old, newUser) {
        if (!this.server.members.find(user => user.id === newUser.id)) {
            return false;
        }

        if (old.status !== newUser.status) {
            if (newUser.status === 'idle' || old.status === 'idle') {
                return;
            }

            let type = newUser.status === 'online' ? 'come online' : 'gone offline';

            return this.logEvent(`**${newUser.username}** has ${type}.`)
        }

        if (old.username !== newUser.username) {
            return this.logEvent(`**${old.username}** has changed their name to **${newUser.username}**`);
        }

        if (old.avatar !== newUser.avatar) {
            return this.logEvent(`**${newUser.username}** has changed their avatar`);
        }
    }
}

module.exports = DiscordEventListener;<commit_msg>Fixing<commit_after>class DiscordEventListener {
    constructor(client, server, channelName) {
        this.client      = client;
        this.server      = server;
        this.channelName = channelName;
    }

    listen() {
        this.channel = this.server.channels.get('name', this.channelName);
        if (this.channel === null || this.channel === undefined) {
            return false;
        }

        this.addListeners();
    }

    addListeners() {
        this.client.on('ready', client => this.logEvent('Bot is ready'));

        this.client.on('channelCreated', this.onChannel.bind(this, 'created'));
        this.client.on('channelDeleted', this.onChannel.bind(this, 'deleted'));
        this.client.on('channelUpdated', this.onChannel.bind(this, 'updated'));

        this.client.on('serverNewMember', this.onServerUser.bind(this, 'new'));
        this.client.on('serverMemberRemoved', this.onServerUser.bind(this, 'removed'));

        this.client.on('userBanned', this.onUser.bind(this, 'ban'));
        this.client.on('userUnbanned', this.onUser.bind(this, 'unban'));

        this.client.on('voiceJoin', this.onVoice.bind(this, 'voice_join'));
        this.client.on('voiceLeave', this.onVoice.bind(this, 'voice_leave'));

        this.client.on('presence', this.onUserPresence.bind(this));
    }

    logEvent(message) {
        this.client.sendMessage(this.channel, message);
    }

    onChannel(type, channel, updatedChannel) {
        if (channel.server === undefined) {
            return;
        }

        if (channel.server.id !== this.server.id) {
            return;
        }

        if (type !== 'updated') {
            return this.logEvent(`Channel ${type}: **${channel.name}**`);
        }

        if (channel.name !== updatedChannel.name) {
            this.logEvent(`Channel name changed: **${channel.name}** -> **${updatedChannel.name}**`);
        }
    }

    onServerUser(type, server, user) {
        if (server.id !== this.server.id) {
            return;
        }

        this.logEvent(`**${user.username}** has ${type === 'new' ? 'joined' : 'left'} the server.`);
    }

    onUser(type, user, server) {
        if (server.id !== this.server.id) {
            return;
        }

        this.logEvent(`**${user.username}** has been ${type}ned`);
    }

    onVoice(type, channel, user) {
        if (channel.server.id !== this.server.id) {
            return;
        }

        this.logEvent(
            `**${user.username}** has ${type === 'voice_join' ? 'joined' : 'left'} the voice channel:  **${channel.name}**.`
        );
    }

    /**
     * @todo Add the users game to the list of games they play
     *
     * @param old
     * @param newUser
     */
    onUserPresence(old, newUser) {
        if (!this.server.members.find(user => user.id === newUser.id)) {
            return false;
        }

        if (old.status !== newUser.status) {
            if (newUser.status === 'idle' || old.status === 'idle') {
                return;
            }

            let type = newUser.status === 'online' ? 'come online' : 'gone offline';

            return this.logEvent(`**${newUser.username}** has ${type}.`)
        }

        if (old.username !== newUser.username) {
            return this.logEvent(`**${old.username}** has changed their name to **${newUser.username}**`);
        }

        if (old.avatar !== newUser.avatar) {
            return this.logEvent(`**${newUser.username}** has changed their avatar`);
        }
    }
}

module.exports = DiscordEventListener;<|endoftext|>


<commit_before>const should = require('should');
const fsbx = require(`../dist/commonjs/index.js`);
const path = require("path");
const { getTestEnv, createEnv } = require("./fixtures/lib.js")
const fs = require("fs");
const mkdirp = require("mkdirp");

describe('Bundle in a bundle', () => {

    it("Should require a bundled package", (done) => {
        createEnv({
            modules: {
                foobar: {
                    files: {
                        "index.ts": `export const HelloFoo = "Yep, that's me1"`
                    },
                    instructions: ">index.ts"
                }
            },
            project: {
                files: {
                    "index.ts": `exports.hello = { bar : require("foobar") }`
                },
                instructions: "> index.ts"
            }
        }).then((result) => {
            if (result.projectSize > 5490) {
                return done(new Error(`Unexpected Bundle Size ${result.projectSize}!! Bundle is not removed from an uglified version`))
            }
            result.project.FuseBox.import("./index")
                .should.deepEqual({ hello: { bar: { HelloFoo: 'Yep, that\'s me1' } } })
            done();
        })
    });

    it("Should require a bundled package and work with uglify", (done) => {
        createEnv({
            modules: {
                foobar: {
                    files: {
                        "index.ts": `export const HelloFoo = "Yep, that's me2!"`
                    },
                    plugins: [fsbx.UglifyJSPlugin()],
                    instructions: ">index.ts"
                }
            },
            project: {
                files: {
                    "index.ts": `exports.hello = { bar : require("foobar") }`
                },
                instructions: "> index.ts"
            }
        }).then((result) => {
            if (result.projectSize > 5370) {
                return done(new Error(`Unexpected Bundle Size ${result.projectSize}!! Bundle is not removed from an uglified version`))
            }

            result.project.FuseBox.import("./index")
                .should.deepEqual({ hello: { bar: { HelloFoo: 'Yep, that\'s me2!' } } })

            done();
        });
    });

    it("Should require bundled file", (done) => {
        let bundleContents;
        createEnv({
            modules: {
                foobar: {
                    files: {
                        "index.ts": `export const HelloFoo = "Yep, that's me2!"`
                    },
                    instructions: ">index.ts",
                    onDone: (info) => {
                        bundleContents = fs.readFileSync(info.filePath).toString();
                    }
                }
            },
            project: {
                files: {
                    "hello.js": () => bundleContents,
                    "index.ts": `exports.hello = { bar : require("./hello.js") }`

                },
                instructions: "> index.ts"
            }
        }).then((result) => {
            if (result.projectSize > 5535) {
                return done(new Error(`Unexpected Bundle Size ${result.projectSize}!! Bundle is not removed from an uglified version`))
            }

            result.project.FuseBox.import("./index")
                .should.deepEqual({ hello: { bar: { HelloFoo: 'Yep, that\'s me2!' } } })

            done();
        });
    });

    it("Should require bundled minified file", (done) => {
        let bundleContents;
        createEnv({
            name: "test-bundle",
            modules: {
                //cache: false,
                foobar: {
                    files: {
                        "index.ts": `export const HelloFoo = "Yep, that's me2!"`
                    },
                    instructions: ">index.ts",
                    plugins: [fsbx.UglifyJSPlugin()],
                    onDone: (info) => {
                        bundleContents = fs.readFileSync(info.filePath).toString();
                    }
                }
            },
            project: {
                //cache: false,
                files: {
                    "hello.js": () => bundleContents,
                    "index.ts": `exports.hello = { bar : require("./hello.js") }`

                },
                instructions: "> index.ts"
            }
        }).then((result) => {
            if (result.projectSize > 5410) {
                return done(new Error(`Unexpected Bundle Size ${result.projectSize}!! Bundle is not removed from an uglified version`))
            }

            result.project.FuseBox.import("./index")
                .should.deepEqual({ hello: { bar: { HelloFoo: 'Yep, that\'s me2!' } } })

            done();
        });
    });
});
<commit_msg>bump bundle size to account for `if (__root__["FuseBox"]) return __root__["FuseBox"];`<commit_after>const should = require('should');
const fsbx = require(`../dist/commonjs/index.js`);
const path = require("path");
const { getTestEnv, createEnv } = require("./fixtures/lib.js")
const fs = require("fs");
const mkdirp = require("mkdirp");

describe('Bundle in a bundle', () => {

    it("Should require a bundled package", (done) => {
        createEnv({
            modules: {
                foobar: {
                    files: {
                        "index.ts": `export const HelloFoo = "Yep, that's me1"`
                    },
                    instructions: ">index.ts"
                }
            },
            project: {
                files: {
                    "index.ts": `exports.hello = { bar : require("foobar") }`
                },
                instructions: "> index.ts"
            }
        }).then((result) => {
            if (result.projectSize > 5497) {
                return done(new Error(`Unexpected Bundle Size ${result.projectSize}!! Bundle is not removed from an uglified version`))
            }
            result.project.FuseBox.import("./index")
                .should.deepEqual({ hello: { bar: { HelloFoo: 'Yep, that\'s me1' } } })
            done();
        })
    });

    it("Should require a bundled package and work with uglify", (done) => {
        createEnv({
            modules: {
                foobar: {
                    files: {
                        "index.ts": `export const HelloFoo = "Yep, that's me2!"`
                    },
                    plugins: [fsbx.UglifyJSPlugin()],
                    instructions: ">index.ts"
                }
            },
            project: {
                files: {
                    "index.ts": `exports.hello = { bar : require("foobar") }`
                },
                instructions: "> index.ts"
            }
        }).then((result) => {
            if (result.projectSize > 5380) {
                return done(new Error(`Unexpected Bundle Size ${result.projectSize}!! Bundle is not removed from an uglified version`))
            }

            result.project.FuseBox.import("./index")
                .should.deepEqual({ hello: { bar: { HelloFoo: 'Yep, that\'s me2!' } } })

            done();
        });
    });

    it("Should require bundled file", (done) => {
        let bundleContents;
        createEnv({
            modules: {
                foobar: {
                    files: {
                        "index.ts": `export const HelloFoo = "Yep, that's me2!"`
                    },
                    instructions: ">index.ts",
                    onDone: (info) => {
                        bundleContents = fs.readFileSync(info.filePath).toString();
                    }
                }
            },
            project: {
                files: {
                    "hello.js": () => bundleContents,
                    "index.ts": `exports.hello = { bar : require("./hello.js") }`

                },
                instructions: "> index.ts"
            }
        }).then((result) => {
            if (result.projectSize > 5548) {
                return done(new Error(`Unexpected Bundle Size ${result.projectSize}!! Bundle is not removed from an uglified version`))
            }

            result.project.FuseBox.import("./index")
                .should.deepEqual({ hello: { bar: { HelloFoo: 'Yep, that\'s me2!' } } })

            done();
        });
    });

    it("Should require bundled minified file", (done) => {
        let bundleContents;
        createEnv({
            name: "test-bundle",
            modules: {
                //cache: false,
                foobar: {
                    files: {
                        "index.ts": `export const HelloFoo = "Yep, that's me2!"`
                    },
                    instructions: ">index.ts",
                    plugins: [fsbx.UglifyJSPlugin()],
                    onDone: (info) => {
                        bundleContents = fs.readFileSync(info.filePath).toString();
                    }
                }
            },
            project: {
                //cache: false,
                files: {
                    "hello.js": () => bundleContents,
                    "index.ts": `exports.hello = { bar : require("./hello.js") }`

                },
                instructions: "> index.ts"
            }
        }).then((result) => {
            if (result.projectSize > 5430) {
                return done(new Error(`Unexpected Bundle Size ${result.projectSize}!! Bundle is not removed from an uglified version`))
            }

            result.project.FuseBox.import("./index")
                .should.deepEqual({ hello: { bar: { HelloFoo: 'Yep, that\'s me2!' } } })

            done();
        });
    });
});
<|endoftext|>


<commit_before>import 'bootstrap';
import ujs from '@rails/ujs';
import Turbolinks from 'turbolinks';

document.addEventListener('turbolinks:load', _event => {
  window.WebFont.load({
    google: {
      families: ['Raleway'],
    },
  });
});

ujs.start();
Turbolinks.start();
<commit_msg>Continue to use Vue<commit_after>import 'bootstrap';

import ujs from '@rails/ujs';
import Turbolinks from 'turbolinks';
import Vue from 'vue';

document.addEventListener('turbolinks:load', _event => {
  window.WebFont.load({
    google: {
      families: ['Raleway'],
    },
  });

  new Vue({
    el: '.f-app',
  });
});

ujs.start();
Turbolinks.start();
<|endoftext|>


<commit_before>//**************************************************
//**Work inspired by multiple jquery swipe plugins**
//**Done by Yohai Ararat ***************************
//**************************************************
(function($) {

  $.spotSwipe = {
    version: '1.0.0',
    enabled: 'ontouchstart' in document.documentElement,
    preventDefault: true,
    threshold: 75
  };

  var startPosX,
    startPosY,
    isMoving = false;

  function onTouchEnd() {
    //  alert(this);
    this.removeEventListener('touchmove', onTouchMove);
    this.removeEventListener('touchend', onTouchEnd);
    isMoving = false;
  }

  function onTouchMove(e) {
    if ($.spotSwipe.preventDefault) { e.preventDefault(); }
    if(isMoving) {
      var x = e.touches[0].pageX;
      var y = e.touches[0].pageY;
      var dx = startPosX - x;
      var dy = startPosY - y;
      var dir;
      if(Math.abs(dx) >= $.spotSwipe.threshold) {
        dir = dx > 0 ? 'left' : 'right'
      }
      else if(Math.abs(dy) >= $.spotSwipe.threshold) {
        dir = dy > 0 ? 'down' : 'up'
      }
      if(dir) {
        onTouchEnd.call(this);
        $(this).trigger('swipe', dir).trigger('swipe' + dir);
      }
    }
  }

  function onTouchStart(e) {
    if (e.touches.length == 1) {
      startPosX = e.touches[0].pageX;
      startPosY = e.touches[0].pageY;
      isMoving = true;
      this.addEventListener('touchmove', onTouchMove, false);
      this.addEventListener('touchend', onTouchEnd, false);
    }
  }

  function init() {
    this.addEventListener && this.addEventListener('touchstart', onTouchStart, false);
  }

  function teardown() {
    this.removeEventListener('touchstart', onTouchStart);
  }

  $.event.special.swipe = { setup: init };

  $.each(['left', 'up', 'down', 'right'], function () {
    $.event.special['swipe' + this] = { setup: function(){
      $(this).on('swipe', $.noop);
    } };
  });
})(jQuery);

//**********************************
//**From the jQuery Mobile Library**
//**need to recreate functionality**
//**and try to improve if possible**
//**********************************

/* Removing the jQuery function ****
************************************

(function( $, window, undefined ) {

	var $document = $( document ),
		// supportTouch = $.mobile.support.touch,
		touchStartEvent = 'touchstart'//supportTouch ? "touchstart" : "mousedown",
		touchStopEvent = 'touchend'//supportTouch ? "touchend" : "mouseup",
		touchMoveEvent = 'touchmove'//supportTouch ? "touchmove" : "mousemove";

	// setup new event shortcuts
	$.each( ( "touchstart touchmove touchend " +
		"swipe swipeleft swiperight" ).split( " " ), function( i, name ) {

		$.fn[ name ] = function( fn ) {
			return fn ? this.bind( name, fn ) : this.trigger( name );
		};

		// jQuery < 1.8
		if ( $.attrFn ) {
			$.attrFn[ name ] = true;
		}
	});

	function triggerCustomEvent( obj, eventType, event, bubble ) {
		var originalType = event.type;
		event.type = eventType;
		if ( bubble ) {
			$.event.trigger( event, undefined, obj );
		} else {
			$.event.dispatch.call( obj, event );
		}
		event.type = originalType;
	}

	// also handles taphold

	// Also handles swipeleft, swiperight
	$.event.special.swipe = {

		// More than this horizontal displacement, and we will suppress scrolling.
		scrollSupressionThreshold: 30,

		// More time than this, and it isn't a swipe.
		durationThreshold: 1000,

		// Swipe horizontal displacement must be more than this.
		horizontalDistanceThreshold: window.devicePixelRatio >= 2 ? 15 : 30,

		// Swipe vertical displacement must be less than this.
		verticalDistanceThreshold: window.devicePixelRatio >= 2 ? 15 : 30,

		getLocation: function ( event ) {
			var winPageX = window.pageXOffset,
				winPageY = window.pageYOffset,
				x = event.clientX,
				y = event.clientY;

			if ( event.pageY === 0 && Math.floor( y ) > Math.floor( event.pageY ) ||
				event.pageX === 0 && Math.floor( x ) > Math.floor( event.pageX ) ) {

				// iOS4 clientX/clientY have the value that should have been
				// in pageX/pageY. While pageX/page/ have the value 0
				x = x - winPageX;
				y = y - winPageY;
			} else if ( y < ( event.pageY - winPageY) || x < ( event.pageX - winPageX ) ) {

				// Some Android browsers have totally bogus values for clientX/Y
				// when scrolling/zooming a page. Detectable since clientX/clientY
				// should never be smaller than pageX/pageY minus page scroll
				x = event.pageX - winPageX;
				y = event.pageY - winPageY;
			}

			return {
				x: x,
				y: y
			};
		},

		start: function( event ) {
			var data = event.originalEvent.touches ?
					event.originalEvent.touches[ 0 ] : event,
				location = $.event.special.swipe.getLocation( data );
			return {
						time: ( new Date() ).getTime(),
						coords: [ location.x, location.y ],
						origin: $( event.target )
					};
		},

		stop: function( event ) {
			var data = event.originalEvent.touches ?
					event.originalEvent.touches[ 0 ] : event,
				location = $.event.special.swipe.getLocation( data );
			return {
						time: ( new Date() ).getTime(),
						coords: [ location.x, location.y ]
					};
		},

		handleSwipe: function( start, stop, thisObject, origTarget ) {
			if ( stop.time - start.time < $.event.special.swipe.durationThreshold &&
				Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold &&
				Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) {
				var direction = start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight";

				triggerCustomEvent( thisObject, "swipe", $.Event( "swipe", { target: origTarget, swipestart: start, swipestop: stop }), true );
				triggerCustomEvent( thisObject, direction,$.Event( direction, { target: origTarget, swipestart: start, swipestop: stop } ), true );
				return true;
			}
			return false;

		},

		// This serves as a flag to ensure that at most one swipe event event is
		// in work at any given time
		eventInProgress: false,

		setup: function() {
			var events,
				thisObject = this,
				$this = $( thisObject ),
				context = {};

			// Retrieve the events data for this element and add the swipe context
			events = $.data( this, "mobile-events" );
			if ( !events ) {
				events = { length: 0 };
				$.data( this, "mobile-events", events );
			}
			events.length++;
			events.swipe = context;

			context.start = function( event ) {

				// Bail if we're already working on a swipe event
				if ( $.event.special.swipe.eventInProgress ) {
					return;
				}
				$.event.special.swipe.eventInProgress = true;

				var stop,
					start = $.event.special.swipe.start( event ),
					origTarget = event.target,
					emitted = false;

				context.move = function( event ) {
					if ( !start || event.isDefaultPrevented() ) {
						return;
					}

					stop = $.event.special.swipe.stop( event );
					if ( !emitted ) {
						emitted = $.event.special.swipe.handleSwipe( start, stop, thisObject, origTarget );
						if ( emitted ) {

							// Reset the context to make way for the next swipe event
							$.event.special.swipe.eventInProgress = false;
						}
					}
					// prevent scrolling
					if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) {
						event.preventDefault();
					}
				};

				context.stop = function() {
						emitted = true;

						// Reset the context to make way for the next swipe event
						$.event.special.swipe.eventInProgress = false;
						$document.off( touchMoveEvent, context.move );
						context.move = null;
				};

				$document.on( touchMoveEvent, context.move )
					.one( touchStopEvent, context.stop );
			};
			$this.on( touchStartEvent, context.start );
		},

		teardown: function() {
			var events, context;

			events = $.data( this, "mobile-events" );
			if ( events ) {
				context = events.swipe;
				delete events.swipe;
				events.length--;
				if ( events.length === 0 ) {
					$.removeData( this, "mobile-events" );
				}
			}

			if ( context ) {
				if ( context.start ) {
					$( this ).off( touchStartEvent, context.start );
				}
				if ( context.move ) {
					$document.off( touchMoveEvent, context.move );
				}
				if ( context.stop ) {
					$document.off( touchStopEvent, context.stop );
				}
			}
		}
	};
	$.each({
		swipeleft: "swipe.left",
		swiperight: "swipe.right"
	}, function( event, sourceEvent ) {

		$.event.special[ event ] = {
			setup: function() {
				$( this ).bind( sourceEvent, $.noop );
			},
			teardown: function() {
				$( this ).unbind( sourceEvent );
			}
		};
	});
})( jQuery, this );
*/<commit_msg>added the threshold for the time value to stop event if it is slower than specific speed and distance<commit_after>//**************************************************
//**Work inspired by multiple jquery swipe plugins**
//**Done by Yohai Ararat ***************************
//**************************************************
(function($) {

  $.spotSwipe = {
    version: '1.0.0',
    enabled: 'ontouchstart' in document.documentElement,
    preventDefault: true,
    moveThreshold: 75,
    timeThreshold: 200
  };

  var   startPosX,
        startPosY,
        startTime,
        elapsedTime,
        isMoving = false;

  function onTouchEnd() {
    //  alert(this);
    this.removeEventListener('touchmove', onTouchMove);
    this.removeEventListener('touchend', onTouchEnd);
    isMoving = false;
  }

  function onTouchMove(e) {
    if ($.spotSwipe.preventDefault) { e.preventDefault(); }
    if(isMoving) {
      var x = e.touches[0].pageX;
      var y = e.touches[0].pageY;
      var dx = startPosX - x;
      var dy = startPosY - y;
      var dir;
      elapsedTime = new Date().getTime() - startTime;
      if(Math.abs(dx) >= $.spotSwipe.moveThreshold && elapsedTime <= $.spotSwipe.timeThreshold) {
        dir = dx > 0 ? 'left' : 'right'
      }
      else if(Math.abs(dy) >= $.spotSwipe.moveThreshold && elapsedTime <= $.spotSwipe.timeThreshold) {
        dir = dy > 0 ? 'down' : 'up'
      }
      if(dir) {
        onTouchEnd.call(this);
        $(this).trigger('swipe', dir).trigger('swipe' + dir);
      }
    }
  }

  function onTouchStart(e) {
    if (e.touches.length == 1) {
      startPosX = e.touches[0].pageX;
      startPosY = e.touches[0].pageY;
      isMoving = true;
      startTime = new Date().getTime()
      this.addEventListener('touchmove', onTouchMove, false);
      this.addEventListener('touchend', onTouchEnd, false);
    }
  }

  function init() {
    this.addEventListener && this.addEventListener('touchstart', onTouchStart, false);
  }

  function teardown() {
    this.removeEventListener('touchstart', onTouchStart);
  }

  $.event.special.swipe = { setup: init };

  $.each(['left', 'up', 'down', 'right'], function () {
    $.event.special['swipe' + this] = { setup: function(){
      $(this).on('swipe', $.noop);
    } };
  });
})(jQuery);

//**********************************
//**From the jQuery Mobile Library**
//**need to recreate functionality**
//**and try to improve if possible**
//**********************************

/* Removing the jQuery function ****
************************************

(function( $, window, undefined ) {

	var $document = $( document ),
		// supportTouch = $.mobile.support.touch,
		touchStartEvent = 'touchstart'//supportTouch ? "touchstart" : "mousedown",
		touchStopEvent = 'touchend'//supportTouch ? "touchend" : "mouseup",
		touchMoveEvent = 'touchmove'//supportTouch ? "touchmove" : "mousemove";

	// setup new event shortcuts
	$.each( ( "touchstart touchmove touchend " +
		"swipe swipeleft swiperight" ).split( " " ), function( i, name ) {

		$.fn[ name ] = function( fn ) {
			return fn ? this.bind( name, fn ) : this.trigger( name );
		};

		// jQuery < 1.8
		if ( $.attrFn ) {
			$.attrFn[ name ] = true;
		}
	});

	function triggerCustomEvent( obj, eventType, event, bubble ) {
		var originalType = event.type;
		event.type = eventType;
		if ( bubble ) {
			$.event.trigger( event, undefined, obj );
		} else {
			$.event.dispatch.call( obj, event );
		}
		event.type = originalType;
	}

	// also handles taphold

	// Also handles swipeleft, swiperight
	$.event.special.swipe = {

		// More than this horizontal displacement, and we will suppress scrolling.
		scrollSupressionThreshold: 30,

		// More time than this, and it isn't a swipe.
		durationThreshold: 1000,

		// Swipe horizontal displacement must be more than this.
		horizontalDistanceThreshold: window.devicePixelRatio >= 2 ? 15 : 30,

		// Swipe vertical displacement must be less than this.
		verticalDistanceThreshold: window.devicePixelRatio >= 2 ? 15 : 30,

		getLocation: function ( event ) {
			var winPageX = window.pageXOffset,
				winPageY = window.pageYOffset,
				x = event.clientX,
				y = event.clientY;

			if ( event.pageY === 0 && Math.floor( y ) > Math.floor( event.pageY ) ||
				event.pageX === 0 && Math.floor( x ) > Math.floor( event.pageX ) ) {

				// iOS4 clientX/clientY have the value that should have been
				// in pageX/pageY. While pageX/page/ have the value 0
				x = x - winPageX;
				y = y - winPageY;
			} else if ( y < ( event.pageY - winPageY) || x < ( event.pageX - winPageX ) ) {

				// Some Android browsers have totally bogus values for clientX/Y
				// when scrolling/zooming a page. Detectable since clientX/clientY
				// should never be smaller than pageX/pageY minus page scroll
				x = event.pageX - winPageX;
				y = event.pageY - winPageY;
			}

			return {
				x: x,
				y: y
			};
		},

		start: function( event ) {
			var data = event.originalEvent.touches ?
					event.originalEvent.touches[ 0 ] : event,
				location = $.event.special.swipe.getLocation( data );
			return {
						time: ( new Date() ).getTime(),
						coords: [ location.x, location.y ],
						origin: $( event.target )
					};
		},

		stop: function( event ) {
			var data = event.originalEvent.touches ?
					event.originalEvent.touches[ 0 ] : event,
				location = $.event.special.swipe.getLocation( data );
			return {
						time: ( new Date() ).getTime(),
						coords: [ location.x, location.y ]
					};
		},

		handleSwipe: function( start, stop, thisObject, origTarget ) {
			if ( stop.time - start.time < $.event.special.swipe.durationThreshold &&
				Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold &&
				Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) {
				var direction = start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight";

				triggerCustomEvent( thisObject, "swipe", $.Event( "swipe", { target: origTarget, swipestart: start, swipestop: stop }), true );
				triggerCustomEvent( thisObject, direction,$.Event( direction, { target: origTarget, swipestart: start, swipestop: stop } ), true );
				return true;
			}
			return false;

		},

		// This serves as a flag to ensure that at most one swipe event event is
		// in work at any given time
		eventInProgress: false,

		setup: function() {
			var events,
				thisObject = this,
				$this = $( thisObject ),
				context = {};

			// Retrieve the events data for this element and add the swipe context
			events = $.data( this, "mobile-events" );
			if ( !events ) {
				events = { length: 0 };
				$.data( this, "mobile-events", events );
			}
			events.length++;
			events.swipe = context;

			context.start = function( event ) {

				// Bail if we're already working on a swipe event
				if ( $.event.special.swipe.eventInProgress ) {
					return;
				}
				$.event.special.swipe.eventInProgress = true;

				var stop,
					start = $.event.special.swipe.start( event ),
					origTarget = event.target,
					emitted = false;

				context.move = function( event ) {
					if ( !start || event.isDefaultPrevented() ) {
						return;
					}

					stop = $.event.special.swipe.stop( event );
					if ( !emitted ) {
						emitted = $.event.special.swipe.handleSwipe( start, stop, thisObject, origTarget );
						if ( emitted ) {

							// Reset the context to make way for the next swipe event
							$.event.special.swipe.eventInProgress = false;
						}
					}
					// prevent scrolling
					if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) {
						event.preventDefault();
					}
				};

				context.stop = function() {
						emitted = true;

						// Reset the context to make way for the next swipe event
						$.event.special.swipe.eventInProgress = false;
						$document.off( touchMoveEvent, context.move );
						context.move = null;
				};

				$document.on( touchMoveEvent, context.move )
					.one( touchStopEvent, context.stop );
			};
			$this.on( touchStartEvent, context.start );
		},

		teardown: function() {
			var events, context;

			events = $.data( this, "mobile-events" );
			if ( events ) {
				context = events.swipe;
				delete events.swipe;
				events.length--;
				if ( events.length === 0 ) {
					$.removeData( this, "mobile-events" );
				}
			}

			if ( context ) {
				if ( context.start ) {
					$( this ).off( touchStartEvent, context.start );
				}
				if ( context.move ) {
					$document.off( touchMoveEvent, context.move );
				}
				if ( context.stop ) {
					$document.off( touchStopEvent, context.stop );
				}
			}
		}
	};
	$.each({
		swipeleft: "swipe.left",
		swiperight: "swipe.right"
	}, function( event, sourceEvent ) {

		$.event.special[ event ] = {
			setup: function() {
				$( this ).bind( sourceEvent, $.noop );
			},
			teardown: function() {
				$( this ).unbind( sourceEvent );
			}
		};
	});
})( jQuery, this );
*/
<|endoftext|>


<commit_before>'use strict';
var _ = require('lodash');
var tap = require('tap');

var checkResources = require('../lib/check/resources.js');

tap.test('checkTypes with valid template', function (t) {
  t.plan(1);
  var template = _.cloneDeep(require('./template.json'));
  return checkResources.checkTypes(template).then(function (errors) {
    t.equal(errors.length, 0, 'has no errors');
  });
});

tap.test('checkTypes with invalid resource type', function (t) {
  t.plan(3);
  var template = _.cloneDeep(require('./template.json'));
  var invalidType = template.Resources.ElasticLoadBalancer.Type = 'AWS::Not::A::Resource';
  return checkResources.checkTypes(template).then(function (errors) {
    var error = errors[0];
    t.equal(errors.length, 1, 'has one error');
    t.match(error, /ElasticLoadBalancer/, 'has the invalid Resource\'s name');
    t.match(error, new RegExp(invalidType), 'has the invalid type\'s name');
  });
});

tap.test('checkTypes with custom resource', function (t) {
  t.plan(1);
  var template = _.cloneDeep(require('./template.json'));
  // Example taken from CustomResource Type Reference
  template.Resources.MyFrontEndTest = {
    'Type': 'Custom::Thing',
    'Version': '1.0',
    'Properties': {
      'ServiceToken': 'arn:aws:sns:us-east-1:84969EXAMPLE:CRTest',
      'key1': 'string',
      'key2': [
        'list'
      ],
      'key3': {
        'key4': 'map'
      }
    }
  }
  return checkResources.checkTypes(template).then(function (errors) {
    t.equal(errors.length, 0, 'has no errors');
  });
});

tap.test('checkValidProperties with invalid resource property', function (t) {
  t.plan(3);
  var template = _.cloneDeep(require('./template.json'));
  var invalidProperty = 'NotAProperty';
  template.Resources.ElasticLoadBalancer.Properties[invalidProperty] = 'AValue';
  return checkResources.checkValidProperties(template).then(function (errors) {
    var error = errors[0];
    t.equal(errors.length, 1, 'has one error');
    t.match(error, /ElasticLoadBalancer/, 'has the invalid Resource\'s name');
    t.match(error, new RegExp(invalidProperty), 'has the invalid property\'s name');
  });
});

tap.test('getRequiredProperties generates data', function (t) {
  t.plan(1);
  var resources = require('../data/resources.json');
  checkResources.getRequiredProperties(resources).then(function (requiredProperties) {
    t.same(requiredProperties['AWS::AutoScaling::LaunchConfiguration'],
           ['ImageId', 'InstanceType'],
           'LaunchConfiguration has required properties ImageId and InstanceType');
  });
})

tap.test('checkValidProperties with missing required property');
tap.test('checkValidProperties with valid DependsOn reference');
tap.test('checkValidProperties with invalid DependsOn reference');
tap.test('checkValidProperties with valid DependsOn reference (multiple)');
tap.test('checkValidProperties with invalid DependsOn reference (multiple)');
tap.test('checkValidProperties with no conditional properties');
tap.test('checkValidProperties with multiple conditional properties');
tap.test('checkValidProperties with invalid property data type'); // e.g. Number vs String
// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html
tap.test('checkValidProperties with CustomResource'); // Only ServiceToken is required

tap.test('areValid with valid template', function (t) {
  t.plan(1);
  var template = require('./template.json');
  return checkResources.areValid(template).then(function (errors) {
    t.equal(errors.length, 0, 'has no errors');
  });
});

tap.test('areValid with invalid resource type', function (t) {
  t.plan(3);
  var template = _.cloneDeep(require('./template.json'));
  var invalidType = template.Resources.ElasticLoadBalancer.Type = 'AWS::Not::A::Resource';
  return checkResources.areValid(template).then(function (errors) {
    var error = errors[0];
    t.equal(errors.length, 1, 'has one error');
    t.match(error, /ElasticLoadBalancer/, 'has the invalid Resource\'s name');
    t.match(error, new RegExp(invalidType), 'has the invalid type\'s name');
  });
});

tap.test('areValid with invalid resource property', function (t) {
  t.plan(3);
  var template = _.cloneDeep(require('./template.json'));
  var invalidProperty = 'NotAProperty';
  template.Resources.LaunchConfig.Properties[invalidProperty] = 'AValue';
  return checkResources.areValid(template).then(function (errors) {
    var error = errors[0];
    t.equal(errors.length, 1, 'has one error');
    t.match(error, /LaunchConfig/, 'has the invalid Resource\'s name');
    t.match(error, new RegExp(invalidProperty), 'has the invalid property\'s name');
  });
});

tap.test('areValid with invalid type and properties', function (t) {
  t.plan(5);
  var template = _.cloneDeep(require('./template.json'));
  var invalidType = template.Resources.ElasticLoadBalancer.Type = 'AWS::Not::A::Resource';
  var invalidProperty = 'NotAProperty';
  template.Resources.LaunchConfig.Properties[invalidProperty] = 'AValue';
  return checkResources.areValid(template).then(function (errors) {
    t.equal(errors.length, 2, 'has one error');
    // Type error
    t.match(errors[0], /ElasticLoadBalancer/, 'has the invalid Resource\'s name');
    t.match(errors[0], new RegExp(invalidType), 'has the invalid type\'s name');
    // Properties error
    t.match(errors[1], /LaunchConfig/, 'has the invalid Resource\'s name');
    t.match(errors[1], new RegExp(invalidProperty), 'has the invalid property\'s name');
  });
});

tap.test('areValid with an excpetion');
<commit_msg>Include additional resource tests for getRequiredProperties.<commit_after>'use strict';
var _ = require('lodash');
var tap = require('tap');

var checkResources = require('../lib/check/resources.js');

tap.test('checkTypes with valid template', function (t) {
  t.plan(1);
  var template = _.cloneDeep(require('./template.json'));
  return checkResources.checkTypes(template).then(function (errors) {
    t.equal(errors.length, 0, 'has no errors');
  });
});

tap.test('checkTypes with invalid resource type', function (t) {
  t.plan(3);
  var template = _.cloneDeep(require('./template.json'));
  var invalidType = template.Resources.ElasticLoadBalancer.Type = 'AWS::Not::A::Resource';
  return checkResources.checkTypes(template).then(function (errors) {
    var error = errors[0];
    t.equal(errors.length, 1, 'has one error');
    t.match(error, /ElasticLoadBalancer/, 'has the invalid Resource\'s name');
    t.match(error, new RegExp(invalidType), 'has the invalid type\'s name');
  });
});

tap.test('checkTypes with custom resource', function (t) {
  t.plan(1);
  var template = _.cloneDeep(require('./template.json'));
  // Example taken from CustomResource Type Reference
  template.Resources.MyFrontEndTest = {
    'Type': 'Custom::Thing',
    'Version': '1.0',
    'Properties': {
      'ServiceToken': 'arn:aws:sns:us-east-1:84969EXAMPLE:CRTest',
      'key1': 'string',
      'key2': [
        'list'
      ],
      'key3': {
        'key4': 'map'
      }
    }
  }
  return checkResources.checkTypes(template).then(function (errors) {
    t.equal(errors.length, 0, 'has no errors');
  });
});

tap.test('checkValidProperties with invalid resource property', function (t) {
  t.plan(3);
  var template = _.cloneDeep(require('./template.json'));
  var invalidProperty = 'NotAProperty';
  template.Resources.ElasticLoadBalancer.Properties[invalidProperty] = 'AValue';
  return checkResources.checkValidProperties(template).then(function (errors) {
    var error = errors[0];
    t.equal(errors.length, 1, 'has one error');
    t.match(error, /ElasticLoadBalancer/, 'has the invalid Resource\'s name');
    t.match(error, new RegExp(invalidProperty), 'has the invalid property\'s name');
  });
});

tap.test('getRequiredProperties generates required properties', function (t) {
  t.plan(2);
  var resources = require('../data/resources.json');
  checkResources.getRequiredProperties(resources).then(function (requiredProperties) {
    t.same(requiredProperties['AWS::AutoScaling::LaunchConfiguration'],
           ['ImageId', 'InstanceType'],
           'LaunchConfiguration has required properties ImageId and InstanceType');
    t.same(requiredProperties['AWS::WAF::Rule'],
           ['MetricName', 'Name'],
           'WAF::Rule has required properties MetricName and Name');
  });
})

tap.test('checkValidProperties with missing required property');
tap.test('checkValidProperties with valid DependsOn reference');
tap.test('checkValidProperties with invalid DependsOn reference');
tap.test('checkValidProperties with valid DependsOn reference (multiple)');
tap.test('checkValidProperties with invalid DependsOn reference (multiple)');
tap.test('checkValidProperties with no conditional properties');
tap.test('checkValidProperties with multiple conditional properties');
tap.test('checkValidProperties with invalid property data type'); // e.g. Number vs String
// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html
tap.test('checkValidProperties with CustomResource'); // Only ServiceToken is required

tap.test('areValid with valid template', function (t) {
  t.plan(1);
  var template = require('./template.json');
  return checkResources.areValid(template).then(function (errors) {
    t.equal(errors.length, 0, 'has no errors');
  });
});

tap.test('areValid with invalid resource type', function (t) {
  t.plan(3);
  var template = _.cloneDeep(require('./template.json'));
  var invalidType = template.Resources.ElasticLoadBalancer.Type = 'AWS::Not::A::Resource';
  return checkResources.areValid(template).then(function (errors) {
    var error = errors[0];
    t.equal(errors.length, 1, 'has one error');
    t.match(error, /ElasticLoadBalancer/, 'has the invalid Resource\'s name');
    t.match(error, new RegExp(invalidType), 'has the invalid type\'s name');
  });
});

tap.test('areValid with invalid resource property', function (t) {
  t.plan(3);
  var template = _.cloneDeep(require('./template.json'));
  var invalidProperty = 'NotAProperty';
  template.Resources.LaunchConfig.Properties[invalidProperty] = 'AValue';
  return checkResources.areValid(template).then(function (errors) {
    var error = errors[0];
    t.equal(errors.length, 1, 'has one error');
    t.match(error, /LaunchConfig/, 'has the invalid Resource\'s name');
    t.match(error, new RegExp(invalidProperty), 'has the invalid property\'s name');
  });
});

tap.test('areValid with invalid type and properties', function (t) {
  t.plan(5);
  var template = _.cloneDeep(require('./template.json'));
  var invalidType = template.Resources.ElasticLoadBalancer.Type = 'AWS::Not::A::Resource';
  var invalidProperty = 'NotAProperty';
  template.Resources.LaunchConfig.Properties[invalidProperty] = 'AValue';
  return checkResources.areValid(template).then(function (errors) {
    t.equal(errors.length, 2, 'has one error');
    // Type error
    t.match(errors[0], /ElasticLoadBalancer/, 'has the invalid Resource\'s name');
    t.match(errors[0], new RegExp(invalidType), 'has the invalid type\'s name');
    // Properties error
    t.match(errors[1], /LaunchConfig/, 'has the invalid Resource\'s name');
    t.match(errors[1], new RegExp(invalidProperty), 'has the invalid property\'s name');
  });
});

tap.test('areValid with an excpetion');
<|endoftext|>