<commit_before>'use strict';
var LIVERELOAD_PORT = 35729;
var SERVER_PORT = 9000;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};
var request = require('request');

module.exports = function (grunt) {
  // show elapsed time at the end
  require('time-grunt')(grunt);
  // load all grunt tasks
  require('load-grunt-tasks')(grunt);

  var worldConfig = {
    app: 'public',
    dist: 'dist'
  };

  var reloadPort = 35729, files;

  grunt.initConfig({
    world: worldConfig,
    pkg: grunt.file.readJSON('package.json'),

    clean: {
      dist: ['.tmp', '<%= world.dist %>/*'],
      server: '.tmp',
      results: 'results/*'
    },

    concat: {
      dist: {
        src: ['<%= world.app %>/**/*.js', '!<%= world.app %>/bower_components/recorderjs/recorderWorker.js'],
        dest: '.tmp/js/main.js'
      }
    },

    connect: {
      options: {
        port: grunt.option('port') || SERVER_PORT,
        // change this to '0.0.0.0' to access the server from outside
        hostname: 'localhost'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, '.tmp'),
              mountFolder(connect, worldConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          base: ".",
          port: 9001,
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, 'test'),
              mountFolder(connect, worldConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, worldConfig.dist)
            ];
          }
        }
      }
    },

    casperjs: {
      files: [
        'test/e2e/*.js'
      ],
      options: {}
    },

    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= world.app %>',
          dest: '<%= world.dist %>',
          src: [
            '*.{ico,txt}',
            'img/{,*/}*.{webp,gif}',
            'styles/fonts/{,*/}*.*',
            'soundfont/**/*.*',
            'bower_components/recorderjs/recorderWorker.js'
          ]
        }, {
          expand: true,
          dot: true,
          cwd: '<%= world.app %>',
          dest: '<%= world.dist %>/styles/public',
          src: ['img/{,*/}*.png', 'bower_components/jquery-ui/themes/smoothness/images/*.{gif,png}']
        }]
      }
    },

    cssmin: {
      dist: {
        files: {
          '<%= world.dist %>/styles/main.css': [
            '.tmp/styles/{,*/}*.css',
            '<%= world.app %>/bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css',
            '<%= world.app %>/bower_components/jquery-ui/themes/smoothness/theme.css',
            '<%= world.app %>/bower_components/backbone-modal/backbone.modal.css',
            '<%= world.app %>/bower_components/backbone-modal/backbone.modal.theme.css',
            '<%= world.app %>/css/{,*/}*.css'
          ]
        }
      }
    },

    htmlmin: {
      dist: {
        options: {
          /*removeCommentsFromCDATA: true,
           // https://github.com/yeoman/grunt-usemin/issues/44
           //collapseWhitespace: true,
           collapseBooleanAttributes: true,
           removeAttributeQuotes: true,
           removeRedundantAttributes: true,
           useShortDoctype: true,
           removeEmptyAttributes: true,
           removeOptionalTags: true*/
        },
        files: [{
          expand: true,
          cwd: '<%= world.app %>',
          src: '*.html',
          dest: '<%= world.dist %>'
        }]
      }
    },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= world.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg}',
          dest: '<%= world.dist %>/images'
        }]
      }
    },

    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      gruntfile: ['Gruntfile.js'],
      all: [
        'Gruntfile.js',
        'public/js/**/*.js',
        'test/unit/**/*.js',
        '!test/unit/lib/**/*.js'
      ]
    },

    karma: {
      options: {
        configFile: 'karma.conf.js',
        reporters: ['progress', 'coverage']
      },
      // Watch configuration
      watch: {
        background: true,
        reporters: ['progress']
      },
      // Single-run configuration for development
      single: {
        singleRun: true
      },
      // Single-run configuration for CI
      ci: {
        singleRun: true,
        coverageReporter: {
          type: 'lcov',
          dir: 'results/coverage/'
        }
      }
    },

    open: {
      server: {
        path: 'http://localhost:<%= connect.options.port %>'
      },
      test: {
        path: 'http://localhost:<%= connect.test.options.port %>'
      }
    },

    rev: {
      dist: {
        files: {
          src: [
            '<%= world.dist %>/scripts/{,*/}*.js',
            '<%= world.dist %>/styles/{,*/}*.css',
            '<%= world.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
            '/styles/fonts/{,*/}*.*'
          ]
        }
      }
    },

    uglify: {
      my_target: {
        files: {
          'dist/main.min.js': ['.tmp/js/*.js']
        }
      }
    },

    useminPrepare: {
      html: '<%= world.app %>/index.html',
      options: {
        dest: '<%= world.dist %>'
      }
    },

    usemin: {
      html: ['<%= world.dist %>/{,*/}*.html'],
      css: ['<%= world.dist %>/styles/{,*/}*.css'],
      options: {
        dirs: ['<%= world.dist %>']
      }
    },

    watch: {
      options: {
        nospawn: true,
        livereload: true
      },
      livereload: {
        options: {
          livereload: grunt.option('livereloadport') || LIVERELOAD_PORT
        },
        files: [
          '<%= world.app %>/*.html',
          '{.tmp,<%= world.app %>}/styles/{,*/}*.css',
          '{.tmp,<%= world.app %>}/scripts/{,*/}*.js',
          '<%= world.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
          '<%= world.app %>/scripts/templates/*.{ejs,mustache,hbs}',
          'test/unit/**/*.js'
        ]
      },
      casperjs: {
        files: [
          'test/e2e/*.js'
        ],
        options: {},
        e2e: {
          files: {
            'results/casper': 'test/e2e/*.js'
          }
        }
      },
      js: {
        files: [
          'app.js',
          'server/**/*.js',
          'config/*.js'
        ],
        tasks: ['develop', 'delayed-livereload']
      },
      gruntfile: {
        files: 'Gruntfile.js',
        tasks: 'jshint:gruntfile'
      },
      client: {
        files: [ 'client/**' ],
        tasks: [ 'build', 'karma:watch:run', 'casperjs' ]
      },
      //al TODO review server: express:dev,
      server: {
        files: [ 'server/**' ],
        tasks: [ 'build', /*'express:dev',*/ 'casperjs' ],
        options: {
          spawn: false // Restart server
        }
      },
      unitTests: {
        files: [ 'test/unit/**/*.js' ],
        tasks: [ 'karma:watch:run' ]
      },
      integrationTests: {
        files: [ 'test/integration/**/*.js' ],
        tasks: [ 'karma:watch:run' ]
      },
      e2eTests: {
        files: [ 'test/e2e/**/*.js' ],
        tasks: [ 'casperjs' ]
      },
      css: {
        files: [
          'public/css/*.css'
        ],
        options: {
          livereload: true
        }
      },
      views: {
        files: [
          'server/views/*.ejs',
          'server/views/**/*.ejs'
        ],
        options: {
          livereload: true
        }
      }
    }
  });

  grunt.config.requires('watch.js.files');
  files = grunt.config('watch.js.files');
  files = grunt.file.expand(files);

  grunt.registerTask('delayed-livereload', 'Live reload after the node server has restarted.', function () {
    var done = this.async();
    setTimeout(function () {
      request.get('http://localhost:' + reloadPort + '/changed?files=' + files.join(','),  function(err, res) {
        var reloaded = !err && res.statusCode === 200;
        if (reloaded)
          grunt.log.ok('Delayed live reload successful.');
        else
          grunt.log.error('Unable to make a delayed live reload.');
        done(reloaded);
      });
    }, 500);
  });

  grunt.registerTask('createDefaultTemplate', function () {
    grunt.file.write('.tmp/scripts/templates.js', 'this.JST = this.JST || {};');
  });

  grunt.registerTask('test', function (isConnected) {
    isConnected = Boolean(isConnected);
    var testTasks = [
      'clean:server',
      'clean:results',
      'createDefaultTemplate',
      'connect:test',
      // Karma works when run using 'Grunt serve:test'
      //'karma:ci',
      'casperjs'
    ];

    if(!isConnected) {
      return grunt.task.run(testTasks);
    } else {
      // already connected so not going to connect again, remove the connect:test task
      testTasks.splice(testTasks.indexOf('connect:test'), 1);
      return grunt.task.run(testTasks);
    }
  });

  grunt.registerTask('build', [
    'clean:dist',
    'createDefaultTemplate',
    'useminPrepare',
    'imagemin',
    'htmlmin',
    'concat',
    'cssmin:dist',
    'uglify',
    'copy',
    'rev',
    'usemin'
  ]);

  grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'open:server', 'connect:dist:keepalive']);
    }

    if (target === 'test') {
      return grunt.task.run([
        'clean:server',
        'createDefaultTemplate',
        'connect:test',
        'open:test',
        'watch'
      ]);
    }

    grunt.task.run([
      'clean:server',
      'createDefaultTemplate',
      'connect:livereload',
      'open:server',
      'watch'
    ]);
  });

  grunt.registerTask('default', [
    'jshint',
    'test',
    'build'
  ]);
};
<commit_msg>fix image references on production<commit_after>'use strict';
var LIVERELOAD_PORT = 35729;
var SERVER_PORT = 9000;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};
var request = require('request');

module.exports = function (grunt) {
  // show elapsed time at the end
  require('time-grunt')(grunt);
  // load all grunt tasks
  require('load-grunt-tasks')(grunt);

  var worldConfig = {
    app: 'public',
    dist: 'dist'
  };

  var reloadPort = 35729, files;

  grunt.initConfig({
    world: worldConfig,
    pkg: grunt.file.readJSON('package.json'),

    clean: {
      dist: ['.tmp', '<%= world.dist %>/*'],
      server: '.tmp',
      results: 'results/*'
    },

    concat: {
      dist: {
        src: ['<%= world.app %>/**/*.js', '!<%= world.app %>/bower_components/recorderjs/recorderWorker.js'],
        dest: '.tmp/js/main.js'
      }
    },

    connect: {
      options: {
        port: grunt.option('port') || SERVER_PORT,
        // change this to '0.0.0.0' to access the server from outside
        hostname: 'localhost'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, '.tmp'),
              mountFolder(connect, worldConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          base: ".",
          port: 9001,
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, 'test'),
              mountFolder(connect, worldConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, worldConfig.dist)
            ];
          }
        }
      }
    },

    casperjs: {
      files: [
        'test/e2e/*.js'
      ],
      options: {}
    },

    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= world.app %>',
          dest: '<%= world.dist %>',
          src: [
            '*.{ico,txt}',
            // 'img/{,*/}*.*',
            'styles/fonts/{,*/}*.*',
            'soundfont/**/*.*',
            'bower_components/recorderjs/recorderWorker.js'
          ]
        }, {
          expand: true,
          dot: true,
          cwd: '<%= world.app %>',
          dest: '<%= world.dist %>/styles/public',
          src: ['img/{,*/}*.png', 'bower_components/jquery-ui/themes/smoothness/images/*.{gif,png}']
        }, {
          expand: true,
          dot: true,
          cwd: '<%= world.app %>',
          dest: '<%= world.dist %>',
          src: ['img/{,*/}*.jpg']
        }]
      }
    },

    cssmin: {
      dist: {
        files: {
          '<%= world.dist %>/styles/main.css': [
            '.tmp/styles/{,*/}*.css',
            '<%= world.app %>/bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css',
            '<%= world.app %>/bower_components/jquery-ui/themes/smoothness/theme.css',
            '<%= world.app %>/bower_components/backbone-modal/backbone.modal.css',
            '<%= world.app %>/bower_components/backbone-modal/backbone.modal.theme.css',
            '<%= world.app %>/css/{,*/}*.css'
          ]
        }
      }
    },

    htmlmin: {
      dist: {
        options: {
          /*removeCommentsFromCDATA: true,
           // https://github.com/yeoman/grunt-usemin/issues/44
           //collapseWhitespace: true,
           collapseBooleanAttributes: true,
           removeAttributeQuotes: true,
           removeRedundantAttributes: true,
           useShortDoctype: true,
           removeEmptyAttributes: true,
           removeOptionalTags: true*/
        },
        files: [{
          expand: true,
          cwd: '<%= world.app %>',
          src: '*.html',
          dest: '<%= world.dist %>'
        }]
      }
    },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= world.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg}',
          dest: '<%= world.dist %>/images'
        }]
      }
    },

    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      gruntfile: ['Gruntfile.js'],
      all: [
        'Gruntfile.js',
        'public/js/**/*.js',
        'test/unit/**/*.js',
        '!test/unit/lib/**/*.js'
      ]
    },

    karma: {
      options: {
        configFile: 'karma.conf.js',
        reporters: ['progress', 'coverage']
      },
      // Watch configuration
      watch: {
        background: true,
        reporters: ['progress']
      },
      // Single-run configuration for development
      single: {
        singleRun: true
      },
      // Single-run configuration for CI
      ci: {
        singleRun: true,
        coverageReporter: {
          type: 'lcov',
          dir: 'results/coverage/'
        }
      }
    },

    open: {
      server: {
        path: 'http://localhost:<%= connect.options.port %>'
      },
      test: {
        path: 'http://localhost:<%= connect.test.options.port %>'
      }
    },

    rev: {
      dist: {
        files: {
          src: [
            '<%= world.dist %>/scripts/{,*/}*.js',
            '<%= world.dist %>/styles/{,*/}*.css',
            '<%= world.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
            '/styles/fonts/{,*/}*.*'
          ]
        }
      }
    },

    uglify: {
      my_target: {
        files: {
          'dist/main.min.js': ['.tmp/js/*.js']
        }
      }
    },

    useminPrepare: {
      html: '<%= world.app %>/index.html',
      options: {
        dest: '<%= world.dist %>'
      }
    },

    usemin: {
      html: ['<%= world.dist %>/{,*/}*.html'],
      css: ['<%= world.dist %>/styles/{,*/}*.css'],
      options: {
        dirs: ['<%= world.dist %>']
      }
    },

    watch: {
      options: {
        nospawn: true,
        livereload: true
      },
      livereload: {
        options: {
          livereload: grunt.option('livereloadport') || LIVERELOAD_PORT
        },
        files: [
          '<%= world.app %>/*.html',
          '{.tmp,<%= world.app %>}/styles/{,*/}*.css',
          '{.tmp,<%= world.app %>}/scripts/{,*/}*.js',
          '<%= world.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
          '<%= world.app %>/scripts/templates/*.{ejs,mustache,hbs}',
          'test/unit/**/*.js'
        ]
      },
      casperjs: {
        files: [
          'test/e2e/*.js'
        ],
        options: {},
        e2e: {
          files: {
            'results/casper': 'test/e2e/*.js'
          }
        }
      },
      js: {
        files: [
          'app.js',
          'server/**/*.js',
          'config/*.js'
        ],
        tasks: ['develop', 'delayed-livereload']
      },
      gruntfile: {
        files: 'Gruntfile.js',
        tasks: 'jshint:gruntfile'
      },
      client: {
        files: [ 'client/**' ],
        tasks: [ 'build', 'karma:watch:run', 'casperjs' ]
      },
      //al TODO review server: express:dev,
      server: {
        files: [ 'server/**' ],
        tasks: [ 'build', /*'express:dev',*/ 'casperjs' ],
        options: {
          spawn: false // Restart server
        }
      },
      unitTests: {
        files: [ 'test/unit/**/*.js' ],
        tasks: [ 'karma:watch:run' ]
      },
      integrationTests: {
        files: [ 'test/integration/**/*.js' ],
        tasks: [ 'karma:watch:run' ]
      },
      e2eTests: {
        files: [ 'test/e2e/**/*.js' ],
        tasks: [ 'casperjs' ]
      },
      css: {
        files: [
          'public/css/*.css'
        ],
        options: {
          livereload: true
        }
      },
      views: {
        files: [
          'server/views/*.ejs',
          'server/views/**/*.ejs'
        ],
        options: {
          livereload: true
        }
      }
    }
  });

  grunt.config.requires('watch.js.files');
  files = grunt.config('watch.js.files');
  files = grunt.file.expand(files);

  grunt.registerTask('delayed-livereload', 'Live reload after the node server has restarted.', function () {
    var done = this.async();
    setTimeout(function () {
      request.get('http://localhost:' + reloadPort + '/changed?files=' + files.join(','),  function(err, res) {
        var reloaded = !err && res.statusCode === 200;
        if (reloaded)
          grunt.log.ok('Delayed live reload successful.');
        else
          grunt.log.error('Unable to make a delayed live reload.');
        done(reloaded);
      });
    }, 500);
  });

  grunt.registerTask('createDefaultTemplate', function () {
    grunt.file.write('.tmp/scripts/templates.js', 'this.JST = this.JST || {};');
  });

  grunt.registerTask('test', function (isConnected) {
    isConnected = Boolean(isConnected);
    var testTasks = [
      'clean:server',
      'clean:results',
      'createDefaultTemplate',
      'connect:test',
      // Karma works when run using 'Grunt serve:test'
      //'karma:ci',
      'casperjs'
    ];

    if(!isConnected) {
      return grunt.task.run(testTasks);
    } else {
      // already connected so not going to connect again, remove the connect:test task
      testTasks.splice(testTasks.indexOf('connect:test'), 1);
      return grunt.task.run(testTasks);
    }
  });

  grunt.registerTask('build', [
    'clean:dist',
    'createDefaultTemplate',
    'useminPrepare',
    'imagemin',
    'htmlmin',
    'concat',
    'cssmin:dist',
    'uglify',
    'copy',
    'rev',
    'usemin'
  ]);

  grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'open:server', 'connect:dist:keepalive']);
    }

    if (target === 'test') {
      return grunt.task.run([
        'clean:server',
        'createDefaultTemplate',
        'connect:test',
        'open:test',
        'watch'
      ]);
    }

    grunt.task.run([
      'clean:server',
      'createDefaultTemplate',
      'connect:livereload',
      'open:server',
      'watch'
    ]);
  });

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


<commit_before>'use strict';

module.exports = function(grunt) {

    grunt.loadNpmTasks('grunt-browserify');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-sass');

    var debug = typeof grunt.option('release') === "undefined";

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

    grunt.registerTask('js', debug ? ['browserify'] : ['browserify', 'uglify']);
    grunt.registerTask('css', debug ? ['sass', 'concat:lib'] : ['sass', 'concat:lib', 'cssmin']);
    grunt.registerTask('app', ['clean', 'quests', 'js', 'css', 'copy']);

    grunt.registerTask('default', ['app', 'compress']);

    grunt.registerTask('quests', function() {
        var exec = require('child_process').exec,
            done = this.async();

        exec('python scripts/assemble_quests.py', {},
            function(err) {
                if (err) {
                    grunt.log.error(err);
                    done(false);
                } else {
                    done(true);
                }
        });
    });

    var srcDir  = 'src/',
        tempDir = 'build/temp/',
        distDir = 'www/',
        zonesJson = srcDir + 'quests/**/*.json',
        jsDir   = srcDir + 'js/',
        sassDir = srcDir + 'sass/',
        jsBundlePath     = distDir + 'bundle.js',
        jsMinBundlePath  = distDir + 'bundle.min.js',
        cssBundlePath    = distDir + 'bundle.css',
        cssVendorPath    = distDir + 'vendor.css',
        cssMinBundlePath = distDir + 'bundle.min.css',
        zipFilePath = tempDir + 'app.zip',
        appAssets = [
            'config.xml',
            'index.html',
            'quests/**/*',
            'sass/lib/leaflet.css',
            'sass/lib/fontello.css',
            'sass/lib/bootstrap.min.css',
            'sass/lib/bootstrap-dialog.min.css',
            'sass/font/*',
            'sass/fonts/*',
            'tiles/**/*',
            'img/**/*',
            'quests.json'
        ];

    grunt.initConfig({
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            app: ['Gruntfile.js', jsDir + '*.js']
        },

        clean: [
            tempDir + '**/*',
            distDir + '**/*'
        ],

        browserify: {
            app: {
                options: {
                    alias: [jsDir + 'app.js:app'],
                    transform: [
                        'browserify-shim',
                        ['jstify', { engine: 'lodash', noMinify: true }]
                    ],
                    bundleOptions: {
                        debug: debug  // Create source maps in debug mode
                    }
                },
                src: [],  // Includes everything in "alias", plus their (recursive) dependencies
                dest: jsBundlePath
            }
        },

        uglify: {
            app: {
                src: [jsBundlePath],
                dest: jsMinBundlePath
            }
        },

        sass: {
            app: {
                src: [sassDir + 'main.scss'],
                dest: cssBundlePath
            }
        },

        concat: {
            lib: {
                src: [
                ],
                dest: cssVendorPath
            }
        },

        cssmin: {
            app: {
                src: [cssBundlePath, cssVendorPath],
                dest: cssMinBundlePath
            }
        },

        copy: {
            app: {
                expand: true,
                cwd: 'src/',
                src: appAssets,
                dest: distDir
            }
        },

        compress: {
            options: { archive: zipFilePath },
            app: {
                expand: true,
                cwd: distDir,
                src: ["**/*"]
            }
        },

        watch: {
            options: {
                cwd: srcDir,
                livereload: 35727  // Starts a livereload server on port 35727
            },
            scripts: {
                files: ['js/**/*.js', 'templates/**/*'],
                tasks: ['js', 'copy']
            },
            styles: {
                files: ['sass/**/*.scss'],
                tasks: ['sass', 'copy']
            },
            quests: {
                files: zonesJson,
                tasks: ['quests', 'copy']
            },
            assets: {
                files: appAssets,
                tasks: ['copy:app']
            }
        }
    });
};
<commit_msg>Don't watch tiles or quests directory.<commit_after>'use strict';

module.exports = function(grunt) {

    grunt.loadNpmTasks('grunt-browserify');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-sass');

    var debug = typeof grunt.option('release') === "undefined";

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

    grunt.registerTask('js', debug ? ['browserify'] : ['browserify', 'uglify']);
    grunt.registerTask('css', debug ? ['sass', 'concat:lib'] : ['sass', 'concat:lib', 'cssmin']);
    grunt.registerTask('app', ['clean', 'quests', 'js', 'css', 'copy']);

    grunt.registerTask('default', ['app', 'compress']);

    grunt.registerTask('quests', function() {
        var exec = require('child_process').exec,
            done = this.async();

        exec('python scripts/assemble_quests.py', {},
            function(err) {
                if (err) {
                    grunt.log.error(err);
                    done(false);
                } else {
                    done(true);
                }
        });
    });

    var srcDir  = 'src/',
        tempDir = 'build/temp/',
        distDir = 'www/',
        zonesJson = srcDir + 'quests/**/*.json',
        jsDir   = srcDir + 'js/',
        sassDir = srcDir + 'sass/',
        jsBundlePath     = distDir + 'bundle.js',
        jsMinBundlePath  = distDir + 'bundle.min.js',
        cssBundlePath    = distDir + 'bundle.css',
        cssVendorPath    = distDir + 'vendor.css',
        cssMinBundlePath = distDir + 'bundle.min.css',
        zipFilePath = tempDir + 'app.zip',
        watchAssets = [
            'config.xml',
            'index.html',
            'sass/lib/leaflet.css',
            'sass/lib/fontello.css',
            'sass/lib/bootstrap.min.css',
            'sass/lib/bootstrap-dialog.min.css',
            'sass/font/*',
            'sass/fonts/*',
            'img/**/*',
            'quests.json'
        ],
        appAssets = watchAssets.concat([
            'quests/**/*',
            'tiles/**/*'
        ]);

    grunt.initConfig({
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            app: ['Gruntfile.js', jsDir + '*.js']
        },

        clean: [
            tempDir + '**/*',
            distDir + '**/*'
        ],

        browserify: {
            app: {
                options: {
                    alias: [jsDir + 'app.js:app'],
                    transform: [
                        'browserify-shim',
                        ['jstify', { engine: 'lodash', noMinify: true }]
                    ],
                    bundleOptions: {
                        debug: debug  // Create source maps in debug mode
                    }
                },
                src: [],  // Includes everything in "alias", plus their (recursive) dependencies
                dest: jsBundlePath
            }
        },

        uglify: {
            app: {
                src: [jsBundlePath],
                dest: jsMinBundlePath
            }
        },

        sass: {
            app: {
                src: [sassDir + 'main.scss'],
                dest: cssBundlePath
            }
        },

        concat: {
            lib: {
                src: [
                ],
                dest: cssVendorPath
            }
        },

        cssmin: {
            app: {
                src: [cssBundlePath, cssVendorPath],
                dest: cssMinBundlePath
            }
        },

        copy: {
            app: {
                expand: true,
                cwd: 'src/',
                src: appAssets,
                dest: distDir
            }
        },

        compress: {
            options: { archive: zipFilePath },
            app: {
                expand: true,
                cwd: distDir,
                src: ["**/*"]
            }
        },

        watch: {
            options: {
                cwd: srcDir,
                livereload: 35727  // Starts a livereload server on port 35727
            },
            scripts: {
                files: ['js/**/*.js', 'templates/**/*'],
                tasks: ['js', 'copy']
            },
            styles: {
                files: ['sass/**/*.scss'],
                tasks: ['sass', 'copy']
            },
            quests: {
                files: zonesJson,
                tasks: ['quests', 'copy']
            },
            assets: {
                files: watchAssets,
                tasks: ['copy:app']
            }
        }
    });
};
<|endoftext|>


<commit_before>var gulp          = require('gulp'),
    sass          = require('gulp-sass'),
    nano          = require('gulp-cssnano'),
    deploy        = require('gulp-gh-pages'),
    concat        = require('gulp-concat'),
    uglify        = require('gulp-uglify'),
    imagemin      = require('gulp-imagemin'),
    pngquant      = require('imagemin-pngquant'),
    minifyHTML    = require('gulp-minify-html'),
    minifyInline  = require('gulp-minify-inline'),
    size          = require('gulp-size');

// Compile Sass with autoprefixer, I've removed sourcemaps
gulp.task('scss', function() {
  gulp.src('css/basekit.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(nano({autoprefixer: {browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']}}))
    .pipe(gulp.dest('css'))
    .pipe(size({ gzip: true, showFiles: true }));
});

// Easy deploy to the gh-pages branch
gulp.task('deploy', function () {
  return gulp.src('**/*')
    .pipe(deploy());
});

// Minify and concat the js files for use
gulp.task('js', function() {
  gulp.src('js/*.js')
    .pipe(concat('basekit.js'))
    .pipe(uglify())
    .pipe(gulp.dest('js/min'))
    .pipe(size({ gzip: true, showFiles: true }));
});

// Optimise images
gulp.task('img', function () {
  return gulp.src('imgs/*')
    .pipe(imagemin({
      progressive: true,
      svgoPlugins: [{removeViewBox: false}],
      multipass: true,
      use: [pngquant()]
    }))
    .pipe(gulp.dest('imgs'));
});

// Minify HTML source and rename the index-dev file
gulp.task('html', function() {
  gulp.src('./html/*.html')
    .pipe(minifyHTML({cdata: true}))
    .pipe(minifyInline())
    .pipe(gulp.dest('./'));
});

// Only watch Sass and JS files
gulp.task('watch', function() {
  gulp.watch('css/**/*.scss', ['scss']);
  gulp.watch('js/*.js', ['js']);
  gulp.watch('html');
});

gulp.task('default', ['watch']);<commit_msg>fixed gulp watch<commit_after>var gulp          = require('gulp'),
    sass          = require('gulp-sass'),
    nano          = require('gulp-cssnano'),
    deploy        = require('gulp-gh-pages'),
    concat        = require('gulp-concat'),
    uglify        = require('gulp-uglify'),
    imagemin      = require('gulp-imagemin'),
    pngquant      = require('imagemin-pngquant'),
    minifyHTML    = require('gulp-minify-html'),
    minifyInline  = require('gulp-minify-inline'),
    size          = require('gulp-size');

// Compile Sass with autoprefixer, I've removed sourcemaps
gulp.task('scss', function() {
  gulp.src('css/basekit.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(nano({autoprefixer: {browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']}}))
    .pipe(gulp.dest('css'))
    .pipe(size({ gzip: true, showFiles: true }));
});

// Easy deploy to the gh-pages branch
gulp.task('deploy', function () {
  return gulp.src('**/*')
    .pipe(deploy());
});

// Minify and concat the js files for use
gulp.task('js', function() {
  gulp.src('js/*.js')
    .pipe(concat('basekit.js'))
    .pipe(uglify())
    .pipe(gulp.dest('js/min'))
    .pipe(size({ gzip: true, showFiles: true }));
});

// Optimise images
gulp.task('img', function () {
  return gulp.src('imgs/*')
    .pipe(imagemin({
      progressive: true,
      svgoPlugins: [{removeViewBox: false}],
      multipass: true,
      use: [pngquant()]
    }))
    .pipe(gulp.dest('imgs'));
});

// Minify HTML source and rename the index-dev file
gulp.task('html', function() {
  gulp.src('./html/*.html')
    .pipe(minifyHTML({cdata: true}))
    .pipe(minifyInline())
    .pipe(gulp.dest('./'));
});

// Only watch Sass and JS files
gulp.task('watch', function() {
  gulp.watch('css/**/*.scss', ['scss']);
  gulp.watch('js/*.js', ['js']);
  gulp.watch('./html/*.html', ['html']);
});

gulp.task('default', ['watch']);<|endoftext|>


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

var webpackConfig = require('./webpack.config');
var webpackDeployConfig = require('./webpack-deploy.config');

module.exports = function(grunt) {
    grunt.loadNpmTasks('gruntify-eslint');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-webpack');

    grunt.initConfig({
        // linting task. Used to ensure code is clean
        //  before trying to build.
        eslint: {
            options: {
                configFile: 'eslint.config.js',
            },
            target: ['src/**/*.jsx', 'src/**/*.js']
        },

        // copies useful files places.
        copy: {
            // this will copy the "test" files into dist,
            //  used for 'rapid' development work.
            test: {
                files: [
                    {expand: true, flatten: true, src: ['src/test.*'], dest: 'dist/'},
                ]
            },
            fonts: {
                files: [
                    {
                        expand: true, flatten: true,
                        src: ['node_modules/font-awesome/fonts/*'],
                        dest: 'dist/fonts/'
                    }
                ]
            }
        },

        less: {
            build: {
                options: {
                    paths: ['src/less'],
                },
                files: {
                    'dist/css/geomoose.css' : 'src/less/gm3.less'
                }
            }
        },

        watch: {
            gm3: {
                files: ['src/gm3/**/*'],
                tasks: ['webpack:build-dev'],
                options: {
                    spawn: false,
                }
            }
        },

        webpack: {
            'build-dev': webpackConfig,
            'build-deploy': webpackDeployConfig
        },

        'webpack-dev-server': {
            options: {
                webpack: webpackConfig,
                publicPath: "./"
            },
            start: Object.assign({}, webpackConfig.devServer)
        }
    });

    grunt.task.registerTask('lint', ['eslint']);

    grunt.task.registerTask('serve', ['webpack-dev-server:start', 'watch:gm3']);

    grunt.task.registerTask('build-dev', ['eslint', 'webpack:build-dev']);

    grunt.task.registerTask('build-css', ['less:build', 'copy:fonts']);

    grunt.task.registerTask('build', ['eslint', 'webpack:build-deploy', 'build-css']);

};

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

var webpackConfig = require('./webpack.config');
var webpackDeployConfig = require('./webpack-deploy.config');

module.exports = function(grunt) {
    grunt.loadNpmTasks('gruntify-eslint');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-webpack');

    grunt.initConfig({
        // linting task. Used to ensure code is clean
        //  before trying to build.
        eslint: {
            options: {
                configFile: 'eslint.config.js',
            },
            target: ['src/**/*.jsx', 'src/**/*.js']
        },

        // copies useful files places.
        copy: {
            // this will copy the "test" files into dist,
            //  used for 'rapid' development work.
            test: {
                files: [
                    {expand: true, flatten: true, src: ['src/test.*'], dest: 'dist/'},
                ]
            },
            fonts: {
                files: [
                    {
                        expand: true, flatten: true,
                        src: ['node_modules/font-awesome/fonts/*'],
                        dest: 'dist/fonts/'
                    }
                ]
            }
        },

        less: {
            build: {
                options: {
                    paths: ['src/less'],
                },
                files: {
                    'dist/css/geomoose.css' : 'src/less/gm3.less'
                }
            }
        },

        watch: {
            gm3: {
                files: ['src/gm3/**/*'],
                tasks: ['webpack:build-dev'],
                options: {
                    spawn: false,
                }
            }
        },

        webpack: {
            'build-dev': webpackConfig,
            'build-deploy': webpackDeployConfig
        },

        'webpack-dev-server': {
            options: {
                webpack: webpackConfig,
                publicPath: "./"
            },
            start: Object.assign({}, webpackConfig.devServer)
        }
    });

    grunt.task.registerTask('lint', ['eslint']);

    grunt.task.registerTask('serve', ['webpack-dev-server:start', 'watch:gm3']);

    // only build the non-minified version.
    grunt.task.registerTask('build-dev', ['eslint', 'webpack:build-dev']);

    // update the css and fonts.
    grunt.task.registerTask('build-css', ['less:build', 'copy:fonts']);

    // build everything
    grunt.task.registerTask('build', ['eslint', 'webpack:build-dev', 'webpack:build-deploy', 'build-css']);
};
<|endoftext|>


<commit_before>const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const apiBasePathRouter = require('./routes');
const versionRouter = require('./routes/version/version');
const userRouter = require('./routes/users/user.router');
const adminRouter = require('./routes/admin/admin.router');
const publicBookmarksRouter = require('./routes/public/public-bookmarks.router');
const {MongoError} = require('mongodb');
const ValidationError = require('./error/validation.error');
const NotFoundError = require('./error/not-found.error');
const PublicBookmarkExistingError = require('./error/public-bookmark-existent.error');
const UseridTokenValidationError = require('./routes/users/userid-validation.error');

const fs = require('fs-extra');
const rfs = require('rotating-file-stream/index');

const HttpStatus = require('http-status-codes/index');

const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./docs/swagger.yaml');

const app = express();

const mongoUserName = process.env.MONGODB_BOOKMARKS_USERNAME || 'bookmarks';
const mongoUserPwd = process.env.MONGODB_BOOKMARKS_PASSWORD || 'secret';
const mongoBookmarksCollectionName = process.env.MONGODB_BOOKMARKS_COLLECTION || 'dev-bookmarks';
const mongoHost = process.env.MONGODB_HOST || 'localhost';
const mongoPort = process.env.MONGODB_PORT || '27017';

const mongooseConnectOptions = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false
};

const mongoUrl = `mongodb://${mongoUserName}:${mongoUserPwd}@${mongoHost}:${mongoPort}/${mongoBookmarksCollectionName}`;
mongoose.connect(mongoUrl, mongooseConnectOptions);

// sets port 3000 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 3000);

let setUpLogging = function () {
  const logDirectory = (process.env.CONTAINER_HOME || '.') + '/log';
  // ensure log directory exists
  fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
  // create a rotating write stream
  let accessLogStream = rfs('access.log', {
    interval: '1d', // rotate daily
    path: logDirectory
  })
  app.use(logger('combined', {stream: accessLogStream}));// logs in file in Apache style format
  app.use(logger('dev'));// logs at the console in 'dev' format
};

setUpLogging();

app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));//swagger docs are not protected

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//add CORS support
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, PATCH, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Location');
  res.setHeader('Access-Control-Expose-Headers', 'Content-Type, Authorization, Location');
  next();
});

app.use('/api', apiBasePathRouter);
app.use('/api/version', versionRouter);
app.use('/api/public/bookmarks', publicBookmarksRouter);
app.use('/api/personal/users', userRouter);
app.use('/api/admin', adminRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  const err = new Error('Not Found');
  err.status = HttpStatus.NOT_FOUND;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res) {
    res.status(err.status || HttpStatus.INTERNAL_SERVER_ERROR);
    res.render({
      message: err.message,
      error: err
    });
  });
}

app.use(function handleNotFoundError(error, req, res, next) {
  if (error instanceof NotFoundError) {
    return res.status(HttpStatus.NOT_FOUND).send({
      message: error.message,
      error: {}
    });
  }
  next(error);
});

app.use(function handlePublicBookmarkExistingError(error, req, res, next) {
  if (error instanceof PublicBookmarkExistingError) {
    return res.status(HttpStatus.CONFLICT).send({
      message: error.message,
      error: {}
    });
  }
  next(error);
});

app.use(function handleUserIdValidationError(error, req, res, next) {
  if (error instanceof UseridTokenValidationError) {
    res.status(HttpStatus.UNAUTHORIZED);
    return res.send({
      httpStatus: HttpStatus.UNAUTHORIZED,
      message: error.message
    });
  }
  next(error);
});

app.use(function handleValidationError(error, request, response, next) {
  if (error instanceof ValidationError) {
    return response
      .status(HttpStatus.BAD_REQUEST)
      .json({
        httpStatus: HttpStatus.BAD_REQUEST,
        message: error.message,
        validationErrors: error.validationErrors
      });
  }
  next(error);
});

app.use(function handleDatabaseError(error, request, response, next) {
  if (error instanceof MongoError) {
    if (error.code === 11000) {
      return response
        .status(HttpStatus.CONFLICT)
        .json({
          type: 'MongoError',
          message: error.message
        });
    } else {
      return response.status(503).json({
        type: 'MongoError',
        message: error.message
      });
    }
  }
  next(error);
});

// production error handler
// no stacktraces leaked to user
app.use(function (error, req, res, next) {
  if (res.headersSent) {
    return next(error)
  } else {
    res.status(error.status || HttpStatus.INTERNAL_SERVER_ERROR);
    res.send({
      message: error.message,
      error: {}
    });
  }

});

module.exports = app;
<commit_msg>add http status also in the error response to be consistent<commit_after>const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const apiBasePathRouter = require('./routes');
const versionRouter = require('./routes/version/version');
const userRouter = require('./routes/users/user.router');
const adminRouter = require('./routes/admin/admin.router');
const publicBookmarksRouter = require('./routes/public/public-bookmarks.router');
const {MongoError} = require('mongodb');
const ValidationError = require('./error/validation.error');
const NotFoundError = require('./error/not-found.error');
const PublicBookmarkExistingError = require('./error/public-bookmark-existent.error');
const UseridTokenValidationError = require('./routes/users/userid-validation.error');

const fs = require('fs-extra');
const rfs = require('rotating-file-stream/index');

const HttpStatus = require('http-status-codes/index');

const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./docs/swagger.yaml');

const app = express();

const mongoUserName = process.env.MONGODB_BOOKMARKS_USERNAME || 'bookmarks';
const mongoUserPwd = process.env.MONGODB_BOOKMARKS_PASSWORD || 'secret';
const mongoBookmarksCollectionName = process.env.MONGODB_BOOKMARKS_COLLECTION || 'dev-bookmarks';
const mongoHost = process.env.MONGODB_HOST || 'localhost';
const mongoPort = process.env.MONGODB_PORT || '27017';

const mongooseConnectOptions = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false
};

const mongoUrl = `mongodb://${mongoUserName}:${mongoUserPwd}@${mongoHost}:${mongoPort}/${mongoBookmarksCollectionName}`;
mongoose.connect(mongoUrl, mongooseConnectOptions);

// sets port 3000 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 3000);

let setUpLogging = function () {
  const logDirectory = (process.env.CONTAINER_HOME || '.') + '/log';
  // ensure log directory exists
  fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
  // create a rotating write stream
  let accessLogStream = rfs('access.log', {
    interval: '1d', // rotate daily
    path: logDirectory
  })
  app.use(logger('combined', {stream: accessLogStream}));// logs in file in Apache style format
  app.use(logger('dev'));// logs at the console in 'dev' format
};

setUpLogging();

app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));//swagger docs are not protected

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//add CORS support
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, PATCH, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Location');
  res.setHeader('Access-Control-Expose-Headers', 'Content-Type, Authorization, Location');
  next();
});

app.use('/api', apiBasePathRouter);
app.use('/api/version', versionRouter);
app.use('/api/public/bookmarks', publicBookmarksRouter);
app.use('/api/personal/users', userRouter);
app.use('/api/admin', adminRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  const err = new Error('Not Found');
  err.status = HttpStatus.NOT_FOUND;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res) {
    res.status(err.status || HttpStatus.INTERNAL_SERVER_ERROR);
    res.render({
      message: err.message,
      error: err
    });
  });
}

app.use(function handleNotFoundError(error, req, res, next) {
  if (error instanceof NotFoundError) {
    return res.status(HttpStatus.NOT_FOUND).send({
      httpStatus: HttpStatus.NOT_FOUND,
      message: error.message,
      error: {}
    });
  }
  next(error);
});

app.use(function handlePublicBookmarkExistingError(error, req, res, next) {
  if (error instanceof PublicBookmarkExistingError) {
    return res.status(HttpStatus.CONFLICT).send({
      httpStatus: HttpStatus.CONFLICT,
      message: error.message,
      error: {}
    });
  }
  next(error);
});

app.use(function handleUserIdValidationError(error, req, res, next) {
  if (error instanceof UseridTokenValidationError) {
    res.status(HttpStatus.UNAUTHORIZED);
    return res.send({
      httpStatus: HttpStatus.UNAUTHORIZED,
      message: error.message
    });
  }
  next(error);
});

app.use(function handleValidationError(error, request, response, next) {
  if (error instanceof ValidationError) {
    return response
      .status(HttpStatus.BAD_REQUEST)
      .json({
        httpStatus: HttpStatus.BAD_REQUEST,
        message: error.message,
        validationErrors: error.validationErrors
      });
  }
  next(error);
});

app.use(function handleDatabaseError(error, request, response, next) {
  if (error instanceof MongoError) {
    if (error.code === 11000) {
      return response
        .status(HttpStatus.CONFLICT)
        .json({
          httpStatus: HttpStatus.CONFLICT,
          type: 'MongoError',
          message: error.message
        });
    } else {
      return response.status(503).json({
        httpStatus: HttpStatus.SERVICE_UNAVAILABLE,
        type: 'MongoError',
        message: error.message
      });
    }
  }
  next(error);
});

// production error handler
// no stacktraces leaked to user
app.use(function (error, req, res, next) {
  if (res.headersSent) {
    return next(error)
  } else {
    res.status(error.status || HttpStatus.INTERNAL_SERVER_ERROR);
    res.send({
      message: error.message,
      error: {}
    });
  }

});

module.exports = app;
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  require('load-grunt-tasks')(grunt);
  var path = require('path')

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    pkgMeta: grunt.file.readJSON('config/meta.json'),
    dest: grunt.option('target') || 'dist',
    basePath: path.join('<%= dest %>', 'App_Plugins', '<%= pkgMeta.name %>'),

    watch: {
      options: {
        spawn: false,
        atBegin: true
      },

      less: {
        files: ['app/**/*.less'],
        tasks: ['less:dist']
      },

      js: {
        files: ['app/**/*.js'],
        tasks: ['concat:dist']
      },

      html: {
        files: ['app/**/*.html'],
        tasks: ['copy:html']
      },

      dll: {
        files: ['app/Umbraco/**/*.dll'],
        tasks: ['copy:dll']
      }
    },

    less: {
      dist: {
        options: {
          paths: ["app/less", "lib/less", "vendor"],
        },
        files: {
          '<%= basePath %>/css/archetype.css': 'app/less/archetype.less',
        }
      }
    },

    concat: {
      options: {
        stripBanners: false
      },
      dist: {
        src: [
          'app/controllers/controller.js',
          'app/controllers/config.controller.js',
          'app/directives/archetypeproperty.js',
          'app/directives/archetypesubmitwatcher.js',
          'app/directives/archetypecustomview.js',
          'app/directives/localize.js',
          'app/services/localization.js',
          'app/helpers/labelhelpers.js',
          'app/resources/propertyeditor.js'
        ],
        dest: '<%= basePath %>/js/archetype.js'
      }
    },

    copy: {
      html: {
        cwd: 'app/views/',
        src: ['archetype.html', 'archetype.default.html', 'archetype.config.html'],
        dest: '<%= basePath %>/views',
        expand: true
      },
      dll: {
        cwd: 'app/Umbraco/Umbraco.Archetype/bin/Release/',
        src: 'Archetype.dll',
        dest: '<%= dest %>/bin/',
        expand: true
      },
      config: {
        files: [
          {
            cwd: 'app/langs/',
            src: ['**'],
            dest: '<%= basePath %>/langs',
            expand: true
          }
        ]
      },
      nuget: {
        files: [
          {
            cwd: '<%= dest %>',
            src: ['**/*', '!bin', '!bin/*'],
            dest: 'tmp/nuget/content',
            expand: true
          },
          {
            cwd: '<%= dest %>/bin',
            src: ['*.dll'],
            dest: 'tmp/nuget/lib/net40',
            expand: true
          }
        ]
      },
      umbraco: {
        cwd: '<%= dest %>',
        src: '**/*',
        dest: 'tmp/umbraco',
        expand: true
      }
    },

    nugetpack: {
    	dist: {
    		src: 'tmp/nuget/package.nuspec',
    		dest: 'pkg'
    	}
    },

    template: {
    	'nuspec': {
			'options': {
    			'data': {
            name: '<%= pkgMeta.name %>',
    				version: '<%= pkgMeta.version %>',
            url: '<%= pkgMeta.url %>',
            license: '<%= pkgMeta.license %>',
            licenseUrl: '<%= pkgMeta.licenseUrl %>',
            author: '<%= pkgMeta.author %>',
            authorUrl: '<%= pkgMeta.authorUrl %>',

    				files: [{ path: 'tmp/nuget/**', target: 'content/App_Plugins/Archetype'}]
	    		}
    		},
    		'files': {
    			'tmp/nuget/package.nuspec': ['config/package.nuspec']
    		}
    	}
    },

    umbracoPackage: {
      options: {
        name: "<%= pkgMeta.name %>",
        version: '<%= pkgMeta.version %>',
        url: '<%= pkgMeta.url %>',
        license: '<%= pkgMeta.license %>',
        licenseUrl: '<%= pkgMeta.licenseUrl %>',
        author: '<%= pkgMeta.author %>',
        authorUrl: '<%= pkgMeta.authorUrl %>',
        manifest: 'config/package.xml',
        readme: 'config/readme.txt',
        sourceDir: 'tmp/umbraco',
        outputDir: 'pkg',
      }
    },

    clean: {
      build: '<%= grunt.config("basePath").substring(0, 4) == "dist" ? "dist/**/*" : "null" %>',
      tmp: ['tmp']
    },

    assemblyinfo: {
      options: {
        files: ['app/Umbraco/Umbraco.Archetype/Archetype.Umbraco.csproj'],
        filename: 'VersionInfo.cs',
        info: {
          version: '<%= (pkgMeta.version.indexOf("-") > 0 ? pkgMeta.version.substring(0, pkgMeta.version.indexOf("-")) : pkgMeta.version) %>',
          fileVersion: '<%= pkgMeta.version %>'
        }
      }
    },

    touch: {
      webconfig: {
        src: ['<%= grunt.option("target") %>\\Web.config']
      }
    },

    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      src: {
        src: ['app/**/*.js', 'lib/**/*.js']
      }
    },

    msbuild: {
      options: {
        stdout: true,
        verbosity: 'quiet',
        maxCpuCount: 4,
		version: 4.0,
        buildParameters: {
          WarningLevel: 2,
          NoWarn: 1607
        }
      },
      dist: {
        src: ['app/Umbraco/Umbraco.Archetype/Archetype.Umbraco.csproj'],
        options: {
          projectConfiguration: 'Release',
          targets: ['Clean', 'Rebuild'],
        }
      }
    }

  });

  grunt.registerTask('default', ['clean', 'less', 'concat', 'assemblyinfo', 'msbuild:dist', 'copy:dll', 'copy:config', 'copy:html']);

  grunt.registerTask('nuget',   ['clean:tmp', 'default', 'copy:nuget', 'template:nuspec', 'nugetpack', 'clean:tmp']);
  grunt.registerTask('umbraco', ['clean:tmp', 'default', 'copy:umbraco', 'umbracoPackage', 'clean:tmp']);
  grunt.registerTask('package', ['clean:tmp', 'default', 'copy:nuget', 'template:nuspec', 'nugetpack', 'copy:umbraco', 'umbracoPackage', 'clean:tmp']);
};<commit_msg>Add Courier dll to the distribution<commit_after>module.exports = function(grunt) {
  require('load-grunt-tasks')(grunt);
  var path = require('path')

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    pkgMeta: grunt.file.readJSON('config/meta.json'),
    dest: grunt.option('target') || 'dist',
    basePath: path.join('<%= dest %>', 'App_Plugins', '<%= pkgMeta.name %>'),

    watch: {
      options: {
        spawn: false,
        atBegin: true
      },

      less: {
        files: ['app/**/*.less'],
        tasks: ['less:dist']
      },

      js: {
        files: ['app/**/*.js'],
        tasks: ['concat:dist']
      },

      html: {
        files: ['app/**/*.html'],
        tasks: ['copy:html']
      },

      dll: {
        files: ['app/Umbraco/**/*.dll'],
        tasks: ['copy:dll']
      }
    },

    less: {
      dist: {
        options: {
          paths: ["app/less", "lib/less", "vendor"],
        },
        files: {
          '<%= basePath %>/css/archetype.css': 'app/less/archetype.less',
        }
      }
    },

    concat: {
      options: {
        stripBanners: false
      },
      dist: {
        src: [
          'app/controllers/controller.js',
          'app/controllers/config.controller.js',
          'app/directives/archetypeproperty.js',
          'app/directives/archetypesubmitwatcher.js',
          'app/directives/archetypecustomview.js',
          'app/directives/localize.js',
          'app/services/localization.js',
          'app/helpers/labelhelpers.js',
          'app/resources/propertyeditor.js'
        ],
        dest: '<%= basePath %>/js/archetype.js'
      }
    },

    copy: {
      html: {
        cwd: 'app/views/',
        src: ['archetype.html', 'archetype.default.html', 'archetype.config.html'],
        dest: '<%= basePath %>/views',
        expand: true
      },
      dll: {
        cwd: 'app/Umbraco/Umbraco.Archetype/bin/Release/',
        src: 'Archetype.dll',
        dest: '<%= dest %>/bin/',
        expand: true
      },
	  dll_courier: {
        cwd: 'app/Umbraco/Archetype.Courier/bin/Debug',
        src: 'Archetype.Courier.dll',
        dest: '<%= dest %>/bin/',
        expand: true
      },
      config: {
        files: [
          {
            cwd: 'app/langs/',
            src: ['**'],
            dest: '<%= basePath %>/langs',
            expand: true
          }
        ]
      },
      nuget: {
        files: [
          {
            cwd: '<%= dest %>',
            src: ['**/*', '!bin', '!bin/*'],
            dest: 'tmp/nuget/content',
            expand: true
          },
          {
            cwd: '<%= dest %>/bin',
            src: ['*.dll'],
            dest: 'tmp/nuget/lib/net40',
            expand: true
          }
        ]
      },
      umbraco: {
        cwd: '<%= dest %>',
        src: '**/*',
        dest: 'tmp/umbraco',
        expand: true
      }
    },

    nugetpack: {
    	dist: {
    		src: 'tmp/nuget/package.nuspec',
    		dest: 'pkg'
    	}
    },

    template: {
    	'nuspec': {
			'options': {
    			'data': {
            name: '<%= pkgMeta.name %>',
    				version: '<%= pkgMeta.version %>',
            url: '<%= pkgMeta.url %>',
            license: '<%= pkgMeta.license %>',
            licenseUrl: '<%= pkgMeta.licenseUrl %>',
            author: '<%= pkgMeta.author %>',
            authorUrl: '<%= pkgMeta.authorUrl %>',

    				files: [{ path: 'tmp/nuget/**', target: 'content/App_Plugins/Archetype'}]
	    		}
    		},
    		'files': {
    			'tmp/nuget/package.nuspec': ['config/package.nuspec']
    		}
    	}
    },

    umbracoPackage: {
      options: {
        name: "<%= pkgMeta.name %>",
        version: '<%= pkgMeta.version %>',
        url: '<%= pkgMeta.url %>',
        license: '<%= pkgMeta.license %>',
        licenseUrl: '<%= pkgMeta.licenseUrl %>',
        author: '<%= pkgMeta.author %>',
        authorUrl: '<%= pkgMeta.authorUrl %>',
        manifest: 'config/package.xml',
        readme: 'config/readme.txt',
        sourceDir: 'tmp/umbraco',
        outputDir: 'pkg',
      }
    },

    clean: {
      build: '<%= grunt.config("basePath").substring(0, 4) == "dist" ? "dist/**/*" : "null" %>',
      tmp: ['tmp']
    },

    assemblyinfo: {
      options: {
        files: ['app/Umbraco/Umbraco.Archetype/Archetype.Umbraco.csproj'],
        filename: 'VersionInfo.cs',
        info: {
          version: '<%= (pkgMeta.version.indexOf("-") > 0 ? pkgMeta.version.substring(0, pkgMeta.version.indexOf("-")) : pkgMeta.version) %>',
          fileVersion: '<%= pkgMeta.version %>'
        }
      }
    },

    touch: {
      webconfig: {
        src: ['<%= grunt.option("target") %>\\Web.config']
      }
    },

    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      src: {
        src: ['app/**/*.js', 'lib/**/*.js']
      }
    },

    msbuild: {
      options: {
        stdout: true,
        verbosity: 'quiet',
        maxCpuCount: 4,
		version: 4.0,
        buildParameters: {
          WarningLevel: 2,
          NoWarn: 1607
        }
      },
      dist: {
        src: ['app/Umbraco/Umbraco.Archetype/Archetype.Umbraco.csproj'],
        options: {
          projectConfiguration: 'Release',
          targets: ['Clean', 'Rebuild'],
        }
      }
    }

  });

  grunt.registerTask('default', ['clean', 'less', 'concat', 'assemblyinfo', 'msbuild:dist', 'copy:dll', 'copy:dll_courier', 'copy:config', 'copy:html']);

  grunt.registerTask('nuget',   ['clean:tmp', 'default', 'copy:nuget', 'template:nuspec', 'nugetpack', 'clean:tmp']);
  grunt.registerTask('umbraco', ['clean:tmp', 'default', 'copy:umbraco', 'umbracoPackage', 'clean:tmp']);
  grunt.registerTask('package', ['clean:tmp', 'default', 'copy:nuget', 'template:nuspec', 'nugetpack', 'copy:umbraco', 'umbracoPackage', 'clean:tmp']);
};<|endoftext|>


<commit_before>var gulp = require('gulp');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var rimraf = require('rimraf');
var codecov = require('gulp-codecov');

gulp.task('clean', function (cb) {
  rimraf('./coverage', cb);
});

gulp.task('instrument', function () {
  return gulp.src(['src/*.js'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['clean', 'instrument'], function () {
  return gulp.src(['test/spec.js'])
    .pipe(mocha())
    .pipe(istanbul.writeReports());
});

gulp.task('coveralls', function () {
  gulp.src('coverage/coverage-final.json')
    .pipe(coveralls());
});

gulp.task('default', ['test']);
<commit_msg>fix: code coverage<commit_after>var gulp = require('gulp');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var rimraf = require('rimraf');
var codecov = require('gulp-codecov');

gulp.task('clean', function (cb) {
  rimraf('./coverage', cb);
});

gulp.task('instrument', function () {
  return gulp.src(['src/*.js'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['clean', 'instrument'], function () {
  return gulp.src(['test/spec.js'])
    .pipe(mocha())
    .pipe(istanbul.writeReports());
});

gulp.task('codecov', function () {
  gulp.src('coverage/coverage-final.json')
    .pipe(codecov());
});

gulp.task('default', ['test']);
<|endoftext|>


<commit_before>//var testacular = require('testacular');

/*global module:false*/
module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-karma');

  // Project configuration.
  grunt.initConfig({
    builddir: 'build',
    pkg: grunt.file.readJSON('package.json'),
    meta: {
      banner: '/**\n' + ' * <%= pkg.description %>\n' +
        ' * @version v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        ' * @link <%= pkg.homepage %>\n' +
        ' * @license MIT License, http://www.opensource.org/licenses/MIT\n' + ' */',
      prefix: '(function (window, angular, undefined) {',
      suffix: '})(window, window.angular);'
    },
    clean: [ '<%= builddir %>' ],
    concat: {
      build: {
        src: [
          '<banner:meta.banner>',
          '<banner:meta.prefix>',
          'src/common.js',
          'src/templateFactory.js',
          'src/urlMatcherFactory.js',
          'src/urlRouter.js',
          'src/state.js',
          'src/viewDirective.js',
          'src/compat.js',
          '<banner:meta.suffix>'
        ],
        dest: '<%= builddir %>/<%= pkg.name %>.js'
      }
    },
    uglify: {
      build: {
        files: {
          '<%= builddir %>/<%= pkg.name %>.min.js': ['<banner:meta.banner>', '<%= concat.build.dest %>']
        }
      }
    },
    jshint: {
      all: ['Gruntfile.js', 'src/*.js', '<%= builddir %>/<%= pkg.name %>.js'],
      options: {
        eqnull: true
      }
    },
    watch: {
      files: ['src/*.js', 'test/**/*.js'],
      tasks: ['build','karma:debug']
    },
    connect: {
      server: {}
    },
	karma: {
		unit: {
			configFile: 'test/test-config.js',
			runnerPort: 9999,
			singleRun: true,
			browsers: ['PhantomJS']
		},

		debug: {
			configFile: 'test/test-config.js',
			runnerPort: 9999,
			singleRun: true,
			browsers: ['PhantomJS']
		}
	}
  });

  grunt.registerTask('default', ['build', 'jshint', 'karma:unit']);
  grunt.registerTask('build', 'Perform a normal build', ['concat', 'uglify']);
  grunt.registerTask('dist', 'Perform a clean build and generate documentation', ['clean', 'build', 'jsdoc']);
  grunt.registerTask('dev', 'Run dev server and watch for changes', ['build', 'connect', 'watch']);

  // grunt.registerTask('test-server', 'Start testacular server', function () {
    // //Mark the task as async but never call done, so the server stays up
    // var done = this.async();
    // testacular.server.start({ configFile: 'test/test-config.js'});
  // });

  // grunt.registerTask('test', 'Run tests (make sure test-server task is run first)', function () {
    // var done = this.async();
    // grunt.util.spawn({
      // cmd: process.platform === 'win32' ? 'karma.cmd' : 'karma',
      // args: process.env.TRAVIS ? ['start', 'test/test-config.js', '--single-run', '--no-auto-watch', '--reporter=dots', '--browsers=Firefox'] : ['run']
    // }, function (error, result, code) {
      // if (error) {
        // grunt.warn("Make sure the testacular server is online: run `grunt test-server`.\n" +
          // "Also make sure you have a browser open to http://localhost:8080/.\n" +
          // error.stdout + error.stderr);
        // //the testacular runner somehow modifies the files if it errors(??).
        // //this causes grunt's watch task to re-fire itself constantly,
        // //unless we wait for a sec
        // setTimeout(done, 1000);
      // } else {
        // grunt.log.write(result.stdout);
        // done();
      // }
    // });
  // });

  grunt.registerTask('jsdoc', 'Generate documentation', function () {
    var done = this.async();
    grunt.util.spawn({
      cmd: 'node_modules/jsdoc/jsdoc',
      args: [ '-c', 'jsdoc-conf.json', '-d', grunt.config('builddir') + '/doc', 'src' ]
    }, function (error, result, code) {
      if (error) {
        grunt.log.write(error.stderr + '\n');
        grunt.warn("jsdoc generation failed");
      } else {
        grunt.log.write(result.stderr + result.stdout);
      }
      done();
    });
  });
};
<commit_msg>Fix prefixes for concat/minify (closes #75)<commit_after>//var testacular = require('testacular');

/*global module:false*/
module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-karma');

  // Project configuration.
  grunt.initConfig({
    builddir: 'build',
    pkg: grunt.file.readJSON('package.json'),
    meta: {
      banner: '/**\n' + ' * <%= pkg.description %>\n' +
        ' * @version v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        ' * @link <%= pkg.homepage %>\n' +
        ' * @license MIT License, http://www.opensource.org/licenses/MIT\n' + ' */'
    },
    clean: [ '<%= builddir %>' ],
    concat: {
      options: {
        banner: '<%= meta.banner %>\n(function (window, angular, undefined) {\n',
        footer: '})(window, window.angular);'
      },
      build: {
        src: [
          '<banner:meta.banner>',
          '<banner:meta.prefix>',
          'src/common.js',
          'src/templateFactory.js',
          'src/urlMatcherFactory.js',
          'src/urlRouter.js',
          'src/state.js',
          'src/viewDirective.js',
          'src/compat.js',
          '<banner:meta.suffix>'
        ],
        dest: '<%= builddir %>/<%= pkg.name %>.js'
      }
    },
    uglify: {
      options: {
        banner: '<%= meta.banner %>\n'
      },
      build: {
        files: {
          '<%= builddir %>/<%= pkg.name %>.min.js': ['<banner:meta.banner>', '<%= concat.build.dest %>']
        }
      }
    },
    jshint: {
      all: ['Gruntfile.js', 'src/*.js', '<%= builddir %>/<%= pkg.name %>.js'],
      options: {
        eqnull: true
      }
    },
    watch: {
      files: ['src/*.js', 'test/**/*.js'],
      tasks: ['build','karma:debug']
    },
    connect: {
      server: {}
    },
	karma: {
		unit: {
			configFile: 'test/test-config.js',
			runnerPort: 9999,
			singleRun: true,
			browsers: ['PhantomJS']
		},

		debug: {
			configFile: 'test/test-config.js',
			runnerPort: 9999,
			singleRun: true,
			browsers: ['PhantomJS']
		}
	}
  });

  grunt.registerTask('default', ['build', 'jshint', 'karma:unit']);
  grunt.registerTask('build', 'Perform a normal build', ['concat', 'uglify']);
  grunt.registerTask('dist', 'Perform a clean build and generate documentation', ['clean', 'build', 'jsdoc']);
  grunt.registerTask('dev', 'Run dev server and watch for changes', ['build', 'connect', 'watch']);

  // grunt.registerTask('test-server', 'Start testacular server', function () {
    // //Mark the task as async but never call done, so the server stays up
    // var done = this.async();
    // testacular.server.start({ configFile: 'test/test-config.js'});
  // });

  // grunt.registerTask('test', 'Run tests (make sure test-server task is run first)', function () {
    // var done = this.async();
    // grunt.util.spawn({
      // cmd: process.platform === 'win32' ? 'karma.cmd' : 'karma',
      // args: process.env.TRAVIS ? ['start', 'test/test-config.js', '--single-run', '--no-auto-watch', '--reporter=dots', '--browsers=Firefox'] : ['run']
    // }, function (error, result, code) {
      // if (error) {
        // grunt.warn("Make sure the testacular server is online: run `grunt test-server`.\n" +
          // "Also make sure you have a browser open to http://localhost:8080/.\n" +
          // error.stdout + error.stderr);
        // //the testacular runner somehow modifies the files if it errors(??).
        // //this causes grunt's watch task to re-fire itself constantly,
        // //unless we wait for a sec
        // setTimeout(done, 1000);
      // } else {
        // grunt.log.write(result.stdout);
        // done();
      // }
    // });
  // });

  grunt.registerTask('jsdoc', 'Generate documentation', function () {
    var done = this.async();
    grunt.util.spawn({
      cmd: 'node_modules/jsdoc/jsdoc',
      args: [ '-c', 'jsdoc-conf.json', '-d', grunt.config('builddir') + '/doc', 'src' ]
    }, function (error, result, code) {
      if (error) {
        grunt.log.write(error.stderr + '\n');
        grunt.warn("jsdoc generation failed");
      } else {
        grunt.log.write(result.stderr + result.stdout);
      }
      done();
    });
  });
};
<|endoftext|>


<commit_before>(function() {
  "use strict";
  module.exports = function() {

    var banner =
      "/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today('yyyy-mm-dd') %> (<%= grunt.template.date('longTime') %>)\n"+
      "* Copyright (c) <%= grunt.template.today('yyyy') %> <%= pkg.author.name %>; Licensed <%= _.pluck(pkg.licenses, 'type').join(', ') %> */\n";

    var sources = {
      scripts: ['Gruntfile.js', 'the-*/*.js'],
      elements: ['the-*/*.html'],
      stylus: ['themes/*/*.styl'],
      css: ['themes/*.css']
    };

    var glob = require('glob');
    var stylExpand = glob.sync('./themes/*.styl').join(' ');

    var jshintOptions = {
      strict: true,
      newcap: false,
      "globals": { "Polymer": true }
    };

    this.initConfig({
      pkg: this.file.readJSON('package.json'),
      'bower-install-simple': {
        deps: {
          options: {
            interactive: false,
            forceLatest: false,
            directory: 'bower_components'
          }
        }
      },
      exec: {
        build_stylus: {
          command: 'node ./node_modules/stylus/bin/stylus ' + stylExpand
        },
        build_fa: {
          command: 'node ./scripts/build-font-awesome-javascript.js'
        }
      },
      browserify: {
        libs: {
          files: {
            'build/noflo.js': ['index.js'],
          },
          options: {
            transform: ['coffeeify']
          },
          browserifyOptions: {
            require: 'noflo'
          }
        }
      },
      jshint: {
        options: jshintOptions,
        all: {
          src: sources.scripts
        },
        force: {
          src: sources.scripts,
          options: { force: true }
        }
      },
      inlinelint: {
        options: jshintOptions,
        all: {
          src: sources.elements,
        },
        force: {
          src: sources.elements,
          options: { force: true }
        }
      },
      connect: {
        server: {
          options: {
            port: 3000,
            hostname: '*', // Allow connection from mobile
            livereload: true
          }
        }
      },
      watch: {
        scripts: {
          files: sources.scripts,
          tasks: ['jshint:force'],
          options: {
            // nospawn: true,
            livereload: true
          }
        },
        elements: {
          files: sources.elements,
          tasks: ['inlinelint:force'],
          options: {
            // nospawn: true,
            livereload: true
          }
        },
        stylus: {
          files: sources.stylus,
          tasks: ['exec:build_stylus'],
          options: {
            // nospawn: true,
            livereload: false
          }
        },
        css: {
          files: sources.css,
          options: {
            // nospawn: true,
            livereload: true
          }
        }
      }
    });

    // Only lint changed file
    // this.event.on('watch', function(action, filepath) {
    //   this.config('jshint.all.src', filepath);
    //   this.config('inlinelint.all.src', filepath);
    // }.bind(this));

    this.loadNpmTasks('grunt-bower-install-simple');
    this.loadNpmTasks('grunt-exec');
    this.loadNpmTasks('grunt-contrib-watch');
    this.loadNpmTasks('grunt-contrib-jshint');
    this.loadNpmTasks('grunt-lint-inline');
    this.loadNpmTasks('grunt-contrib-connect');
    this.loadNpmTasks('grunt-browserify');

    this.registerTask('dev', ['test', 'connect:server', 'watch']);
    this.registerTask('build', ['bower-install-simple', 'exec:build_stylus', 'exec:build_fa', 'browserify:libs']);
    this.registerTask('test', ['jshint:all', 'inlinelint:all', 'build']);
    this.registerTask('default', ['test']);
  };

}).call(this);
<commit_msg>Join the build foehn icons<commit_after>(function() {
  "use strict";
  module.exports = function() {

    var banner =
      "/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today('yyyy-mm-dd') %> (<%= grunt.template.date('longTime') %>)\n"+
      "* Copyright (c) <%= grunt.template.today('yyyy') %> <%= pkg.author.name %>; Licensed <%= _.pluck(pkg.licenses, 'type').join(', ') %> */\n";

    var sources = {
      scripts: ['Gruntfile.js', 'the-*/*.js'],
      elements: ['the-*/*.html'],
      stylus: ['themes/*/*.styl'],
      css: ['themes/*.css']
    };

    var glob = require('glob');
    var stylExpand = glob.sync('./themes/*.styl').join(' ');

    var jshintOptions = {
      strict: true,
      newcap: false,
      "globals": { "Polymer": true }
    };

    this.initConfig({
      pkg: this.file.readJSON('package.json'),
      'bower-install-simple': {
        deps: {
          options: {
            interactive: false,
            forceLatest: false,
            directory: 'bower_components'
          }
        }
      },
      exec: {
        build_stylus: {
          command: 'node ./node_modules/stylus/bin/stylus ' + stylExpand
        },
        build_fa: {
          command: 'node ./scripts/build-font-awesome-javascript.js'
        },
        build_fo: {
          command: 'node ./scripts/build-font-foehn-javascript.js'
        }

      },
      browserify: {
        libs: {
          files: {
            'build/noflo.js': ['index.js'],
          },
          options: {
            transform: ['coffeeify']
          },
          browserifyOptions: {
            require: 'noflo'
          }
        }
      },
      jshint: {
        options: jshintOptions,
        all: {
          src: sources.scripts
        },
        force: {
          src: sources.scripts,
          options: { force: true }
        }
      },
      inlinelint: {
        options: jshintOptions,
        all: {
          src: sources.elements,
        },
        force: {
          src: sources.elements,
          options: { force: true }
        }
      },
      connect: {
        server: {
          options: {
            port: 3000,
            hostname: '*', // Allow connection from mobile
            livereload: true
          }
        }
      },
      watch: {
        scripts: {
          files: sources.scripts,
          tasks: ['jshint:force'],
          options: {
            // nospawn: true,
            livereload: true
          }
        },
        elements: {
          files: sources.elements,
          tasks: ['inlinelint:force'],
          options: {
            // nospawn: true,
            livereload: true
          }
        },
        stylus: {
          files: sources.stylus,
          tasks: ['exec:build_stylus'],
          options: {
            // nospawn: true,
            livereload: false
          }
        },
        css: {
          files: sources.css,
          options: {
            // nospawn: true,
            livereload: true
          }
        }
      }
    });

    // Only lint changed file
    // this.event.on('watch', function(action, filepath) {
    //   this.config('jshint.all.src', filepath);
    //   this.config('inlinelint.all.src', filepath);
    // }.bind(this));

    this.loadNpmTasks('grunt-bower-install-simple');
    this.loadNpmTasks('grunt-exec');
    this.loadNpmTasks('grunt-contrib-watch');
    this.loadNpmTasks('grunt-contrib-jshint');
    this.loadNpmTasks('grunt-lint-inline');
    this.loadNpmTasks('grunt-contrib-connect');
    this.loadNpmTasks('grunt-browserify');

    this.registerTask('dev', ['test', 'connect:server', 'watch']);
    this.registerTask('build', ['bower-install-simple', 'exec:build_stylus', 'exec:build_fa', 'exec:build_fo', 'browserify:libs']);
    this.registerTask('test', ['jshint:all', 'inlinelint:all', 'build']);
    this.registerTask('default', ['test']);
  };

}).call(this);
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    mainBowerFiles = require('main-bower-files'),
    minifyCss = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    addsrc = require('gulp-add-src'),
    sass = require('gulp-sass'),
    exec = require('gulp-exec'),
    ngAnnotate = require('gulp-ng-annotate'),
    sourcemaps = require('gulp-sourcemaps'),
    browserSync = require('browser-sync').create(),
    watch = require('gulp-watch'),
    plumber = require('gulp-plumber'),
    jshint = require('gulp-jshint'),
    notify = require('gulp-notify'),
    templateCache = require('gulp-angular-templatecache'),
    spawn = require('child_process').spawn,
    node;

//****************************************************************
//JavaScripts section
gulp.task('scripts', function() {
    return gulp.src([
            'app/angular/**/*.js',
            'app/scripts/**/*.js'])
        .pipe(plumber())
        .pipe(sourcemaps.init())
        .pipe(ngAnnotate())
        .pipe(jshint())
        // .pipe(jshint.reporter('default'))
        .pipe(concat('application.min.js'))
        .pipe(sourcemaps.write('maps'))
        .pipe(gulp.dest('public/js'))
        .pipe(notify({ message: 'Script task complete' }));;
});

gulp.task('vendor-js', function() {
    return gulp.src(mainBowerFiles('**/*.js'))
        .pipe(plumber())
        .pipe(concat('vendors.min.js'))
        .pipe(gulp.dest('public/js'));
});

//****************************************************************
//CSS section
//External styles
gulp.task('normalize', function() {
    return gulp.src(mainBowerFiles('**/*.css'))
        .pipe(minifyCss({compatibility: 'ie8'}))
        .pipe(gulp.dest('public/css'));
});

gulp.task('vendor-css', ['normalize'], function(){
});

//Custom styles
gulp.task('styles', function() {
    return gulp.src([
            'app/styles/**/*.scss',
            'app/styles/**/*.css'])
        .pipe(sass().on('error', sass.logError))
        .pipe(concat('application.min.css'))
        .pipe(minifyCss({compatibility: 'ie8'}))
        .pipe(gulp.dest('public/css'))
        .pipe(notify({ message: 'Styles task complete' }));
});

//****************************************************************
//General section
// Vendors scripts and styles
gulp.task('vendors', ['vendor-css', 'vendor-js'], function () {
});

//****************************************************************
// watching scss/js/html files
gulp.task('watch', ['vendors', 'scripts', 'styles', 'template', 'server'], function() {
    gulp.watch('app/styles/**/*.css', ['styles']);
    gulp.watch('app/styles/**/*.scss', ['styles']);
    gulp.watch([
        'app/scripts/**/*.js',
        'app/angular/**/*.js'
        ], ['scripts']);
    gulp.watch('app/angular/**/*.html', ['template']);
    gulp.watch([
        'config/*.js',
        'routes/*.js',
        'views/*.ejs',
        'app.js',
        'app/models/*.js'
        ], ['server']);
});

//****************************************************************
// Angular templates
gulp.task('template', function() {
    return gulp.src('app/angular/**/*.html')
        .pipe(templateCache('templates.js', {standalone:true}))
        .pipe(gulp.dest('app/angular'))
        .pipe(notify({ message: 'Template task complete' }));
});

//****************************************************************
/**
 * $ gulp server
 * description: launch the server. If there's a server already running, kill it.
 */
gulp.task('server', function() {
  if (node) node.kill()
  node = spawn('node', ['./bin/www'], {stdio: 'inherit'})
  node.on('close', function (code) {
    if (code === 8) {
      gulp.log('Error detected, waiting for changes...');
    }
  });
})

// clean up if an error goes unhandled.
process.on('exit', function() {
    if (node) node.kill()
})

//Default task
gulp.task('default', ['watch'], function() {
});

// heroku task
gulp.task('heroku:test', ['vendors', 'scripts', 'styles', 'template']);

<commit_msg>gulp templates fix<commit_after>var gulp = require('gulp'),
    mainBowerFiles = require('main-bower-files'),
    minifyCss = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    addsrc = require('gulp-add-src'),
    sass = require('gulp-sass'),
    exec = require('gulp-exec'),
    ngAnnotate = require('gulp-ng-annotate'),
    sourcemaps = require('gulp-sourcemaps'),
    browserSync = require('browser-sync').create(),
    watch = require('gulp-watch'),
    plumber = require('gulp-plumber'),
    jshint = require('gulp-jshint'),
    notify = require('gulp-notify'),
    templateCache = require('gulp-angular-templatecache'),
    spawn = require('child_process').spawn,
    node;

//****************************************************************
//JavaScripts section
gulp.task('scripts', ['template'], function() {
    return gulp.src([
            'app/angular/**/*.js',
            'app/scripts/**/*.js'])
        .pipe(plumber())
        .pipe(sourcemaps.init())
        .pipe(ngAnnotate())
        .pipe(jshint())
        // .pipe(jshint.reporter('default'))
        .pipe(concat('application.min.js'))
        .pipe(sourcemaps.write('maps'))
        .pipe(gulp.dest('public/js'))
        .pipe(notify({ message: 'Script task complete' }));;
});

gulp.task('vendor-js', function() {
    return gulp.src(mainBowerFiles('**/*.js'))
        .pipe(plumber())
        .pipe(concat('vendors.min.js'))
        .pipe(gulp.dest('public/js'));
});

//****************************************************************
//CSS section
//External styles
gulp.task('normalize', function() {
    return gulp.src(mainBowerFiles('**/*.css'))
        .pipe(minifyCss({compatibility: 'ie8'}))
        .pipe(gulp.dest('public/css'));
});

gulp.task('vendor-css', ['normalize'], function(){
});

//Custom styles
gulp.task('styles', function() {
    return gulp.src([
            'app/styles/**/*.scss',
            'app/styles/**/*.css'])
        .pipe(sass().on('error', sass.logError))
        .pipe(concat('application.min.css'))
        .pipe(minifyCss({compatibility: 'ie8'}))
        .pipe(gulp.dest('public/css'))
        .pipe(notify({ message: 'Styles task complete' }));
});

//****************************************************************
//General section
// Vendors scripts and styles
gulp.task('vendors', ['vendor-css', 'vendor-js'], function () {
});

//****************************************************************
// watching scss/js/html files
gulp.task('watch', ['vendors', 'scripts', 'styles', 'server'], function() {
    gulp.watch('app/styles/**/*.css', ['styles']);
    gulp.watch('app/styles/**/*.scss', ['styles']);
    gulp.watch([
        'app/scripts/**/*.js',
        'app/angular/**/*.js'
        ], ['scripts']);
    gulp.watch('app/angular/**/*.html', ['template']);
    gulp.watch([
        'config/*.js',
        'routes/*.js',
        'views/*.ejs',
        'app.js',
        'app/models/*.js'
        ], ['server']);
});

//****************************************************************
// Angular templates
gulp.task('template', function() {
    return gulp.src('app/angular/**/*.html')
        .pipe(templateCache('templates.js', {standalone:true}))
        .pipe(gulp.dest('app/angular'))
        .pipe(notify({ message: 'Template task complete' }));
});

//****************************************************************
/**
 * $ gulp server
 * description: launch the server. If there's a server already running, kill it.
 */
gulp.task('server', function() {
  if (node) node.kill()
  node = spawn('node', ['./bin/www'], {stdio: 'inherit'})
  node.on('close', function (code) {
    if (code === 8) {
      gulp.log('Error detected, waiting for changes...');
    }
  });
})

// clean up if an error goes unhandled.
process.on('exit', function() {
    if (node) node.kill()
})

//Default task
gulp.task('default', ['watch'], function() {
});

// heroku task
gulp.task('heroku:test', ['vendors', 'scripts', 'styles']);

<|endoftext|>


<commit_before>module.exports = function(grunt) {
  'use strict';

  grunt.initConfig({
    // running `grunt less` will compile once
    less: {
      development: {
        options: {
          paths: ['./assets/css']
        },
        files: {
          './assets/css/style.css': './assets/less/style.less',
          './assets/css/event.css': './assets/less/event.less',
        }
      },
      dist: {
        options: {
          paths: ['./dist/assets/css'],
          compress: true,
          sourceMap: true
        },
        files: {
          './dist/assets/css/style.min.css': './assets/less/style.less',
          './dist/assets/css/event.min.css': './assets/less/event.less',
        }
      }
    },
    autoprefixer: {
      development: {
        browsers: ['last 2 versions'],
        expand: true,
        flatten: true,
        map: true,
        src: './assets/css/*.css',
        dest: './assets/css'
      },
      dist: {
        browsers: ['last 2 versions'],
        expand: true,
        flatten: true,
        map: true,
        src: './dist/assets/css/*.css',
        dest: './dist/assets/css'
      },
    },
    uglify: {
      dist: {
        options: {
          mangle: false,
          sourceMap: true
        },
        files: {
          'dist/assets/js/main.min.js': [ './assets/js/main.js' ]
        }
      }
    },
    jshint: {
      options: {
        'globals': {
          'module': false,
          'angular': false,
          'console': false,
          'google': false,
          'WebmakerAuthClient': false
        },
        'bitwise': true,
        'browser': true,
        'curly': true,
        'eqeqeq': true,
        'freeze': true,
        'immed': true,
        'indent': 2,
        'latedef': true,
        'newcap': true,
        'noempty': true,
        'quotmark': 'single',
        'trailing': true,
        'undef': true,
        'unused': 'vars'
      },
      files: [
        'Gruntfile.js',
        'asset/js/**/*.js'
      ]
    },
    // running `grunt watch` will watch for changes
    watch: {
      less: {
        files: './assets/less/*.less',
        tasks: ['less']
      },
      // prefixing: {
      //   files: './assets/less/*.less',
      //   tasks: ['autoprefixer']
      // }
    },
    connect: {
      server: {
        options: {
          port: 9999,
          useAvailablePort: true
        }
      }
    }
  });

  grunt.loadNpmTasks( 'grunt-contrib-jshint' );
  grunt.loadNpmTasks( 'grunt-contrib-uglify' );
  grunt.loadNpmTasks( 'grunt-contrib-less' );
  grunt.loadNpmTasks( 'grunt-contrib-connect' );
  grunt.loadNpmTasks( 'grunt-autoprefixer' );
  grunt.loadNpmTasks( 'grunt-contrib-watch' );

  grunt.registerTask( 'default', [ 'jshint', 'less:development', 'autoprefixer:development' ] );
  grunt.registerTask( 'build', [ 'jshint', 'less:dist', 'autoprefixer:dist', 'uglify' ] );
};
<commit_msg>re-adding watch<commit_after>module.exports = function(grunt) {
  'use strict';

  grunt.initConfig({
    // running `grunt less` will compile once
    less: {
      development: {
        options: {
          paths: ['./assets/css']
        },
        files: {
          './assets/css/style.css': './assets/less/style.less',
          './assets/css/event.css': './assets/less/event.less',
        }
      },
      dist: {
        options: {
          paths: ['./dist/assets/css'],
          compress: true,
          sourceMap: true
        },
        files: {
          './dist/assets/css/style.min.css': './assets/less/style.less',
          './dist/assets/css/event.min.css': './assets/less/event.less',
        }
      }
    },
    autoprefixer: {
      development: {
        browsers: ['last 2 versions'],
        expand: true,
        flatten: true,
        map: true,
        src: './assets/css/*.css',
        dest: './assets/css'
      },
      dist: {
        browsers: ['last 2 versions'],
        expand: true,
        flatten: true,
        map: true,
        src: './dist/assets/css/*.css',
        dest: './dist/assets/css'
      },
    },
    uglify: {
      dist: {
        options: {
          mangle: false,
          sourceMap: true
        },
        files: {
          'dist/assets/js/main.min.js': [ './assets/js/main.js' ]
        }
      }
    },
    jshint: {
      options: {
        'globals': {
          'module': false,
          'angular': false,
          'console': false,
          'google': false,
          'WebmakerAuthClient': false
        },
        'bitwise': true,
        'browser': true,
        'curly': true,
        'eqeqeq': true,
        'freeze': true,
        'immed': true,
        'indent': 2,
        'latedef': true,
        'newcap': true,
        'noempty': true,
        'quotmark': 'single',
        'trailing': true,
        'undef': true,
        'unused': 'vars'
      },
      files: [
        'Gruntfile.js',
        'asset/js/**/*.js'
      ]
    },
    // running `grunt watch` will watch for changes
    watch: {
      less: {
        files: './assets/less/*.less',
        tasks: ['less']
      },
      prefixing: {
        files: './assets/less/*.less',
        tasks: ['autoprefixer']
      }
    },
    connect: {
      server: {
        options: {
          port: 9999,
          useAvailablePort: true
        }
      }
    }
  });

  grunt.loadNpmTasks( 'grunt-contrib-jshint' );
  grunt.loadNpmTasks( 'grunt-contrib-uglify' );
  grunt.loadNpmTasks( 'grunt-contrib-less' );
  grunt.loadNpmTasks( 'grunt-contrib-connect' );
  grunt.loadNpmTasks( 'grunt-autoprefixer' );
  grunt.loadNpmTasks( 'grunt-contrib-watch' );

  grunt.registerTask( 'default', [ 'jshint', 'less:development', 'autoprefixer:development' ] );
  grunt.registerTask( 'watch', [ 'less:development', 'autoprefixer:development', 'connect', 'watch' ] );
  grunt.registerTask( 'build', [ 'jshint', 'less:dist', 'autoprefixer:dist', 'uglify' ] );
};
<|endoftext|>