<commit_before>/**
 * boxselectiontool.js
 *
 * requirements:
 *   tools.js
 *   slider.js
 *   stack.js
 */

/**
 * Box selection tool. Allows drawing of a box on the view.
 */
function BoxSelectionTool()
{
    this.stack = null;
    this.cropBox = false;
    this.cropBoxCache = {};
    this.zoomlevel = null;

    // Output unit and factor wrt. nm
    this.output_unit = unescape( "nm" );
    this.output_unit_factor = 1.0;

    this.getCropBox = function()
    {
        return this.cropBox;
    };
};

BoxSelectionTool.prototype.toPx = function( world_coord, resolution )
{
    return world_coord / resolution * this.stack.scale;
};

BoxSelectionTool.prototype.toWorld = function( px_coord, resolution )
{
    return px_coord / this.stack.scale * resolution;
};

/**
 * A method that expects a value in nano meters to convert
 * it depending on the tool settings.
 */
BoxSelectionTool.prototype.convertWorld = function( val )
{
    return val * this.output_unit_factor;
};

BoxSelectionTool.prototype.getScreenLeft = function(stack)
{
    return ( ( stack.x - stack.viewWidth / stack.scale / 2 ) + stack.translation.x ) * stack.resolution.x;
};

BoxSelectionTool.prototype.getScreenTop = function(stack)
{
    return ( ( stack.y - stack.viewHeight / stack.scale / 2 ) + stack.translation.y ) * stack.resolution.y;
};

/**
 * Gets the bounding box of the current crop box in world
 * and pixel coordinates.
 */
BoxSelectionTool.prototype.getCropBoxBoundingBox = function(stack)
{
    var t = Math.min( this.cropBox.top, this.cropBox.bottom );
    var b = Math.max( this.cropBox.top, this.cropBox.bottom );
    var l = Math.min( this.cropBox.left, this.cropBox.right );
    var r = Math.max( this.cropBox.left, this.cropBox.right );
    var width = r - l;
    var height = b - t;
    //! left-most border of the view in physical project coordinates
    var screen_left = this.getScreenLeft(stack);
    var screen_top = this.getScreenTop(stack);

    var rx = stack.resolution.x / stack.scale;
    var ry = stack.resolution.y / stack.scale;

    var left_px = Math.floor( ( l - screen_left ) / rx );
    var top_px = Math.floor( ( t - screen_top ) / ry );
    var width_px = Math.floor( ( r - l ) / rx );
    var height_px = Math.floor( ( b - t ) / ry );
    var right_px = left_px + width_px;
    var bottom_px = top_px + height_px;

    return { left_world : l, top_world : t, right_world : r, bottom_world : b, width_world : width, height_world : height,
             left_px : left_px, top_px : top_px, right_px : right_px, bottom_px : bottom_px, width_px : width_px, height_px : height_px }
};

/**
 * Updates the visual representation of the current crop box.
 */
BoxSelectionTool.prototype.updateCropBox = function()
{
    // update all cached cropping boxes
    for ( var s in this.cropBoxCache )
    {
        var cb = this.cropBoxCache[ s ];
        var cropBoxBB = this.getCropBoxBoundingBox(cb.stack);

        cb.view.style.visibility = "visible";
        cb.view.style.left = cropBoxBB.left_px + "px";
        cb.view.style.top = cropBoxBB.top_px + "px";
        cb.view.style.width = cropBoxBB.width_px  + "px";
        cb.view.style.height = cropBoxBB.height_px  + "px";

        var world_unit = this.output_unit;
        var current_scale = this.stack.scale;
        var output_scale = 1 / Math.pow( 2, this.zoomlevel );
        var output_width_px = ( cropBoxBB.width_px / current_scale) * output_scale;
        var output_height_px = ( cropBoxBB.height_px / current_scale) * output_scale;
        var output_width_world = this.convertWorld( cropBoxBB.width_world );
        var output_height_world = this.convertWorld( cropBoxBB.height_world );

        cb.textWorld.replaceChild( document.createTextNode( output_width_world.toFixed( 3 ) + " x " + output_height_world.toFixed( 3 ) + " " + world_unit ), cb.textWorld.firstChild );
        cb.textScreen.replaceChild( document.createTextNode( output_width_px.toFixed( 0 ) + " x " + output_height_px.toFixed( 0 ) + " px" ), cb.textScreen.firstChild );
    }

    statusBar.replaceLast( this.convertWorld( cropBoxBB.left_world).toFixed( 3 ) + ", " + this.convertWorld( cropBoxBB.top_world ).toFixed( 3 ) +
        " -> " + this.convertWorld( cropBoxBB.right_world ).toFixed( 3 ) + "," + this.convertWorld( cropBoxBB.bottom_world ).toFixed( 3 ) );

    return;
};

/**
 * Redraws the content.
 */
BoxSelectionTool.prototype.redraw = function()
{
    // update crop box if available
    if ( this.cropBox )
        this.updateCropBox();
};

/**
 * Creates a new cropping box and attaches it to the stack.
 */
BoxSelectionTool.prototype.initCropBox = function( stack )
{
    var view = stack.getView();
    var cb = {};
    cb.view = document.createElement( "div" );
    cb.view.className = "cropBox";
    cb.view.style.visibility = "hidden";
    cb.textWorld = document.createElement( "p" );
    cb.textWorld.className = "world";
    cb.textWorld.appendChild( document.createTextNode( "0 x 0" ) );
    cb.textScreen = document.createElement( "p" );
    cb.textScreen.className = "screen";
    cb.textScreen.appendChild( document.createTextNode( "0 x 0" ) );
    cb.view.appendChild( cb.textWorld );
    cb.view.appendChild( cb.textScreen );
    view.appendChild( cb.view );
    cb.stack = stack;

    return cb;
};

/**
 * Creates a new crop box and attaches it to the view. Its position and extent
 * are expected to be in screen coordinates. Any existing crop box gets removed
 * first.
 */
BoxSelectionTool.prototype.createCropBox = function( screenX, screenY, screenWidth, screenHeight )
{
    if(typeof(screenWidth)==='undefined') screenWidth = 0;
    if(typeof(screenHeight)==='undefined') screenHeight = 0;
    var s = this.stack;
    var worldX = (s.x + ( screenX  - s.viewWidth / 2 ) / s.scale ) * s.resolution.x;
    var worldY = (s.y + ( screenY - s.viewHeight / 2 ) / s.scale ) * s.resolution.y;
    var worldWidth = this.toWorld( screenWidth, s.resolution.x );
    var worldHeight = this.toWorld( screenHeight, s.resolution.y );

    this.createCropBoxByWorld(worldX, worldY, worldWidth, worldHeight);
};

/**
 * Creates a new crop box and attaches it to the view. Its position and extent
 * are expected to be in world coordinates. Any existing crop box gets removed
 * first.
 */
BoxSelectionTool.prototype.createCropBoxByWorld = function( worldX, worldY, worldWidth, worldHeight )
{
    var view = this.stack.getView();
    if ( this.cropBox && this.cropBox.view.parentNode == view )
    {
        view.removeChild( this.cropBox.view );
        delete this.cropBox;
        this.cropBox = false;
    }
    this.cropBox = this.initCropBox( this.stack );
    this.cropBox.left = worldX + this.stack.translation.x;
    this.cropBox.top = worldY + this.stack.translation.y;
    this.cropBox.right = this.cropBox.left + worldWidth;
    this.cropBox.bottom = this.cropBox.top + worldHeight;
    this.cropBox.xdist = 0;
    this.cropBox.ydist = 0;
    this.cropBox.xorigin = this.cropBox.left;
    this.cropBox.yorigin = this.cropBox.top;

    // update the cache
    this.cropBoxCache[ this.stack.getId() ] = this.cropBox;

    // update other (passive) crop boxes
    this.updateCropBox();
};

/**
 * unregister all project related GUI control connections and event
 * handlers, toggle off tool activity signals (like buttons)
 */
BoxSelectionTool.prototype.destroy = function()
{
    // clear cache
    for ( var s in this.cropBoxCache )
    {
        var cb = this.cropBoxCache[ s ];
        cb.stack.getView().removeChild( cb.view );
        delete this.cropBoxCache[ s ];
    }
    this.cropBoxCache = {};
    this.cropBox = false;

    this.stack = null;

    return;
};

/**
* install this tool in a stack.
* register all GUI control elements and event handlers
*/
BoxSelectionTool.prototype.register = function( parentStack )
{
    // make sure the tool knows all (and only) open projecs
    var project = parentStack.getProject();
    var stacks = projects_available[ project.id ];
    for (var s in stacks)
    {
        var id = stacks[ s ].id
        var opened_stack = project.getStack( id );
        if ( id in this.cropBoxCache )
        {
            // remove the entry if the project isn't opened
            if ( !opened_stack )
                delete this.cropBoxCache[ id ];
        }
        else
        {
            // make sure it has got a cropping box container in the cache
            if ( opened_stack )
                this.cropBoxCache[ id ] = this.initCropBox( opened_stack );
        }
    }

    // bring a cached version back to life and
    // deactivate other available cropping boxes
    for ( var s in this.cropBoxCache )
    {
        var cb = this.cropBoxCache[ s ];
        if (cb.stack == parentStack)
        {
            this.cropBox = cb;
            this.cropBox.view.className = "cropBox";
        }
        else
        {
            cb.view.className = "cropBoxNonActive";
        }
    }

    this.stack = parentStack;
    this.zoomlevel = this.stack.s;

    return;
};

<commit_msg>Box selection tool: draw box in separate layer<commit_after>/**
 * boxselectiontool.js
 *
 * requirements:
 *   tools.js
 *   slider.js
 *   stack.js
 */

/**
 * Box selection tool. Allows drawing of a box on the view.
 */
function BoxSelectionTool()
{
    this.stack = null;
    this.cropBox = false;
    this.cropBoxCache = {};
    this.zoomlevel = null;

    // Output unit and factor wrt. nm
    this.output_unit = unescape( "nm" );
    this.output_unit_factor = 1.0;

    this.getCropBox = function()
    {
        return this.cropBox;
    };
};

BoxSelectionTool.prototype.toPx = function( world_coord, resolution )
{
    return world_coord / resolution * this.stack.scale;
};

BoxSelectionTool.prototype.toWorld = function( px_coord, resolution )
{
    return px_coord / this.stack.scale * resolution;
};

/**
 * A method that expects a value in nano meters to convert
 * it depending on the tool settings.
 */
BoxSelectionTool.prototype.convertWorld = function( val )
{
    return val * this.output_unit_factor;
};

BoxSelectionTool.prototype.getScreenLeft = function(stack)
{
    return ( ( stack.x - stack.viewWidth / stack.scale / 2 ) + stack.translation.x ) * stack.resolution.x;
};

BoxSelectionTool.prototype.getScreenTop = function(stack)
{
    return ( ( stack.y - stack.viewHeight / stack.scale / 2 ) + stack.translation.y ) * stack.resolution.y;
};

/**
 * Gets the bounding box of the current crop box in world
 * and pixel coordinates.
 */
BoxSelectionTool.prototype.getCropBoxBoundingBox = function(stack)
{
    var t = Math.min( this.cropBox.top, this.cropBox.bottom );
    var b = Math.max( this.cropBox.top, this.cropBox.bottom );
    var l = Math.min( this.cropBox.left, this.cropBox.right );
    var r = Math.max( this.cropBox.left, this.cropBox.right );
    var width = r - l;
    var height = b - t;
    //! left-most border of the view in physical project coordinates
    var screen_left = this.getScreenLeft(stack);
    var screen_top = this.getScreenTop(stack);

    var rx = stack.resolution.x / stack.scale;
    var ry = stack.resolution.y / stack.scale;

    var left_px = Math.floor( ( l - screen_left ) / rx );
    var top_px = Math.floor( ( t - screen_top ) / ry );
    var width_px = Math.floor( ( r - l ) / rx );
    var height_px = Math.floor( ( b - t ) / ry );
    var right_px = left_px + width_px;
    var bottom_px = top_px + height_px;

    return { left_world : l, top_world : t, right_world : r, bottom_world : b, width_world : width, height_world : height,
             left_px : left_px, top_px : top_px, right_px : right_px, bottom_px : bottom_px, width_px : width_px, height_px : height_px }
};

/**
 * Updates the visual representation of the current crop box.
 */
BoxSelectionTool.prototype.updateCropBox = function()
{
    // update all cached cropping boxes
    for ( var s in this.cropBoxCache )
    {
        var cb = this.cropBoxCache[ s ];
        cb.layer.redraw()
    }

    return;
};

/**
 * Redraws the content.
 */
BoxSelectionTool.prototype.redraw = function()
{
    // nothing to do here
};

/**
 * Creates a new cropping box and attaches it to the stack.
 */
BoxSelectionTool.prototype.initCropBox = function( stack )
{
    var cb = {};
    cb.stack = stack;

    // Add new layer (it removes existing ones by itself)
    cb.layer = new BoxSelectionLayer(stack, this, cb);
    stack.addLayer("BoxSelectionLayer", cb.layer);

    return cb;
};

/**
 * Creates a new crop box and attaches it to the view. Its position and extent
 * are expected to be in screen coordinates. Any existing crop box gets removed
 * first.
 */
BoxSelectionTool.prototype.createCropBox = function( screenX, screenY, screenWidth, screenHeight )
{
    if(typeof(screenWidth)==='undefined') screenWidth = 0;
    if(typeof(screenHeight)==='undefined') screenHeight = 0;
    var s = this.stack;
    var worldX = (s.x + ( screenX  - s.viewWidth / 2 ) / s.scale ) * s.resolution.x;
    var worldY = (s.y + ( screenY - s.viewHeight / 2 ) / s.scale ) * s.resolution.y;
    var worldWidth = this.toWorld( screenWidth, s.resolution.x );
    var worldHeight = this.toWorld( screenHeight, s.resolution.y );

    this.createCropBoxByWorld(worldX, worldY, worldWidth, worldHeight);
};

/**
 * Creates a new crop box and attaches it to the view. Its position and extent
 * are expected to be in world coordinates. Any existing crop box gets removed
 * first.
 */
BoxSelectionTool.prototype.createCropBoxByWorld = function( worldX, worldY, worldWidth, worldHeight )
{
    var view = this.stack.getView();
    if ( this.cropBox )
    {
        delete this.cropBox;
        this.cropBox = false;
    }
    this.cropBox = this.initCropBox( this.stack );
    this.cropBox.left = worldX + this.stack.translation.x;
    this.cropBox.top = worldY + this.stack.translation.y;
    this.cropBox.right = this.cropBox.left + worldWidth;
    this.cropBox.bottom = this.cropBox.top + worldHeight;
    this.cropBox.xdist = 0;
    this.cropBox.ydist = 0;
    this.cropBox.xorigin = this.cropBox.left;
    this.cropBox.yorigin = this.cropBox.top;

    // update the cache
    this.cropBoxCache[ this.stack.getId() ] = this.cropBox;

    // update other (passive) crop boxes
    this.updateCropBox();
};

/**
 * unregister all project related GUI control connections and event
 * handlers, toggle off tool activity signals (like buttons)
 */
BoxSelectionTool.prototype.destroy = function()
{
    // clear cache
    for ( var s in this.cropBoxCache )
    {
        var cb = this.cropBoxCache[ s ];
        cb.stack.removeLayer( "BoxSelectionLayer" );
        delete this.cropBoxCache[ s ];
    }
    this.cropBoxCache = {};
    this.cropBox = false;

    this.stack = null;

    return;
};

/**
* install this tool in a stack.
* register all GUI control elements and event handlers
*/
BoxSelectionTool.prototype.register = function( parentStack )
{
    // make sure the tool knows all (and only) open projecs
    var project = parentStack.getProject();
    var stacks = projects_available[ project.id ];
    for (var s in stacks)
    {
        var id = stacks[ s ].id
        var opened_stack = project.getStack( id );
        if ( id in this.cropBoxCache )
        {
            // remove the entry if the project isn't opened
            if ( !opened_stack )
                delete this.cropBoxCache[ id ];
        }
        else
        {
            // make sure it has got a cropping box container in the cache
            if ( opened_stack )
                this.cropBoxCache[ id ] = this.initCropBox( opened_stack );
        }
    }

    // bring a cached version back to life and
    // deactivate other available cropping boxes
    for ( var s in this.cropBoxCache )
    {
        var cb = this.cropBoxCache[ s ];
        var is_active = (cb.stack == parentStack);
        cb.layer.setActive( is_active );
        if (is_active)
            this.cropBox = cb;
    }

    this.stack = parentStack;
    this.zoomlevel = this.stack.s;

    return;
};

/**
 * The box selection layer that hosts the a box selection/region of
 * interest.
 */
function BoxSelectionLayer( stack, tool, crop_box)
{
    this.setOpacity = function( val )
    {
        view.style.opacity = val;
        opacity = val;
    }

    this.getOpacity = function()
    {
        return opacity;
    }

    this.redraw = function()
    {
        // hack to make the tool redraw the canvas
        //tool.redraw();
        console.log("redraw layer");

        var cropBoxBB = tool.getCropBoxBoundingBox(stack);

        view.style.visibility = "visible";
        view.style.left = cropBoxBB.left_px + "px";
        view.style.top = cropBoxBB.top_px + "px";
        view.style.width = cropBoxBB.width_px  + "px";
        view.style.height = cropBoxBB.height_px  + "px";

        var current_scale = stack.scale;
        var output_scale = 1 / Math.pow( 2, tool.zoomlevel );
        var output_width_px = ( cropBoxBB.width_px / current_scale) * output_scale;
        var output_height_px = ( cropBoxBB.height_px / current_scale) * output_scale;
        var output_width_world = tool.convertWorld( cropBoxBB.width_world );
        var output_height_world = tool.convertWorld( cropBoxBB.height_world );

        // Update text nodes
        textWorld.replaceChild( document.createTextNode(
            output_width_world.toFixed( 3 ) + " x " +
            output_height_world.toFixed( 3 ) + " " + tool.output_unit ),
            textWorld.firstChild );
        textScreen.replaceChild( document.createTextNode(
            output_width_px.toFixed( 0 ) + " x " +
            output_height_px.toFixed( 0 ) + " px" ),
            textScreen.firstChild );

        // let active crop box show status info
        if (is_active) {
            statusBar.replaceLast(
                tool.convertWorld(cropBoxBB.left_world).toFixed( 3 ) + ", " +
                tool.convertWorld( cropBoxBB.top_world ).toFixed( 3 ) + " -> " +
                tool.convertWorld( cropBoxBB.right_world ).toFixed( 3 ) + "," +
                tool.convertWorld( cropBoxBB.bottom_world ).toFixed( 3 ) );
        }

        return;
    }

    this.resize = function( width, height )
    {
        return;
    }

    this.show = function ()
    {
        view.style.display = "block";
    };

    this.hide = function ()
    {
        view.style.display = "none";
    };

    this.getView = function()
    {
        return view;
    }

    this.unregister = function()
    {
        if ( stack && view.parentNode == stack.getView() )
            stack.getView().removeChild( view );
    };

    this.setActive = function( active )
    {
        is_active = active;

        if (active)
            view.className = "cropBox";
        else
            view.className = "cropBoxNonActive";
    };

    var self = this;

    // indicates if this the currently active crop box
    var is_active = true;

    var stack = stack;
    var crop_box = crop_box;

    var view = document.createElement( "div" );
    view.className = "cropBox";
    view.style.visibility = "hidden";
    var textWorld = document.createElement( "p" );
    textWorld.className = "world";
    textWorld.appendChild( document.createTextNode( "0 x 0" ) );
    view.appendChild( textWorld );
    var textScreen = document.createElement( "p" );
    textScreen.className = "screen";
    textScreen.appendChild( document.createTextNode( "0 x 0" ) );
    view.appendChild( textScreen );

    // internal opacity variable
    var opacity = 100;

    // add view to DOM
    stack.getView().appendChild( view );
};

<|endoftext|>


<commit_before>
/* =========================================================================
 * Svelto - Tasks - Config - Defaults (Plugins)
 * =========================================================================
 * Copyright (c) 2015-2017 Fabio Spampinato
 * Licensed under MIT (https://github.com/svelto/svelto/blob/master/LICENSE)
 * ========================================================================= */

/* REQUIRE */

const _       = require ( 'lodash' ),
     path     = require ( 'path' ),
     cssnano  = require ( 'cssnano' ),
     imagemin = require ( 'gulp-imagemin' );

/* BABEL PRESET */

// We are using relative paths because if we add an external path (ie. `../ext`) to `config.paths.input.roots` it won't find the presets

const levels = [0, -2], // [0] Inside Svelto [-2] Svelto is inside a `node_modules`
      cwd = process.cwd ();

let preset;

for ( let i = 0, l = levels.length; i < l; i++ ) {

  const level = levels[i],
        attempt = path.join ( cwd, _.repeat ( '../', - level ), './node_modules/babel-preset-es2015' ),
        required = _.attempt ( require, attempt );

  if ( _.isError ( required ) ) continue;

  preset = attempt;

  break;

}

/* PLUGINS */

const plugins = {
  autoprefixer: {
    enabled: true,
    options: {
      browsers: ['ie >= 10', 'ie_mob >= 10', 'edge >= 13', 'ff >= 30', 'chrome >= 34', 'safari >= 7', 'opera >= 23', 'ios >= 7', 'android >= 4.4', 'bb >= 10'],
      cascade: true,
    }
  },
  babel: {
    enabled: true,
    options: {
      presets: [preset],
      babelrc: false,
      compact: false
    }
  },
  closure: {
    enabled: false,
    options: {
      assumeFunctionWrapper: true,
      compilationLevel: 'SIMPLE',
      languageIn: 'ECMASCRIPT5_STRICT',
      languageOut: 'ECMASCRIPT5_STRICT',
      outputWrapper: '(function(){\n%output%\n}).call(this)',
      warningLevel: 'QUIET'
    }
  },
  del: {
    options: {
      force: false
    }
  },
  dependencies: {
    enabled: true,
    options: {
      before: /@before[\s]+([\S]+\.[\S]+)[\s]*/g,
      require: /@require[\s]+([\S]+\.[\S]+)[\s]*/g,
      log: false
    }
  },
  extend: {
    enabled: true,
    options: {
      log: false
    }
  },
  filter: {
    enabled: true,
    options: {
      log: false
    }
  },
  github: {
    enabled: false,
    auth: {
      type: 'oauth',
      token: false
    }
  },
  imagemin: {
    enabled: true,
    plugins: [
      imagemin.gifsicle ({
        interlaced: true,
        optimizationLevel: 3
      }),
      imagemin.jpegtran ({
        progressive: true
      }),
      imagemin.optipng ({
        optimizationLevel: 7
      }),
      imagemin.svgo ({
        multipass: true,
        plugins: [{
          cleanupIDs: false,
        }, {
          removeViewBox: false
        }]
      })
    ],
    options: {}
  },
  jsonminify: {
    enabled: true,
    options: {}
  },
  override: {
    enabled: true,
    options: {
      log: false
    }
  },
  postcss: {
    enabled: true,
    plugins: [
      cssnano ({
        autoprefixer: false,
        normalizeUrl: false,
        svgo: false,
        zindex: false
      })
    ],
    options: {}
  },
  sass: {
    enabled: true,
    options: {
      outputStyle: 'expanded',
      precision: 10
    }
  },
  uglify: {
    enabled: true,
    options: {}
  }
};

/* EXPORT */

module.exports = plugins;
<commit_msg>Babel: greatly improved preset resolution logic<commit_after>
/* =========================================================================
 * Svelto - Tasks - Config - Defaults (Plugins)
 * =========================================================================
 * Copyright (c) 2015-2017 Fabio Spampinato
 * Licensed under MIT (https://github.com/svelto/svelto/blob/master/LICENSE)
 * ========================================================================= */

/* REQUIRE */

const _       = require ( 'lodash' ),
     path     = require ( 'path' ),
     cssnano  = require ( 'cssnano' ),
     imagemin = require ( 'gulp-imagemin' );

/* PLUGINS */

const plugins = {
  autoprefixer: {
    enabled: true,
    options: {
      browsers: ['ie >= 10', 'ie_mob >= 10', 'edge >= 13', 'ff >= 30', 'chrome >= 34', 'safari >= 7', 'opera >= 23', 'ios >= 7', 'android >= 4.4', 'bb >= 10'],
      cascade: true,
    }
  },
  babel: {
    enabled: true,
    options: {
      presets: ['babel-preset-es2015'].map ( require.resolve ),
      babelrc: false,
      compact: false
    }
  },
  closure: {
    enabled: false,
    options: {
      assumeFunctionWrapper: true,
      compilationLevel: 'SIMPLE',
      languageIn: 'ECMASCRIPT5_STRICT',
      languageOut: 'ECMASCRIPT5_STRICT',
      outputWrapper: '(function(){\n%output%\n}).call(this)',
      warningLevel: 'QUIET'
    }
  },
  del: {
    options: {
      force: false
    }
  },
  dependencies: {
    enabled: true,
    options: {
      before: /@before[\s]+([\S]+\.[\S]+)[\s]*/g,
      require: /@require[\s]+([\S]+\.[\S]+)[\s]*/g,
      log: false
    }
  },
  extend: {
    enabled: true,
    options: {
      log: false
    }
  },
  filter: {
    enabled: true,
    options: {
      log: false
    }
  },
  github: {
    enabled: false,
    auth: {
      type: 'oauth',
      token: false
    }
  },
  imagemin: {
    enabled: true,
    plugins: [
      imagemin.gifsicle ({
        interlaced: true,
        optimizationLevel: 3
      }),
      imagemin.jpegtran ({
        progressive: true
      }),
      imagemin.optipng ({
        optimizationLevel: 7
      }),
      imagemin.svgo ({
        multipass: true,
        plugins: [{
          cleanupIDs: false,
        }, {
          removeViewBox: false
        }]
      })
    ],
    options: {}
  },
  jsonminify: {
    enabled: true,
    options: {}
  },
  override: {
    enabled: true,
    options: {
      log: false
    }
  },
  postcss: {
    enabled: true,
    plugins: [
      cssnano ({
        autoprefixer: false,
        normalizeUrl: false,
        svgo: false,
        zindex: false
      })
    ],
    options: {}
  },
  sass: {
    enabled: true,
    options: {
      outputStyle: 'expanded',
      precision: 10
    }
  },
  uglify: {
    enabled: true,
    options: {}
  }
};

/* EXPORT */

module.exports = plugins;
<|endoftext|>


<commit_before>/**
* When JSdoc encounters names it disables the automatic code inspection ability;
* this is especially problematic for cases like
*
* > @class MyClass
* > @constructor
*
* because the properties without an explicit @memberof or fullname are not being included in
* in the newer JSDoc output.
*
* This is a simple plugin, as discussed https://github.com/jsdoc3/jsdoc/issues/804#event-195287680
* to rewrite the @class [@constructor] to @alias @class which enables JSDoc to collect better data.
*/

exports.handlers = {};
exports.handlers.jsdocCommentFound = function (e) {

    var raw = e.comment;

    if (/^(\s*[*])\s*@class\b/m.exec(raw))
    {
        // @class X / @constructor -> @alias X / @class
        raw = raw.replace(/^(\s*[*])\s*@class\s+(\S+).*?$/mg, "$1 @alias $2\n$1 @class");
        raw = raw.replace(/^(\s*[*])\s*@constructor\b.*?$/mg, "$1");

        e.comment = raw;
    }

};
<commit_msg>jsdoc - namealias fix<commit_after>/**
* When JSdoc encounters names it disables the automatic code inspection ability;
* this is especially problematic for cases like
*
* > @class MyClass
* > @constructor
*
* because the properties without an explicit @memberof or fullname are not being included in
* in the newer JSDoc output.
*
* This is a simple plugin, as discussed https://github.com/jsdoc3/jsdoc/issues/804#event-195287680
* to rewrite the @class [@constructor] to @alias @class which enables JSDoc to collect better data.
*/

exports.handlers = {};
exports.handlers.jsdocCommentFound = function (e) {

    var raw = e.comment;

    var m = /^(\s*[*])\s*@class\b/m.exec(raw);
    if (m)
    {
        // @class X -> @alias X / @class
        raw = raw.replace(/^(\s*[*])\s*@class[ \t]+(\S+).*?((?=[\r\n]+))/mg, "$1 @alias $2$3$1 @class");
        // @constructor -> {removed}
        raw = raw.replace(/^(\s*[*])\s*@constructor\b.*?(?=[\r\n]+)/mg, "$1");

        e.comment = raw;
    }

};
<|endoftext|>


<commit_before>/*
 * grunt
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman
 * Licensed under the MIT license.
 * http://benalman.com/about/license/
 */

/*global phantom:true*/

'use strict';

var fs = require('fs');

// The temporary file used for communications.
var tmpfile = phantom.args[0];
// The page .html file to load.
var url = phantom.args[1];
// Extra, optionally overridable stuff.
var options = JSON.parse(phantom.args[2] || {});

// Default options.
if (!options.timeout) { options.timeout = 5000; }

// Keep track of the last time a client message was sent.
var last = new Date();

// Messages are sent to the parent by appending them to the tempfile.
var sendMessage = function(arg) {
  var args = Array.isArray(arg) ? arg : [].slice.call(arguments);
  last = new Date();
  fs.write(tmpfile, JSON.stringify(args) + '\n', 'a');
};

// This allows grunt to abort if the PhantomJS version isn't adequate.
sendMessage('private', 'version', phantom.version);

// Abort if the page doesn't send any messages for a while.
setInterval(function() {
  if (new Date() - last > options.timeout) {
    sendMessage('fail.timeout');
    phantom.exit();
  }
}, 100);

// Create a new page.
var page = require('webpage').create();

// The client page must send its messages via alert(jsonstring).
page.onAlert = function(args) {
  sendMessage(JSON.parse(args));
};

// Keep track if the client-side helper script already has been injected.
var injected;
page.onUrlChanged = function(newUrl) {
  injected = false;
  sendMessage('onUrlChanged', newUrl);
};

// Relay console logging messages.
page.onConsoleMessage = function(message) {
  sendMessage('console', message);
};

// For debugging.
page.onResourceRequested = function(request) {
  sendMessage('onResourceRequested', request.url);
};

page.onResourceReceived = function(request) {
  if (request.stage === 'end') {
    sendMessage('onResourceReceived', request.url);
  }
};

page.onError = function(msg, trace) {
  sendMessage('onError', msg, trace);
};

// Run when the page has finished loading.
page.onLoadFinished = function(status) {
  // The window has loaded.
  sendMessage('onLoadFinished', status);
  if (status === 'success') {
    if (options.inject && !injected) {
      // Inject client-side helper script, but only if it has not yet been
      // injected.
      sendMessage('inject', options.inject);
      page.injectJs(options.inject);
    }
  } else {
    // File loading failure.
    sendMessage('fail.load', url);
    phantom.exit();
  }
};

// Actually load url.
page.open(url);
<commit_msg>Adjust PhantomJS bootstrap to inject bridge on DOMContentLoaded. Closes gh-219.<commit_after>/*
 * grunt
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman
 * Licensed under the MIT license.
 * http://benalman.com/about/license/
 */

/*global phantom:true*/

'use strict';

var fs = require('fs');

// The temporary file used for communications.
var tmpfile = phantom.args[0];
// The page .html file to load.
var url = phantom.args[1];
// Extra, optionally overridable stuff.
var options = JSON.parse(phantom.args[2] || {});

// Default options.
if (!options.timeout) { options.timeout = 5000; }

// Keep track of the last time a client message was sent.
var last = new Date();

// Messages are sent to the parent by appending them to the tempfile.
var sendMessage = function(arg) {
  var args = Array.isArray(arg) ? arg : [].slice.call(arguments);
  last = new Date();
  fs.write(tmpfile, JSON.stringify(args) + '\n', 'a');
};

// This allows grunt to abort if the PhantomJS version isn't adequate.
sendMessage('private', 'version', phantom.version);

// Abort if the page doesn't send any messages for a while.
setInterval(function() {
  if (new Date() - last > options.timeout) {
    sendMessage('fail.timeout');
    phantom.exit();
  }
}, 100);

// Create a new page.
var page = require('webpage').create();

// Inject bridge script into client page.
var injected;
var inject = function() {
  if (injected) { return; }
  // Inject client-side helper script.
  sendMessage('inject', options.inject);
  page.injectJs(options.inject);
  injected = true;
};

// Keep track if the client-side helper script already has been injected.
page.onUrlChanged = function(newUrl) {
  injected = false;
  sendMessage('onUrlChanged', newUrl);
};

// The client page must send its messages via alert(jsonstring).
page.onAlert = function(str) {
  // The only thing that should ever alert "inject" is the custom event
  // handler this script adds to be executed on DOMContentLoaded.
  if (str === 'inject') {
    inject();
    return;
  }
  // Otherwise, parse the specified message string and send it back to grunt.
  // Unless there's a parse error. Then, complain.
  try {
    sendMessage(JSON.parse(str));
  } catch(err) {
    sendMessage('error.invalidJSON', str);
  }
};

// Relay console logging messages.
page.onConsoleMessage = function(message) {
  sendMessage('console', message);
};

// For debugging.
page.onResourceRequested = function(request) {
  sendMessage('onResourceRequested', request.url);
};

page.onResourceReceived = function(request) {
  if (request.stage === 'end') {
    sendMessage('onResourceReceived', request.url);
  }
};

page.onError = function(msg, trace) {
  sendMessage('error.onError', msg, trace);
};

// Run before the page is loaded.
page.onInitialized = function() {
  sendMessage('onInitialized');
  // Abort if there is no bridge to inject.
  if (!options.inject) { return; }
  // Tell the client that when DOMContentLoaded fires, it needs to tell this
  // script to inject the bridge. This should ensure that the bridge gets
  // injected before any other DOMContentLoaded or window.load event handler.
  page.evaluate(function() {
    /*jshint browser:true, devel:true */
    document.addEventListener('DOMContentLoaded', function() {
      alert('inject');
    }, false);
  });
};

// Run when the page has finished loading.
page.onLoadFinished = function(status) {
  // The window has loaded.
  sendMessage('onLoadFinished', status);
  if (status !== 'success') {
    // File loading failure.
    sendMessage('fail.load', url);
    phantom.exit();
  }
};

// Actually load url.
page.open(url);
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
(function() {
    "use strict";

    var browsers = [{
        browserName: "internet explorer",
        platform: "WIN8.1",
        version: "11"
    }, {
        browserName: "safari",
        platform: "OS X 10.9",
        version: "7"
    }, {
        browserName: "firefox",
        platform: "Win8.1",
        version: "28"
    }];

    module.exports = {
        all: {
            options: {
                urls: [
                    "http://127.0.0.1:9999/bin/tests/Promise/test.html?autostart"
                ],
                tunnelTimeout: 5,
                build: process.env.TRAVIS_JOB_ID,
                concurrency: 3,
                browsers: browsers,
                testname: "winjs qunit tests",
                tags: ["winjs"]
            }
        }
    };
})();<commit_msg>Using wwa-application tests as default for saucelabs<commit_after>// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
(function() {
    "use strict";

    var browsers = [{
        browserName: "internet explorer",
        platform: "WIN8.1",
        version: "11"
    }, {
        browserName: "safari",
        platform: "OS X 10.9",
        version: "7"
    }, {
        browserName: "firefox",
        platform: "Win8.1",
        version: "28"
    }];

    module.exports = {
        all: {
            options: {
                urls: [
                    "http://127.0.0.1:9999/bin/tests/WWA-Application/test.html?autostart"
                ],
                tunnelTimeout: 5,
                build: process.env.TRAVIS_JOB_ID,
                concurrency: 3,
                browsers: browsers,
                testname: "winjs qunit tests",
                tags: ["winjs"]
            }
        }
    };
})();<|endoftext|>


<commit_before>Package.describe({
  summary: "\u001b[32mv0.0.3\n"+
  "\u001b[33m-----------------------------------------\n"+
  "\u001b[0m Throttle is a simple means of limiting   \n"+
  "\u001b[0m Serverside interactions (emails, etc)    \n"+
  "\u001b[33m-----------------------------zeroasterisk\n"
});

Package.on_use(function (api, where) {
  api.use(['meteor', 'underscore'], 'server');
  api.add_files('throttle.js', ['server']);
});

Package.on_test(function (api) {
  api.use('throttle');
  api.add_files('throttle_tests.js', ['client', 'server']);
});
<commit_msg>versionfix<commit_after>Package.describe({
  summary: "\u001b[32mv0.1.0\n"+
  "\u001b[33m-----------------------------------------\n"+
  "\u001b[0m Throttle is a simple means of limiting   \n"+
  "\u001b[0m Serverside interactions (emails, etc)    \n"+
  "\u001b[33m-----------------------------zeroasterisk\n"
});

Package.on_use(function (api, where) {
  api.use(['meteor', 'underscore'], 'server');
  api.add_files('throttle.js', ['server']);
});

Package.on_test(function (api) {
  api.use('throttle');
  api.add_files('throttle_tests.js', ['client', 'server']);
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'qulture:qr-ui-base',
  version: '0.0.12',
  summary: 'QR base react components and styles',
  git: 'https://github.com/qulture/qr-ui-base',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.3.2.4');
  api.export('QRComponents');

  api.use('ecmascript');
  api.use('fourseven:scss@3.4.3');
  api.use('wolves:bourbon@3.1.0');
  api.use('cinn:react-form-helpers@0.0.1');

  api.addAssets([
    'public/fonts/font-icons.eot',
    'public/fonts/font-icons.ttf',
    'public/fonts/font-icons.woff',
    'public/fonts/font-icons.svg'
  ], 'client');

  api.addFiles('styles/_qr-base.scss', 'client', { isImport: true });
});
<commit_msg>0.0.13 version<commit_after>Package.describe({
  name: 'qulture:qr-ui-base',
  version: '0.0.13',
  summary: 'QR base react components and styles',
  git: 'https://github.com/qulture/qr-ui-base',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.3.2.4');
  api.export('QRComponents');

  api.use('ecmascript');
  api.use('fourseven:scss@3.4.3');
  api.use('wolves:bourbon@3.1.0');
  api.use('cinn:react-form-helpers@0.0.1');

  api.addAssets([
    'public/fonts/font-icons.eot',
    'public/fonts/font-icons.ttf',
    'public/fonts/font-icons.woff',
    'public/fonts/font-icons.svg'
  ], 'client');

  api.addFiles('styles/_qr-base.scss', 'client', { isImport: true });
});
<|endoftext|>


<commit_before>const React = require("react");
const {connect} = require("react-redux");
const {selectNewTabSites} = require("selectors/selectors");
const TopSites = require("components/TopSites/TopSites");
const GroupedActivityFeed = require("components/ActivityFeed/ActivityFeed");
const Spotlight = require("components/Spotlight/Spotlight");
const Search = require("components/Search/Search");
const Loader = require("components/Loader/Loader");
const ContextMenu = require("components/ContextMenu/ContextMenu");
const {actions} = require("common/action-manager");
const {Link} = require("react-router");
const setFavicon = require("lib/set-favicon");
const classNames = require("classnames");
const PAGE_NAME = "NEW_TAB";

const {MAX_TOP_ACTIVITY_ITEMS} = require("common/constants");

const NewTabPage = React.createClass({
  getInitialState() {
    return {
      showSettingsMenu: false,
      renderedOnce: false,
      showRecommendations: true
    };
  },
  toggleRecommendation() {
    this.props.dispatch(actions.NotifyEvent({
      event: "TOGGLE_RECOMMENDATION",
      page: PAGE_NAME,
      showRecommendations: !this.state.showRecommendations
    }));
    this.props.dispatch(actions.NotifyToggleRecommendations());
    this.props.dispatch(actions.RequestHighlightsLinks());
    this.setState({showRecommendations: !this.state.showRecommendations});
  },
  componentDidMount() {
    document.title = "New Tab";
    setFavicon("newtab-icon.svg");
  },
  componentWillReceiveProps(nextProps) {
    if (nextProps.isReady && !this.state.renderedOnce) {
      this.props.dispatch(actions.NotifyPerf("NEWTAB_RENDER"));
      this.setState({renderedOnce: true});
    }
  },
  render() {
    const props = this.props;
    const recommendationLabel = "Show Trending Highlights";
    const recommendationIcon = props.Spotlight.recommendationShown ? "check" : "   ";
    const showRecommendationOption = props.showRecommendationOption;

    return (

          <Search />

        <Loader
          className="loading-notice"
          show={!this.props.isReady}
          label="Hang on tight! We are analyzing your history to personalize your experience"
          centered={true} />

            <TopSites page={PAGE_NAME} sites={props.TopSites.rows} />

            <Spotlight page={PAGE_NAME} showRating={props.Spotlight.metadataRating} sites={props.Spotlight.rows} />

Recent Activity

            <GroupedActivityFeed sites={props.TopActivity.rows} length={MAX_TOP_ACTIVITY_ITEMS} page={PAGE_NAME}
                                 maxPreviews={1} />

            <Link className="bottom-link" to="/timeline"> See all activity</Link>

               this.setState({showSettingsMenu: !this.state.showSettingsMenu})} >
                   Settings

              <ContextMenu
                ref="settingsMenu"
                visible={this.state.showSettingsMenu}
                onUpdate={showSettingsMenu => this.setState({showSettingsMenu})}
                options={[
                  {icon: recommendationIcon, label: recommendationLabel, onClick: this.toggleRecommendation}
                ]} />

      <Link className="debug-link" to="/debug">debug</Link>
    );
  }
});

NewTabPage.propTypes = {
  TopSites: React.PropTypes.object.isRequired,
  Spotlight: React.PropTypes.object.isRequired,
  TopActivity: React.PropTypes.object.isRequired,
  dispatch: React.PropTypes.func.isRequired
};

module.exports = connect(selectNewTabSites)(NewTabPage);
module.exports.NewTabPage = NewTabPage;
<commit_msg>fix(metrics): #1271 Send NEWTAB_RENDER on didUpdate, not receiveProps<commit_after>const React = require("react");
const {connect} = require("react-redux");
const {selectNewTabSites} = require("selectors/selectors");
const TopSites = require("components/TopSites/TopSites");
const GroupedActivityFeed = require("components/ActivityFeed/ActivityFeed");
const Spotlight = require("components/Spotlight/Spotlight");
const Search = require("components/Search/Search");
const Loader = require("components/Loader/Loader");
const ContextMenu = require("components/ContextMenu/ContextMenu");
const {actions} = require("common/action-manager");
const {Link} = require("react-router");
const setFavicon = require("lib/set-favicon");
const classNames = require("classnames");
const PAGE_NAME = "NEW_TAB";

let renderedOnce = false;

const {MAX_TOP_ACTIVITY_ITEMS} = require("common/constants");

const NewTabPage = React.createClass({
  getInitialState() {
    return {
      showSettingsMenu: false,
      showRecommendations: true
    };
  },
  toggleRecommendation() {
    this.props.dispatch(actions.NotifyEvent({
      event: "TOGGLE_RECOMMENDATION",
      page: PAGE_NAME,
      showRecommendations: !this.state.showRecommendations
    }));
    this.props.dispatch(actions.NotifyToggleRecommendations());
    this.props.dispatch(actions.RequestHighlightsLinks());
    this.setState({showRecommendations: !this.state.showRecommendations});
  },
  componentDidMount() {
    document.title = "New Tab";
    setFavicon("newtab-icon.svg");
  },
  componentDidUpdate() {
    // Note that isReady is set in the newTabPage selector (check the selectors/ folder)
    // and it is possible it never fires, if responses are not received.
    if (!renderedOnce && this.props.isReady) {
      this.props.dispatch(actions.NotifyPerf("NEWTAB_RENDER"));
      renderedOnce = true;
    }
  },
  render() {
    const props = this.props;
    const recommendationLabel = "Show Trending Highlights";
    const recommendationIcon = props.Spotlight.recommendationShown ? "check" : "   ";
    const showRecommendationOption = props.showRecommendationOption;

    return (

          <Search />

        <Loader
          className="loading-notice"
          show={!this.props.isReady}
          label="Hang on tight! We are analyzing your history to personalize your experience"
          centered={true} />

            <TopSites page={PAGE_NAME} sites={props.TopSites.rows} />

            <Spotlight page={PAGE_NAME} showRating={props.Spotlight.metadataRating} sites={props.Spotlight.rows} />

Recent Activity

            <GroupedActivityFeed sites={props.TopActivity.rows} length={MAX_TOP_ACTIVITY_ITEMS} page={PAGE_NAME}
                                 maxPreviews={1} />

            <Link className="bottom-link" to="/timeline"> See all activity</Link>

               this.setState({showSettingsMenu: !this.state.showSettingsMenu})} >
                   Settings

              <ContextMenu
                ref="settingsMenu"
                visible={this.state.showSettingsMenu}
                onUpdate={showSettingsMenu => this.setState({showSettingsMenu})}
                options={[
                  {icon: recommendationIcon, label: recommendationLabel, onClick: this.toggleRecommendation}
                ]} />

      <Link className="debug-link" to="/debug">debug</Link>
    );
  }
});

NewTabPage.propTypes = {
  TopSites: React.PropTypes.object.isRequired,
  Spotlight: React.PropTypes.object.isRequired,
  TopActivity: React.PropTypes.object.isRequired,
  dispatch: React.PropTypes.func.isRequired
};

module.exports = connect(selectNewTabSites)(NewTabPage);
module.exports.NewTabPage = NewTabPage;
<|endoftext|>


<commit_before>var strings = require("ringo/utils/strings");
var assert = require("assert");
include('ringo/skin');
var filters = require('ringo/skin/filters');

exports.testBasic = function () {
    var skin = createSkin('simple');
    assert.strictEqual('simple', render(skin));
    assert.strictEqual('simple', render(skin, {}));
};

exports.testValue = function () {
    var skin = createSkin('before <% value %> after');
    var context = {value: 'HERE'};
    assert.strictEqual('before HERE after', render(skin, context));
};

exports.testMacro = function () {
    var skin, context;

    skin = createSkin('before <% foo %> after');
    context = {foo_macro: function () 'HERE'};
    assert.strictEqual('before HERE after', render(skin, context));

    skin = createSkin('before <% foo HERE %> after');
    context = {foo_macro: function (macro) macro.parameters[0]};
    assert.strictEqual('before HERE after', render(skin, context));

    skin = createSkin('before <% foo bar=HERE %> after');
    context = {foo_macro: function (macro) macro.getParameter('bar')};
    assert.strictEqual('before HERE after', render(skin, context));
};

exports.testNestedMacro = function () {
    var skin = createSkin('<% echo <% foo %> %>');

    assert.strictEqual('a', render(skin, {foo: 'a'}));

    // ensure that rendering a skin (with nested macros) multiple times in
    // differing contexts works as expected.
    assert.strictEqual('b', render(skin, {foo: 'b'}));
};

exports.testFilter = function () {
    var skin, context;

    skin = createSkin('before <% x | foo %> after');
    context = {foo_filter: function (str) 'HERE'};
    assert.strictEqual('before HERE after', render(skin, context));

    skin = createSkin('before <% x | foo HERE %> after');
    context = {foo_filter: function (str, filter) filter.parameters[0]};
    assert.strictEqual('before HERE after', render(skin, context));

    skin = createSkin('before <% x | foo bar=HERE %> after');
    context = {foo_filter: function (str, filter) filter.getParameter('bar')};
    assert.strictEqual('before HERE after', render(skin, context));
};

exports.testSubskin = function () {
    var skin;
    var context;

    skin = createSkin('a<% subskin sub %>b');
    assert.strictEqual('a', render(skin));

    skin = createSkin('a<% render sub %><% subskin sub %>b');
    assert.strictEqual('ab', render(skin));

    skin = createSkin('a<% s %><% subskin sub %>b');
    context = {
        s_macro: function(macro, context, skin) skin.renderSubskin('sub')
    };
    assert.strictEqual('ab', render(skin, context));
};

exports.testSubskinWhitespace = function () {
    var skin;

    skin = createSkin('a\n<% subskin sub %>\nb\n');
    assert.strictEqual('a\n', render(skin));

    skin = createSkin('a\n<% render sub %>\n<% subskin sub %>\nb\n');
    assert.strictEqual('a\n\nb\n', render(skin));
};

exports.testExtends = function () {
    var skin;

    skin = createSkin(getResource('./skins/child.html'));
    assert.strictEqual('foo\n\nbar', render(skin).trim());
}

exports.testExternalSubskin = function () {
    var skin;

    skin = createSkin(getResource('./skins/foo.html'));
    assert.strictEqual('foo\nbar\nbaz\n', render(skin));
};

// --- builtins ---

exports.testIfBuiltin = function () {
    var skin = createSkin('<% if <% x %> render tt %>' +
                          '<% if not <% x %> render ff %>' +
                          '\n<% x %>' +
                          '<% subskin tt %>tt' +
                          '<% subskin ff %>ff');

    assert.strictEqual('tt\ntrue',     render(skin, {x: true}).trim());
    assert.strictEqual('tt\n42',       render(skin, {x: 42}).trim());
    assert.strictEqual('tt',           render(skin, {x: []}).trim());

    assert.strictEqual('ff\nfalse',    render(skin, {x: false}).trim());
    assert.strictEqual('ff',           render(skin, {x: null}).trim());
    assert.strictEqual('ff',           render(skin, {}).trim());
};

exports.testForBuiltinBasic = function () {
    var skin;

    skin = createSkin('<% for x in <% xs %> render item %>' +
                      '<% subskin item %><% x %>,');
    assert.strictEqual('foo,bar,baz,', render(skin, {xs: ['foo', 'bar', 'baz']}));
    assert.strictEqual('',             render(skin, {xs: []}));

    skin = createSkin('<% for x in ["Foo", "Bar", "Baz"] render item %>' +
                      '<% subskin item %><% x %>');
    assert.strictEqual('FooBarBaz',    render(skin));

    skin = createSkin('<% for x in [Foo, Bar, Baz] render item %>' +
                      '<% subskin item %><% x %>');
    assert.strictEqual('FooBarBaz',    render(skin));
};

exports.testForBuiltinSeparator = function () {
    var skin = createSkin('<% for x in <% xs %> separator=: render item %>' +
                          '<% subskin item %><% x %>');
    assert.strictEqual('foo:bar:baz',  render(skin, {xs: ['foo', 'bar', 'baz']}));
    assert.strictEqual('foo',          render(skin, {xs: ['foo']}));
    assert.strictEqual('',             render(skin, {xs: []}));
};

exports.testForBuiltinWrap = function () {
    var skin = createSkin('<% for x in <% xs %> wrap=[A,Z] render item %>' +
                          '<% subskin item %><% x %>');
    assert.strictEqual('AaZAbZAcZ',    render(skin, {xs: ['a', 'b', 'c']}));
    assert.strictEqual('AaZ',          render(skin, {xs: ['a']}));
    assert.strictEqual('',             render(skin, {xs: []}));
};

exports.testForBuiltinIndex = function () {
    var skin = createSkin('<% for x in <% xs %> render item %>' +
                          '<% subskin item %><% index %>');
    assert.strictEqual('012',          render(skin, {xs: ['a', 'b', 'c']}));
    assert.strictEqual('0',            render(skin, {xs: ['a']}));
    assert.strictEqual('',             render(skin, {xs: []}));
};

exports.testForBuiltinNestedFor = function () {
    var skin;

    skin = createSkin('<% for x in <% xs %> and y in <% ys %> render item %>' +
                      '<% subskin item %>(<% x %><% y %>)');
    assert.strictEqual('(14)(15)(24)(25)', render(skin, {xs: [1, 2], ys: [4, 5]}));

    skin = createSkin('<% for x in <% xs %> for y in <% ys %> render item %>' +
                      '<% subskin item %>(<% x %><% y %>)');
    assert.strictEqual('(14)(15)(24)(25)', render(skin, {xs: [1, 2], ys: [4, 5]}));
};

exports.testSetBuiltin = function () {
    var skin;

    skin = createSkin('<% set {x: "foo"} render item %>' +
                      '<% subskin item %><% x %>');
    assert.strictEqual('foo', render(skin));
    assert.strictEqual('foo', render(skin, {x: 'bar'}));

    skin = createSkin('<% render item %>' +
                      '<% set {x: "Override"} render item %>' +
                      '<% render item %>' +
                      '<% subskin item %><% x %>');
    assert.strictEqual('OriginalOverrideOriginal', render(skin, {x: 'Original'}));
};

// --- filters ---

exports.testLowercaseFilter = function () {
    var string = 'ALL CAPS';
    var skin = createSkin('<% value | lowercase %>');
    var context = {value: string, lowercase_filter: filters.lowercase_filter};
    assert.strictEqual(string.toLowerCase(), render(skin, context));
};

exports.testUppercaseFilter = function () {
    var string = 'wannabe caps';
    var skin = createSkin('<% value | uppercase %>');
    var context = {value: string, uppercase_filter: filters.uppercase_filter};
    assert.strictEqual(string.toUpperCase(), render(skin, context));
};

exports.testCapitalizeFilter = function () {
    var string = 'capitalize me.';
    var skin = createSkin('<% value | capitalize %>');
    var context = {value: string, capitalize_filter: filters.capitalize_filter};
    assert.strictEqual(strings.capitalize(string), render(skin, context));
};

exports.testTitleizeFilter = function () {
    var string = 'titleize me';
    var skin = createSkin('<% value | titleize %>');
    var context = {value: string, titleize_filter: filters.titleize_filter};
    assert.strictEqual(strings.titleize(string), render(skin, context));
};

exports.testTrimFilter = function () {
    var string = ' trim me  ';
    var skin = createSkin('<% value | trim %>');
    var context = {value: string, trim_filter: filters.trim_filter};
    assert.strictEqual(string.trim(), render(skin, context));
};

exports.testStripTagsFilter = function () {
    var string = '<tag>content</tag>';
    var skin = createSkin('<% value | stripTags %>');
    var context = {value: string, stripTags_filter: filters.stripTags_filter};
    assert.strictEqual(strings.stripTags(string), render(skin, context));
};

exports.testEscapeUrlFilter = function () {
    var string = 'http://ringojs.org/Web Framework/';
    var skin = createSkin('<% value | escapeUrl %>');
    var context = {value: string, escapeUrl_filter: filters.escapeUrl_filter};
    assert.strictEqual(java.net.URLEncoder.encode(string, 'utf8'),
            render(skin, context));
};

exports.testEscapeHtmlFilter = function () {
    var string = '
Some text.
';
    var skin = createSkin('<% value | escapeHtml %>');
    var context = {value: string, escapeHtml_filter: filters.escapeHtml_filter};
    assert.strictEqual(strings.escapeHtml(string), render(skin, context));
};

exports.testTruncateFilter = function () {
    var string = 'foobarbaz';
    var skin = createSkin('<% value | truncate limit="10" %>');
    var context = {value: string, truncate_filter: filters.truncate_filter};
    // This filter shall leave short enough strings alone.
    assert.strictEqual(string, render(skin, context));
};
<commit_msg>Tests: nested if in skins<commit_after>var strings = require("ringo/utils/strings");
var assert = require("assert");
include('ringo/skin');
var filters = require('ringo/skin/filters');

exports.testBasic = function () {
    var skin = createSkin('simple');
    assert.strictEqual('simple', render(skin));
    assert.strictEqual('simple', render(skin, {}));
};

exports.testValue = function () {
    var skin = createSkin('before <% value %> after');
    var context = {value: 'HERE'};
    assert.strictEqual('before HERE after', render(skin, context));
};

exports.testMacro = function () {
    var skin, context;

    skin = createSkin('before <% foo %> after');
    context = {foo_macro: function () 'HERE'};
    assert.strictEqual('before HERE after', render(skin, context));

    skin = createSkin('before <% foo HERE %> after');
    context = {foo_macro: function (macro) macro.parameters[0]};
    assert.strictEqual('before HERE after', render(skin, context));

    skin = createSkin('before <% foo bar=HERE %> after');
    context = {foo_macro: function (macro) macro.getParameter('bar')};
    assert.strictEqual('before HERE after', render(skin, context));
};

exports.testNestedMacro = function () {
    var skin = createSkin('<% echo <% foo %> %>');

    assert.strictEqual('a', render(skin, {foo: 'a'}));

    // ensure that rendering a skin (with nested macros) multiple times in
    // differing contexts works as expected.
    assert.strictEqual('b', render(skin, {foo: 'b'}));
};

exports.testFilter = function () {
    var skin, context;

    skin = createSkin('before <% x | foo %> after');
    context = {foo_filter: function (str) 'HERE'};
    assert.strictEqual('before HERE after', render(skin, context));

    skin = createSkin('before <% x | foo HERE %> after');
    context = {foo_filter: function (str, filter) filter.parameters[0]};
    assert.strictEqual('before HERE after', render(skin, context));

    skin = createSkin('before <% x | foo bar=HERE %> after');
    context = {foo_filter: function (str, filter) filter.getParameter('bar')};
    assert.strictEqual('before HERE after', render(skin, context));
};

exports.testSubskin = function () {
    var skin;
    var context;

    skin = createSkin('a<% subskin sub %>b');
    assert.strictEqual('a', render(skin));

    skin = createSkin('a<% render sub %><% subskin sub %>b');
    assert.strictEqual('ab', render(skin));

    skin = createSkin('a<% s %><% subskin sub %>b');
    context = {
        s_macro: function(macro, context, skin) skin.renderSubskin('sub')
    };
    assert.strictEqual('ab', render(skin, context));
};

exports.testSubskinWhitespace = function () {
    var skin;

    skin = createSkin('a\n<% subskin sub %>\nb\n');
    assert.strictEqual('a\n', render(skin));

    skin = createSkin('a\n<% render sub %>\n<% subskin sub %>\nb\n');
    assert.strictEqual('a\n\nb\n', render(skin));
};

exports.testExtends = function () {
    var skin;

    skin = createSkin(getResource('./skins/child.html'));
    assert.strictEqual('foo\n\nbar', render(skin).trim());
}

exports.testExternalSubskin = function () {
    var skin;

    skin = createSkin(getResource('./skins/foo.html'));
    assert.strictEqual('foo\nbar\nbaz\n', render(skin));
};

// --- builtins ---

exports.testIfBuiltin = function () {
    var skin = createSkin('<% if <% x %> render tt %>' +
                          '<% if not <% x %> render ff %>' +
                          '\n<% x %>' +
                          '<% subskin tt %>tt' +
                          '<% subskin ff %>ff');

    assert.strictEqual('tt\ntrue',     render(skin, {x: true}).trim());
    assert.strictEqual('tt\n42',       render(skin, {x: 42}).trim());
    assert.strictEqual('tt',           render(skin, {x: []}).trim());

    assert.strictEqual('ff\nfalse',    render(skin, {x: false}).trim());
    assert.strictEqual('ff',           render(skin, {x: null}).trim());
    assert.strictEqual('ff',           render(skin, {}).trim());
};

exports.testIfBuiltinNested = function () {
    function testOne(skin, boolFn, x, y) {
        assert.strictEqual(boolFn(x, y) ? 'tt' : '',
                           render(skin, {x: x, y: y}));
    }

    function testAll(skin, boolFn) {
        for each (let x in [true, false])
            for each (let y in [true, false])
                testOne(skin, boolFn, x, y);
    }

    var tests = [
        // if-if (== if-and)
        ['<% if <% x %> if <% y %> echo "tt" %>',           function (x, y) x && y],
        // if-and
        ['<% if <% x %> and <% y %> echo "tt" %>',          function (x, y) x && y],
        ['<% if <% x %> and not <% y %> echo "tt" %>',      function (x, y) x && !y],
        ['<% if not <% x %> and <% y %> echo "tt" %>',      function (x, y) !x && y],
        ['<% if not <% x %> and not <% y %> echo "tt" %>',  function (x, y) !x && !y],
        // if-or
        ['<% if <% x %> or <% y %> echo "tt" %>',           function (x, y) x || y],
        ['<% if <% x %> or not <% y %> echo "tt" %>',       function (x, y) x || !y],
        ['<% if not <% x %> or <% y %> echo "tt" %>',       function (x, y) !x || y],
        ['<% if not <% x %> or not <% y %> echo "tt" %>',   function (x, y) !x || !y],
    ];

    for each (let [skinStr, boolFn] in tests) {
        testAll(createSkin(skinStr), boolFn);
    }
};

exports.testForBuiltinBasic = function () {
    var skin;

    skin = createSkin('<% for x in <% xs %> render item %>' +
                      '<% subskin item %><% x %>,');
    assert.strictEqual('foo,bar,baz,', render(skin, {xs: ['foo', 'bar', 'baz']}));
    assert.strictEqual('',             render(skin, {xs: []}));

    skin = createSkin('<% for x in ["Foo", "Bar", "Baz"] render item %>' +
                      '<% subskin item %><% x %>');
    assert.strictEqual('FooBarBaz',    render(skin));

    skin = createSkin('<% for x in [Foo, Bar, Baz] render item %>' +
                      '<% subskin item %><% x %>');
    assert.strictEqual('FooBarBaz',    render(skin));
};

exports.testForBuiltinSeparator = function () {
    var skin = createSkin('<% for x in <% xs %> separator=: render item %>' +
                          '<% subskin item %><% x %>');
    assert.strictEqual('foo:bar:baz',  render(skin, {xs: ['foo', 'bar', 'baz']}));
    assert.strictEqual('foo',          render(skin, {xs: ['foo']}));
    assert.strictEqual('',             render(skin, {xs: []}));
};

exports.testForBuiltinWrap = function () {
    var skin = createSkin('<% for x in <% xs %> wrap=[A,Z] render item %>' +
                          '<% subskin item %><% x %>');
    assert.strictEqual('AaZAbZAcZ',    render(skin, {xs: ['a', 'b', 'c']}));
    assert.strictEqual('AaZ',          render(skin, {xs: ['a']}));
    assert.strictEqual('',             render(skin, {xs: []}));
};

exports.testForBuiltinIndex = function () {
    var skin = createSkin('<% for x in <% xs %> render item %>' +
                          '<% subskin item %><% index %>');
    assert.strictEqual('012',          render(skin, {xs: ['a', 'b', 'c']}));
    assert.strictEqual('0',            render(skin, {xs: ['a']}));
    assert.strictEqual('',             render(skin, {xs: []}));
};

exports.testForBuiltinNestedFor = function () {
    var skin;

    skin = createSkin('<% for x in <% xs %> and y in <% ys %> render item %>' +
                      '<% subskin item %>(<% x %><% y %>)');
    assert.strictEqual('(14)(15)(24)(25)', render(skin, {xs: [1, 2], ys: [4, 5]}));

    skin = createSkin('<% for x in <% xs %> for y in <% ys %> render item %>' +
                      '<% subskin item %>(<% x %><% y %>)');
    assert.strictEqual('(14)(15)(24)(25)', render(skin, {xs: [1, 2], ys: [4, 5]}));
};

exports.testSetBuiltin = function () {
    var skin;

    skin = createSkin('<% set {x: "foo"} render item %>' +
                      '<% subskin item %><% x %>');
    assert.strictEqual('foo', render(skin));
    assert.strictEqual('foo', render(skin, {x: 'bar'}));

    skin = createSkin('<% render item %>' +
                      '<% set {x: "Override"} render item %>' +
                      '<% render item %>' +
                      '<% subskin item %><% x %>');
    assert.strictEqual('OriginalOverrideOriginal', render(skin, {x: 'Original'}));
};

// --- filters ---

exports.testLowercaseFilter = function () {
    var string = 'ALL CAPS';
    var skin = createSkin('<% value | lowercase %>');
    var context = {value: string, lowercase_filter: filters.lowercase_filter};
    assert.strictEqual(string.toLowerCase(), render(skin, context));
};

exports.testUppercaseFilter = function () {
    var string = 'wannabe caps';
    var skin = createSkin('<% value | uppercase %>');
    var context = {value: string, uppercase_filter: filters.uppercase_filter};
    assert.strictEqual(string.toUpperCase(), render(skin, context));
};

exports.testCapitalizeFilter = function () {
    var string = 'capitalize me.';
    var skin = createSkin('<% value | capitalize %>');
    var context = {value: string, capitalize_filter: filters.capitalize_filter};
    assert.strictEqual(strings.capitalize(string), render(skin, context));
};

exports.testTitleizeFilter = function () {
    var string = 'titleize me';
    var skin = createSkin('<% value | titleize %>');
    var context = {value: string, titleize_filter: filters.titleize_filter};
    assert.strictEqual(strings.titleize(string), render(skin, context));
};

exports.testTrimFilter = function () {
    var string = ' trim me  ';
    var skin = createSkin('<% value | trim %>');
    var context = {value: string, trim_filter: filters.trim_filter};
    assert.strictEqual(string.trim(), render(skin, context));
};

exports.testStripTagsFilter = function () {
    var string = '<tag>content</tag>';
    var skin = createSkin('<% value | stripTags %>');
    var context = {value: string, stripTags_filter: filters.stripTags_filter};
    assert.strictEqual(strings.stripTags(string), render(skin, context));
};

exports.testEscapeUrlFilter = function () {
    var string = 'http://ringojs.org/Web Framework/';
    var skin = createSkin('<% value | escapeUrl %>');
    var context = {value: string, escapeUrl_filter: filters.escapeUrl_filter};
    assert.strictEqual(java.net.URLEncoder.encode(string, 'utf8'),
            render(skin, context));
};

exports.testEscapeHtmlFilter = function () {
    var string = '
Some text.
';
    var skin = createSkin('<% value | escapeHtml %>');
    var context = {value: string, escapeHtml_filter: filters.escapeHtml_filter};
    assert.strictEqual(strings.escapeHtml(string), render(skin, context));
};

exports.testTruncateFilter = function () {
    var string = 'foobarbaz';
    var skin = createSkin('<% value | truncate limit="10" %>');
    var context = {value: string, truncate_filter: filters.truncate_filter};
    // This filter shall leave short enough strings alone.
    assert.strictEqual(string, render(skin, context));
};
<|endoftext|>


<commit_before>Package.describe({
  name: 'jagi:astronomy-validators',
  version: '0.9.0',
  summary: 'Validators for Meteor Astronomy',
  git: 'https://github.com/jagi/meteor-astronomy-validators.git'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  api.use('jagi:astronomy@0.9.1');
  api.use('jagi:reactive-map@0.1.0');
  api.use('underscore');
  api.use('ui');

  api.imply('jagi:astronomy');

  // Module.
  api.addFiles('lib/module/global.js', ['client', 'server']);
  api.addFiles('lib/module/utils.js', ['client', 'server']);
  api.addFiles('lib/module/error.js', ['client', 'server']);
  api.addFiles('lib/module/validator.js', ['client', 'server']);
  api.addFiles('lib/module/init_module.js', ['client', 'server']);
  api.addFiles('lib/module/init_class.js', ['client', 'server']);
  api.addFiles('lib/module/init_instance.js', ['client', 'server']);
  api.addFiles('lib/module/module.js', ['client', 'server']);

  // Validators.
  api.addFiles('lib/validators/and.js', ['client', 'server']);
  api.addFiles('lib/validators/or.js', ['client', 'server']);

  api.addFiles('lib/validators/is_string.js', ['client', 'server']);
  api.addFiles('lib/validators/is_number.js', ['client', 'server']);
  api.addFiles('lib/validators/is_array.js', ['client', 'server']);
  api.addFiles('lib/validators/is_object.js', ['client', 'server']);
  api.addFiles('lib/validators/is_date.js', ['client', 'server']);
  api.addFiles('lib/validators/is_null.js', ['client', 'server']);
  api.addFiles('lib/validators/is_not_null.js', ['client', 'server']);
  api.addFiles('lib/validators/is_email.js', ['client', 'server']);

  api.addFiles('lib/validators/min_length.js', ['client', 'server']);
  api.addFiles('lib/validators/max_length.js', ['client', 'server']);
  api.addFiles('lib/validators/greater_than.js', ['client', 'server']);
  api.addFiles('lib/validators/greater_than_or_equal.js', ['client', 'server']);
  api.addFiles('lib/validators/less_than.js', ['client', 'server']);
  api.addFiles('lib/validators/less_than_or_equal.js', ['client', 'server']);
  api.addFiles('lib/validators/has_property.js', ['client', 'server']);

  api.addFiles('lib/validators/equal.js', ['client', 'server']);
  api.addFiles('lib/validators/equal_to.js', ['client', 'server']);
  api.addFiles('lib/validators/regexp.js', ['client', 'server']);
  api.addFiles('lib/validators/choice.js', ['client', 'server']);
  api.addFiles('lib/validators/unique.js', ['client', 'server']);

  api.export(['Validators'], ['client', 'server']);
});
<commit_msg>Bump version to 0.9.1<commit_after>Package.describe({
  name: 'jagi:astronomy-validators',
  version: '0.9.1',
  summary: 'Validators for Meteor Astronomy',
  git: 'https://github.com/jagi/meteor-astronomy-validators.git'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  api.use('jagi:astronomy@0.9.1');
  api.use('jagi:reactive-map@0.1.0');
  api.use('underscore');
  api.use('ui');

  api.imply('jagi:astronomy');

  // Module.
  api.addFiles('lib/module/global.js', ['client', 'server']);
  api.addFiles('lib/module/utils.js', ['client', 'server']);
  api.addFiles('lib/module/error.js', ['client', 'server']);
  api.addFiles('lib/module/validator.js', ['client', 'server']);
  api.addFiles('lib/module/init_module.js', ['client', 'server']);
  api.addFiles('lib/module/init_class.js', ['client', 'server']);
  api.addFiles('lib/module/init_instance.js', ['client', 'server']);
  api.addFiles('lib/module/module.js', ['client', 'server']);

  // Validators.
  api.addFiles('lib/validators/and.js', ['client', 'server']);
  api.addFiles('lib/validators/or.js', ['client', 'server']);

  api.addFiles('lib/validators/is_string.js', ['client', 'server']);
  api.addFiles('lib/validators/is_number.js', ['client', 'server']);
  api.addFiles('lib/validators/is_array.js', ['client', 'server']);
  api.addFiles('lib/validators/is_object.js', ['client', 'server']);
  api.addFiles('lib/validators/is_date.js', ['client', 'server']);
  api.addFiles('lib/validators/is_null.js', ['client', 'server']);
  api.addFiles('lib/validators/is_not_null.js', ['client', 'server']);
  api.addFiles('lib/validators/is_email.js', ['client', 'server']);

  api.addFiles('lib/validators/min_length.js', ['client', 'server']);
  api.addFiles('lib/validators/max_length.js', ['client', 'server']);
  api.addFiles('lib/validators/greater_than.js', ['client', 'server']);
  api.addFiles('lib/validators/greater_than_or_equal.js', ['client', 'server']);
  api.addFiles('lib/validators/less_than.js', ['client', 'server']);
  api.addFiles('lib/validators/less_than_or_equal.js', ['client', 'server']);
  api.addFiles('lib/validators/has_property.js', ['client', 'server']);

  api.addFiles('lib/validators/equal.js', ['client', 'server']);
  api.addFiles('lib/validators/equal_to.js', ['client', 'server']);
  api.addFiles('lib/validators/regexp.js', ['client', 'server']);
  api.addFiles('lib/validators/choice.js', ['client', 'server']);
  api.addFiles('lib/validators/unique.js', ['client', 'server']);

  api.export(['Validators'], ['client', 'server']);
});
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash'),
    path = require('path'),
    sinon = require('sinon'),
    fs = require('fs'),
    KnexMigrator = require('../lib'),
    testUtils = require('./utils');

let sandbox = sinon.sandbox.create();

describe('knex-migrator rollback (default)', function () {
    this.timeout(1000 * 10);

    let knexMigrator,
        migrationPath = path.join(__dirname, 'assets', 'migrations_6'),
        migratorConfigPath = __dirname + '/assets/MigratorConfig.js',
        versionsFolder = __dirname + '/assets/migrations_6/versions',
        migration121 = __dirname + '/assets/migrations_6/versions/1.21',
        migration121File = __dirname + '/assets/migrations_6/versions/1.21/1-test.js',
        connection;

    before(function () {
        if (fs.existsSync(migration121File)) {
            fs.unlinkSync(migration121File);
        }

        if (fs.existsSync(migration121)) {
            fs.rmdirSync(migration121);
        }

        if (fs.existsSync(versionsFolder)) {
            fs.rmdirSync(versionsFolder);
        }

        testUtils.writeMigratorConfig({
            migratorConfigPath: migratorConfigPath,
            migrationPath: migrationPath,
            currentVersion: '1.20'
        });

        knexMigrator = new KnexMigrator({
            knexMigratorFilePath: __dirname + '/assets'
        });
    });

    before(function () {
        return knexMigrator.reset();
    });

    before(function () {
        connection = testUtils.connect();
    });

    after(function (done) {
        connection && connection.destroy(done);

        if (fs.existsSync(migration121File)) {
            fs.unlinkSync(migration121File);
        }

        if (fs.existsSync(migration121)) {
            fs.rmdirSync(migration121);
        }

        if (fs.existsSync(versionsFolder)) {
            fs.rmdirSync(versionsFolder);
        }

        if (fs.existsSync(migratorConfigPath)) {
            fs.unlinkSync(migratorConfigPath);

            _.each(require.cache, function (value, key) {
                if (key.match(/assets\/MigratorConfig\.js/)) {
                    delete require.cache[key];
                }
            });
        }
    });

    beforeEach(function () {
        sandbox.spy(knexMigrator, 'beforeEach');
        sandbox.spy(knexMigrator, 'afterEach');
    });

    afterEach(function () {
        sandbox.restore();
    });

    it('knex-migrator init', function () {
        return knexMigrator.init();
    });

    it('knex-migrator migrate', function () {
        fs.mkdirSync(versionsFolder);
        fs.mkdirSync(migration121);

        let jsFile = testUtils.generateMigrationScript({
            up: 'UPDATE users set name="Kind";',
            down: 'UPDATE users set name="Hausmann";'
        });

        fs.writeFileSync(migration121File, jsFile);
        knexMigrator.currentVersion = '1.21';
        return knexMigrator.migrate();
    });

    it('knex-migrator rollback', function () {
        return knexMigrator.rollback({force: true});
    });

    it('knex-migrator health', function () {
        return knexMigrator.isDatabaseOK()
            .then(function () {
                'Database should not be okay'.should.eql(false);
            })
            .catch(function (err) {
                err.message.should.eql('Migrations are missing. Please run knex-migrator migrate.');
            });
    });

    it('db check', function () {
        return connection('migrations')
            .then(function (migrations) {
                migrations.length.should.eql(2);
            });
    });

    it('knex-migrator rollback', function () {
        return knexMigrator.rollback({force: true})
            .then(function () {
                'No rollback expected.'.should.eql(false);
            })
            .catch(function (err) {
                err.message.should.eql('No migrations available to rollback.');
            })
    });
});
<commit_msg>Fixed tests<commit_after>'use strict';

const _ = require('lodash'),
    path = require('path'),
    sinon = require('sinon'),
    fs = require('fs'),
    KnexMigrator = require('../lib'),
    testUtils = require('./utils');

let sandbox = sinon.sandbox.create();

describe('knex-migrator rollback (default)', function () {
    this.timeout(1000 * 10);

    let knexMigrator,
        migrationPath = path.join(__dirname, 'assets', 'migrations_6'),
        migratorConfigPath = __dirname + '/assets/MigratorConfig.js',
        versionsFolder = __dirname + '/assets/migrations_6/versions',
        migration121 = __dirname + '/assets/migrations_6/versions/1.21',
        migration121File = __dirname + '/assets/migrations_6/versions/1.21/1-test.js',
        connection;

    before(function () {
        if (fs.existsSync(migration121File)) {
            fs.unlinkSync(migration121File);
        }

        if (fs.existsSync(migration121)) {
            fs.rmdirSync(migration121);
        }

        if (fs.existsSync(versionsFolder)) {
            fs.rmdirSync(versionsFolder);
        }

        testUtils.writeMigratorConfig({
            migratorConfigPath: migratorConfigPath,
            migrationPath: migrationPath,
            currentVersion: '1.20'
        });

        knexMigrator = new KnexMigrator({
            knexMigratorFilePath: __dirname + '/assets'
        });
    });

    before(function () {
        return knexMigrator.reset();
    });

    before(function () {
        connection = testUtils.connect();
    });

    after(function (done) {
        connection && connection.destroy(done);

        if (fs.existsSync(migration121File)) {
            fs.unlinkSync(migration121File);
        }

        if (fs.existsSync(migration121)) {
            fs.rmdirSync(migration121);
        }

        if (fs.existsSync(versionsFolder)) {
            fs.rmdirSync(versionsFolder);
        }

        if (fs.existsSync(migratorConfigPath)) {
            fs.unlinkSync(migratorConfigPath);

            _.each(require.cache, function (value, key) {
                if (key.match(/assets\/MigratorConfig\.js/)) {
                    delete require.cache[key];
                }
            });
        }
    });

    beforeEach(function () {
        sandbox.spy(knexMigrator, 'beforeEach');
        sandbox.spy(knexMigrator, 'afterEach');
    });

    afterEach(function () {
        sandbox.restore();
    });

    it('knex-migrator init', function () {
        return knexMigrator.init();
    });

    it('knex-migrator migrate', function () {
        fs.mkdirSync(versionsFolder);
        fs.mkdirSync(migration121);

        let jsFile = testUtils.generateMigrationScript({
            up: 'UPDATE users set name="Kind";',
            down: 'UPDATE users set name="Hausmann";'
        });

        fs.writeFileSync(migration121File, jsFile);
        knexMigrator.currentVersion = '1.21';
        return knexMigrator.migrate();
    });

    it('knex-migrator rollback', function () {
        return knexMigrator.rollback({force: true});
    });

    it('knex-migrator health', function () {
        return knexMigrator.isDatabaseOK()
            .then(function () {
                'Database should not be okay'.should.eql(false);
            })
            .catch(function (err) {
                err.message.should.eql('Migrations are missing. Please run `knex-migrator migrate`.');
            });
    });

    it('db check', function () {
        return connection('migrations')
            .then(function (migrations) {
                migrations.length.should.eql(2);
            });
    });

    it('knex-migrator rollback', function () {
        return knexMigrator.rollback({force: true})
            .then(function () {
                'No rollback expected.'.should.eql(false);
            })
            .catch(function (err) {
                err.message.should.eql('No migrations available to rollback.');
            })
    });
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'qnipp:treeview',
  version: '1.1.0',
  // Brief, one-line summary of the package.
  summary: 'Show and edit data from a collection using jsTree',
  // URL to the Git repository containing the source code for this package.
  git: '',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function (api) {
  api.versionsFrom('1.2.1');
  api.use(['ecmascript']);
  api.use(['blaze', 'templating', 'jquery', 'reactive-dict'], 'client');
  api.use(['qnipp:jstree@3.3.0'], 'client');
  api.addFiles('client/tree_view.html', 'client');
  api.addFiles('client/tree_view.js', 'client');

});

Package.onTest(function (api) {
});
<commit_msg>Setting version number 1.1.1<commit_after>Package.describe({
  name: 'qnipp:treeview',
  version: '1.1.1',
  // Brief, one-line summary of the package.
  summary: 'Show and edit data from a collection using jsTree',
  // URL to the Git repository containing the source code for this package.
  git: '',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function (api) {
  api.versionsFrom('1.2.1');
  api.use(['ecmascript']);
  api.use(['blaze', 'templating', 'jquery', 'reactive-dict'], 'client');
  api.use(['qnipp:jstree@3.3.0'], 'client');
  api.addFiles('client/tree_view.html', 'client');
  api.addFiles('client/tree_view.js', 'client');

});

Package.onTest(function (api) {
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'qnipp:treeview',
  version: '1.0.0',
  // Brief, one-line summary of the package.
  summary: 'Show and edit data from a collection using jsTree',
  // URL to the Git repository containing the source code for this package.
  git: '',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.2.1');
  api.use(['ecmascript']);
  api.use(['blaze', 'templating', 'jquery', 'reactive-dict'], 'client');
  api.use(['qnipp:jstree@3.3.0'], 'client');
  api.addFiles('client/tree_view.html', 'client');
  api.addFiles('client/tree_view.js', 'client');

});

Package.onTest(function(api) {
});
<commit_msg>Setting version number 1.1.0<commit_after>Package.describe({
  name: 'qnipp:treeview',
  version: '1.1.0',
  // Brief, one-line summary of the package.
  summary: 'Show and edit data from a collection using jsTree',
  // URL to the Git repository containing the source code for this package.
  git: '',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function (api) {
  api.versionsFrom('1.2.1');
  api.use(['ecmascript']);
  api.use(['blaze', 'templating', 'jquery', 'reactive-dict'], 'client');
  api.use(['qnipp:jstree@3.3.0'], 'client');
  api.addFiles('client/tree_view.html', 'client');
  api.addFiles('client/tree_view.js', 'client');

});

Package.onTest(function (api) {
});
<|endoftext|>


<commit_before>/* eslint-disable no-var, prefer-arrow-callback */
var packages = [
  'ecmascript',
  'reactive-var',
  'promise',
  'blaze-html-templates',
];

Package.describe({
  name: 'swydo:blaze-apollo',
  version: '0.2.0',
  summary: 'Blaze integration for the Apollo Client',
  git: 'https://github.com/swydo/blaze-apollo',
  documentation: 'README.md',
});

Package.onUse(function use(api) {
  api.versionsFrom('1.3.2.4');

  api.use(packages, 'client');

  api.mainModule('client.js', 'client');
});

Package.onTest(function test(api) {
  api.use('swydo:blaze-apollo');

  api.use(packages, 'client');
  api.use([
    'tracker',
    'practicalmeteor:mocha',
    'practicalmeteor:sinon',
  ]);

  api.mainModule('client.spec.js', 'client');
});
<commit_msg>0.3.0<commit_after>/* eslint-disable no-var, prefer-arrow-callback */
var packages = [
  'ecmascript',
  'reactive-var',
  'promise',
  'blaze-html-templates',
];

Package.describe({
  name: 'swydo:blaze-apollo',
  version: '0.3.0',
  summary: 'Blaze integration for the Apollo Client',
  git: 'https://github.com/swydo/blaze-apollo',
  documentation: 'README.md',
});

Package.onUse(function use(api) {
  api.versionsFrom('1.3.2.4');

  api.use(packages, 'client');

  api.mainModule('client.js', 'client');
});

Package.onTest(function test(api) {
  api.use('swydo:blaze-apollo');

  api.use(packages, 'client');
  api.use([
    'tracker',
    'practicalmeteor:mocha',
    'practicalmeteor:sinon',
  ]);

  api.mainModule('client.spec.js', 'client');
});
<|endoftext|>


<commit_before>/*
* Official docs:
* https://nodejs.org/docs/latest/api/path.html
*/

Package.describe({
  name: 'jss:path',
  version: '0.0.3',
  summary: 'Wrapper for Node "path" package.',
  git: 'https://github.com/JSSolutions/meteor-path'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');
  api.addFiles('path.js', 'server');
  api.export('path', 'server');
});

Npm.depends({
  'util-is': '0.1.0',
  path: '0.11.14'
});

Package.onTest(function(api) {
  api.use(['tinytest', 'jss:path'], 'server');
  api.addFiles('tests.js', 'server');
});<commit_msg>updated version<commit_after>/*
* Official docs:
* https://nodejs.org/docs/latest/api/path.html
*/

Package.describe({
  name: 'jss:path',
  version: '0.0.3',
  summary: 'Wrapper for Node "path" package.',
  git: 'https://github.com/JSSolutions/meteor-path'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');
  api.addFiles('path.js', 'server');
  api.export('path', 'server');
});

Npm.depends({
  'util-is': '0.1.0',
  path: '0.12.7'
});

Package.onTest(function(api) {
  api.use(['tinytest', 'jss:path'], 'server');
  api.addFiles('tests.js', 'server');
});
<|endoftext|>


<commit_before>/* @flow */

/*::
type FSAddDirAction = {|type: 'mkdir', path: string|}
type FSAddFileAction = {|type: '>', path: string|}
type FSDeleteAction = {|type: 'delete', path: string|}
type FSMoveAction = {|type: 'mv', src: string, dst: string|}
type FSRestoreAction = {|type: 'restore', pathInTrash: string|}
type FSTrashAction = {|type: 'trash', path: string|}
type FSUpdateFileAction = {|type: '>>'|}
type FSWaitAction = {|type: 'wait', ms: number|}

type FSAction
  = FSAddDirAction
  | FSAddFileAction
  | FSDeleteAction
  | FSMoveAction
  | FSRestoreAction
  | FSTrashAction
  | FSUpdateFileAction
  | FSWaitAction

type PrepAddFileExpectation = {|method: 'addFileAsync', path: string|}
type PrepDeleteFileExpectation = {|method: 'deleteFileAsync', path: string|}
type PrepDeleteFolderExpectation = {|method: 'deleteFolderAsync', path: string|}
type PrepMoveFileExpectation = {|method: 'moveFileAsync', src: string, dst: string|}
type PrepMoveFolderExpectation = {|method: 'moveFolderAsync', src: string, dst: string|}
type PrepPutFolderExpectation = {|method: 'putFolderAsync', path: string|}
type PrepRestoreFileExpectation = {|method: 'restoreFileAsync', dst: string|}
type PrepRestoreFolderExpectation = {|method: 'restoreFolderAsync', dst: string|}
type PrepTrashFileExpectation = {|method: 'trashFileAsync', path: string|}
type PrepTrashFolderExpectation = {|method: 'trashFolderAsync', path: string|}
type PrepUpdateFileExpectation = {|method: 'updateFileAsync', path: string|}

type PrepExpectation
  = PrepAddFileExpectation
  | PrepDeleteFileExpectation
  | PrepDeleteFolderExpectation
  | PrepMoveFileExpectation
  | PrepMoveFolderExpectation
  | PrepPutFolderExpectation
  | PrepRestoreFileExpectation
  | PrepRestoreFolderExpectation
  | PrepTrashFileExpectation
  | PrepTrashFolderExpectation
  | PrepUpdateFileExpectation

export type Scenario = {|
  noremote?: true,
  init?: Array<{|
    ino: number, path: string
  |}>,
  actions: Array<FSAction>,
  expected: {|
    prepCalls?: Array<PrepExpectation>,
    tree?: Array<string>,
    remoteTrash?: Array<string>
  |}
|}
*/
<commit_msg>test/scenarios: Missing init[].content definition<commit_after>/* @flow */

/*::
type FSAddDirAction = {|type: 'mkdir', path: string|}
type FSAddFileAction = {|type: '>', path: string|}
type FSDeleteAction = {|type: 'delete', path: string|}
type FSMoveAction = {|type: 'mv', src: string, dst: string|}
type FSRestoreAction = {|type: 'restore', pathInTrash: string|}
type FSTrashAction = {|type: 'trash', path: string|}
type FSUpdateFileAction = {|type: '>>'|}
type FSWaitAction = {|type: 'wait', ms: number|}

type FSAction
  = FSAddDirAction
  | FSAddFileAction
  | FSDeleteAction
  | FSMoveAction
  | FSRestoreAction
  | FSTrashAction
  | FSUpdateFileAction
  | FSWaitAction

type PrepAddFileExpectation = {|method: 'addFileAsync', path: string|}
type PrepDeleteFileExpectation = {|method: 'deleteFileAsync', path: string|}
type PrepDeleteFolderExpectation = {|method: 'deleteFolderAsync', path: string|}
type PrepMoveFileExpectation = {|method: 'moveFileAsync', src: string, dst: string|}
type PrepMoveFolderExpectation = {|method: 'moveFolderAsync', src: string, dst: string|}
type PrepPutFolderExpectation = {|method: 'putFolderAsync', path: string|}
type PrepRestoreFileExpectation = {|method: 'restoreFileAsync', dst: string|}
type PrepRestoreFolderExpectation = {|method: 'restoreFolderAsync', dst: string|}
type PrepTrashFileExpectation = {|method: 'trashFileAsync', path: string|}
type PrepTrashFolderExpectation = {|method: 'trashFolderAsync', path: string|}
type PrepUpdateFileExpectation = {|method: 'updateFileAsync', path: string|}

type PrepExpectation
  = PrepAddFileExpectation
  | PrepDeleteFileExpectation
  | PrepDeleteFolderExpectation
  | PrepMoveFileExpectation
  | PrepMoveFolderExpectation
  | PrepPutFolderExpectation
  | PrepRestoreFileExpectation
  | PrepRestoreFolderExpectation
  | PrepTrashFileExpectation
  | PrepTrashFolderExpectation
  | PrepUpdateFileExpectation

export type Scenario = {|
  noremote?: true,
  init?: Array<{|
    ino: number, path: string, content?: string
  |}>,
  actions: Array<FSAction>,
  expected: {|
    prepCalls?: Array<PrepExpectation>,
    tree?: Array<string>,
    remoteTrash?: Array<string>
  |}
|}
*/
<|endoftext|>


<commit_before>Package.describe({
	summary: "Flipbox plugin for Semantic-UI. An alternative to checkbox/toggle/slider for offering two options.",
  	version: "1.0.0",
  	git: "https://github.com/richsilv/meteor-semantic-flipbox.git"
});

Package.on_use(function (api) {
 	api.versionsFrom("METEOR@0.9.1");
	api.use('jquery', 'client');

	api.add_files('client/flipbox.css', 'client');
	api.add_files('client/flipbox.js', 'client');
});<commit_msg>minor amendments<commit_after>Package.describe({
	summary: "Flipbox plugin for Semantic-UI. An alternative to checkbox/toggle/slider for offering two options.",
  	version: "1.0.1",
  	git: "https://github.com/richsilv/meteor-semantic-flipbox.git"
});

Package.on_use(function (api) {
 	api.versionsFrom("METEOR@0.9.1");
	api.use('jquery', 'client');

	api.add_files('client/flipbox.css', 'client');
	api.add_files('client/flipbox.js', 'client');
});<|endoftext|>