<commit_before>import { resolve, relative, isAbsolute, dirname } from "path"
import { eachOfSeries } from "async"
import { camelCase } from "lodash"
import fileExists from "file-exists"
import meow from "meow"
import chalk from "chalk"

import { rollup } from "rollup"
import rebase from "rollup-plugin-rebase"
import nodeResolve from "rollup-plugin-node-resolve"
import commonjs from "rollup-plugin-commonjs"
import jsonPlugin from "rollup-plugin-json"
import yamlPlugin from "rollup-plugin-yaml"
import replacePlugin from "rollup-plugin-replace"

import getTranspilers from "./getTranspilers"
import getBanner from "./getBanner"

const CWD = process.cwd()
const PKG_CONFIG = require(resolve(CWD, "package.json"))

var cache

const command = meow(`
  Usage
    $ prepublish

  Options
    --entry-node      Entry file for NodeJS target [default = auto]
    --entry-web       Entry file for Browser target [default = auto]

    --output-folder   Configure the output folder [default = auto]

    -t, --transpiler  Chose the transpiler/config to use. Either "react", "latest" or "buble". [default = latest]
    -x, --minified    Enabled minification of output files
    -m, --sourcemap   Create a source map file during processing

    -v, --verbose     Verbose output mode [default = false]
    -q, --quiet       Quiet output mode [default = false]
`, {
  default: {
    entryNode: null,
    entryWeb: null,

    outputFolder: null,

    transpiler: "react",
    minified: false,
    sourcemap: true,

    verbose: false,
    quiet: false
  }
})

const verbose = command.flags.verbose
const quiet = command.flags.quiet

if (verbose) {
  console.log("Flags:", command.flags)
}

/* eslint-disable dot-notation */
const outputFileMatrix = {
  "node-classic-commonjs": PKG_CONFIG["main"] || null,
  "node-classic-esmodule": PKG_CONFIG["module"] || PKG_CONFIG["jsnext:main"] || null,
  "node-classic-iife": PKG_CONFIG["main:iife"] || PKG_CONFIG["main:bundle"] || null,
  "node-modern-commonjs": PKG_CONFIG["main:modern"] || null,
  "node-modern-esmodule": PKG_CONFIG["module:modern"] || null,
  "node-modern-iife": PKG_CONFIG["main:modern:iife"] || PKG_CONFIG["main:modern:bundle"] || null,
  "web-classic-esmodule": PKG_CONFIG["web"] || PKG_CONFIG["browser"] || PKG_CONFIG["browserify"] || null,
  "web-modern-esmodule": PKG_CONFIG["web:modern"] || PKG_CONFIG["browser:modern"] || PKG_CONFIG["browserify:modern"] || null
}

const outputFolder = command.flags.outputFolder
if (outputFolder) {
  outputFileMatrix["node-classic-commonjs"] = `${outputFolder}/node.classic.commonjs.js`
  outputFileMatrix["node-classic-esmodule"] = `${outputFolder}/node.classic.esmodule.js`
  outputFileMatrix["node-classic-iife"] = `${outputFolder}/node.classic.iife.js`
  outputFileMatrix["node-modern-commonjs"] = `${outputFolder}/node.modern.commonjs.js`
  outputFileMatrix["node-modern-esmodule"] = `${outputFolder}/node.modern.esmodule.js`
  outputFileMatrix["node-modern-iife"] = `${outputFolder}/node.modern.iife.js`
  outputFileMatrix["web-classic-esmodule"] = `${outputFolder}/web.classic.esmodule.js`
  outputFileMatrix["web-modern-esmodule"] = `${outputFolder}/web.modern.esmodule.js`
}

// Rollups support these formats: 'amd', 'cjs', 'es', 'iife', 'umd'
const format2Rollup = {
  commonjs: "cjs",
  esmodule: "es",
  iife: "iife"
}

const moduleId = PKG_CONFIG.name
const moduleName = PKG_CONFIG.moduleName || camelCase(moduleId)
const banner = getBanner(PKG_CONFIG)
const targets = {}
const formats = [ "esmodule", "commonjs", "iife" ]

if (command.flags.entryNode) {
  targets.node = [ command.flags.entryNode ]
} else {
  targets.node = [
    "src/node/public.js",
    "src/node/export.js",
    "src/node.js",

    "src/server/public.js",
    "src/server/export.js",
    "src/server.js",

    "src/server.js",
    "src/public.js",
    "src/export.js",
    "src/index.js"
  ]
}

if (command.flags.entryWeb) {
  targets.web = [ command.flags.entryWeb ]
} else {
  targets.web = [
    "src/web/public.js",
    "src/web/export.js",
    "src/web.js",

    "src/browser/public.js",
    "src/browser/export.js",
    "src/browser.js",

    "src/client/public.js",
    "src/client/export.js",
    "src/client.js"
  ]
}

eachOfSeries(targets, (envEntries, targetId, envCallback) =>
{
  var entry = lookupBest(envEntries)
  if (entry)
  {
    if (!quiet) {
      console.log(`Using entry ${chalk.blue(entry)} for target ${chalk.blue(targetId)}`)
    }

    eachOfSeries(formats, (format, formatIndex, formatCallback) =>
    {
      const transpilers = getTranspilers(command.flags.transpiler, {
        minified: command.flags.minified,
        runtime: format !== "iife"
      })

      eachOfSeries(transpilers, (currentTranspiler, transpilerId, variantCallback) =>
      {
        var destFile = outputFileMatrix[`${targetId}-${transpilerId}-${format}`]
        if (destFile) {
          return bundleTo({ entry, targetId, transpilerId, currentTranspiler, format, destFile, variantCallback })
        } else {
          return variantCallback(null)
        }
      }, formatCallback)
    }, envCallback)
  }
  else
  {
    envCallback(null)
  }
})

function lookupBest(candidates) {
  var filtered = candidates.filter(fileExists.sync)
  return filtered[0]
}

function bundleTo({ entry, targetId, transpilerId, currentTranspiler, format, destFile, variantCallback }) {
  if (!quiet) {
    console.log(`${chalk.green(">>> Bundling")} ${chalk.magenta(PKG_CONFIG.name)}-${chalk.magenta(PKG_CONFIG.version)}
      as ${chalk.blue(transpilerId)} defined as ${chalk.blue(format)} to ${chalk.green(destFile)}...`)
  }

  var prefix = "process.env."
  var variables = {
    [`${prefix}NAME`]: JSON.stringify(PKG_CONFIG.name),
    [`${prefix}VERSION`]: JSON.stringify(PKG_CONFIG.version),
    [`${prefix}TARGET`]: JSON.stringify(targetId)
  }

  var fileRebase = rebase({ outputFolder: dirname(destFile), entry, verbose })
  rollup({
    entry,
    cache,
    onwarn: (message) => console.warn(message),
    external(dependency)
    {
      if (dependency === entry) {
        return false
      }

      if (fileRebase.isExternal(dependency)) {
        return true
      }

      // Inline all external features when building for IIFE
      // There is no `require` or `import` available in that context.
      if (format === "iife") {
        return false
      }

      if (isAbsolute(dependency)) {
        var relativePath = relative(CWD, dependency)
        return Boolean(/node_modules/.exec(relativePath))
      }

      return dependency.charAt(0) !== "."
    },
    plugins:
    [
      nodeResolve({
        extensions: [ ".mjs", ".js", ".jsx", ".ts", ".tsx", ".json" ],
        jsnext: true,
        module: true,
        main: true
      }),
      commonjs({
        include: "node_modules/**"
      }),
      jsonPlugin,
      yamlPlugin,
      replacePlugin(variables),
      currentTranspiler,
      fileRebase
    ]
  })
    .then((bundle) =>
      bundle.write({
        format: format2Rollup[format],
        moduleId,
        moduleName,
        banner,
        sourceMap: command.flags.sourcemap,
        dest: destFile
      })
    )
    .then(() =>
      variantCallback(null)
    )
    .catch((error) =>
    {
      console.error(error)
      variantCallback(`Error during bundling ${format}: ${error}`)
    })
}
<commit_msg>Minor tweaks<commit_after>import { resolve, relative, isAbsolute, dirname } from "path"
import { eachOfSeries } from "async"
import { camelCase } from "lodash"
import fileExists from "file-exists"
import meow from "meow"
import chalk from "chalk"

import { rollup } from "rollup"
import rebase from "rollup-plugin-rebase"
import nodeResolve from "rollup-plugin-node-resolve"
import commonjs from "rollup-plugin-commonjs"
import jsonPlugin from "rollup-plugin-json"
import yamlPlugin from "rollup-plugin-yaml"
import replacePlugin from "rollup-plugin-replace"

import getTranspilers from "./getTranspilers"
import getBanner from "./getBanner"

const CWD = process.cwd()
const PKG_CONFIG = require(resolve(CWD, "package.json"))

var cache

/* eslint-disable no-console */

const command = meow(`
  Usage
    $ prepublish

  Options
    --entry-node      Entry file for NodeJS target [default = auto]
    --entry-web       Entry file for Browser target [default = auto]

    --output-folder   Configure the output folder [default = auto]

    -t, --transpiler  Chose the transpiler/config to use. Either "react", "latest" or "buble". [default = latest]
    -x, --minified    Enabled minification of output files
    -m, --sourcemap   Create a source map file during processing

    -v, --verbose     Verbose output mode [default = false]
    -q, --quiet       Quiet output mode [default = false]
`, {
  default: {
    entryNode: null,
    entryWeb: null,

    outputFolder: null,

    transpiler: "react",
    minified: false,
    sourcemap: true,

    verbose: false,
    quiet: false
  }
})

const verbose = command.flags.verbose
const quiet = command.flags.quiet

if (verbose) {
  console.log("Flags:", command.flags)
}

/* eslint-disable dot-notation */
const outputFileMatrix = {
  "node-classic-commonjs": PKG_CONFIG["main"] || null,
  "node-classic-esmodule": PKG_CONFIG["module"] ||
    PKG_CONFIG["jsnext:main"] ||
    null,
  "node-classic-iife": PKG_CONFIG["main:iife"] ||
    PKG_CONFIG["main:bundle"] ||
    null,
  "node-modern-commonjs": PKG_CONFIG["main:modern"] || null,
  "node-modern-esmodule": PKG_CONFIG["module:modern"] || null,
  "node-modern-iife": PKG_CONFIG["main:modern:iife"] ||
    PKG_CONFIG["main:modern:bundle"] ||
    null,
  "web-classic-esmodule": PKG_CONFIG["web"] ||
    PKG_CONFIG["browser"] ||
    PKG_CONFIG["browserify"] ||
    null,
  "web-modern-esmodule": PKG_CONFIG["web:modern"] ||
    PKG_CONFIG["browser:modern"] ||
    PKG_CONFIG["browserify:modern"] ||
    null
}

const outputFolder = command.flags.outputFolder
if (outputFolder) {
  outputFileMatrix["node-classic-commonjs"] = `${outputFolder}/node.classic.commonjs.js`
  outputFileMatrix["node-classic-esmodule"] = `${outputFolder}/node.classic.esmodule.js`
  outputFileMatrix["node-classic-iife"] = `${outputFolder}/node.classic.iife.js`
  outputFileMatrix["node-modern-commonjs"] = `${outputFolder}/node.modern.commonjs.js`
  outputFileMatrix["node-modern-esmodule"] = `${outputFolder}/node.modern.esmodule.js`
  outputFileMatrix["node-modern-iife"] = `${outputFolder}/node.modern.iife.js`
  outputFileMatrix["web-classic-esmodule"] = `${outputFolder}/web.classic.esmodule.js`
  outputFileMatrix["web-modern-esmodule"] = `${outputFolder}/web.modern.esmodule.js`
}

// Rollups support these formats: 'amd', 'cjs', 'es', 'iife', 'umd'
const format2Rollup = {
  commonjs: "cjs",
  esmodule: "es",
  iife: "iife"
}

const moduleId = PKG_CONFIG.name
const moduleName = PKG_CONFIG.moduleName || camelCase(moduleId)
const banner = getBanner(PKG_CONFIG)
const targets = {}
const formats = [ "esmodule", "commonjs", "iife" ]

if (command.flags.entryNode) {
  targets.node = [ command.flags.entryNode ]
} else {
  targets.node = [
    "src/node/public.js",
    "src/node/export.js",
    "src/node.js",

    "src/server/public.js",
    "src/server/export.js",
    "src/server.js",

    "src/server.js",
    "src/public.js",
    "src/export.js",
    "src/index.js"
  ]
}

if (command.flags.entryWeb) {
  targets.web = [ command.flags.entryWeb ]
} else {
  targets.web = [
    "src/web/public.js",
    "src/web/export.js",
    "src/web.js",

    "src/browser/public.js",
    "src/browser/export.js",
    "src/browser.js",

    "src/client/public.js",
    "src/client/export.js",
    "src/client.js"
  ]
}

eachOfSeries(targets, (envEntries, targetId, envCallback) =>
{
  var entry = lookupBest(envEntries)
  if (entry)
  {
    if (!quiet) {
      console.log(`Using entry ${chalk.blue(entry)} for target ${chalk.blue(targetId)}`)
    }

    eachOfSeries(formats, (format, formatIndex, formatCallback) =>
    {
      const transpilers = getTranspilers(command.flags.transpiler, {
        minified: command.flags.minified,
        runtime: format !== "iife"
      })

      eachOfSeries(transpilers, (currentTranspiler, transpilerId, variantCallback) =>
      {
        var destFile = outputFileMatrix[`${targetId}-${transpilerId}-${format}`]
        if (destFile) {
          return bundleTo({ entry, targetId, transpilerId, currentTranspiler, format, destFile, variantCallback })
        } else {
          return variantCallback(null)
        }
      }, formatCallback)
    }, envCallback)
  }
  else
  {
    envCallback(null)
  }
})

function lookupBest(candidates) {
  var filtered = candidates.filter(fileExists.sync)
  return filtered[0]
}

function bundleTo({ entry, targetId, transpilerId, currentTranspiler, format, destFile, variantCallback }) {
  if (!quiet) {
    /* eslint-disable max-len */
    console.log(`${chalk.green(">>> Bundling")} ${chalk.magenta(PKG_CONFIG.name)}-${chalk.magenta(PKG_CONFIG.version)} as ${chalk.blue(transpilerId)} defined as ${chalk.blue(format)} to ${chalk.green(destFile)}...`)
  }

  var prefix = "process.env."
  var variables = {
    [`${prefix}NAME`]: JSON.stringify(PKG_CONFIG.name),
    [`${prefix}VERSION`]: JSON.stringify(PKG_CONFIG.version),
    [`${prefix}TARGET`]: JSON.stringify(targetId)
  }

  var fileRebase = rebase({ outputFolder: dirname(destFile), entry, verbose })
  rollup({
    entry,
    cache,
    onwarn: (message) => console.warn(message),
    external(dependency)
    {
      if (dependency === entry) {
        return false
      }

      if (fileRebase.isExternal(dependency)) {
        return true
      }

      // Inline all external features when building for IIFE
      // There is no `require` or `import` available in that context.
      if (format === "iife") {
        return false
      }

      if (isAbsolute(dependency)) {
        var relativePath = relative(CWD, dependency)
        return Boolean(/node_modules/.exec(relativePath))
      }

      return dependency.charAt(0) !== "."
    },
    plugins:
    [
      nodeResolve({
        extensions: [ ".mjs", ".js", ".jsx", ".ts", ".tsx", ".json" ],
        jsnext: true,
        module: true,
        main: true
      }),
      commonjs({
        include: "node_modules/**"
      }),
      jsonPlugin,
      yamlPlugin,
      replacePlugin(variables),
      currentTranspiler,
      fileRebase
    ]
  })
    .then((bundle) =>
      bundle.write({
        format: format2Rollup[format],
        moduleId,
        moduleName,
        banner,
        sourceMap: command.flags.sourcemap,
        dest: destFile
      })
    )
    .then(() =>
      variantCallback(null)
    )
    .catch((error) =>
    {
      console.error(error)
      variantCallback(`Error during bundling ${format}: ${error}`)
    })
}
<|endoftext|>


<commit_before>/*global module:false*/
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
    return connect['static'](require('path').resolve(dir));
};
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({

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

    connect: {
      options: {
        port:9000
      },
      // load unbuilt code w/ livereload
      unbuilt: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, './src/')
            ];
          }
        }
      },
      // load built app
      build: {
        options: {
          base: 'dist',
          // change this to '0.0.0.0' to access the server from outside
          hostname: 'localhost'
        }
      }
    },

    //Open default browser at the app
    open: {
      unbuilt: {
        path: 'http://localhost:<%= connect.options.port %>/unbuilt.html'
      },
      build: {
        path: 'http://localhost:<%= connect.options.port %>/'
      }
    },
    //setup watch tasks
    watch: {
      options: {
        nospan: true,
        livereload: LIVERELOAD_PORT
      },

      source: {
        files: ['./src/js/**/*.js'],
        tasks: ['jshint']
      },
      livereload:{
        options: {
          livereload:LIVERELOAD_PORT
        },
        files:[
          './src/js/**/*.js',
          './src/**/*.html',
          './src/css/**/*.css'
        ]
      }
    },
    esri_slurp: {
      options: {
        version: '3.12'
      },
      dev: {
        options: {
          beautify: false
        },
        dest: 'src/esri'
      }
    },
    // clean the output directory before each build
    clean: {
      build: ['dist'],
      deploy: ['dist/**/*.consoleStripped.js','dist/**/*.uncompressed.js','dist/**/*.js.map'],
      bower: ['src/bootstrap-map-js', 'src/dijit', 'src/dojo', 'src/dojo-bootstrap', 'src/dojox', 'src/put-selector', 'src/util', 'src/xstyle'],
      slurp: ['src/esri']
    },
    // dojo build configuration, mainly taken from dojo boilerplate
    dojo: {
      dist: {
        options: {
          profile: 'profiles/app.profile.js' // Profile for build
        }
      },
      options: {
        dojo: 'src/dojo/dojo.js', // Path to dojo.js file in dojo source
        load: 'build', // Optional: Utility to bootstrap (Default: 'build')
        // profiles: [], // Optional: Array of Profiles for build
        // appConfigFile: '', // Optional: Config file for dojox/app
        // package: '', // Optional: Location to search package.json (Default: nothing)
        // packages: [], // Optional: Array of locations of package.json (Default: nothing)
        // require: '', // Optional: Module to require for the build (Default: nothing)
        // requires: [], // Optional: Array of modules to require for the build (Default: nothing)
        releaseDir: '../dist', // Optional: release dir rel to basePath (Default: 'release')
        cwd: './', // Directory to execute build within
        // dojoConfig: '', // Optional: Location of dojoConfig (Default: null),
        // Optional: Base Path to pass at the command line
        // Takes precedence over other basePaths
        // Default: null
        basePath: './src'
      }
    },
    processhtml: {
      build: {
        files: {
          'dist/index.html': ['src/index.html']
        }
      }
    },
    copy: {
      build: {
        src: 'src/dashboard.html',
        dest: 'dist/dashboard.html'
      }
    },
    'gh-pages': {
      src: {
        options: {
          base: 'src'
        },
        src: ['index.html', 'dashboard.html', 'app/**']
      },
      dist: {
        options: {
          base: 'dist'
        },
        src: ['index.html', 'dashboard.html', 'app/css/**', 'dojo/dojo.js', 'dojo/resources/**', 'esri/images/**', 'esri/dijit/images/**', 'esri/dijit/font/**']
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-open');
  grunt.loadNpmTasks('grunt-gh-pages');
  grunt.loadNpmTasks('grunt-esri-slurp');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-dojo');
  grunt.loadNpmTasks('grunt-processhtml');
  grunt.loadNpmTasks('grunt-contrib-copy');

  grunt.registerTask('default', ['serve']);

  grunt.registerTask('serve', function (target) {
    var trgt = target || 'unbuilt';
    grunt.task.run([
      'jshint',
      'connect:' + trgt,
      'open:' + trgt,
      'watch'
    ]);
  });

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

  grunt.registerTask('slurp', ['clean:slurp', 'esri_slurp:dev']);

  grunt.registerTask('build', ['jshint', 'clean:build', 'dojo', 'processhtml', 'copy:build']);
};
<commit_msg>unbuilt is index.html<commit_after>/*global module:false*/
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
    return connect['static'](require('path').resolve(dir));
};
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({

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

    connect: {
      options: {
        port:9000
      },
      // load unbuilt code w/ livereload
      unbuilt: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, './src/')
            ];
          }
        }
      },
      // load built app
      build: {
        options: {
          base: 'dist',
          // change this to '0.0.0.0' to access the server from outside
          hostname: 'localhost'
        }
      }
    },

    //Open default browser at the app
    open: {
      unbuilt: {
        path: 'http://localhost:<%= connect.options.port %>/'
      },
      build: {
        path: 'http://localhost:<%= connect.options.port %>/'
      }
    },
    //setup watch tasks
    watch: {
      options: {
        nospan: true,
        livereload: LIVERELOAD_PORT
      },

      source: {
        files: ['./src/js/**/*.js'],
        tasks: ['jshint']
      },
      livereload:{
        options: {
          livereload:LIVERELOAD_PORT
        },
        files:[
          './src/js/**/*.js',
          './src/**/*.html',
          './src/css/**/*.css'
        ]
      }
    },
    esri_slurp: {
      options: {
        version: '3.12'
      },
      dev: {
        options: {
          beautify: false
        },
        dest: 'src/esri'
      }
    },
    // clean the output directory before each build
    clean: {
      build: ['dist'],
      deploy: ['dist/**/*.consoleStripped.js','dist/**/*.uncompressed.js','dist/**/*.js.map'],
      bower: ['src/bootstrap-map-js', 'src/dijit', 'src/dojo', 'src/dojo-bootstrap', 'src/dojox', 'src/put-selector', 'src/util', 'src/xstyle'],
      slurp: ['src/esri']
    },
    // dojo build configuration, mainly taken from dojo boilerplate
    dojo: {
      dist: {
        options: {
          profile: 'profiles/app.profile.js' // Profile for build
        }
      },
      options: {
        dojo: 'src/dojo/dojo.js', // Path to dojo.js file in dojo source
        load: 'build', // Optional: Utility to bootstrap (Default: 'build')
        // profiles: [], // Optional: Array of Profiles for build
        // appConfigFile: '', // Optional: Config file for dojox/app
        // package: '', // Optional: Location to search package.json (Default: nothing)
        // packages: [], // Optional: Array of locations of package.json (Default: nothing)
        // require: '', // Optional: Module to require for the build (Default: nothing)
        // requires: [], // Optional: Array of modules to require for the build (Default: nothing)
        releaseDir: '../dist', // Optional: release dir rel to basePath (Default: 'release')
        cwd: './', // Directory to execute build within
        // dojoConfig: '', // Optional: Location of dojoConfig (Default: null),
        // Optional: Base Path to pass at the command line
        // Takes precedence over other basePaths
        // Default: null
        basePath: './src'
      }
    },
    processhtml: {
      build: {
        files: {
          'dist/index.html': ['src/index.html']
        }
      }
    },
    copy: {
      build: {
        src: 'src/dashboard.html',
        dest: 'dist/dashboard.html'
      }
    },
    'gh-pages': {
      src: {
        options: {
          base: 'src'
        },
        src: ['index.html', 'dashboard.html', 'app/**']
      },
      dist: {
        options: {
          base: 'dist'
        },
        src: ['index.html', 'dashboard.html', 'app/css/**', 'dojo/dojo.js', 'dojo/resources/**', 'esri/images/**', 'esri/dijit/images/**', 'esri/dijit/font/**']
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-open');
  grunt.loadNpmTasks('grunt-gh-pages');
  grunt.loadNpmTasks('grunt-esri-slurp');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-dojo');
  grunt.loadNpmTasks('grunt-processhtml');
  grunt.loadNpmTasks('grunt-contrib-copy');

  grunt.registerTask('default', ['serve']);

  grunt.registerTask('serve', function (target) {
    var trgt = target || 'unbuilt';
    grunt.task.run([
      'jshint',
      'connect:' + trgt,
      'open:' + trgt,
      'watch'
    ]);
  });

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

  grunt.registerTask('slurp', ['clean:slurp', 'esri_slurp:dev']);

  grunt.registerTask('build', ['jshint', 'clean:build', 'dojo', 'processhtml', 'copy:build']);
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, Route, IndexRoute, browserHistory} from 'react-router';
import reduxThunk from 'redux-thunk';

import App from './components/app';
import Feature from './components/feature';
import RequireAuth  from './components/auth/require_auth';
import Signin from './components/auth/signin';
import Signout from './components/auth/signout';
import Signup from './components/auth/signup';
import Welcome from './components/welcome';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <Router history={browserHistory}>
      <Route path="/" component={App}>
        <IndexRoute component={Welcome}/>
        <Route path="signin" component={Signin} />
        <Route path="signout" component={Signout} />
        <Route path="signup" component={Signup} />
        <Route path="feature" component={RequireAuth(Feature)} />
      </Route>
    </Router>
  </Provider>
  , document.querySelector('.container'));
<commit_msg>Automatically authenticates user through dispatch to store<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, Route, IndexRoute, browserHistory} from 'react-router';
import reduxThunk from 'redux-thunk';
import { AUTH_USER } from './actions/types'

import App from './components/app';
import Feature from './components/feature';
import RequireAuth  from './components/auth/require_auth';
import Signin from './components/auth/signin';
import Signout from './components/auth/signout';
import Signup from './components/auth/signup';
import Welcome from './components/welcome';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers)

const token = localStorage.getItem('token');
// If we have a token, consider the user to be signed in
if (token) {
  // update application state
  store.dispatch({ type: AUTH_USER })
}
ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path="/" component={App}>
        <IndexRoute component={Welcome}/>
        <Route path="signin" component={Signin} />
        <Route path="signout" component={Signout} />
        <Route path="signup" component={Signup} />
        <Route path="feature" component={RequireAuth(Feature)} />
      </Route>
    </Router>
  </Provider>
  , document.querySelector('.container'));
<|endoftext|>


<commit_before>var els = "";

function LoadCSSJS(e, t, m) {

	"use strict";

	if (els.indexOf("["+e+"]") == -1) {
		Loader(e, t, m);
		els += "["+e+"]";
	}
	else
		alert("File "+e+" already added!");

}
function Loader(e, t, m){

	if (t == "css") {
		var f=document.createElement("link");
		f.setAttribute("rel", "stylesheet");
    		f.setAttribute("href", e);
    		(m ? "" : m="all");
    		f.setAttribute("media", m);
    		f.setAttribute("type", "text/css");
	} else if (t == "js") {
		var f = document.createElement("script");
		f.setAttribute("type", "text/javascript");
        	f.setAttribute("src", e);
	}
	if (typeof f != "undefined") {
		var a = document.getElementsByTagName("head");
		a = a[a.length-1];
		a.appendChild(s);
	}

}
<commit_msg>Update LoadCSSJS.js<commit_after>function LoadCSSJS(e, t, m) {

	"use strict";

	var els = "";

	if (els.indexOf("["+e+"]") == -1) {
		Loader(e, t, m);
		els += "["+e+"]";
	}
	else
		alert("File "+e+" already added!");

}
function Loader(e, t, m){

	if (t == "css") {
		var f=document.createElement("link");
		f.setAttribute("rel", "stylesheet");
    		f.setAttribute("href", e);
    		(m ? "" : m="all");
    		f.setAttribute("media", m);
    		f.setAttribute("type", "text/css");
	} else if (t == "js") {
		var f = document.createElement("script");
		f.setAttribute("type", "text/javascript");
        	f.setAttribute("src", e);
	}
	if (typeof f != "undefined") {
		var a = document.getElementsByTagName("head");
		a = a[a.length-1];
		a.appendChild(s);
	}

}
<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {
	require('jit-grunt')(grunt);

	grunt.loadNpmTasks('grunt-env');

	// Unified Watch Object
	var watchFiles = {
		serverViews: ['app/views/**/*.*'],
		serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js', '!app/tests/'],
		clientViews: ['public/modules/**/views/**/*.html'],
		clientJS: ['public/js/*.js', 'public/modules/**/*.js'],
		clientCSS: ['public/modules/**/*.css'],
		serverTests: ['app/tests/**/*.js'],
		clientTests: ['public/modules/**/tests/*.js'],
		allTests: ['public/modules/**/tests/*.js', 'app/tests/**/*.js'],
	};

	// Project Configuration
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		watch: {
			serverViews: {
				files: watchFiles.serverViews,
				options: {
					livereload: true,
					spawn: false
				}
			},
			serverJS: {
				files: watchFiles.serverJS,
				tasks: ['newer:jshint'],
				options: {
					livereload: true,
					spawn: false
				}
			},
			clientViews: {
				files: watchFiles.clientViews,
				tasks: ['html2js:main'],
				options: {
					livereload: true,
					spawn: false
				}
			},
			clientJS: {
				files: watchFiles.clientJS,
				tasks: ['newer:jshint'],
				options: {
					livereload: true,
					spawn: false
				}
			},
			clientCSS: {
				files: watchFiles.clientCSS,
				tasks: ['newer:csslint'],
				options: {
					livereload: true,
					spawn: false
				}
			},
			mochaTests: {
				files: watchFiles.serverTests,
				tasks: ['test:server'],
			}
		},
		jshint: {
			all: {
				src: watchFiles.clientJS.concat(watchFiles.serverJS),
				options: {
					jshintrc: true
				}
			},
			allTests: {
				src: watchFiles.allTests,
				options: {
					jshintrc: true
				}
			}
		},
		csslint: {
			options: {
				csslintrc: '.csslintrc'
			},
			all: {
				src: watchFiles.clientCSS
			}
		},
		uglify: {
			production: {
				options: {
					mangle: false
				},
				files: {
					'public/dist/application.min.js': 'public/dist/application.js'
				}
			}
		},
		cssmin: {
			combine: {
				files: {
					'public/dist/application.min.css': '<%= applicationCSSFiles %>'
				}
			}
		},
		nodemon: {
			dev: {
				script: 'server.js',
				options: {
					nodeArgs: ['--debug'],
					ext: 'js,html',
					watch: watchFiles.serverViews.concat(watchFiles.serverJS)
				}
			}
		},
		'node-inspector': {
			custom: {
				options: {
					'web-port': 1337,
					'web-host': 'localhost',
					'debug-port': 5858,
					'save-live-edit': true,
					'no-preload': true,
					'stack-trace-limit': 50,
					'hidden': []
				}
			}
		},
		ngAnnotate: {
			production: {
				files: {
					'public/dist/application.js': '<%= applicationJavaScriptFiles %>'
				}
			}
		},
		concurrent: {
			default: ['nodemon', 'watch'],
			debug: ['nodemon', 'watch', 'node-inspector'],
			options: {
				logConcurrentOutput: true,
				limit: 10
			}
		},
		env: {
			test: {
				NODE_ENV: 'test',
			},
			secure: {
				NODE_ENV: 'secure',
				src: '.env'
			},
			default: {
				src: '/opt/deploy/.env'
			},
			production: {
				src: '.prod.env'
			}
		},
		mochaTest: {
			src: watchFiles.serverTests,
			options: {
				reporter: 'spec',
				quiet: false,
				require: 'server.js',
				ui: 'bdd'
			}
		},
		karma: {
			unit: {
				configFile: 'karma.conf.js'
			}
		},
		protractor: {
			options: {
				configFile: 'protractor.conf.js',
				keepAlive: true,
				noColor: false
			},
			e2e: {
				options: {
					args: {} // Target-specific arguments
				}
			}
	    },
	    mocha_istanbul: {
            coverage: {
                src: watchFiles.allTests, // a folder works nicely
                options: {
                    mask: '*.test.js',
                    require: ['server.js'],
                }
            },
            coverageClient: {
                src: watchFiles.clientTests, // specifying file patterns works as well
                options: {
                    coverageFolder: 'coverageClient',
                    mask: '*.test.js',
                    require: ['server.js'],
                }
            },
            coverageServer: {
                src: watchFiles.serverTests,
                options: {
                    coverageFolder: 'coverageServer',
                    mask: '*.test.js',
                    require: ['server.js'],
                }
            },
            coveralls: {
                src: watchFiles.allTests, // multiple folders also works
                options: {
                	require: ['server.js'],
                    coverage: true, // this will make the grunt.event.on('coverage') event listener to be triggered
                    check: {
                        lines: 75,
                        statements: 75
                    },
                    root: './lib', // define where the cover task should consider the root of libraries that are covered by tests
                    reportFormats: ['cobertura','lcovonly']
                }
            }
        },
        istanbul_check_coverage: {
          default: {
            options: {
              coverageFolder: 'coverage*', // will check both coverage folders and merge the coverage results
              check: {
                lines: 80,
                statements: 80
              }
            }
          }
        },
        html2js: {
		  options: {
		    base: 'NodeForm',
		    module: 'NodeForm.templates',
		    singleModule: true,
		    useStrict: true,
		    htmlmin: {
		      collapseBooleanAttributes: true,
		      collapseWhitespace: true,
		      removeAttributeQuotes: true,
		      removeComments: true,
		      removeEmptyAttributes: true,
		      removeRedundantAttributes: true,
		    }
		  },
		  main: {
		    src: ['public/modules/**/views/**.html', 'public/modules/**/views/**/*.html'],
		    dest: 'public/populate_template_cache.js'
		  }
		}
	});

	grunt.event.on('coverage', function(lcov, done){
	    var coveralls = require('coveralls');
	    coveralls.handleInput(lcov, function(err){
	        if (err) {
	        	grunt.log.error("Failed to submit lcov file to coveralls: " + err);
	            return done(err);
	        }
	        grunt.verbose.ok("Successfully submitted lcov file to coveralls");
	        done();
	    });
	});

	// Making grunt default to force in order not to break the project.
	grunt.option('force', true);

	// A Task for loading the configuration object
	grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() {
		var init = require('./config/init')();
		var config = require('./config/config');

		grunt.config.set('applicationJavaScriptFiles', config.assets.js);
		grunt.config.set('applicationCSSFiles', config.assets.css);
	});

	// Code coverage tasks.
	grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']);
    grunt.registerTask('coverage', ['env:test', 'mocha_istanbul:coverage']);
    grunt.registerTask('coverage:client', ['env:test', 'mocha_istanbul:coverageClient']);
    grunt.registerTask('coverage:server', ['env:test', 'mocha_istanbul:coverageServer']);

	// Default task(s).
	grunt.registerTask('default', ['lint', 'html2js:main', 'env:default', 'concurrent:default']);
	grunt.registerTask('default', ['lint', 'html2js:main', 'uglify:production', 'cssmin', 'ngAnnotate', 'env:production', 'concurrent:default']);

	// Debug task.
	grunt.registerTask('debug', ['lint', 'html2js:main', 'concurrent:debug']);

	// Secure task(s).
	grunt.registerTask('secure', ['env:secure', 'lint', 'html2js:main', 'concurrent:default']);

	// Lint task(s).
	grunt.registerTask('lint', ['jshint', 'csslint']);
	grunt.registerTask('lint:tests', ['jshint:allTests']);

	// Build task(s).
	grunt.registerTask('build', ['lint', 'loadConfig', 'uglify', 'cssmin', 'ngAnnotate', 'html2js:main']);

	// Test task.
	grunt.registerTask('test', ['lint:tests', 'test:server', 'test:client']);
	grunt.registerTask('test:server', ['lint:tests', 'env:test', 'mochaTest']);
	grunt.registerTask('test:client', ['lint:tests', 'html2js:main', 'env:test', 'karma:unit']);
};
<commit_msg>fixed bugs in gruntfile<commit_after>'use strict';

module.exports = function(grunt) {
	require('jit-grunt')(grunt);

	grunt.loadNpmTasks('grunt-env');

	// Unified Watch Object
	var watchFiles = {
		serverViews: ['app/views/**/*.*'],
		serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js', '!app/tests/'],
		clientViews: ['public/modules/**/views/**/*.html'],
		clientJS: ['public/js/*.js', 'public/modules/**/*.js'],
		clientCSS: ['public/modules/**/*.css'],
		serverTests: ['app/tests/**/*.js'],
		clientTests: ['public/modules/**/tests/*.js'],
		allTests: ['public/modules/**/tests/*.js', 'app/tests/**/*.js'],
	};

	// Project Configuration
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		watch: {
			serverViews: {
				files: watchFiles.serverViews,
				options: {
					livereload: true,
					spawn: false
				}
			},
			serverJS: {
				files: watchFiles.serverJS,
				tasks: ['newer:jshint'],
				options: {
					livereload: true,
					spawn: false
				}
			},
			clientViews: {
				files: watchFiles.clientViews,
				tasks: ['html2js:main'],
				options: {
					livereload: true,
					spawn: false
				}
			},
			clientJS: {
				files: watchFiles.clientJS,
				tasks: ['newer:jshint'],
				options: {
					livereload: true,
					spawn: false
				}
			},
			clientCSS: {
				files: watchFiles.clientCSS,
				tasks: ['newer:csslint'],
				options: {
					livereload: true,
					spawn: false
				}
			},
			mochaTests: {
				files: watchFiles.serverTests,
				tasks: ['test:server'],
			}
		},
		jshint: {
			all: {
				src: watchFiles.clientJS.concat(watchFiles.serverJS),
				options: {
					jshintrc: true
				}
			},
			allTests: {
				src: watchFiles.allTests,
				options: {
					jshintrc: true
				}
			}
		},
		csslint: {
			options: {
				csslintrc: '.csslintrc'
			},
			all: {
				src: watchFiles.clientCSS
			}
		},
		uglify: {
			production: {
				options: {
					mangle: false
				},
				files: {
					'public/dist/application.min.js': 'public/dist/application.js'
				}
			}
		},
		cssmin: {
			combine: {
				files: {
					'public/dist/application.min.css': '<%= applicationCSSFiles %>'
				}
			}
		},
		nodemon: {
			dev: {
				script: 'server.js',
				options: {
					nodeArgs: ['--debug'],
					ext: 'js,html',
					watch: watchFiles.serverViews.concat(watchFiles.serverJS)
				}
			}
		},
		'node-inspector': {
			custom: {
				options: {
					'web-port': 1337,
					'web-host': 'localhost',
					'debug-port': 5858,
					'save-live-edit': true,
					'no-preload': true,
					'stack-trace-limit': 50,
					'hidden': []
				}
			}
		},
		ngAnnotate: {
			production: {
				files: {
					'public/dist/application.js': '<%= applicationJavaScriptFiles %>'
				}
			}
		},
		concurrent: {
			default: ['nodemon', 'watch'],
			debug: ['nodemon', 'watch', 'node-inspector'],
			options: {
				logConcurrentOutput: true,
				limit: 10
			}
		},
		env: {
			test: {
				NODE_ENV: 'test',
			},
			secure: {
				NODE_ENV: 'secure',
			},
			default: {
				src: '/opt/deploy/.env'
			}
		},
		mochaTest: {
			src: watchFiles.serverTests,
			options: {
				reporter: 'spec',
				quiet: false,
				require: 'server.js',
				ui: 'bdd'
			}
		},
		karma: {
			unit: {
				configFile: 'karma.conf.js'
			}
		},
		protractor: {
			options: {
				configFile: 'protractor.conf.js',
				keepAlive: true,
				noColor: false
			},
			e2e: {
				options: {
					args: {} // Target-specific arguments
				}
			}
	    },
	    mocha_istanbul: {
            coverage: {
                src: watchFiles.allTests, // a folder works nicely
                options: {
                    mask: '*.test.js',
                    require: ['server.js'],
                }
            },
            coverageClient: {
                src: watchFiles.clientTests, // specifying file patterns works as well
                options: {
                    coverageFolder: 'coverageClient',
                    mask: '*.test.js',
                    require: ['server.js'],
                }
            },
            coverageServer: {
                src: watchFiles.serverTests,
                options: {
                    coverageFolder: 'coverageServer',
                    mask: '*.test.js',
                    require: ['server.js'],
                }
            },
            coveralls: {
                src: watchFiles.allTests, // multiple folders also works
                options: {
                	require: ['server.js'],
                    coverage: true, // this will make the grunt.event.on('coverage') event listener to be triggered
                    check: {
                        lines: 75,
                        statements: 75
                    },
                    root: './lib', // define where the cover task should consider the root of libraries that are covered by tests
                    reportFormats: ['cobertura','lcovonly']
                }
            }
        },
        istanbul_check_coverage: {
          default: {
            options: {
              coverageFolder: 'coverage*', // will check both coverage folders and merge the coverage results
              check: {
                lines: 80,
                statements: 80
              }
            }
          }
        },
        html2js: {
		  options: {
		    base: 'NodeForm',
		    module: 'NodeForm.templates',
		    singleModule: true,
		    useStrict: true,
		    htmlmin: {
		      collapseBooleanAttributes: true,
		      collapseWhitespace: true,
		      removeAttributeQuotes: true,
		      removeComments: true,
		      removeEmptyAttributes: true,
		      removeRedundantAttributes: true,
		    }
		  },
		  main: {
		    src: ['public/modules/**/views/**.html', 'public/modules/**/views/**/*.html'],
		    dest: 'public/populate_template_cache.js'
		  }
		}
	});

	grunt.event.on('coverage', function(lcov, done){
	    var coveralls = require('coveralls');
	    coveralls.handleInput(lcov, function(err){
	        if (err) {
	        	grunt.log.error("Failed to submit lcov file to coveralls: " + err);
	            return done(err);
	        }
	        grunt.verbose.ok("Successfully submitted lcov file to coveralls");
	        done();
	    });
	});

	// Making grunt default to force in order not to break the project.
	grunt.option('force', true);

	// A Task for loading the configuration object
	grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() {
		var init = require('./config/init')();
		var config = require('./config/config');

		grunt.config.set('applicationJavaScriptFiles', config.assets.js);
		grunt.config.set('applicationCSSFiles', config.assets.css);
	});

	// Code coverage tasks.
	grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']);
    grunt.registerTask('coverage', ['env:test', 'mocha_istanbul:coverage']);
    grunt.registerTask('coverage:client', ['env:test', 'mocha_istanbul:coverageClient']);
    grunt.registerTask('coverage:server', ['env:test', 'mocha_istanbul:coverageServer']);

	// Default task(s).
	grunt.registerTask('default', ['lint', 'html2js:main', 'env', 'concurrent:default']);

	// Debug task.
	grunt.registerTask('debug', ['lint', 'html2js:main', 'concurrent:debug']);

	// Secure task(s).
	grunt.registerTask('secure', ['env:secure', 'lint', 'html2js:main', 'concurrent:default']);

	// Lint task(s).
	grunt.registerTask('lint', ['jshint', 'csslint']);
	grunt.registerTask('lint:tests', ['jshint:allTests']);

	// Build task(s).
	grunt.registerTask('build', ['lint', 'loadConfig', 'uglify', 'cssmin', 'ngAnnotate', 'html2js:main']);

	// Test task.
	grunt.registerTask('test', ['lint:tests', 'test:server', 'test:client']);
	grunt.registerTask('test:server', ['lint:tests', 'env:test', 'mochaTest']);
	grunt.registerTask('test:client', ['lint:tests', 'html2js:main', 'env:test', 'karma:unit']);
};
<|endoftext|>


<commit_before>'use strict'

/**
 * @module serverless-plugin-warmup
 *
 * @see {@link https://serverless.com/framework/docs/providers/aws/guide/plugins/}
 *
 * @requires 'fs-extra'
 * @requires 'path'
 * */
const fs = require('fs-extra')
const path = require('path')

/**
 * @classdesc Keep your lambdas warm during Winter
 * @class WarmUp
 * */
class WarmUp {
  /**
   * @description Serverless Warm Up
   * @constructor
   *
   * @param {!Object} serverless - Serverless object
   * @param {!Object} options - Serverless options
   * */
  constructor (serverless, options) {
    /** Serverless variables */
    this.serverless = serverless
    this.options = options

    this.provider = this.serverless.getProvider('aws')

    this.hooks = {
      'after:package:initialize': this.afterPackageInitialize.bind(this),
      'after:package:createDeploymentArtifacts': this.afterCreateDeploymentArtifacts.bind(this),
      'after:deploy:deploy': this.afterDeployFunctions.bind(this)
    }

    // See https://github.com/serverless/serverless/issues/2631
    this.options.stage = this.options.stage ||
      this.serverless.service.provider.stage ||
      (this.serverless.service.defaults && this.serverless.service.defaults.stage) ||
      'dev'
    this.options.region = this.options.region ||
      this.serverless.service.provider.region ||
      (this.serverless.service.defaults && this.serverless.service.defaults.region) ||
      'us-east-1'

    this.warmupOpts = this.configPlugin(this.serverless.service, this.options.stage)
  }

  /**
   * @description After package initialize hook. Create warmer function and add it to the service.
   *
   * @fulfil {} — Warm up set
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  async afterPackageInitialize () {
    this.functionsToWarmup = this.getFunctionsToBeWarmedUp(this.serverless.service, this.options.stage, this.warmupOpts)

    if (!this.functionsToWarmup.length) {
      this.serverless.cli.log('WarmUp: no functions to warm up')
      return
    }

    await this.createWarmUpFunctionArtifact(this.functionsToWarmup)
    await this.addWarmUpFunctionToService()
  }

  /**
   * @description After create deployment artifacts. Clean prefix folder.
   *
   * @fulfil {} — Optimization finished
   * @reject {Error} Optimization error
   *
   * @return {Promise}
   * */
  async afterCreateDeploymentArtifacts () {
    if (this.warmupOpts.cleanFolder) {
      await this.cleanFolder()
    }
  }

  /**
   * @description After deploy functions hooks
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  async afterDeployFunctions () {
    if (this.warmupOpts.prewarm) {
      this.functionsToWarmup = this.functionsToWarmup || this.getFunctionsToBeWarmedUp(this.serverless.service, this.options.stage, this.warmupOpts)

      if (this.functionsToWarmup.length <= 0) {
        this.serverless.cli.log('WarmUp: no functions to prewarm')
        return
      }

      await this.warmUpFunctions()
    }
  }

  /**
   * @description Clean a global configuration object
   * and fill the missing options using the given defaults
   *
   * @return {Object} - Global configuration options
   * */
  getGlobalConfig (possibleConfig, defaultOpts) {
    const config = (typeof possibleConfig === 'object') ? possibleConfig : {}
    const folderName = (typeof config.folderName === 'string') ? config.folderName : '_warmup'
    const pathFolder = path.join(this.serverless.config.servicePath, folderName)

    // Keep backwards compatibility for now
    config.events = (typeof config.schedule === 'string')
      ? [{ schedule: config.schedule }]
      : (Array.isArray(config.schedule))
        ? config.schedule.map(schedule => ({ schedule }))
        : config.events

    return {
      folderName,
      pathFolder,
      pathFile: `${pathFolder}/index.js`,
      pathHandler: `${folderName}/index.warmUp`,
      cleanFolder: (typeof config.cleanFolder === 'boolean') ? config.cleanFolder : defaultOpts.cleanFolder,
      name: (typeof config.name === 'string') ? config.name : defaultOpts.name,
      role: (typeof config.role === 'string') ? config.role : defaultOpts.role,
      tags: (typeof config.tags === 'object') ? config.tags : defaultOpts.tags,
      vpc: config.vpc === false ? { securityGroupIds: [], subnetIds: [] }
        : (typeof config.vpc === 'object' ? config.vpc : defaultOpts.vpc),
      events: (Array.isArray(config.events)) ? config.events : defaultOpts.events,
      memorySize: (typeof config.memorySize === 'number') ? config.memorySize : defaultOpts.memorySize,
      timeout: (typeof config.timeout === 'number') ? config.timeout : defaultOpts.timeout,
      prewarm: (typeof config.prewarm === 'boolean') ? config.prewarm : defaultOpts.prewarm
    }
  }

  /**
   * @description Clean a function-specific configuration object
   * and fill the missing options using the given defaults
   *
   * @return {Object} - Function-specific configuration options
   * */
  getFunctionConfig (possibleConfig, defaultOpts) {
    const config = (['boolean', 'string'].includes(typeof possibleConfig) || Array.isArray(possibleConfig))
      ? { enabled: possibleConfig }
      : (possibleConfig || {})

    // Keep backwards compatibility for now
    if (config.default) {
      config.enabled = possibleConfig.default
    }
    if (config.source) {
      config.payload = possibleConfig.source
    }
    if (config.sourceRaw) {
      config.payloadRaw = config.sourceRaw
    }

    return {
      enabled: (typeof config.enabled === 'boolean' ||
          typeof config.enabled === 'string' ||
          Array.isArray(config.enabled))
        ? config.enabled
        : defaultOpts.enabled,
      payload: (typeof config.payload !== 'undefined')
        ? (config.payloadRaw ? config.payload : JSON.stringify(config.payload))
        : defaultOpts.payload,
      concurrency: (typeof config.concurrency === 'number') ? config.concurrency : defaultOpts.concurrency
    }
  }

  /**
   * @description Configure the plugin based on the context of serverless.yml
   *
   * @return {Object} - Configuration options to be used by the plugin
   * */
  configPlugin (service, stage) {
    const globalDefaultOpts = {
      folderName: '_warmup',
      cleanFolder: true,
      memorySize: 128,
      name: `${service.service}-${stage}-warmup-plugin`,
      events: [{ schedule: 'rate(5 minutes)' }],
      timeout: 10,
      prewarm: false
    }

    const functionDefaultOpts = {
      enabled: false,
      payload: JSON.stringify({ source: 'serverless-plugin-warmup' }),
      concurrency: 1
    }

    const customConfig = service.custom ? service.custom.warmup : undefined

    return Object.assign(
      this.getGlobalConfig(customConfig, globalDefaultOpts),
      this.getFunctionConfig(customConfig, functionDefaultOpts)
    )
  }

  /**
   * @description After package initialize hook. Create warmer function and add it to the service.
   *
   * @return {Array} - List of functions to be warmed up and their specific configs
   * */
  getFunctionsToBeWarmedUp (service, stage, warmupOpts) {
    return service.getAllFunctions()
      .map(name => service.getFunction(name))
      .map(config => ({ name: config.name, config: this.getFunctionConfig(config.warmup, warmupOpts) }))
      .filter(({ config: { enabled } }) => (
        enabled === true ||
        enabled === 'true' ||
        enabled === stage ||
        (Array.isArray(enabled) && enabled.indexOf(stage) !== -1)
      ))
  }

  /**
   * @description Clean prefix folder
   *
   * @fulfil {} — Folder cleaned
   * @reject {Error} File system error
   *
   * @return {Promise}
   * */
  async cleanFolder () {
    return fs.remove(this.warmupOpts.pathFolder)
  }

  /**
   * @description Write warm up ES6 function
   *
   * @param {Array} functions - Functions to be warmed up
   *
   * @fulfil {} — Warm up function created
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  async createWarmUpFunctionArtifact (functions) {
    /** Log warmup start */
    this.serverless.cli.log(`WarmUp: setting ${functions.length} lambdas to be warm`)

    /** Log functions being warmed up */
    functions.forEach(func => this.serverless.cli.log(`WarmUp: ${func.name}`))

    const warmUpFunction = `"use strict";

/** Generated by Serverless WarmUp Plugin at ${new Date().toISOString()} */
const aws = require("aws-sdk");
aws.config.region = "${this.options.region}";
const lambda = new aws.Lambda();
const functions = ${JSON.stringify(functions)};

module.exports.warmUp = async (event, context) => {
  console.log("Warm Up Start");

  const invokes = await Promise.all(functions.map(async (func) => {
    console.log(\`Warming up function: \${func.name} with concurrency: \${func.config.concurrency}\`);

    const params = {
      ClientContext: Buffer.from(\`{"custom":\${func.config.payload}}\`).toString('base64'),
      FunctionName: func.name,
      InvocationType: "RequestResponse",
      LogType: "None",
      Qualifier: process.env.SERVERLESS_ALIAS || "$LATEST",
      Payload: func.config.payload
    };

    try {
      await Promise.all(Array(func.config.concurrency).fill(0)
        .map(async _ => await lambda.invoke(params).promise()))
      console.log(\`Warm Up Invoke Success: \${func.name}\`);
      return true;
    } catch (e) {
      console.log(\`Warm Up Invoke Error: \${func.name}\`, e);
      return false;
    }
  }));

  console.log(\`Warm Up Finished with \${invokes.filter(r => !r).length} invoke errors\`);
}`

    /** Write warm up file */
    return fs.outputFile(this.warmupOpts.pathFile, warmUpFunction)
  }

  /**
   * @description Add warm up function to service
   *
   * @return {Object} Warm up service function object
   * */
  addWarmUpFunctionToService () {
    /** SLS warm up function */
    this.serverless.service.functions.warmUpPlugin = Object.assign(
      {
        description: 'Serverless WarmUp Plugin',
        events: this.warmupOpts.events,
        handler: this.warmupOpts.pathHandler,
        memorySize: this.warmupOpts.memorySize,
        name: this.warmupOpts.name,
        runtime: 'nodejs8.10',
        package: {
          individually: true,
          exclude: ['**'],
          include: [this.warmupOpts.folderName + '/**']
        },
        timeout: this.warmupOpts.timeout
      },
      this.warmupOpts.role ? { role: this.warmupOpts.role } : {},
      this.warmupOpts.tags ? { tags: this.warmupOpts.tags } : {},
      this.warmupOpts.vpc ? { vpc: this.warmupOpts.vpc } : {}
    )

    return this.serverless.service.functions.warmUpPlugin
  }

  /**
   * @description Warm up the functions immediately after deployment
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  async warmUpFunctions () {
    this.serverless.cli.log('WarmUp: Pre-warming up your functions')

    try {
      const params = {
        FunctionName: this.warmupOpts.name,
        InvocationType: 'RequestResponse',
        LogType: 'None',
        Qualifier: process.env.SERVERLESS_ALIAS || '$LATEST',
        Payload: this.warmupOpts.payload
      }

      await this.provider.request('Lambda', 'invoke', params)
      this.serverless.cli.log('WarmUp: Functions sucessfuly pre-warmed')
    } catch (err) {
      this.serverless.cli.log('WarmUp: Error while pre-warming functions', err)
    }
  }
}

/** Export WarmUp class */
module.exports = WarmUp
<commit_msg>Move config initialization outside of constructor<commit_after>'use strict'

/**
 * @module serverless-plugin-warmup
 *
 * @see {@link https://serverless.com/framework/docs/providers/aws/guide/plugins/}
 *
 * @requires 'fs-extra'
 * @requires 'path'
 * */
const fs = require('fs-extra')
const path = require('path')

/**
 * @classdesc Keep your lambdas warm during Winter
 * @class WarmUp
 * */
class WarmUp {
  /**
   * @description Serverless Warm Up
   * @constructor
   *
   * @param {!Object} serverless - Serverless object
   * @param {!Object} options - Serverless options
   * */
  constructor (serverless, options) {
    /** Serverless variables */
    this.serverless = serverless
    this.options = options

    this.provider = this.serverless.getProvider('aws')

    this.hooks = {
      'after:package:initialize': this.afterPackageInitialize.bind(this),
      'after:package:createDeploymentArtifacts': this.afterCreateDeploymentArtifacts.bind(this),
      'after:deploy:deploy': this.afterDeployFunctions.bind(this)
    }

    // See https://github.com/serverless/serverless/issues/2631
    this.options.stage = this.options.stage ||
      this.serverless.service.provider.stage ||
      (this.serverless.service.defaults && this.serverless.service.defaults.stage) ||
      'dev'
    this.options.region = this.options.region ||
      this.serverless.service.provider.region ||
      (this.serverless.service.defaults && this.serverless.service.defaults.region) ||
      'us-east-1'
  }

  /**
   * @description After package initialize hook. Create warmer function and add it to the service.
   *
   * @fulfil {} — Warm up set
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  async afterPackageInitialize () {
    this.warmupOpts = this.configPlugin(this.serverless.service, this.options.stage)
    this.functionsToWarmup = this.getFunctionsToBeWarmedUp(this.serverless.service, this.options.stage, this.warmupOpts)

    if (!this.functionsToWarmup.length) {
      this.serverless.cli.log('WarmUp: no functions to warm up')
      return
    }

    await this.createWarmUpFunctionArtifact(this.functionsToWarmup)
    await this.addWarmUpFunctionToService()
  }

  /**
   * @description After create deployment artifacts. Clean prefix folder.
   *
   * @fulfil {} — Optimization finished
   * @reject {Error} Optimization error
   *
   * @return {Promise}
   * */
  async afterCreateDeploymentArtifacts () {
    this.warmupOpts = this.warmupOpts || this.configPlugin(this.serverless.service, this.options.stage)
    if (this.warmupOpts.cleanFolder) {
      await this.cleanFolder()
    }
  }

  /**
   * @description After deploy functions hooks
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  async afterDeployFunctions () {
    this.warmupOpts = this.warmupOpts || this.configPlugin(this.serverless.service, this.options.stage)
    if (this.warmupOpts.prewarm) {
      this.functionsToWarmup = this.functionsToWarmup || this.getFunctionsToBeWarmedUp(this.serverless.service, this.options.stage, this.warmupOpts)

      if (this.functionsToWarmup.length <= 0) {
        this.serverless.cli.log('WarmUp: no functions to prewarm')
        return
      }

      await this.warmUpFunctions()
    }
  }

  /**
   * @description Clean a global configuration object
   * and fill the missing options using the given defaults
   *
   * @return {Object} - Global configuration options
   * */
  getGlobalConfig (possibleConfig, defaultOpts) {
    const config = (typeof possibleConfig === 'object') ? possibleConfig : {}
    const folderName = (typeof config.folderName === 'string') ? config.folderName : '_warmup'
    const pathFolder = path.join(this.serverless.config.servicePath, folderName)

    // Keep backwards compatibility for now
    config.events = (typeof config.schedule === 'string')
      ? [{ schedule: config.schedule }]
      : (Array.isArray(config.schedule))
        ? config.schedule.map(schedule => ({ schedule }))
        : config.events

    return {
      folderName,
      pathFolder,
      pathFile: `${pathFolder}/index.js`,
      pathHandler: `${folderName}/index.warmUp`,
      cleanFolder: (typeof config.cleanFolder === 'boolean') ? config.cleanFolder : defaultOpts.cleanFolder,
      name: (typeof config.name === 'string') ? config.name : defaultOpts.name,
      role: (typeof config.role === 'string') ? config.role : defaultOpts.role,
      tags: (typeof config.tags === 'object') ? config.tags : defaultOpts.tags,
      vpc: config.vpc === false ? { securityGroupIds: [], subnetIds: [] }
        : (typeof config.vpc === 'object' ? config.vpc : defaultOpts.vpc),
      events: (Array.isArray(config.events)) ? config.events : defaultOpts.events,
      memorySize: (typeof config.memorySize === 'number') ? config.memorySize : defaultOpts.memorySize,
      timeout: (typeof config.timeout === 'number') ? config.timeout : defaultOpts.timeout,
      prewarm: (typeof config.prewarm === 'boolean') ? config.prewarm : defaultOpts.prewarm
    }
  }

  /**
   * @description Clean a function-specific configuration object
   * and fill the missing options using the given defaults
   *
   * @return {Object} - Function-specific configuration options
   * */
  getFunctionConfig (possibleConfig, defaultOpts) {
    const config = (['boolean', 'string'].includes(typeof possibleConfig) || Array.isArray(possibleConfig))
      ? { enabled: possibleConfig }
      : (possibleConfig || {})

    // Keep backwards compatibility for now
    if (config.default) {
      config.enabled = possibleConfig.default
    }
    if (config.source) {
      config.payload = possibleConfig.source
    }
    if (config.sourceRaw) {
      config.payloadRaw = config.sourceRaw
    }

    return {
      enabled: (typeof config.enabled === 'boolean' ||
          typeof config.enabled === 'string' ||
          Array.isArray(config.enabled))
        ? config.enabled
        : defaultOpts.enabled,
      payload: (typeof config.payload !== 'undefined')
        ? (config.payloadRaw ? config.payload : JSON.stringify(config.payload))
        : defaultOpts.payload,
      concurrency: (typeof config.concurrency === 'number') ? config.concurrency : defaultOpts.concurrency
    }
  }

  /**
   * @description Configure the plugin based on the context of serverless.yml
   *
   * @return {Object} - Configuration options to be used by the plugin
   * */
  configPlugin (service, stage) {
    const globalDefaultOpts = {
      folderName: '_warmup',
      cleanFolder: true,
      memorySize: 128,
      name: `${service.service}-${stage}-warmup-plugin`,
      events: [{ schedule: 'rate(5 minutes)' }],
      timeout: 10,
      prewarm: false
    }

    const functionDefaultOpts = {
      enabled: false,
      payload: JSON.stringify({ source: 'serverless-plugin-warmup' }),
      concurrency: 1
    }

    const customConfig = service.custom ? service.custom.warmup : undefined

    return Object.assign(
      this.getGlobalConfig(customConfig, globalDefaultOpts),
      this.getFunctionConfig(customConfig, functionDefaultOpts)
    )
  }

  /**
   * @description After package initialize hook. Create warmer function and add it to the service.
   *
   * @return {Array} - List of functions to be warmed up and their specific configs
   * */
  getFunctionsToBeWarmedUp (service, stage, warmupOpts) {
    return service.getAllFunctions()
      .map(name => service.getFunction(name))
      .map(config => ({ name: config.name, config: this.getFunctionConfig(config.warmup, warmupOpts) }))
      .filter(({ config: { enabled } }) => (
        enabled === true ||
        enabled === 'true' ||
        enabled === stage ||
        (Array.isArray(enabled) && enabled.indexOf(stage) !== -1)
      ))
  }

  /**
   * @description Clean prefix folder
   *
   * @fulfil {} — Folder cleaned
   * @reject {Error} File system error
   *
   * @return {Promise}
   * */
  async cleanFolder () {
    return fs.remove(this.warmupOpts.pathFolder)
  }

  /**
   * @description Write warm up ES6 function
   *
   * @param {Array} functions - Functions to be warmed up
   *
   * @fulfil {} — Warm up function created
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  async createWarmUpFunctionArtifact (functions) {
    /** Log warmup start */
    this.serverless.cli.log(`WarmUp: setting ${functions.length} lambdas to be warm`)

    /** Log functions being warmed up */
    functions.forEach(func => this.serverless.cli.log(`WarmUp: ${func.name}`))

    const warmUpFunction = `"use strict";

/** Generated by Serverless WarmUp Plugin at ${new Date().toISOString()} */
const aws = require("aws-sdk");
aws.config.region = "${this.options.region}";
const lambda = new aws.Lambda();
const functions = ${JSON.stringify(functions)};

module.exports.warmUp = async (event, context) => {
  console.log("Warm Up Start");

  const invokes = await Promise.all(functions.map(async (func) => {
    console.log(\`Warming up function: \${func.name} with concurrency: \${func.config.concurrency}\`);

    const params = {
      ClientContext: Buffer.from(\`{"custom":\${func.config.payload}}\`).toString('base64'),
      FunctionName: func.name,
      InvocationType: "RequestResponse",
      LogType: "None",
      Qualifier: process.env.SERVERLESS_ALIAS || "$LATEST",
      Payload: func.config.payload
    };

    try {
      await Promise.all(Array(func.config.concurrency).fill(0)
        .map(async _ => await lambda.invoke(params).promise()))
      console.log(\`Warm Up Invoke Success: \${func.name}\`);
      return true;
    } catch (e) {
      console.log(\`Warm Up Invoke Error: \${func.name}\`, e);
      return false;
    }
  }));

  console.log(\`Warm Up Finished with \${invokes.filter(r => !r).length} invoke errors\`);
}`

    /** Write warm up file */
    return fs.outputFile(this.warmupOpts.pathFile, warmUpFunction)
  }

  /**
   * @description Add warm up function to service
   *
   * @return {Object} Warm up service function object
   * */
  addWarmUpFunctionToService () {
    /** SLS warm up function */
    this.serverless.service.functions.warmUpPlugin = Object.assign(
      {
        description: 'Serverless WarmUp Plugin',
        events: this.warmupOpts.events,
        handler: this.warmupOpts.pathHandler,
        memorySize: this.warmupOpts.memorySize,
        name: this.warmupOpts.name,
        runtime: 'nodejs8.10',
        package: {
          individually: true,
          exclude: ['**'],
          include: [this.warmupOpts.folderName + '/**']
        },
        timeout: this.warmupOpts.timeout
      },
      this.warmupOpts.role ? { role: this.warmupOpts.role } : {},
      this.warmupOpts.tags ? { tags: this.warmupOpts.tags } : {},
      this.warmupOpts.vpc ? { vpc: this.warmupOpts.vpc } : {}
    )

    return this.serverless.service.functions.warmUpPlugin
  }

  /**
   * @description Warm up the functions immediately after deployment
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  async warmUpFunctions () {
    this.serverless.cli.log('WarmUp: Pre-warming up your functions')

    try {
      const params = {
        FunctionName: this.warmupOpts.name,
        InvocationType: 'RequestResponse',
        LogType: 'None',
        Qualifier: process.env.SERVERLESS_ALIAS || '$LATEST',
        Payload: this.warmupOpts.payload
      }

      await this.provider.request('Lambda', 'invoke', params)
      this.serverless.cli.log('WarmUp: Functions sucessfuly pre-warmed')
    } catch (err) {
      this.serverless.cli.log('WarmUp: Error while pre-warming functions', err)
    }
  }
}

/** Export WarmUp class */
module.exports = WarmUp
<|endoftext|>


<commit_before>/*!
 * Bootstrap-sync's Gruntfile
 * https://github.com/StevenBlack/bootstrap-sync
 * Copyright 2014-2015 Twitter, Inc.
 * Licensed under MIT (https://raw.githubusercontent.com/StevenBlack/bootstrap-sync/master/LICENSE-MIT)
 */
module.exports = function( grunt ) {
	'use strict';

	var optionsfile = 'gruntoptions.json';
	var _           = require('lodash');
	var pkg         = grunt.file.readJSON( 'package.json' );
	var options     = grunt.file.exists( optionsfile ) ? grunt.file.readJSON( optionsfile ) : {} ;
	var settings    = _.merge( {}, pkg.defaults, options );

	// Project configuration.
	grunt.initConfig({

		// Metadata.
		pkg: pkg,
		options: options,
		settings: settings,

		jqueryCheck: 'if (typeof jQuery === \'undefined\') { throw new Error(\'Bootstrap\\\'s JavaScript requires jQuery\') }\n\n' ,

		clean: {
			'bootstrap-source': [ '<%= settings.location.bootstrap.local %>/' ],
			'fonts': [ '<%= settings.location.deploy.fonts %>/' ],
			'css': [ '<%= settings.location.deploy.css %>/', "!<%= settings.location.deploy.css %>/main.css" ],
			'js': [ '<%= settings.location.deploy.js %>/' ]
		},

		copy: {
			'bootstrap-source': {
				nonull: true,
				expand: true,
				cwd: '<%= settings.location.bootstrap.authoritative %>/',
				src: [ '<%= settings.location.deploy.fonts %>/*', '<%= settings.location.deploy.js %>/*', 'less/**' ],
				dest: '<%= settings.location.bootstrap.local %>/',
			},
			'bootstrap-tweaks': {
				src: [ 'less/*' ],
				dest: '<%= settings.location.bootstrap.local %>/',
			},
			'bootstrap-fonts': {
				expand: true,
				flatten: true,
				src: [ '<%= settings.location.bootstrap.local %>/fonts/*' ],
				dest: '<%= settings.location.deploy.fonts %>/'
			},
			'fontawesome': {
				expand: true,
				flatten: true,
				src: [ '<%= settings.location.fontawesome.local %>/fonts/*' ],
				dest: '<%= settings.location.deploy.fonts %>/'
			}
		},

		concat: {
			options: {
				// Using the banner to inject a jQuery check.
				banner: '<%= jqueryCheck %>',
				stripBanners: false
			},
			bootstrapjs: {
				src: ( function() {
						var cwd = settings.location.bootstrap.local + '/';
						var arr = settings.task.concat.bootstrapjs.src;
						return arr.map(function(file) { return cwd + "/" + file; });
						}()
				),
				dest: '<%= settings.location.deploy.js %>/<%= settings.filename.js %>'
			}
		},

		uglify: {
			options: { report: 'min', compress: true },
			bootstrap: { src: [ '<%= concat.bootstrapjs.dest %>' ], dest: '<%= settings.location.deploy.js %>/<%= settings.filename.jsmin %>' }
		},

		less: {
			compileCore: {
				options: {
					strictMath: true,
					outputSourceFiles: true
				},
				files: { '<%= settings.location.deploy.css %>/<%= settings.filename.css %>': '<%= settings.location.bootstrap.local %>/less/<%= settings.filename.less %>' }
			}
		},

		cssmin: {
			combine: {
				files: {
					'<%= settings.location.deploy.css %>/<%= settings.filename.cssmin %>': [ '<%= settings.location.deploy.css %>/<%= settings.filename.css %>', '_font-awesome/css/font-awesome.css' ]
				}
			}
		}

	});

	// This one-liner replaces multiple grunt.loadNpmTasks() calls
	// See http://www.thomasboyt.com/2013/09/01/maintainable-grunt.html
	require('load-grunt-tasks')(grunt, { scope: 'devDependencies' });

	// Bootstrap tasks
	//    cleanup
	grunt.registerTask( 'clean-bootstrap', [ 'clean:bootstrap-source' ] );
	grunt.registerTask( 'clean-fonts', [ 'clean:fonts' ] );

	//    constructing
	grunt.registerTask( 'fetch-fresh-bootstrap', [ 'copy:bootstrap-source' ] );
	grunt.registerTask( 'apply-bootstrap-tweaks', [ 'copy:bootstrap-tweaks' ] );
	grunt.registerTask( 'update-fonts', [ 'clean-fonts', 'copy:bootstrap-fonts', 'copy:fontawesome' ] );
	grunt.registerTask( 'bootstrap', [ 'clean-bootstrap', 'fetch-fresh-bootstrap', 'apply-bootstrap-tweaks', 'update-fonts' ] );

	// Less and css tasks
	grunt.registerTask( 'clean-css', [ 'clean:css' ] );
	grunt.registerTask( 'less-compile', [ 'less:compileCore' ]);
	grunt.registerTask( 'css-minify', [ 'cssmin' ]);
	grunt.registerTask( 'css', [ 'clean-css', 'less-compile', 'css-minify']);

	// js tasks
	grunt.registerTask( 'clean-js', [ 'clean:js' ] );
	grunt.registerTask( 'js-bootstrap', ['clean-js', 'concat:bootstrapjs']);
	grunt.registerTask( 'js-minify', [ 'uglify:bootstrap']);
	grunt.registerTask( 'js', [ 'js-bootstrap', 'js-minify' ]);

	// all
	grunt.registerTask(  'clean-all', ['clean-bootstrap', 'clean-fonts', 'clean-css', 'clean-js' ]);
	grunt.registerTask(  'default', ['bootstrap', 'css', 'js' ]);

};

<commit_msg>Fix some typos in the gruntfile.<commit_after>/*!
 * Bootstrap-sync's Gruntfile
 * https://github.com/StevenBlack/bootstrap-sync
 * Copyright 2014-2015 Twitter, Inc.
 * Licensed under MIT (https://raw.githubusercontent.com/StevenBlack/bootstrap-sync/master/LICENSE-MIT)
 */
module.exports = function( grunt ) {
	'use strict';

	var optionsfile = 'gruntoptions.json';
	var _           = require('lodash');
	var pkg         = grunt.file.readJSON( 'package.json' );
	var options     = grunt.file.exists( optionsfile ) ? grunt.file.readJSON( optionsfile ) : {} ;
	var settings    = _.merge( {}, pkg.defaults, options );

	// Project configuration.
	grunt.initConfig({

		// Metadata.
		pkg: pkg,
		options: options,
		settings: settings,

		jqueryCheck: 'if (typeof jQuery === \'undefined\') { throw new Error(\'Bootstrap\\\'s JavaScript requires jQuery\') }\n\n' ,

		clean: {
			'bootstrap-source': [ '<%= settings.location.bootstrap.local %>/' ],
			'fonts': [ '<%= settings.location.deploy.fonts %>/' ],
			'css': [ '<%= settings.location.deploy.css %>/', "!<%= settings.location.deploy.css %>/main.css" ],
			'js': [ '<%= settings.location.deploy.js %>/' ]
		},

		copy: {
			'bootstrap-source': {
				nonull: true,
				expand: true,
				cwd: '<%= settings.location.bootstrap.authoritative %>/',
				src: [ '<%= settings.location.deploy.fonts %>/*', '<%= settings.location.deploy.js %>/*', 'less/**' ],
				dest: '<%= settings.location.bootstrap.local %>/'
			},
			'bootstrap-tweaks': {
				src: [ 'less/*' ],
				dest: '<%= settings.location.bootstrap.local %>/'
			},
			'bootstrap-fonts': {
				expand: true,
				flatten: true,
				src: [ '<%= settings.location.bootstrap.local %>/fonts/*' ],
				dest: '<%= settings.location.deploy.fonts %>/'
			},
			'fontawesome': {
				expand: true,
				flatten: true,
				src: [ '<%= settings.location.fontawesome.local %>/fonts/*' ],
				dest: '<%= settings.location.deploy.fonts %>/'
			}
		},

		concat: {
			options: {
				// Using the banner to inject a jQuery check.
				banner: '<%= jqueryCheck %>',
				stripBanners: false
			},
			bootstrapjs: {
				src: ( function() {
						var cwd = settings.location.bootstrap.local + '/';
						var arr = settings.task.concat.bootstrapjs.src;
						return arr.map(function(file) { return cwd + "/" + file; });
						}()
				),
				dest: '<%= settings.location.deploy.js %>/<%= settings.filename.js %>'
			}
		},

		uglify: {
			options: { report: 'min', compress: true },
			bootstrap: { src: [ '<%= concat.bootstrapjs.dest %>' ], dest: '<%= settings.location.deploy.js %>/<%= settings.filename.jsmin %>' }
		},

		less: {
			compileCore: {
				options: {
					strictMath: true,
					outputSourceFiles: true
				},
				files: { '<%= settings.location.deploy.css %>/<%= settings.filename.css %>': '<%= settings.location.bootstrap.local %>/less/<%= settings.filename.less %>' }
			}
		},

		cssmin: {
			combine: {
				files: {
					'<%= settings.location.deploy.css %>/<%= settings.filename.cssmin %>': [ '<%= settings.location.deploy.css %>/<%= settings.filename.css %>', '_font-awesome/css/font-awesome.css' ]
				}
			}
		}

	});

	// This one-liner replaces multiple grunt.loadNpmTasks() calls
	// See http://www.thomasboyt.com/2013/09/01/maintainable-grunt.html
	require('load-grunt-tasks')(grunt, { scope: 'devDependencies' });

	// Bootstrap tasks
	//    cleanup
	grunt.registerTask( 'clean-bootstrap', [ 'clean:bootstrap-source' ] );
	grunt.registerTask( 'clean-fonts', [ 'clean:fonts' ] );

	//    constructing
	grunt.registerTask( 'fetch-fresh-bootstrap', [ 'copy:bootstrap-source' ] );
	grunt.registerTask( 'apply-bootstrap-tweaks', [ 'copy:bootstrap-tweaks' ] );
	grunt.registerTask( 'update-fonts', [ 'clean-fonts', 'copy:bootstrap-fonts', 'copy:fontawesome' ] );
	grunt.registerTask( 'bootstrap', [ 'clean-bootstrap', 'fetch-fresh-bootstrap', 'apply-bootstrap-tweaks', 'update-fonts' ] );

	// Less and css tasks
	grunt.registerTask( 'clean-css', [ 'clean:css' ] );
	grunt.registerTask( 'less-compile', [ 'less:compileCore' ]);
	grunt.registerTask( 'css-minify', [ 'cssmin' ]);
	grunt.registerTask( 'css', [ 'clean-css', 'less-compile', 'css-minify']);

	// js tasks
	grunt.registerTask( 'clean-js', [ 'clean:js' ] );
	grunt.registerTask( 'js-bootstrap', ['clean-js', 'concat:bootstrapjs']);
	grunt.registerTask( 'js-minify', [ 'uglify:bootstrap']);
	grunt.registerTask( 'js', [ 'js-bootstrap', 'js-minify' ]);

	// all
	grunt.registerTask(  'clean-all', ['clean-bootstrap', 'clean-fonts', 'clean-css', 'clean-js' ]);
	grunt.registerTask(  'default', ['bootstrap', 'css', 'js' ]);

};

<|endoftext|>


<commit_before>class Grid {
  constructor (width, height) {
    this.__width = Math.abs(width);
    this.__height = Math.abs(height);
    this.clear()
  }

  set (x, y, value) {
    this.__cells[this.__getIndex(x, y)] = value;
    return this;
  }

  get (x, y) {
    return this.__cells[this.__getIndex(x, y)] || null;
  }

  has (x, y) {
    return this.get(x, y) != null;
  }

  get width () {
    return this.__width;
  }

  get height () {
    return this.__height;
  }

  get length () {
    return this.__width * this.__height;
  }

  forEach (callback, reverse = false) {
    const cells = this.__cells,
          w = this.__width,
          h = this.__height,
          limitX = !reverse ? w : -1,
          limitY = !reverse ? h : -1;
    let x = !reverse ? 0 : w - 1,
        y = !reverse ? 0 : h - 1;

    while (y != limitY) {
      let proceed;
      x = !reverse ? 0 : w - 1
      while (x != limitX) {
        proceed = callback(cells[this.__getIndex(x, y)], x, y, this);
        if (false === proceed) break;
        x += reverse ? -1 : 1;
        console.log(x, y)
      }
      if (false === proceed) break;
      y += reverse ? -1 : 1;
      console.log(x, y)
    }
    return this;
  }

  clone () {
    return Grid.fromArray(
      this.__width,
      this.__height,
      this.__cells
    );
  }

  clear () {
    this.__cells = Array(this.__width * this.__height);
    return this;
  }

  clipX (x) {
    return this.__clip(x, 0, this.__width - 1);
  }

  clipY (y) {
    return this.__clip(y, 0, this.__height - 1);
  }

  toArray () {
    return this.__cells.slice(0);
  }

  toString () {
    return this.__cells.join(',');
  }

  // internals
  __getIndex (x, y) {
    x = this.clipX(x)
    y = this.clipY(y)
    return x + (y * this.__width);
  }

  __clip (n, min, max) {
    return Math.min(Math.max(n, min), max);
  }
}

Grid.fromArray = (width, height, array) => {
  const grid = new Grid(width, height);
  let i = 0;
  grid.forEach((val, x, y) => {
    grid.set(x, y, array[i++])
  })
  return grid;
}

if (typeof module !== 'undefined') {
  module.exports = Grid;
} else {
  window.Grid = Grid
}
<commit_msg>remove console.log lines<commit_after>class Grid {
  constructor (width, height) {
    this.__width = Math.abs(width);
    this.__height = Math.abs(height);
    this.clear()
  }

  set (x, y, value) {
    this.__cells[this.__getIndex(x, y)] = value;
    return this;
  }

  get (x, y) {
    return this.__cells[this.__getIndex(x, y)] || null;
  }

  has (x, y) {
    return this.get(x, y) != null;
  }

  get width () {
    return this.__width;
  }

  get height () {
    return this.__height;
  }

  get length () {
    return this.__width * this.__height;
  }

  forEach (callback, reverse = false) {
    const cells = this.__cells,
          w = this.__width,
          h = this.__height,
          limitX = !reverse ? w : -1,
          limitY = !reverse ? h : -1;
    let x = !reverse ? 0 : w - 1,
        y = !reverse ? 0 : h - 1;

    while (y != limitY) {
      let proceed;
      x = !reverse ? 0 : w - 1
      while (x != limitX) {
        proceed = callback(cells[this.__getIndex(x, y)], x, y, this);
        if (false === proceed) break;
        x += reverse ? -1 : 1;
      }
      if (false === proceed) break;
      y += reverse ? -1 : 1;
    }
    return this;
  }

  clone () {
    return Grid.fromArray(
      this.__width,
      this.__height,
      this.__cells
    );
  }

  clear () {
    this.__cells = Array(this.__width * this.__height);
    return this;
  }

  clipX (x) {
    return this.__clip(x, 0, this.__width - 1);
  }

  clipY (y) {
    return this.__clip(y, 0, this.__height - 1);
  }

  toArray () {
    return this.__cells.slice(0);
  }

  toString () {
    return this.__cells.join(',');
  }

  // internals
  __getIndex (x, y) {
    x = this.clipX(x)
    y = this.clipY(y)
    return x + (y * this.__width);
  }

  __clip (n, min, max) {
    return Math.min(Math.max(n, min), max);
  }
}

Grid.fromArray = (width, height, array) => {
  const grid = new Grid(width, height);
  let i = 0;
  grid.forEach((val, x, y) => {
    grid.set(x, y, array[i++])
  })
  return grid;
}

if (typeof module !== 'undefined') {
  module.exports = Grid;
} else {
  window.Grid = Grid
}
<|endoftext|>


<commit_before>'use strict'

const table = require('./base-table')
const varint = require('varint')

exports = module.exports

exports.addPrefix = (multicodecStrOrCode, data) => {
  let pfx

  if (Buffer.isBuffer(multicodecStrOrCode)) {
    pfx = multicodecStrOrCode
  } else {
    if (table[multicodecStrOrCode]) {
      pfx = table[multicodecStrOrCode]
    } else {
      throw new Error('multicodec not recognized')
    }
  }
  return Buffer.concat([pfx, data])
}

exports.rmPrefix = (data) => {
  varint.decode(data)
  return data.slice(varint.decode.bytes)
}

exports.getCodec = (prefixedData) => {
  const v = varint.decode(prefixedData)
  const code = new Buffer(v.toString(16), 'hex')
  let codec

  Object.keys(table)
        .forEach((mc) => {
          if (code.equals(table[mc])) {
            codec = mc
          }
        })

  return codec
}
<commit_msg>change forEach to some so that you can speed up the table search by shortciruting the loop once the codec is found<commit_after>'use strict'

const table = require('./base-table')
const varint = require('varint')

exports = module.exports

exports.addPrefix = (multicodecStrOrCode, data) => {
  let pfx

  if (Buffer.isBuffer(multicodecStrOrCode)) {
    pfx = multicodecStrOrCode
  } else {
    if (table[multicodecStrOrCode]) {
      pfx = table[multicodecStrOrCode]
    } else {
      throw new Error('multicodec not recognized')
    }
  }
  return Buffer.concat([pfx, data])
}

exports.rmPrefix = (data) => {
  varint.decode(data)
  return data.slice(varint.decode.bytes)
}

exports.getCodec = (prefixedData) => {
  const v = varint.decode(prefixedData)
  const code = new Buffer(v.toString(16), 'hex')
  let codec

  Object.keys(table)
        .some(mc => {
          if (code.equals(table[mc])) {
            codec = mc
            return
          }
        })

  return codec
}
<|endoftext|>