<commit_before>module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        concat: {
            options: {
                separator: '\n'
            },
            dist: {
                src: [
                    "src/cli_header.js",
                    "src/class_system.js",
                    "src/datatypes.js",
                    "src/util.js",
                    "src/head.js",
                    "src/geometry.js",
                    "src/feature.js",
                    "src/dumpers.js",
                    "src/parser.js",
                    "src/cli.js"
                ],
                dest: 'dist/<%= pkg.name %>.js'
            },
            lite: {
                src: [
                    "src/class_system.js",
                    "src/util.js",
                    "src/head.js",
                    "src/geometry.js",
                    "src/feature.js",
                    "src/dumpers.js",
                    "src/parser.js"
                ],
                dest: 'dist/<%= pkg.name %>_lite.js'
            }
        },
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
            },
            dist: {
                files: {
                    'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
                }
            },
            lite: {
                files: {
                    'dist/<%= pkg.name %>_lite.min.js': ['<%= concat.lite.dest %>']
                }
            }
        },

        jshint: {
            files: ['gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
            options: {
                // options here to override JSHint defaults
                globals: {
                    jQuery: true,
                    console: true,
                    module: true,
                    document: true
                }
            }
        },
        buster: {
            test: {
                server: {
                    port: 1112
                }
            }
        },
        watch: {
            files: ['<%= jshint.files %>'],
            tasks: ['buster', 'default']
        }
    });

    grunt.loadNpmTasks('grunt-contrib-uglify');

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-buster');

    grunt.registerTask('default', ['concat', 'uglify']);

};
<commit_msg>add cli support to sosi_lite<commit_after>module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        concat: {
            options: {
                separator: '\n'
            },
            dist: {
                src: [
                    "src/cli_header.js",
                    "src/class_system.js",
                    "src/datatypes.js",
                    "src/util.js",
                    "src/head.js",
                    "src/geometry.js",
                    "src/feature.js",
                    "src/dumpers.js",
                    "src/parser.js",
                    "src/cli.js"
                ],
                dest: 'dist/<%= pkg.name %>.js'
            },
            lite: {
                src: [
                    "src/cli_header.js",
                    "src/class_system.js",
                    "src/util.js",
                    "src/head.js",
                    "src/geometry.js",
                    "src/feature.js",
                    "src/dumpers.js",
                    "src/parser.js",
                    "src/cli.js"
                ],
                dest: 'dist/<%= pkg.name %>_lite.js'
            }
        },
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
            },
            dist: {
                files: {
                    'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
                }
            },
            lite: {
                files: {
                    'dist/<%= pkg.name %>_lite.min.js': ['<%= concat.lite.dest %>']
                }
            }
        },

        jshint: {
            files: ['gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
            options: {
                // options here to override JSHint defaults
                globals: {
                    jQuery: true,
                    console: true,
                    module: true,
                    document: true
                }
            }
        },
        buster: {
            test: {
                server: {
                    port: 1112
                }
            }
        },
        watch: {
            files: ['<%= jshint.files %>'],
            tasks: ['buster', 'default']
        }
    });

    grunt.loadNpmTasks('grunt-contrib-uglify');

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-buster');

    grunt.registerTask('default', ['concat', 'uglify']);

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        concat: {
            options: {
                // define a string to put between each file in the concatenated output
                //separator: ';'
            },
            dist: {
                // the files to concatenate
                src: ['src/core.js',
                      'src/ext/*.js',
                      'src/lib/*.js',
                      'src/lib/initializer/*.js',
                      'src/lib/zone/*.js',
                      'src/lib/assetProvider/*.js',
                      'src/ui.core.js',
                      'src/engine/*.js'],
                // the location of the resulting JS file
                dest: 'dist/<%= pkg.name %>.js'
            }
        },
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
            },
            build: {
                src: 'dist/<%= pkg.name %>.js',
                dest: 'dist/<%= pkg.name %>.min.js'
            }
        },
        jshint: {
            // define the files to lint
            files: ['Gruntfile.js', 'src/*.js'],
            // configure JSHint (documented at http://www.jshint.com/docs/)
            options: {
                // more options here if you want to override JSHint defaults
                globals: {
                    jQuery: true,
                    console: true,
                    module: true
                }
            }
        }
    });
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.registerTask('default', ['concat','uglify']);
    grunt.registerTask('test', ['jshint']);
};
<commit_msg>Modifier and ModifierProvider classes added to the compilation.<commit_after>module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        concat: {
            options: {
                // define a string to put between each file in the concatenated output
                //separator: ';'
            },
            dist: {
                // the files to concatenate
                src: ['src/core.js',
                      'src/ext/*.js',
                      'src/lib/*.js',
                      'src/lib/initializer/*.js',
                      'src/lib/zone/*.js',
                      'src/lib/assetProvider/*.js',
                      'src/lib/modifierProvider/*.js',
                      'src/lib/modifier/*.js',
                      'src/ui.core.js',
                      'src/engine/*.js'],
                // the location of the resulting JS file
                dest: 'dist/<%= pkg.name %>.js'
            }
        },
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
            },
            build: {
                src: 'dist/<%= pkg.name %>.js',
                dest: 'dist/<%= pkg.name %>.min.js'
            }
        },
        jshint: {
            // define the files to lint
            files: ['Gruntfile.js', 'src/*.js'],
            // configure JSHint (documented at http://www.jshint.com/docs/)
            options: {
                // more options here if you want to override JSHint defaults
                globals: {
                    jQuery: true,
                    console: true,
                    module: true
                }
            }
        }
    });
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.registerTask('default', ['concat','uglify']);
    grunt.registerTask('test', ['jshint']);
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

/*!
 * Vitaé®
 * Curriculum Vitaé of Prabhat Kumar — CEO, Founder & Scientist.
 * ___________________________________________________________________________
 *
 * Grunt, http://gruntjs.com/ — The JavaScript Task Runner.
 * ___________________________________________________________________________
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * ___________________________________________________________________________
 *
 * @date      : 30-Nov-2016
 * @license   : MIT
 * @require   : Node.js®
 * @require   : NPM
 * @require   : grunt-cli
 * @build     : SEED™ — Umeå
 *              └────── A Sequømics Product — http://sequomics.com/.
 * ___________________________________________________________________________
 *
 * --/The Heart of Build System/-- of "Vitaé®".
 * ___________________________________________________________________________
 */

// # Usage: $ node -v
// # Usage: $ npm -v
// # Usage: $ grunt -version

// Invoking strict mode.
// @purpose: Strict mode applies to entire scripts or to individual functions.
"use strict";

// To load required NPM modules.
// -----------------------------
var chalk    = require('chalk');
var glob     = require('glob');

///-------------------
// An object literals.
///-------------------
var build = {
  // Nonidentifier property names are quoted.
  "system"    : "SEED™",
  "name"      : "Umeå",
  "year"      : "2016",
  "audience"  : "for all designer and scientist."
};

// Global variables.
// -----------------
var rootPath = './';
var appsPath = './app/';

// Default color defined.
// ----------------------
var noop     = chalk.red;
var yeep     = chalk.green;
var okay     = chalk.blue;

// To get 'version', i.e. required to work on
// SEED™: Grunt based build system. | See: http://seed.sequomics.com/.
var version = process.env.VERSION || require('./package.json').version;

///------------------------
// A smart banner function.
///------------------------
var banner = [
  '/*!                                                                                ',
  ' * Build System — ' + yeep(build.system) + ': ' + okay(build.name) + ' — ' + version                  ,
  ' * ' + noop(build.audience)                                                                           ,
  ' * ---------------------------------------------------------------------------                       ',
  ' * Copyright © 2015 - ' + new Date().getFullYear() + ', Sequømics Corporation, All rights reserved.  ',
  ' * Available via the Apache, version 2.0. [http://www.apache.org/licenses/]                          ',
  ' * See: http://seed.sequomics.com/ — for details.                                                    ',
  ' * ---------------------------------------------------------------------------                       ',
  ' */                                                                                ',
  '\n',
].map(function(s) {
  return s.replace(/\s+$/, '');
}).join("\n");

// ----------------------------------------------------------------------------------------------------------
// All Grunt Operations Defined... |--------------------------------------------| 30/Nov/2016 | SEED™ — Umeå.
//                           Copyright © 2016, Prabhat Kumar, All rights reserved.
// ----------------------------------------------------------------------------------------------------------

module.exports = function(grunt) {

  // Force use of Unix newlines.
  grunt.util.linefeed = '\n';

  // 1. time-grunt ——> $ npm install time-grunt --save-dev
  // -----------------------------------------------------
  // Display the elapsed execution time of grunt tasks.
  require('time-grunt')(grunt);

  // Utility to load the different option files,
  // based on their names.
  function loadConfig(path) {
    var object = {};
    var key;

    glob.sync('*', {
      cwd: path
    }).forEach(function(option) {
      key = option.replace(/\.js$/,'');
      object[key] = require(path + option);
    });
    return object;
  }

  /// Initial Configurations.
  var config = {
    pkg: grunt.file.readJSON('./package.json')
  };
<commit_msg>Initial commit<commit_after>#!/usr/bin/env node

/*!
 * Vitaé®
 * Curriculum Vitaé of Prabhat Kumar — CEO, Founder & Scientist.
 * ___________________________________________________________________________
 *
 * Grunt, http://gruntjs.com/ — The JavaScript Task Runner.
 * ___________________________________________________________________________
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * ___________________________________________________________________________
 *
 * @date      : 30-Nov-2016
 * @license   : MIT
 * @require   : Node.js®
 * @require   : NPM
 * @require   : grunt-cli
 * @build     : SEED™ — Umeå
 *              └────── A Sequømics Product — http://sequomics.com/.
 * ___________________________________________________________________________
 *
 * --/The Heart of Build System/-- of "Vitaé®".
 * ___________________________________________________________________________
 */

// # Usage: $ node -v
// # Usage: $ npm -v
// # Usage: $ grunt -version

// Invoking strict mode.
// @purpose: Strict mode applies to entire scripts or to individual functions.
"use strict";

// To load required NPM modules.
// -----------------------------
var chalk    = require('chalk');
var glob     = require('glob');

///-------------------
// An object literals.
///-------------------
var build = {
  // Nonidentifier property names are quoted.
  "system"    : "SEED™",
  "name"      : "Umeå",
  "year"      : "2016",
  "audience"  : "for all designer and scientist."
};

// Global variables.
// -----------------
var rootPath = './';
var appsPath = './app/';

// Default color defined.
// ----------------------
var noop     = chalk.red;
var yeep     = chalk.green;
var okay     = chalk.blue;

// To get 'version', i.e. required to work on
// SEED™: Grunt based build system. | See: http://seed.sequomics.com/.
var version = process.env.VERSION || require('./package.json').version;

///------------------------
// A smart banner function.
///------------------------
var banner = [
  '/*!                                                                                ',
  ' * Build System — ' + yeep(build.system) + ': ' + okay(build.name) + ' — ' + version                  ,
  ' * ' + noop(build.audience)                                                                           ,
  ' * ---------------------------------------------------------------------------                       ',
  ' * Copyright © 2015 - ' + new Date().getFullYear() + ', Sequømics Corporation, All rights reserved.  ',
  ' * Available via the Apache, version 2.0. [http://www.apache.org/licenses/]                          ',
  ' * See: http://seed.sequomics.com/ — for details.                                                    ',
  ' * ---------------------------------------------------------------------------                       ',
  ' */                                                                                ',
  '\n',
].map(function(s) {
  return s.replace(/\s+$/, '');
}).join("\n");

// ----------------------------------------------------------------------------------------------------------
// All Grunt Operations Defined... |--------------------------------------------| 30/Nov/2016 | SEED™ — Umeå.
//                           Copyright © 2016, Prabhat Kumar, All rights reserved.
// ----------------------------------------------------------------------------------------------------------

module.exports = function(grunt) {

  // Force use of Unix newlines.
  grunt.util.linefeed = '\n';

  // 1. time-grunt ——> $ npm install time-grunt --save-dev
  // -----------------------------------------------------
  // Display the elapsed execution time of grunt tasks.
  require('time-grunt')(grunt);

  // Utility to load the different option files,
  // based on their names.
  function loadConfig(path) {
    var object = {};
    var key;

    glob.sync('*', {
      cwd: path
    }).forEach(function(option) {
      key = option.replace(/\.js$/,'');
      object[key] = require(path + option);
    });
    return object;
  }

  /// Initial Configurations.
  var config = {
    pkg: grunt.file.readJSON('./package.json')
  };

  /// Loading Externally-Defined Tasks.
  /// http://gruntjs.com/api/grunt
  grunt.loadTasks('tasks');
<|endoftext|>


<commit_before>#!/usr/bin/env node

var adventure = require('adventure');
var shop = adventure('javascript-adventure');

var problems = [ '01_Hello_World', '02_Functions' ];
problems.forEach(function (prob) {
    shop.add(prob.replace(/_/g, ' '), function () { return require('./problems/' + prob.toLowerCase())});
});

shop.execute(process.argv.slice(2));
<commit_msg>Update path<commit_after>#!/usr/bin/env node

var adventure = require('adventure');
var shop = adventure('javascript-adventure');
var path = require('path');

var problems = [ '01_Hello_World', '02_Functions' ];
problems.forEach(function (prob) {
    shop.add(prob.replace(/_/g, ' '), function () {
        return require(path.join(__dirname, '/problems/' + prob.toLowerCase()))});
});

shop.execute(process.argv.slice(2));
<|endoftext|>


<commit_before>'use strict';

module.exports = function( grunt ) {

	// https://github.com/tkellen/node-matchdep
	// load all grunt tasks // Filter devDependencies (with config string indicating file to be required)
	require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

	// Project configuration
	// ---------------------

	grunt.initConfig({

		CONFIGS: {
			BUILD: 'build',
			TMP: 'tmp',
			HOSTNAME: 'file:///Users/mma',
			PATH: '<%= CONFIGS.HOSTNAME %>/Desktop/repo/bitbucket/d3.ma/index.html'
		},

		pkg: grunt.file.readJSON('package.json'),

		BANNER: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> \n Author: <%= pkg.author.name %> (<%= pkg.author.email %>)\n*/',

		// https://github.com/gruntjs/grunt-contrib-jshint
		// Validate files with JSHint. it is a multi task
		// https://github.com/cowboy/grunt/blob/master/docs/task_lint.md#specifying-jshint-options-and-globals
		jshint: {
			options: {
				jshintrc: '.jshintrc'
				// force: true,  // Report JSHint errors but not fail the task.
				//
				//A map of global variables, with keys as names and a boolean value to determine if they are assignable.
				// globals:   {
				//   jQuery: true
				// }
			},
			all: [
				'Gruntfile.js',
				'src/**/*.js'
			]
		},

		// https://github.com/gruntjs/grunt-contrib-clean
		// Clean files and folders. always be cautious of the paths you clean.
		clean: {
			options: {
				// force: true
			},
			build: {
				src: [
					'<%= CONFIGS.BUILD %>'
				]
			},
			tmp: {
				src: [
					'<%= CONFIGS.TMP %>'
				]
			}
		},

		// Uglify task does concat
		// https://github.com/gruntjs/grunt-contrib-concat
		concat: {
			options: {
				separator: '', //Concatenated files will be joined on this string.
				banner:  '<%= BANNER %>'
				//footer: STRING  //Appended to the end of the concatenated output.
				//stripBanners: true  //Strip JavaScript banner comments from source files. /* ... */ block comments are stripped, but NOT /*! ... */ comments.
			},
			build: {
				src: [
					'src/intro.js',
					'src/common/core.js',
					'src/common/utils.js',
					'src/common/container.js',
					'src/components/clippath.js',

					'src/core/scale.js',
					'src/core/base.js',

					'src/components/axis.js',

					'src/basic/bars.js',
					'src/basic/line.js',
					'src/basic/area.js',
					'src/basic/circle.js',

					'src/outro.js'
				],
				dest: '<%= CONFIGS.TMP %>/d3.ma.js'
				// nonull: true  // Warn if a given file is missing or invalid
			}
		},

		// https://github.com/gruntjs/grunt-contrib-copy
		copy: {
			build: {
				files: [{
					src: ['<%= CONFIGS.TMP %>/d3.ma.js'],
					dest: '<%= CONFIGS.BUILD %>/d3.ma.js'
				}]
			},
			release: {
				files: [
					{
						expand: true,
						dot: false,   // Enable the dot file when copy
						cwd: '<%= CONFIGS.BUILD %>',
						dest: '',
						src: [
							'*.js'
						]
					}
				]
			}
		},

		// https://github.com/gruntjs/grunt-contrib-uglify
		// Currently is being used by requirejs task, ONLY manual usage
		uglify: {
			options: {
				banner: '<%= BANNER %>',
				report: 'gzip',
				preserveComments: 'false'
			},
			minify: {
				files: [{
					src: ['<%= CONFIGS.BUILD %>/d3.ma.js'],
					dest: '<%= CONFIGS.BUILD %>/d3.ma.min.js'
				}]
			}
		},

		// https://github.com/onehealth/grunt-open
		open: {
			dev: {
				path: '<%= CONFIGS.PATH %>'
			}
		},

		watch: {
			livereload: {
				files: [
					'index.html',
					'src/{,**/}*.js'
				],
				tasks: ['livereload']
			},
			test: {
				files: [
					'src/{,**/}*.js'
				],
				tasks: ['livereload', 'build']
			}
		},

		// https://github.com/karma-runner/grunt-karma
		// @usage  grunt test:karma  or   grunt karma
		// karma.conf.js should work independently, can be called by `karma start`
		// Setting defined here should override the karma.conf.js setting
		// watch task is for running a development, update on file changes
		// single task is running for a single time, output its coverage report
		karma: {
			options: {
				configFile: 'karma.conf.js',
				browsers: ['Firefox'],
				reporters: 'dots'
			},
			watch: {
				options: {
					singleRun: false,
					autoWatch: true
				}
			},
			single: {
				options: {
					singleRun: true,
					autoWatch: false
				}
			}
		},

		concurrent: {
			test: {
				options: {
					logConcurrentOutput: true
				},
				tasks: ['watch:test', 'karma:watch']
			}
		}
	});

	grunt.renameTask('regarde', 'watch');

	// Running Development Environment
	grunt.registerTask('server', function () {

		grunt.task.run([
			'livereload-start',
			'open:dev',
			'watch:livereload'
		]);
	});

	grunt.registerTask('lint', ['jshint']);

	// Running Production Environment
	grunt.registerTask('build', function () {

		grunt.task.run([
			'test:ci',
			'copy:build',
			'uglify'
		]);
	});

	grunt.registerTask('test', [
		'concat',
		'livereload-start',
		'concurrent:test'
	]);

	grunt.registerTask('test:ci', [
		'concat',
		'karma:single'
	]);

	grunt.registerTask('release', [
		'build',
		'copy:release',
		'clean'
	]);

	// grunt.registerMultiTask('log', 'Log stuff.', function() {
	// 	grunt.log.writeln(this.target + ': ' + this.data);
	// });

	grunt.registerTask('default', [ 'build' ]);
};
<commit_msg>update the grunt build, tmp process<commit_after>'use strict';

module.exports = function( grunt ) {

	// https://github.com/tkellen/node-matchdep
	// load all grunt tasks // Filter devDependencies (with config string indicating file to be required)
	require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

	// Project configuration
	// ---------------------

	grunt.initConfig({

		CONFIGS: {
			BUILD: 'build',
			TMP: 'tmp',
			HOSTNAME: 'file:///Users/mma',
			PATH: '<%= CONFIGS.HOSTNAME %>/Desktop/repo/bitbucket/d3.ma/index.html'
		},

		pkg: grunt.file.readJSON('package.json'),

		BANNER: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> \n Author: <%= pkg.author.name %> (<%= pkg.author.email %>)\n*/',

		// https://github.com/gruntjs/grunt-contrib-jshint
		// Validate files with JSHint. it is a multi task
		// https://github.com/cowboy/grunt/blob/master/docs/task_lint.md#specifying-jshint-options-and-globals
		jshint: {
			options: {
				jshintrc: '.jshintrc'
				// force: true,  // Report JSHint errors but not fail the task.
				//
				//A map of global variables, with keys as names and a boolean value to determine if they are assignable.
				// globals:   {
				//   jQuery: true
				// }
			},
			all: [
				'Gruntfile.js',
				'src/**/*.js'
			]
		},

		// https://github.com/gruntjs/grunt-contrib-clean
		// Clean files and folders. always be cautious of the paths you clean.
		clean: {
			options: {
				// force: true
			},
			build: {
				src: [
					'<%= CONFIGS.BUILD %>'
				]
			},
			tmp: {
				src: [
					'<%= CONFIGS.TMP %>'
				]
			}
		},

		// Uglify task does concat
		// https://github.com/gruntjs/grunt-contrib-concat
		concat: {
			options: {
				separator: '', //Concatenated files will be joined on this string.
				banner:  '<%= BANNER %>'
				//footer: STRING  //Appended to the end of the concatenated output.
				//stripBanners: true  //Strip JavaScript banner comments from source files. /* ... */ block comments are stripped, but NOT /*! ... */ comments.
			},
			build: {
				src: [
					'src/intro.js',
					'src/common/core.js',
					'src/common/utils.js',
					'src/common/container.js',
					'src/components/clippath.js',

					'src/core/scale.js',
					'src/core/base.js',

					'src/components/axis.js',

					'src/basic/bars.js',
					'src/basic/line.js',
					'src/basic/area.js',
					'src/basic/circle.js',

					'src/outro.js'
				],
				dest: '<%= CONFIGS.TMP %>/d3.ma.js'
				// nonull: true  // Warn if a given file is missing or invalid
			}
		},

		// https://github.com/gruntjs/grunt-contrib-copy
		copy: {
			build: {
				files: [{
					src: ['<%= CONFIGS.TMP %>/d3.ma.js'],
					dest: '<%= CONFIGS.BUILD %>/d3.ma.js'
				}]
			},
			release: {
				files: [
					{
						expand: true,
						dot: false,   // Enable the dot file when copy
						cwd: '<%= CONFIGS.BUILD %>',
						dest: '',
						src: [
							'*.js'
						]
					}
				]
			}
		},

		// https://github.com/gruntjs/grunt-contrib-uglify
		// Currently is being used by requirejs task, ONLY manual usage
		uglify: {
			options: {
				banner: '<%= BANNER %>',
				report: 'gzip',
				preserveComments: 'false'
			},
			minify: {
				files: [{
					src: ['<%= CONFIGS.BUILD %>/d3.ma.js'],
					dest: '<%= CONFIGS.BUILD %>/d3.ma.min.js'
				}]
			}
		},

		// https://github.com/onehealth/grunt-open
		open: {
			dev: {
				path: '<%= CONFIGS.PATH %>'
			}
		},

		watch: {
			livereload: {
				files: [
					'index.html',
					'src/{,**/}*.js'
				],
				tasks: ['livereload']
			},
			test: {
				files: [
					'src/{,**/}*.js'
				],
				tasks: ['livereload', 'build']
			}
		},

		// https://github.com/karma-runner/grunt-karma
		// @usage  grunt test:karma  or   grunt karma
		// karma.conf.js should work independently, can be called by `karma start`
		// Setting defined here should override the karma.conf.js setting
		// watch task is for running a development, update on file changes
		// single task is running for a single time, output its coverage report
		karma: {
			options: {
				configFile: 'karma.conf.js',
				browsers: ['Firefox'],
				reporters: 'dots'
			},
			watch: {
				options: {
					singleRun: false,
					autoWatch: true
				}
			},
			single: {
				options: {
					singleRun: true,
					autoWatch: false
				}
			}
		},

		concurrent: {
			test: {
				options: {
					logConcurrentOutput: true
				},
				tasks: ['watch:test', 'karma:watch']
			}
		}
	});

	grunt.renameTask('regarde', 'watch');

	// Running Development Environment
	grunt.registerTask('server', function () {

		grunt.task.run([
			'livereload-start',
			'open:dev',
			'watch:livereload'
		]);
	});

	grunt.registerTask('lint', ['jshint']);

	// Running Production Environment
	grunt.registerTask('build', function () {

		grunt.task.run([
			'test:ci',
			'copy:build',
			'uglify',
			'clean:tmp'
		]);
	});

	grunt.registerTask('test', [
		'concat',
		'livereload-start',
		'concurrent:test'
	]);

	grunt.registerTask('test:ci', [
		'concat',
		'karma:single'
	]);

	grunt.registerTask('release', [
		'build',
		'copy:release',
		'clean:build'
	]);

	// grunt.registerMultiTask('log', 'Log stuff.', function() {
	// 	grunt.log.writeln(this.target + ': ' + this.data);
	// });

	grunt.registerTask('default', [ 'build' ]);
};
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const util = require('util');
const puppeteer = require('puppeteer');

function initMocha(reporter) {

    console.log = (console => {
        const log = console.log.bind(console);
        return (...args) => args.length ? log(...args) : log('');
    })(console);

    function shimMochaInstance(m) {

        m.setup({ reporter: Mocha.reporters[reporter] || Mocha.reporters.spec });

        const run = m.run.bind(m);

        m.run = () => {
            const all = [], pending = [], failures = [], passes = [];

            function error(err) {
                if (!err) return {};

                let res = {};
                Object.getOwnPropertyNames(err).forEach(key => res[key] = err[key]);
                return res;
            }

            function clean(test) {
                return {
                    title: test.title,
                    fullTitle: test.fullTitle(),
                    duration: test.duration,
                    err: error(test.err)
                };
            }

            function result(stats) {
                return {
                    result: {
                        stats: {
                            tests: all.length,
                            passes: passes.length,
                            pending: pending.length,
                            failures: failures.length,
                            start: stats.start.toISOString(),
                            end: stats.end.toISOString(),
                            duration: stats.duration
                        },
                        tests: all.map(clean),
                        pending: pending.map(clean),
                        failures: failures.map(clean),
                        passes: passes.map(clean)
                    },
                    coverage: window.__coverage__
                };
            }

            function setResult() {
                window.__mochaResult__ = result(this.stats);
            }

            const runner = run(() => setTimeout(() => setResult.call(runner), 0))
                .on('pass', test => { passes.push(test); all.push(test); })
                .on('fail', test => { failures.push(test); all.push(test); })
                .on('pending', test => { pending.push(test); all.push(test); });

            return runner;
        };
    }

    function shimMochaProcess(M) {
        // Mocha needs a process.stdout.write in order to change the cursor position.
        !M.process && (M.process = {});
        !M.process.stdout && (M.process.stdout = {});

        M.process.stdout.write = data => console.log('stdout:', data);
        M.reporters.Base.useColors = true;
        M.reporters.none = function None(runner) {
            M.reporters.Base.call(this, runner);
        };
    }

    Object.defineProperty(window, 'mocha', {
        get: function() { return undefined },
        set: function(m) {
            shimMochaInstance(m);
            delete window.mocha;
            window.mocha = m
        },
        configurable: true
    })

    Object.defineProperty(window, 'Mocha', {
        get: function() { return undefined },
        set: function(m) {
            shimMochaProcess(m);
            delete window.Mocha;
            window.Mocha = m;
        },
        configurable: true
    });
}

function configureViewport(width, height, page) {
    if (!width && !height) return page;

    let viewport = page.viewport();
    width && (viewport.width = width);
    height && (viewport.height = height);

    return page.setViewport(viewport).then(() => page);
}

function handleConsole({ args }) {
    Promise.all(args.map(a => a.jsonValue()))
        .then(args => {
            // process stdout stub
            let isStdout = args[0] === 'stdout:';
            isStdout && (args = args.slice(1));
            //
            let msg = util.format(...args);
            !isStdout && (msg += '\n');
            process.stdout.write(msg);
        });
}

function prepareUrl(filePath) {
    if (/^[a-zA-Z]+:\/\//.test(filePath)) {
        // path is URL
        return filePath;
    }

    // local path
    let resolvedPath = path.resolve(filePath);
    return `file://${resolvedPath}`;
}

module.exports = function ({ file, reporter, timeout, width, height, args, executablePath, visible }) {
    return new Promise(resolve => {

        // validate options
        if (!file) {
            throw new Error('Test page path is required.');
        }

        args = [].concat(args || []).map(arg => '--' + arg);
        !timeout && (timeout = 60000);

        const url = prepareUrl(file);

        const options = {
            ignoreHTTPSErrors: true,
            headless: !visible,
            executablePath,
            args
        };

        const result = puppeteer
            .launch(options)
            .then(browser => browser.newPage()
                .then(configureViewport.bind(this, width, height))
                .then(page => {
                    page.on('console', handleConsole);
                    page.on('dialog', dialog => dialog.dismiss());
                    page.on('pageerror', err => console.error(err));

                    return page.evaluateOnNewDocument(initMocha, reporter)
                        .then(() => page.goto(url))
                        .then(() => page.waitForFunction(() => window.__mochaResult__, { timeout: timeout }))
                        .then(() => page.evaluate(() => window.__mochaResult__))
                        .then(obj => {
                            browser.close();
                            return obj;
                        });
                }));

        resolve(result);
    });
};
<commit_msg>fix empty result bug<commit_after>'use strict';

const path = require('path');
const util = require('util');
const puppeteer = require('puppeteer');

function initMocha(reporter) {

    console.log = (console => {
        const log = console.log.bind(console);
        return (...args) => args.length ? log(...args) : log('');
    })(console);

    function shimMochaInstance(m) {

        m.setup({ reporter: Mocha.reporters[reporter] || Mocha.reporters.spec });

        const run = m.run.bind(m);

        m.run = () => {
            const all = [], pending = [], failures = [], passes = [];

            function error(err) {
                if (!err) return {};

                let res = {};
                Object.getOwnPropertyNames(err).forEach(key => res[key] = err[key]);
                return res;
            }

            function clean(test) {
                return {
                    title: test.title,
                    fullTitle: test.fullTitle(),
                    duration: test.duration,
                    err: error(test.err)
                };
            }

            function result(stats) {
                return {
                    result: {
                        stats: {
                            tests: all.length,
                            passes: passes.length,
                            pending: pending.length,
                            failures: failures.length,
                            start: stats.start.toISOString(),
                            end: stats.end.toISOString(),
                            duration: stats.duration
                        },
                        tests: all.map(clean),
                        pending: pending.map(clean),
                        failures: failures.map(clean),
                        passes: passes.map(clean)
                    },
                    coverage: window.__coverage__
                };
            }

            function setResult() {
                !window.__mochaResult__ && (window.__mochaResult__ = result(this.stats));
            }

            const runner = run(() => setTimeout(() => setResult.call(runner), 0))
                .on('pass', test => { passes.push(test); all.push(test); })
                .on('fail', test => { failures.push(test); all.push(test); })
                .on('pending', test => { pending.push(test); all.push(test); })
                .on('end', setResult);

            return runner;
        };
    }

    function shimMochaProcess(M) {
        // Mocha needs a process.stdout.write in order to change the cursor position.
        !M.process && (M.process = {});
        !M.process.stdout && (M.process.stdout = {});

        M.process.stdout.write = data => console.log('stdout:', data);
        M.reporters.Base.useColors = true;
        M.reporters.none = function None(runner) {
            M.reporters.Base.call(this, runner);
        };
    }

    Object.defineProperty(window, 'mocha', {
        get: function() { return undefined },
        set: function(m) {
            shimMochaInstance(m);
            delete window.mocha;
            window.mocha = m
        },
        configurable: true
    })

    Object.defineProperty(window, 'Mocha', {
        get: function() { return undefined },
        set: function(m) {
            shimMochaProcess(m);
            delete window.Mocha;
            window.Mocha = m;
        },
        configurable: true
    });
}

function configureViewport(width, height, page) {
    if (!width && !height) return page;

    let viewport = page.viewport();
    width && (viewport.width = width);
    height && (viewport.height = height);

    return page.setViewport(viewport).then(() => page);
}

function handleConsole({ args }) {
    Promise.all(args.map(a => a.jsonValue()))
        .then(args => {
            // process stdout stub
            let isStdout = args[0] === 'stdout:';
            isStdout && (args = args.slice(1));
            //
            let msg = util.format(...args);
            !isStdout && (msg += '\n');
            process.stdout.write(msg);
        });
}

function prepareUrl(filePath) {
    if (/^[a-zA-Z]+:\/\//.test(filePath)) {
        // path is URL
        return filePath;
    }

    // local path
    let resolvedPath = path.resolve(filePath);
    return `file://${resolvedPath}`;
}

module.exports = function ({ file, reporter, timeout, width, height, args, executablePath, visible }) {
    return new Promise(resolve => {

        // validate options
        if (!file) {
            throw new Error('Test page path is required.');
        }

        args = [].concat(args || []).map(arg => '--' + arg);
        !timeout && (timeout = 60000);

        const url = prepareUrl(file);

        const options = {
            ignoreHTTPSErrors: true,
            headless: !visible,
            executablePath,
            args
        };

        const result = puppeteer
            .launch(options)
            .then(browser => browser.newPage()
                .then(configureViewport.bind(this, width, height))
                .then(page => {
                    page.on('console', handleConsole);
                    page.on('dialog', dialog => dialog.dismiss());
                    page.on('pageerror', err => console.error(err));

                    return page.evaluateOnNewDocument(initMocha, reporter)
                        .then(() => page.goto(url))
                        .then(() => page.waitForFunction(() => window.__mochaResult__, { timeout: timeout }))
                        .then(() => page.evaluate(() => window.__mochaResult__))
                        .then(obj => {
                            browser.close();
                            return obj;
                        });
                }));

        resolve(result);
    });
};
<|endoftext|>


<commit_before>const Command = require("../base/Command");
const moment = require("moment");
require("moment-duration-format");

class CheckAct extends Command {
    constructor(Bot) {
        super(Bot, {
            name: "checkactivity",
            aliases: ["activity", "check", "ca"],
            guildOnly: true,
            permLevel: 3,
            category: "Admin",
            flags: {},
            subArgs: {
                sort: {         // Sort by name or time
                    aliases: []
                },
                time: {         // Filter based on them being inactive past x hours
                    aliases: ["hour", "hours"]
                },
                role: {         // Filter the list to a single role
                    aliases: []
                },
                // ingame: {       // Show the last active times based on their in-game lastActivity
                //     aliases: ["ig"]
                // }
            }
        });
    }

    async run(Bot, message, args, options) {
        if (!message.guildSettings.useActivityLog) {
            return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NOT_ACTIVE"));
        }

        let userID = args[0];
        let activityLog = await Bot.cache.get(Bot.config.mongodb.swgohbotdb, "activityLog", {guildID: message.guild.id});
        if (Array.isArray(activityLog)) activityLog = activityLog[0];
        if (!userID) {
            // List everything for that server (With limitations)
            let objArr = Object.keys(activityLog.log).map(u => {
                return {
                    user: u,
                    time: activityLog.log[u]
                };
            });
            for (const u of objArr) {
                const user = await message.guild.members.get(u.user);
                if (!user || user.user.bot) {
                    u.user = null;
                } else {
                    u.user = Bot.truncate(user.nickname ? user.nickname : user.user.username, 20);
                    u.roles = user.roles;
                }
            }
            // Remove any bots
            objArr = objArr.filter(u => u.user !== null);
            if (options.subArgs.time && !isNaN(options.subArgs.time)) {
                // Convert the time from hours to milliseconds
                //                                   ms    sec  min
                const time = options.subArgs.time * 1000 * 60 * 60;
                // Filter out anyone that has been inactive for longer than x hours
                objArr = objArr.filter(u => {
                    const diff = moment().diff(moment(u.time));
                    return diff >= time;
                });
            }
            if (options.subArgs.role && options.subArgs.role.length > 0) {
                // Filter out anyone that does not have the specified role (Name or mention/ id)
                const roleNId = options.subArgs.role;
                // Try finding by ID first
                let role = message.guild.roles.get(roleNId.replace(/[^0-9]/gi, ""));
                if (!role) {
                    // If it can't find the role by ID, try by name
                    role = message.guild.roles.find(r => r.name === roleNId);
                }
                if (!role) {
                    // If it can't find it by role or name, error
                    return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_ROLE", roleNId));
                }
                // Now that we have a role, filter out anyone that doens't have it
                objArr = objArr.filter(u => {
                    const outRole = u.roles.find(r => r.id === role.id);
                    return !outRole ? false : true;
                });
            }
            if (options.subArgs.sort && options.subArgs.sort.toLowerCase() === "name") {
                // If they want to sort by name, do so
                objArr = objArr.sort((a, b) => a.user.toLowerCase() > b.user.toLowerCase() ? 1 : -1);
            } else {
                // Otherwise, sort by how recently they've been on
                objArr = objArr.sort((a, b) => b.time - a.time);
            }
            // If there's no one left after filtering everyone out, let em know
            if (!objArr.length) return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_MATCH"), {title: message.language.get("COMMAND_CHECKACTIVITY_NO_MATCH_TITLE")});
            // Convert the time from a unix-format time string into something human readable
            objArr = objArr.map(u => {
                u.time = getTime(moment().diff(moment(u.time)), true);
                return u;
            });

            // Limit it to 50 people if there are more
            if (objArr.length > 50) {
                objArr = objArr.slice(0, 100);
            }

            // Format the output into a table so it looks nice
            const headerValues = message.language.get("COMMAND_CHECKACTIVITY_TABLE_HEADERS");
            const outArr = Bot.makeTable({
                user: {value: headerValues.user, startWith: "`", endWith: "|", align: "left"},
                time: {value: headerValues.time, endWith: "`"}
            }, objArr);

            const fields = Bot.msgArray(outArr, "\n", 700).map(m => {
                return {name: "-", value: m};
            });

            const desc = fields.shift();
            return message.channel.send({embed: {
                author: {name: message.language.get("COMMAND_CHECKACTIVITY_LOG_HEADER", message.guild.name, objArr.length)},
                description: desc.value,
                fields: fields,
                color: 0x00FF00
            }});
        } else {
            // Make sure it's a valid userID
            if (!Bot.isUserID(userID)) {
                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_INVALID_USER"));
            }
            userID = Bot.getUserID(userID);
            const user = message.guild.members.get(userID);
            const name = user.nickname ? user.nickname : user.user.username;
            // Try and check the activity for just one user
            if (activityLog.log[userID]) {
                // Spit out user's last activity
                const lastActive = activityLog.log[userID];
                const diff = moment().diff(moment(lastActive));

                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_USER_CHECK", name, getTime(diff)), {title: message.language.get("COMMAND_CHECKACTIVITY_USER_CHECK_HEADER"), color: 0x00FF00});
            } else {
                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_USER"));
            }
        }
        function getTime(diff, numOnly) {
            const days = 1000 * 60 * 60 * 24;
            const hours= 1000 * 60 * 60;
            const mins = 1000 * 60;

            let out = diff / days;
            if (out > 1) {
                return (out < 10 ? " " : "") + out.toFixed(1) + (numOnly ? "d" : " days");
            }
            out = diff / hours;
            if (out > 1) {
                return (out < 10 ? " " : "") + out.toFixed(1) + (numOnly ? "h" : " hours");
            }
            out = diff / mins;
            return (out < 10 ? "   " : "  ") + parseInt(out) + (numOnly ? "m" : " minutes");
        }
    }
}

module.exports = CheckAct;

<commit_msg>Added -t as a new alias for time in checkact<commit_after>const Command = require("../base/Command");
const moment = require("moment");
require("moment-duration-format");

class CheckAct extends Command {
    constructor(Bot) {
        super(Bot, {
            name: "checkactivity",
            aliases: ["activity", "check", "ca"],
            guildOnly: true,
            permLevel: 3,
            category: "Admin",
            flags: {},
            subArgs: {
                sort: {         // Sort by name or time
                    aliases: []
                },
                time: {         // Filter based on them being inactive past x hours
                    aliases: ["t", "hour", "hours"]
                },
                role: {         // Filter the list to a single role
                    aliases: []
                },
                // ingame: {       // Show the last active times based on their in-game lastActivity
                //     aliases: ["ig"]
                // }
            }
        });
    }

    async run(Bot, message, args, options) {
        if (!message.guildSettings.useActivityLog) {
            return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NOT_ACTIVE"));
        }

        let userID = args[0];
        let activityLog = await Bot.cache.get(Bot.config.mongodb.swgohbotdb, "activityLog", {guildID: message.guild.id});
        if (Array.isArray(activityLog)) activityLog = activityLog[0];
        if (!userID) {
            // List everything for that server (With limitations)
            let objArr = Object.keys(activityLog.log).map(u => {
                return {
                    user: u,
                    time: activityLog.log[u]
                };
            });
            for (const u of objArr) {
                const user = await message.guild.members.get(u.user);
                if (!user || user.user.bot) {
                    u.user = null;
                } else {
                    u.user = Bot.truncate(user.nickname ? user.nickname : user.user.username, 20);
                    u.roles = user.roles;
                }
            }
            // Remove any bots
            objArr = objArr.filter(u => u.user !== null);
            if (options.subArgs.time && !isNaN(options.subArgs.time)) {
                // Convert the time from hours to milliseconds
                //                                   ms    sec  min
                const time = options.subArgs.time * 1000 * 60 * 60;
                // Filter out anyone that has been inactive for longer than x hours
                objArr = objArr.filter(u => {
                    const diff = moment().diff(moment(u.time));
                    return diff >= time;
                });
            }
            if (options.subArgs.role && options.subArgs.role.length > 0) {
                // Filter out anyone that does not have the specified role (Name or mention/ id)
                const roleNId = options.subArgs.role;
                // Try finding by ID first
                let role = message.guild.roles.get(roleNId.replace(/[^0-9]/gi, ""));
                if (!role) {
                    // If it can't find the role by ID, try by name
                    role = message.guild.roles.find(r => r.name === roleNId);
                }
                if (!role) {
                    // If it can't find it by role or name, error
                    return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_ROLE", roleNId));
                }
                // Now that we have a role, filter out anyone that doens't have it
                objArr = objArr.filter(u => {
                    const outRole = u.roles.find(r => r.id === role.id);
                    return !outRole ? false : true;
                });
            }
            if (options.subArgs.sort && options.subArgs.sort.toLowerCase() === "name") {
                // If they want to sort by name, do so
                objArr = objArr.sort((a, b) => a.user.toLowerCase() > b.user.toLowerCase() ? 1 : -1);
            } else {
                // Otherwise, sort by how recently they've been on
                objArr = objArr.sort((a, b) => b.time - a.time);
            }
            // If there's no one left after filtering everyone out, let em know
            if (!objArr.length) return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_MATCH"), {title: message.language.get("COMMAND_CHECKACTIVITY_NO_MATCH_TITLE")});
            // Convert the time from a unix-format time string into something human readable
            objArr = objArr.map(u => {
                u.time = getTime(moment().diff(moment(u.time)), true);
                return u;
            });

            // Limit it to 50 people if there are more
            if (objArr.length > 50) {
                objArr = objArr.slice(0, 100);
            }

            // Format the output into a table so it looks nice
            const headerValues = message.language.get("COMMAND_CHECKACTIVITY_TABLE_HEADERS");
            const outArr = Bot.makeTable({
                user: {value: headerValues.user, startWith: "`", endWith: "|", align: "left"},
                time: {value: headerValues.time, endWith: "`"}
            }, objArr);

            const fields = Bot.msgArray(outArr, "\n", 700).map(m => {
                return {name: "-", value: m};
            });

            const desc = fields.shift();
            return message.channel.send({embed: {
                author: {name: message.language.get("COMMAND_CHECKACTIVITY_LOG_HEADER", message.guild.name, objArr.length)},
                description: desc.value,
                fields: fields,
                color: 0x00FF00
            }});
        } else {
            // Make sure it's a valid userID
            if (!Bot.isUserID(userID)) {
                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_INVALID_USER"));
            }
            userID = Bot.getUserID(userID);
            const user = message.guild.members.get(userID);
            const name = user.nickname ? user.nickname : user.user.username;
            // Try and check the activity for just one user
            if (activityLog.log[userID]) {
                // Spit out user's last activity
                const lastActive = activityLog.log[userID];
                const diff = moment().diff(moment(lastActive));

                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_USER_CHECK", name, getTime(diff)), {title: message.language.get("COMMAND_CHECKACTIVITY_USER_CHECK_HEADER"), color: 0x00FF00});
            } else {
                return super.error(message, message.language.get("COMMAND_CHECKACTIVITY_NO_USER"));
            }
        }
        function getTime(diff, numOnly) {
            const days = 1000 * 60 * 60 * 24;
            const hours= 1000 * 60 * 60;
            const mins = 1000 * 60;

            let out = diff / days;
            if (out > 1) {
                return (out < 10 ? " " : "") + out.toFixed(1) + (numOnly ? "d" : " days");
            }
            out = diff / hours;
            if (out > 1) {
                return (out < 10 ? " " : "") + out.toFixed(1) + (numOnly ? "h" : " hours");
            }
            out = diff / mins;
            return (out < 10 ? "   " : "  ") + parseInt(out) + (numOnly ? "m" : " minutes");
        }
    }
}

module.exports = CheckAct;

<|endoftext|>


<commit_before>module.exports = function(grunt) {
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> v<%= pkg.version %> */\n'
            },
            build: {
                src: 'lib/<%= pkg.name %>.js',
                dest: 'dist/<%= pkg.name %>.min.js'
            }
        },
        jshint: {
            files: [ 'lib/**/*.js', 'test/**/*.js' ],
            options: {
                bitwise: true,
                camelcase: true,
                curly: true,
                eqeqeq: true,
                forin: true,
                immed: true,
                indent: 4,
                latedef: true,
                newcap: true,
                noempty: true,
                nonew: true,
                quotmark: true,
                jquery: true,
                undef: true,
                unused: true,
                strict: true,
                trailing: true,
                browser: true,
                node: true,
                white: false,
                globals: {
                    define: true,
                    window: true
                }
            }
        },
        nodeunit: {
            all: ['test/*.js']
        }
    });

    //
    // Plugins
    //
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-nodeunit');
    grunt.loadNpmTasks('grunt-contrib-jshint');

    //
    // Tasks
    //
    grunt.registerTask('default', ['jshint', 'uglify']);
    grunt.registerTask('test', ['nodeunit']);
    grunt.registerTask('lint', ['jshint']);
    grunt.registerTask('travis', ['nodeunit', 'jshint']);
    grunt.registerTask('all', ['nodeunit', 'jshint', 'uglify']);
};<commit_msg>Only run jQuery test in browser<commit_after>module.exports = function(grunt) {
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> v<%= pkg.version %> */\n'
            },
            build: {
                src: 'lib/<%= pkg.name %>.js',
                dest: 'dist/<%= pkg.name %>.min.js'
            }
        },
        jshint: {
            files: [ 'lib/**/*.js', 'test/**/*.js' ],
            options: {
                bitwise: true,
                camelcase: true,
                curly: true,
                eqeqeq: true,
                forin: true,
                immed: true,
                indent: 4,
                latedef: true,
                newcap: true,
                noempty: true,
                nonew: true,
                quotmark: true,
                jquery: true,
                undef: true,
                unused: true,
                strict: true,
                trailing: true,
                browser: true,
                node: true,
                white: false,
                globals: {
                    define: true,
                    window: true
                }
            }
        },
        nodeunit: {
            all: ['test/test-breakup.js', 'test/test-breakup-caolan.js']
        }
    });

    //
    // Plugins
    //
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-nodeunit');
    grunt.loadNpmTasks('grunt-contrib-jshint');

    //
    // Tasks
    //
    grunt.registerTask('default', ['jshint', 'uglify']);
    grunt.registerTask('test', ['nodeunit']);
    grunt.registerTask('lint', ['jshint']);
    grunt.registerTask('travis', ['nodeunit', 'jshint']);
    grunt.registerTask('all', ['nodeunit', 'jshint', 'uglify']);
};<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var RSVP = require('rsvp');
var Command = require('../lib/command');
var FirebaseError = require('../lib/error');
var gcp = require('../lib/gcp');
var getProjectId = require('../lib/getProjectId');
var logger = require('../lib/logger');
var requireAccess = require('../lib/requireAccess');
var scopes = require('../lib/scopes');

var POLL_INTERVAL = 3000; // 3 sec

function _pollLogs(projectId, filter, pos) {
  return new RSVP.Promise(function(resolve, reject) {
    function poll() {
      var nf = filter;
      if (pos.timestamp) {
        nf += ' timestamp>"' + pos.timestamp + '" ';
      }
      if (pos.insertId) {
        nf += ' insertId>"' + pos.insertId + '" ';
      }

      gcp.cloudlogging.listEntries(projectId, nf, 1000, 'asc').then(function(entries) {
        for (var i = 0; i < _.size(entries); i++) {
          var entry = entries[i];
          logger.info(
            entry.timestamp,
            entry.severity.substring(0, 1),
            entry.resource.labels.function_name + ':',
            entry.textPayload);
          pos.timestamp = entry.timestamp;
          pos.insertId = entry.insertId;
        }
        setTimeout(poll, POLL_INTERVAL);
      }).catch(function(err) {
        return reject(err);
      });
    }
    poll();
  });
}

module.exports = new Command('functions:log')
  .description('read logs from GCF Kubernetes cluster')
  .option('--only <function_names>', 'only show logs of specified, comma-seperated functions (e.g. "funcA,funcB")')
  .option('-n, --lines <num_lines>', 'specify number of log lines to fetch')
  .option('-f, --follow', 'stream logs from GCF cluster')
  .before(requireAccess, [scopes.OPENID, scopes.CLOUD_PLATFORM])
  .action(function(options) {
    var filter = 'resource.type="cloud_function"';
    if (options.only) {
      var funcNames = options.only.split(',');
      var funcFilters = _.map(funcNames, function(funcName) {
        return 'labels."cloudfunctions.googleapis.com/function_name"="' + funcName + '" ';
      });
      filter += funcFilters.join('OR ');
    }
    var projectId = getProjectId(options);
    return gcp.cloudlogging.listEntries(projectId, filter, options.lines || 35, 'desc')
    .then(function(entries) {
      for (var i = _.size(entries); i-- > 0;) {
        var entry = entries[i];
        logger.info(
          entry.timestamp,
          entry.severity.substring(0, 1),
          entry.resource.labels.function_name + ':',
          entry.textPayload);
      }
      if (options.follow) {
        var pos = {};
        if (!_.isEmpty(entries)) {
          var lastEntry = _.first(entries);
          pos = {
            timestamp: lastEntry.timestamp,
            insertId: lastEntry.insertId
          };
        }
        return _pollLogs(projectId, filter, pos);
      } else if (_.isEmpty(entries)) {
        logger.info('No log entries found.');
      }
      return RSVP.resolve(entries);
    }).catch(function(err) {
      return RSVP.reject(new FirebaseError(
        'Failed to list log entries ' + err.message, {exit: 1}));
    });
  });
<commit_msg>update functions log filter syntax (#100)<commit_after>'use strict';

var _ = require('lodash');
var RSVP = require('rsvp');
var Command = require('../lib/command');
var FirebaseError = require('../lib/error');
var gcp = require('../lib/gcp');
var getProjectId = require('../lib/getProjectId');
var logger = require('../lib/logger');
var requireAccess = require('../lib/requireAccess');
var scopes = require('../lib/scopes');

var POLL_INTERVAL = 3000; // 3 sec

function _pollLogs(projectId, filter, pos) {
  return new RSVP.Promise(function(resolve, reject) {
    function poll() {
      var nf = filter;
      if (pos.timestamp) {
        nf += ' timestamp>"' + pos.timestamp + '" ';
      }
      if (pos.insertId) {
        nf += ' insertId>"' + pos.insertId + '" ';
      }

      gcp.cloudlogging.listEntries(projectId, nf, 1000, 'asc').then(function(entries) {
        for (var i = 0; i < _.size(entries); i++) {
          var entry = entries[i];
          logger.info(
            entry.timestamp,
            entry.severity.substring(0, 1),
            entry.resource.labels.function_name + ':',
            entry.textPayload);
          pos.timestamp = entry.timestamp;
          pos.insertId = entry.insertId;
        }
        setTimeout(poll, POLL_INTERVAL);
      }).catch(function(err) {
        return reject(err);
      });
    }
    poll();
  });
}

module.exports = new Command('functions:log')
  .description('read logs from deployed functions')
  .option('--only <function_names>', 'only show logs of specified, comma-seperated functions (e.g. "funcA,funcB")')
  .option('-n, --lines <num_lines>', 'specify number of log lines to fetch')
  .option('-f, --follow', 'stream logs from GCF cluster')
  .before(requireAccess, [scopes.OPENID, scopes.CLOUD_PLATFORM])
  .action(function(options) {
    var filter = 'resource.type="cloud_function" ';
    if (options.only) {
      var funcNames = options.only.split(',');
      var funcFilters = _.map(funcNames, function(funcName) {
        return 'resource.labels.function_name="' + funcName + '" ';
      });
      filter += funcFilters.join('OR ');
    }
    var projectId = getProjectId(options);
    return gcp.cloudlogging.listEntries(projectId, filter, options.lines || 35, 'desc')
    .then(function(entries) {
      for (var i = _.size(entries); i-- > 0;) {
        var entry = entries[i];
        logger.info(
          entry.timestamp,
          entry.severity.substring(0, 1),
          entry.resource.labels.function_name + ':',
          entry.textPayload);
      }
      if (options.follow) {
        var pos = {};
        if (!_.isEmpty(entries)) {
          var lastEntry = _.first(entries);
          pos = {
            timestamp: lastEntry.timestamp,
            insertId: lastEntry.insertId
          };
        }
        return _pollLogs(projectId, filter, pos);
      } else if (_.isEmpty(entries)) {
        logger.info('No log entries found.');
      }
      return RSVP.resolve(entries);
    }).catch(function(err) {
      return RSVP.reject(new FirebaseError(
        'Failed to list log entries ' + err.message, {exit: 1}));
    });
  });
<|endoftext|>


<commit_before>module.exports = function(grunt) {
    grunt.registerTask('watch', ['watch']);
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        config: grunt.file.readJSON('config.json'),
        connect: {
          server: {
            options: {
              port: 8080,
              //keepalive: true, keeping grunt running
              livereload:true,
              base: 'index.html',
              open: {
                target: 'http://localhost:8080',
                appName: 'Google Chrome',
              }
            }
          }
        },
        watch: {
          js: {
            files: ['dev/pyro.js'],
            tasks:['jsdoc'],
            options:{
              livereload:{
                port:35739
              },
            }
          }
        },
        aws_s3:{
          production:{
            options: {
              accessKeyId: '<%= config.AWSAccessKeyId %>',
              secretAccessKey: '<%= config.AWSSecretKey %>',
              bucket:'pyro-cdn',
              uploadConcurrency: 2
            },
            files:[
              {'action': 'upload', expand: true, cwd: 'dist/', src: ['pyro.min.js'], dest: '<%= pkg.version %>'},
              {'action': 'upload', expand: true, cwd: 'dev/', src: ['pyro.js'], dest: '<%= pkg.version %>'},
            ]
          },
          staging:{
            options: {
              accessKeyId: '<%= config.AWSAccessKeyId %>',
              secretAccessKey: '<%= config.AWSSecretKey %>',
              bucket:'pyro-cdn',
              uploadConcurrency: 2
            },
            files:[
              {'action': 'upload', expand: true, cwd: 'dist/', src: ['pyro.min.js'], dest: 'staging/<%= pkg.version %>'},
              {'action': 'upload', expand: true, cwd: 'dev/', src: ['pyro.js'], dest: 'staging/<%= pkg.version %>'}            ]
          },
          docs:{
            options: {
              accessKeyId: '<%= config.AWSAccessKeyId %>', // Use the variables
              secretAccessKey: '<%= config.AWSSecretKey %>', // You can also use env variables
              bucket:'pyro-labs',
              uploadConcurrency: 50, // 50 simultaneous uploads
            },
            files:[
              {'action': 'upload', expand: true, cwd: 'dist/docs', src: ['**'], dest: 'docs', differential:true}
            ]
          }
        },
        uglify:{
          my_target:{
            files:{
              'dist/pyro.min.js': ['dev/pyro.js']
            }
          }
        },
        jsdoc: {
          dist:{
            src: ['dev/pyro.js'],
            options: {
              destination: 'dist/docs',
              template : "node_modules/grunt-jsdoc/node_modules/ink-docstrap/template",
              configure : "node_modules/grunt-jsdoc/node_modules/ink-docstrap/template/jsdoc.conf.json"
            }
          }
        },
        bump:{
        options:{
          files:['package.json'],
          updateConfigs:['pkg'],
          commit:true,
          commitMessage:'[RELEASE] Release v%VERSION%',
          commitFiles:[],
          createTag:true,
          tagName:'v%VERSION%',
          push:true,
          pushTo:'upstream',
          gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
          globalReplace: false
        }
      },
    });

    //Plugin for "watch"
    grunt.loadNpmTasks('grunt-contrib-watch');

    //Connect plugin
    grunt.loadNpmTasks('grunt-contrib-connect');

    //Open plugin
    grunt.loadNpmTasks('grunt-open');

    // S3 File Handling Plugin (For uploading build)
    grunt.loadNpmTasks('grunt-aws-s3');

    //Uglify/Minify
    grunt.loadNpmTasks('grunt-contrib-uglify');

    // Auto documentation
    grunt.loadNpmTasks('grunt-jsdoc');

    //Auto Versioning
    grunt.loadNpmTasks('grunt-bump');

    // Default task(s).
    grunt.registerTask('default', [ 'watch']);
    /* Builds minified script and creates documentation
      @task
    */
    grunt.registerTask('build', ['uglify', 'jsdoc']);

    grunt.registerTask('docs', ['jsdoc']);

    grunt.registerTask('stage', ['jsdoc', 'uglify', 'aws_s3:staging', 'aws_s3:docs'])

    grunt.registerTask('release', ['bump:prerelease','jsdoc', 'uglify', 'aws_s3:production', 'aws_s3:docs']);

    grunt.registerTask('serve', ['connect'], function() {
        grunt.task.run('connect');
    });
};<commit_msg>Added stageDocs task as well as changed version number to docs location.<commit_after>module.exports = function(grunt) {
    grunt.registerTask('watch', ['watch']);
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        config: grunt.file.readJSON('config.json'),
        connect: {
          server: {
            options: {
              port: 8080,
              //keepalive: true, keeping grunt running
              livereload:true,
              base: 'index.html',
              open: {
                target: 'http://localhost:8080',
                appName: 'Google Chrome',
              }
            }
          }
        },
        watch: {
          js: {
            files: ['dev/pyro.js'],
            tasks:['jsdoc'],
            options:{
              livereload:{
                port:35739
              },
            }
          }
        },
        aws_s3:{
          production:{
            options: {
              accessKeyId: '<%= config.AWSAccessKeyId %>',
              secretAccessKey: '<%= config.AWSSecretKey %>',
              bucket:'pyro-cdn',
              uploadConcurrency: 2
            },
            files:[
              {'action': 'upload', expand: true, cwd: 'dist/', src: ['pyro.min.js'], dest: '<%= pkg.version %>'},
              {'action': 'upload', expand: true, cwd: 'dev/', src: ['pyro.js'], dest: '<%= pkg.version %>'},
            ]
          },
          staging:{
            options: {
              accessKeyId: '<%= config.AWSAccessKeyId %>',
              secretAccessKey: '<%= config.AWSSecretKey %>',
              bucket:'pyro-cdn',
              uploadConcurrency: 2
            },
            files:[
              {'action': 'upload', expand: true, cwd: 'dist/', src: ['pyro.min.js'], dest: 'staging/<%= pkg.version %>'},
              {'action': 'upload', expand: true, cwd: 'dev/', src: ['pyro.js'], dest: 'staging/<%= pkg.version %>'}
            ]
          },
          docs:{
            options: {
              accessKeyId: '<%= config.AWSAccessKeyId %>', // Use the variables
              secretAccessKey: '<%= config.AWSSecretKey %>', // You can also use env variables
              bucket:'pyro-labs',
              uploadConcurrency: 50, // 50 simultaneous uploads
            },
            files:[
              {'action': 'upload', expand: true, cwd: 'dist/docs', src: ['**'], dest: 'docs/<%= pkg.version %>', differential:true}
            ]
          },
          stageDocs:{
            options: {
              accessKeyId: '<%= config.AWSAccessKeyId %>', // Use the variables
              secretAccessKey: '<%= config.AWSSecretKey %>', // You can also use env variables
              bucket:'pyro-labs',
              uploadConcurrency: 50, // 50 simultaneous uploads
            },
            files:[
              {'action': 'upload', expand: true, cwd: 'dist/docs', src: ['**'], dest: 'docs/staging/<%= pkg.version %>', differential:true}
            ]
          }
        },
        uglify:{
          my_target:{
            files:{
              'dist/pyro.min.js': ['dev/pyro.js']
            }
          }
        },
        jsdoc: {
          dist:{
            src: ['dev/pyro.js'],
            options: {
              destination: 'dist/docs',
              template : "node_modules/grunt-jsdoc/node_modules/ink-docstrap/template",
              configure : "node_modules/grunt-jsdoc/node_modules/ink-docstrap/template/jsdoc.conf.json"
            }
          }
        },
        bump:{
        options:{
          files:['package.json'],
          updateConfigs:['pkg'],
          commit:true,
          commitMessage:'[RELEASE] Release v%VERSION%',
          commitFiles:[],
          createTag:true,
          tagName:'v%VERSION%',
          push:true,
          pushTo:'upstream',
          gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
          globalReplace: false
        }
      },
    });

    //Plugin for "watch"
    grunt.loadNpmTasks('grunt-contrib-watch');

    //Connect plugin
    grunt.loadNpmTasks('grunt-contrib-connect');

    //Open plugin
    grunt.loadNpmTasks('grunt-open');

    // S3 File Handling Plugin (For uploading build)
    grunt.loadNpmTasks('grunt-aws-s3');

    //Uglify/Minify
    grunt.loadNpmTasks('grunt-contrib-uglify');

    // Auto documentation
    grunt.loadNpmTasks('grunt-jsdoc');

    //Auto Versioning
    grunt.loadNpmTasks('grunt-bump');

    // Default task(s).
    grunt.registerTask('default', [ 'watch']);
    /* Builds minified script and creates documentation
      @task
    */
    grunt.registerTask('build', ['uglify', 'jsdoc']);

    grunt.registerTask('docs', ['jsdoc']);

    grunt.registerTask('stage', ['jsdoc', 'uglify', 'aws_s3:staging', 'aws_s3:stageDocs'])

    grunt.registerTask('release', ['bump:prerelease','jsdoc', 'uglify', 'aws_s3:production', 'aws_s3:docs']);

    grunt.registerTask('serve', ['connect'], function() {
        grunt.task.run('connect');
    });
};<|endoftext|>