<commit_before>'use strict';

var _        = require('lodash'),
    jsonPath = require('jsonpath'),
    fs       = require('fs'),
    glob     = require("glob"),
    Chance   = require('chance')

var hazy = {}

//    ___             __ _
//   / __\___  _ __  / _(_) __ _
//  / /  / _ \| '_ \| |_| |/ _` |
// / /__| (_) | | | |  _| | (_| |
// \____/\___/|_| |_|_| |_|\__, |
//                         |___/

hazy.config = {
  seed: null,
  lazy: true,
  debug: false,
  matcher: {
    use: true
  },
  errors: {
    quiet: false,
    soft: false
  }
}

hazy.meta = {
  random: {
    types: {
      basic  : ['bool', 'character', 'integer', 'natural', 'string'],
      text   : ['paragraph', 'sentence', 'syllable', 'word'],
      person : ['age', 'birthday', 'cpf', 'first', 'gender', 'last', 'name', 'prefix', 'ssn', 'suffix'],
      mobile : ['android_id', 'apple_token', 'bb_pin', 'wp7_anid', 'wp8_anid2'],
      web    : ['color', 'domain', 'email', 'fbid', 'google_analytics', 'hashtag', 'ip', 'ipv6', 'klout', 'tld', 'twitter', 'url'],
      geo    : ['address', 'altitude', 'areacode', 'city', 'coordinates', 'country', 'depth', 'geohash', 'latitude', 'longitude', 'phone', 'postal', 'province', 'state', 'street', 'zip'],
      time   : ['ampm', 'date', 'hammertime', 'hour', 'millisecond', 'minute', 'month', 'second', 'timestamp', 'year'],
      misc   : ['guid', 'hash', 'normal', 'radio', 'tv']
    } // TODO - support n, unique and weighted! very useful
  }
}

//    __
//   / /  __ _ _ __   __ _
//  / /  / _` | '_ \ / _` |
// / /__| (_| | | | | (_| |
// \____/\__,_|_| |_|\__, |
//                   |___/

hazy.lang = {
  expression: {
    first : /\|(:|~|@|\*)(.*?)?\|/,
    all   : /\|(:|~|@|\*)(.*?)?\|/g
  },

  tokens: {
    // expression start/end
    "|": function(prev, next) {
      var isNextTokenEnd = /\|/.test(next)

      if (isNextTokenEnd) {
        throw hazy.lang.exception('Cannot define an empty expression')
      }

      if (!next) {
        // TODO - return a special value saying that this is the end of the token expression sequence. currenlty not technically needed
      }
    },

    // property separator / accessor
    ":": function(prev, next) { // property accessor
      if (!prev) {
        throw 'Syntax error, : requires a left operand'
      }

      return prev[next]
    },

    // random data
    "~": function(prev, next) {
      var randProp   = next.split(':')[0],
          randVal    = next.split(':')[1],
          canUseProp = hazy.random.hasOwnProperty(randProp)

      if (canUseProp) {
        var randObjByProp  = hazy.random[randProp],
            randObjSubType = randVal // get property of random operator following ":"

        if (!randObjByProp || !randObjByProp[randObjSubType]) {
          throw hazy.lang.exception('Invalid random data type "' + randObjSubType + '". Supported:', hazy.meta.random.types[randProp])
        }

        return randObjByProp[randObjSubType]()
      } else {
        throw hazy.lang.exception('Invalid random data category "' + randProp + '". Supported', hazy.meta.random.types)
      }
    },

    // embed fixture
    "@": function(prev, next) {
      return hazy.fixture.get(next.trim())
    },

    // query and embed fixture
    "*": function(prev, next) {
      return hazy.fixture.query(next.trim())
    },

    // TODO - / escape character

    // TODO - ? random character

    validate: function(token) {
      return this.hasOwnProperty(token)
    },

    process: function(token, prev, next, rest) {
      return _.bindKey(hazy.lang.tokens, token, prev, next, rest)()
    }
  },

  // extracts tokens from strs and evaluates them. interpolates strings, ignores and simply returns other data types
  process: function(str) {
    var matches = str.split(hazy.lang.expression.all),
        tokens  = []

    _.forEach(matches, function(match, i) {
      var isToken = hazy.lang.tokens.validate(match)

      if (isToken) {
        var prevMatch   = matches[i - 1],
            nextMatch   = matches[i + 1],
            restMatches = _.drop(matches, i + 1),
            tokenResult = this.tokens.process(match, prevMatch, nextMatch, restMatches)

        if (tokenResult) {
          // if processed token result is a string, substitute original string as we iterate
          if (_.isString(tokenResult)) {
            str = str.replace(hazy.lang.expression.first, tokenResult)
          } else {
            tokens.push(tokenResult)
          }
        }
      }
    }, this)

    if (!_.isEmpty(tokens)) {
      return _.reduce(tokens) || str
    }

    return str
  },

  exception: function(msg) {
    return '[Hazy syntax error] ' + msg
  }
}

//    __                 _
//   /__\ __ _ _ __   __| | ___  _ __ ___
//  / \/// _` | '_ \ / _` |/ _ \| '_ ` _ \
// / _  \ (_| | | | | (_| | (_) | | | | | |
// \/ \_/\__,_|_| |_|\__,_|\___/|_| |_| |_|
//

hazy.random = _.mapValues(hazy.meta.random.types, function(value, key) {
  var hazyRandObj = {}

  _.forEach(value, function(v) {
     hazyRandObj[v] = function() { return new Chance()[v]() }
  })

  return hazyRandObj
})

//    ___ _      _
//   / __(_)_  _| |_ _   _ _ __ ___  ___
//  / _\ | \ \/ / __| | | | '__/ _ \/ __|
// / /   | |>  <| |_| |_| | | |  __/\__ \
// \/    |_/_/\_\\__|\__,_|_|  \___||___/
//

hazy.fixture = {
  pool: {},

  // fetches a fixture from the pool and processes it if necessary
  get: function(key) {
    var fixture = this.pool[key]

    if (hazy.config.matcher.use) {
      return hazy.matcher.processDeep(fixture)
    }

    return fixture
  },

  // lazily acquires a fixture from the pool, processing it only once
  lazyGet: _.memoize(function(key) {
    return hazy.fixture.get(key)
  }),

  // fetches all fixtures from the pool and processes them if necessary
  all: function() {
    return _.map(hazy.fixture.pool, function(fixture, name) {
      return hazy.fixture.get(name)
    })
  },

  // registers a processable fixture into the fixture pool
  register: function(name, fixture, lazy) {
    this.pool[name] = this.process(fixture) // FIXME - wrap with a special lazy object opposed to just wrapping with a function, too ambiguous
  },

   // dynamically process fixture values by type (object, string, array, or function)
  process: function(fixture) {
    var processedFixture = fixture

    if (_.isPlainObject(fixture)) {
      _.forEach(fixture, function(value, key) {
        var processedKey = hazy.lang.process(key),
            nextFixture  = value

        processedFixture[processedKey] = hazy.fixture.process(nextFixture)
      })
    }

    if (_.isString(fixture)) {
      return hazy.lang.process(fixture)
    }

    if (_.isArray(fixture)) {
      return _.map(fixture, hazy.fixture.process)
    }

    return processedFixture
  },

  // queries the fixture pool for anything that matches the jsonpath pattern
  query: function(pattern) {
    return hazy.matcher.search(pattern)
  },

  // load and register a fixture from files matching a glob pattern
  load: function(pattern, options) {
    glob(pattern, options, function (err, files) {
      if (err) {
        throw 'Failed to load file'
      }

      _.forEach(files, function(file) {
        hazy.fixture.register(file.name, JSON.parse(file))
      })
    })
  }
}

//               _       _
//   /\/\   __ _| |_ ___| |__   ___ _ __ ___
//  /    \ / _` | __/ __| '_ \ / _ \ '__/ __|
// / /\/\ \ (_| | || (__| | | |  __/ |  \__ \
// \/    \/\__,_|\__\___|_| |_|\___|_|  |___/
//

hazy.matcher = {
  pool: {},

  register: function(path, value) {
    this.pool[path] = value
  },

  config: function(config) {
    var matcherPath    = config.path,
        matcherHandler = config.handler

    if (this.pool[matcherPath]) {
      delete this.pool[matcherPath]
    }

    this.pool[matcherPath] = {path: matcherPath, handler: matcherHandler}
  },

  // provides a map of all matched patterns in a fixture (pattern as key)
  matches: function(fixture) {
    var matches = {}

    if (hazy.config.matcher.use) {
      _.forEach(hazy.matcher.pool, function(v, pattern) {
        if (_.isObject(fixture)) {
          var jpMatches = jsonPath.query(fixture, pattern)

          if (!_.isEmpty(jpMatches)) {
            matches[pattern] = jpMatches
          }
        }
      })
    } else {
      // WARN - matching disabled
    }

    return matches
  },

  // determines if any matches in the pool apply to the fixture
  hasMatch: function(fixture) {
    return !_.isEmpty(
      hazy.matcher.matches(fixture)
    )
  },

  // search the fixture pool for fixtures matching a specific pattern (intentionally non-lazy- prone to recursion hell and there's also little benefit in evaluating random values)
  search: function(pattern) {
    var fixtures = _.values(hazy.fixture.pool)

    return _(fixtures)
      .map(function(fixture) {
        var jpMatches = jsonPath.query(fixture, pattern)

        if (!_.isEmpty(jpMatches)) {
          return fixture
        }
      })
      .reject(_.isUndefined)
      .value()
  },

  // executes a single pattern matcher handler on a fixture
  process: function(pattern, fixture) {
    var matcher = hazy.matcher.pool[pattern]

    if (_.isObject(matcher) && _.isFunction(matcher.handler)) {
      var matches = jsonPath.query(fixture, pattern)

      return matcher.handler(fixture, matches, pattern)
    } else {
      throw 'Match pattern does not apply to fixture or handler is not a function'
    }
  },

  // executes handlers for all pattern matches on a fixture
  processDeep: function(fixture) {
    var patternMatches   = this.matches(fixture)
    var processedFixture = fixture

    _.forEach(patternMatches, function(match, pattern) {
      processedFixture = hazy.matcher.process(pattern, fixture) || processedFixture
    })

    return processedFixture
  }
}

//    ___       _ _     _
//   / __\_   _(_) | __| |
//  /__\// | | | | |/ _` |
// / \/  \ |_| | | | (_| |
// \_____/\__,_|_|_|\__,_|
//

// creates a clone of the current hazy object (shallow, new memory references)
hazy.fork = function() {
  return _.clone(hazy, false)
}

// convenience reference to lodash so that developers don't have to explicitly import the lib in their own code
hazy.util = _

module.exports = hazy
<commit_msg>:feelsgood: re-organized random<commit_after>'use strict';

var _        = require('lodash'),
    jsonPath = require('jsonpath'),
    fs       = require('fs'),
    glob     = require("glob"),
    Chance   = require('chance')

var hazy = {}

//    ___             __ _
//   / __\___  _ __  / _(_) __ _
//  / /  / _ \| '_ \| |_| |/ _` |
// / /__| (_) | | | |  _| | (_| |
// \____/\___/|_| |_|_| |_|\__, |
//                         |___/

hazy.config = {
  seed: null,
  lazy: true,
  debug: false,
  matcher: {
    use: true
  },
  errors: {
    quiet: false,
    soft: false
  }
}

hazy.meta = {
  random: {
    types: {
      basic  : ['bool', 'character', 'integer', 'natural', 'string'],
      text   : ['paragraph', 'sentence', 'syllable', 'word'],
      person : ['age', 'birthday', 'cpf', 'first', 'gender', 'last', 'name', 'prefix', 'ssn', 'suffix'],
      mobile : ['android_id', 'apple_token', 'bb_pin', 'wp7_anid', 'wp8_anid2'],
      web    : ['color', 'domain', 'email', 'fbid', 'google_analytics', 'hashtag', 'ip', 'ipv6', 'klout', 'tld', 'twitter', 'url'],
      geo    : ['address', 'altitude', 'areacode', 'city', 'coordinates', 'country', 'depth', 'geohash', 'latitude', 'longitude', 'phone', 'postal', 'province', 'state', 'street', 'zip'],
      time   : ['ampm', 'date', 'hammertime', 'hour', 'millisecond', 'minute', 'month', 'second', 'timestamp', 'year'],
      misc   : ['guid', 'hash', 'normal', 'radio', 'tv']
    } // TODO - support n, unique and weighted! very useful
  }
}

//    __
//   / /  __ _ _ __   __ _
//  / /  / _` | '_ \ / _` |
// / /__| (_| | | | | (_| |
// \____/\__,_|_| |_|\__, |
//                   |___/

hazy.lang = {
  expression: {
    first : /\|(:|~|@|\*)(.*?)?\|/,
    all   : /\|(:|~|@|\*)(.*?)?\|/g
  },

  tokens: {
    // expression start/end
    "|": function(prev, next) {
      var isNextTokenEnd = /\|/.test(next)

      if (isNextTokenEnd) {
        throw hazy.lang.exception('Cannot define an empty expression')
      }

      if (!next) {
        // TODO - return a special value saying that this is the end of the token expression sequence. currenlty not technically needed
      }
    },

    // property separator / accessor
    ":": function(prev, next) { // property accessor
      if (!prev) {
        throw 'Syntax error, : requires a left operand'
      }

      return prev[next]
    },

    // random data
    "~": function(prev, next) {
      var randProp   = next.split(':')[0],
          randVal    = next.split(':')[1],
          canUseProp = hazy.random.hasOwnProperty(randProp)

      if (canUseProp) {
        var randObjByProp  = hazy.random[randProp],
            randObjSubType = randVal // get property of random operator following ":"

        if (!randObjByProp || !randObjByProp[randObjSubType]) {
          throw hazy.lang.exception('Invalid random data type "' + randObjSubType + '". Supported:', hazy.meta.random.types[randProp])
        }

        return randObjByProp[randObjSubType]()
      } else {
        throw hazy.lang.exception('Invalid random data category "' + randProp + '". Supported', hazy.meta.random.types)
      }
    },

    // embed fixture
    "@": function(prev, next) {
      return hazy.fixture.get(next.trim())
    },

    // query and embed fixture
    "*": function(prev, next) {
      return hazy.fixture.query(next.trim())
    },

    // TODO - / escape character

    // TODO - ? random character

    validate: function(token) {
      return this.hasOwnProperty(token)
    },

    process: function(token, prev, next, rest) {
      return _.bindKey(hazy.lang.tokens, token, prev, next, rest)()
    }
  },

  // extracts tokens from strs and evaluates them. interpolates strings, ignores and simply returns other data types
  process: function(str) {
    var matches = str.split(hazy.lang.expression.all),
        tokens  = []

    _.forEach(matches, function(match, i) {
      var isToken = hazy.lang.tokens.validate(match)

      if (isToken) {
        var prevMatch   = matches[i - 1],
            nextMatch   = matches[i + 1],
            restMatches = _.drop(matches, i + 1),
            tokenResult = this.tokens.process(match, prevMatch, nextMatch, restMatches)

        if (tokenResult) {
          // if processed token result is a string, substitute original string as we iterate
          if (_.isString(tokenResult)) {
            str = str.replace(hazy.lang.expression.first, tokenResult)
          } else {
            tokens.push(tokenResult)
          }
        }
      }
    }, this)

    if (!_.isEmpty(tokens)) {
      return _.reduce(tokens) || str
    }

    return str
  },

  exception: function(msg) {
    return '[Hazy syntax error] ' + msg
  }
}

//    ___ _      _
//   / __(_)_  _| |_ _   _ _ __ ___  ___
//  / _\ | \ \/ / __| | | | '__/ _ \/ __|
// / /   | |>  <| |_| |_| | | |  __/\__ \
// \/    |_/_/\_\\__|\__,_|_|  \___||___/
//

hazy.fixture = {
  pool: {},

  // fetches a fixture from the pool and processes it if necessary
  get: function(key) {
    var fixture = this.pool[key]

    if (hazy.config.matcher.use) {
      return hazy.matcher.processDeep(fixture)
    }

    return fixture
  },

  // lazily acquires a fixture from the pool, processing it only once
  lazyGet: _.memoize(function(key) {
    return hazy.fixture.get(key)
  }),

  // fetches all fixtures from the pool and processes them if necessary
  all: function() {
    return _.map(hazy.fixture.pool, function(fixture, name) {
      return hazy.fixture.get(name)
    })
  },

  // registers a processable fixture into the fixture pool
  register: function(name, fixture, lazy) {
    this.pool[name] = this.process(fixture) // FIXME - wrap with a special lazy object opposed to just wrapping with a function, too ambiguous
  },

   // dynamically process fixture values by type (object, string, array, or function)
  process: function(fixture) {
    var processedFixture = fixture

    if (_.isPlainObject(fixture)) {
      _.forEach(fixture, function(value, key) {
        var processedKey = hazy.lang.process(key),
            nextFixture  = value

        processedFixture[processedKey] = hazy.fixture.process(nextFixture)
      })
    }

    if (_.isString(fixture)) {
      return hazy.lang.process(fixture)
    }

    if (_.isArray(fixture)) {
      return _.map(fixture, hazy.fixture.process)
    }

    return processedFixture
  },

  // queries the fixture pool for anything that matches the jsonpath pattern
  query: function(pattern) {
    return hazy.matcher.search(pattern)
  },

  // load and register a fixture from files matching a glob pattern
  load: function(pattern, options) {
    glob(pattern, options, function (err, files) {
      if (err) {
        throw 'Failed to load file'
      }

      _.forEach(files, function(file) {
        hazy.fixture.register(file.name, JSON.parse(file))
      })
    })
  }
}

//               _       _
//   /\/\   __ _| |_ ___| |__   ___ _ __ ___
//  /    \ / _` | __/ __| '_ \ / _ \ '__/ __|
// / /\/\ \ (_| | || (__| | | |  __/ |  \__ \
// \/    \/\__,_|\__\___|_| |_|\___|_|  |___/
//

hazy.matcher = {
  pool: {},

  register: function(path, value) {
    this.pool[path] = value
  },

  config: function(config) {
    var matcherPath    = config.path,
        matcherHandler = config.handler

    if (this.pool[matcherPath]) {
      delete this.pool[matcherPath]
    }

    this.pool[matcherPath] = {path: matcherPath, handler: matcherHandler}
  },

  // provides a map of all matched patterns in a fixture (pattern as key)
  matches: function(fixture) {
    var matches = {}

    if (hazy.config.matcher.use) {
      _.forEach(hazy.matcher.pool, function(v, pattern) {
        if (_.isObject(fixture)) {
          var jpMatches = jsonPath.query(fixture, pattern)

          if (!_.isEmpty(jpMatches)) {
            matches[pattern] = jpMatches
          }
        }
      })
    } else {
      // WARN - matching disabled
    }

    return matches
  },

  // determines if any matches in the pool apply to the fixture
  hasMatch: function(fixture) {
    return !_.isEmpty(
      hazy.matcher.matches(fixture)
    )
  },

  // search the fixture pool for fixtures matching a specific pattern (intentionally non-lazy- prone to recursion hell and there's also little benefit in evaluating random values)
  search: function(pattern) {
    var fixtures = _.values(hazy.fixture.pool)

    return _(fixtures)
      .map(function(fixture) {
        var jpMatches = jsonPath.query(fixture, pattern)

        if (!_.isEmpty(jpMatches)) {
          return fixture
        }
      })
      .reject(_.isUndefined)
      .value()
  },

  // executes a single pattern matcher handler on a fixture
  process: function(pattern, fixture) {
    var matcher = hazy.matcher.pool[pattern]

    if (_.isObject(matcher) && _.isFunction(matcher.handler)) {
      var matches = jsonPath.query(fixture, pattern)

      return matcher.handler(fixture, matches, pattern)
    } else {
      throw 'Match pattern does not apply to fixture or handler is not a function'
    }
  },

  // executes handlers for all pattern matches on a fixture
  processDeep: function(fixture) {
    var patternMatches   = this.matches(fixture)
    var processedFixture = fixture

    _.forEach(patternMatches, function(match, pattern) {
      processedFixture = hazy.matcher.process(pattern, fixture) || processedFixture
    })

    return processedFixture
  }
}

//    __                 _
//   /__\ __ _ _ __   __| | ___  _ __ ___
//  / \/// _` | '_ \ / _` |/ _ \| '_ ` _ \
// / _  \ (_| | | | | (_| | (_) | | | | | |
// \/ \_/\__,_|_| |_|\__,_|\___/|_| |_| |_|
//

hazy.random = _.mapValues(hazy.meta.random.types, function(value, key) {
  var hazyRandObj = {}

  _.forEach(value, function(v) {
     hazyRandObj[v] = function() { return new Chance()[v]() }
  })

  return hazyRandObj
})

//    ___       _ _     _
//   / __\_   _(_) | __| |
//  /__\// | | | | |/ _` |
// / \/  \ |_| | | | (_| |
// \_____/\__,_|_|_|\__,_|
//

// creates a clone of the current hazy object (shallow, new memory references)
hazy.fork = function() {
  return _.clone(hazy, false)
}

// convenience reference to lodash so that developers don't have to explicitly import the lib in their own code
hazy.util = _

module.exports = hazy
<|endoftext|>


<commit_before>import Axios from 'axios';
import {
  BAD_REQUEST,
  FORBIDDEN,
  NOT_FOUND,
  TOO_MANY_REQUESTS,
} from './responses';

/**
 * An interface to the haveibeenpwned.com API (version 2).
 */
const hibp = {
  /**
   * The Axios instance used for API queries. Not meant for general use.
   *
   * @private
   */
  _axios: Axios.create({
    baseURL: 'https://haveibeenpwned.com/api',
    headers: {
      Accept: 'application/vnd.haveibeenpwned.v2+json',
    },
  }),

  /**
   * Fetches data from the supplied API endpoint.
   *
   * HTTP status code 200 returns an Object (data found).
   * HTTP status code 404 returns null (no data found).
   * HTTP status code 400 throws an Error (bad request).
   * HTTP status code 403 throws an Error (forbidden).
   * HTTP status code 429 throws an Error (too many requests).
   *
   * @private
   * @param {string} endpoint the API endpoint to query
   * @returns {Promise} a Promise which resolves to the data resulting from the
   * query (or null for 404 Not Found responses), or rejects with an Error
   */
  _fetchFromApi: endpoint => Promise
    .resolve(hibp._axios.get(endpoint))
    .then(res => res.data)
    .catch((err) => {
      if (err.response) {
        switch (err.response.status) {
          case BAD_REQUEST.status:
            throw new Error(BAD_REQUEST.statusText);
          case FORBIDDEN.status:
            throw new Error(FORBIDDEN.statusText);
          case NOT_FOUND.status:
            return null;
          case TOO_MANY_REQUESTS.status:
            throw new Error(err.response.data);
          default:
            throw new Error(err.response.statusText);
        }
      } else {
        throw err;
      }
    }),

  /**
   * Fetches breach data for the specified account.
   *
   * @param {string} account a username or email address
   * @param {Object} [options] a configuration object
   * @param {string} [options.domain] a domain by which to filter the results
   * (default: all domains)
   * @param {boolean} [options.truncate] truncate the results to only include
   * the name of each breach (default: false)
   * @returns {Promise} a Promise which resolves to an array of breach Objects
   * (or null if no breaches were found), or rejects with an Error
   * @example
   * hibp.breachedAccount('foo')
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   * @example
   * hibp.breachedAccount('bar', { truncate: true })
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   * @example
   * hibp.breachedAccount('baz', { domain: 'adobe.com', truncate: true })
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   */
  breachedAccount: (account, options = {}) => {
    const endpoint = `/breachedaccount/${encodeURIComponent(account)}?`;
    const params = [];
    if (options.domain) {
      params.push(`domain=${encodeURIComponent(options.domain)}`);
    }
    if (options.truncate) {
      params.push('truncateResponse=true');
    }
    return hibp._fetchFromApi(`${endpoint}${params.join('&')}`);
  },

  /**
   * Fetches all breached sites in the system.
   *
   * @param {Object} [options] a configuration object
   * @param {string} [options.domain] a domain by which to filter the results
   * (default: all domains)
   * @returns {Promise} a Promise which resolves to an array of breach Objects
   * (an empty array if no breaches were found), or rejects with an Error
   * @example
   * hibp.breaches()
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   * @example
   * hibp.breaches({ domain: 'adobe.com' })
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   */
  breaches: (options = {}) => {
    const endpoint = '/breaches?';
    const params = [];
    if (options.domain) {
      params.push(`domain=${encodeURIComponent(options.domain)}`);
    }
    return hibp._fetchFromApi(`${endpoint}${params.join('&')}`);
  },

  /**
   * Fetches breach data for a single site by breach name.
   *
   * @param {string} breachName the name of a breach in the system
   * @returns {Promise} a Promise which resolves to an Object representing a
   * breach (or null if no breach was found), or rejects with an Error
   * @example
   * hibp.breach('Adobe')
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   */
  breach: breachName => (
    hibp._fetchFromApi(`/breach/${encodeURIComponent(breachName)}`)
  ),

  /**
   * Fetches all data classes in the system.
   *
   * @returns {Promise} a Promise which resolves to an array of strings (or
   * null if no data classes were found), or rejects with an Error
   * @example
   * hibp.dataClasses()
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   */
  dataClasses: () => hibp._fetchFromApi('/dataclasses'),

  /**
   * Fetches all pastes for an account (email address).
   *
   * @param {string} email the email address to query
   * @returns {Promise} a Promise which resolves to an array of paste Objects
   * (or null if no pastes were found), or rejects with an Error
   * @example
   * hibp.pasteAccount('foo@bar.com')
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   */
  pasteAccount: email => (
    hibp._fetchFromApi(`/pasteaccount/${encodeURIComponent(email)}`)
  ),
};

export default hibp;
<commit_msg>Tweak object capitalization in JSDoc comments<commit_after>import Axios from 'axios';
import {
  BAD_REQUEST,
  FORBIDDEN,
  NOT_FOUND,
  TOO_MANY_REQUESTS,
} from './responses';

/**
 * An interface to the haveibeenpwned.com API (version 2).
 */
const hibp = {
  /**
   * The Axios instance used for API queries. Not meant for general use.
   *
   * @private
   */
  _axios: Axios.create({
    baseURL: 'https://haveibeenpwned.com/api',
    headers: {
      Accept: 'application/vnd.haveibeenpwned.v2+json',
    },
  }),

  /**
   * Fetches data from the supplied API endpoint.
   *
   * HTTP status code 200 returns an Object (data found).
   * HTTP status code 404 returns null (no data found).
   * HTTP status code 400 throws an Error (bad request).
   * HTTP status code 403 throws an Error (forbidden).
   * HTTP status code 429 throws an Error (too many requests).
   *
   * @private
   * @param {string} endpoint the API endpoint to query
   * @returns {Promise} a Promise which resolves to the data resulting from the
   * query (or null for 404 Not Found responses), or rejects with an Error
   */
  _fetchFromApi: endpoint => Promise
    .resolve(hibp._axios.get(endpoint))
    .then(res => res.data)
    .catch((err) => {
      if (err.response) {
        switch (err.response.status) {
          case BAD_REQUEST.status:
            throw new Error(BAD_REQUEST.statusText);
          case FORBIDDEN.status:
            throw new Error(FORBIDDEN.statusText);
          case NOT_FOUND.status:
            return null;
          case TOO_MANY_REQUESTS.status:
            throw new Error(err.response.data);
          default:
            throw new Error(err.response.statusText);
        }
      } else {
        throw err;
      }
    }),

  /**
   * Fetches breach data for the specified account.
   *
   * @param {string} account a username or email address
   * @param {Object} [options] a configuration object
   * @param {string} [options.domain] a domain by which to filter the results
   * (default: all domains)
   * @param {boolean} [options.truncate] truncate the results to only include
   * the name of each breach (default: false)
   * @returns {Promise} a Promise which resolves to an array of breach objects
   * (or null if no breaches were found), or rejects with an Error
   * @example
   * hibp.breachedAccount('foo')
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   * @example
   * hibp.breachedAccount('bar', { truncate: true })
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   * @example
   * hibp.breachedAccount('baz', { domain: 'adobe.com', truncate: true })
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   */
  breachedAccount: (account, options = {}) => {
    const endpoint = `/breachedaccount/${encodeURIComponent(account)}?`;
    const params = [];
    if (options.domain) {
      params.push(`domain=${encodeURIComponent(options.domain)}`);
    }
    if (options.truncate) {
      params.push('truncateResponse=true');
    }
    return hibp._fetchFromApi(`${endpoint}${params.join('&')}`);
  },

  /**
   * Fetches all breached sites in the system.
   *
   * @param {Object} [options] a configuration object
   * @param {string} [options.domain] a domain by which to filter the results
   * (default: all domains)
   * @returns {Promise} a Promise which resolves to an array of breach objects
   * (an empty array if no breaches were found), or rejects with an Error
   * @example
   * hibp.breaches()
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   * @example
   * hibp.breaches({ domain: 'adobe.com' })
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   */
  breaches: (options = {}) => {
    const endpoint = '/breaches?';
    const params = [];
    if (options.domain) {
      params.push(`domain=${encodeURIComponent(options.domain)}`);
    }
    return hibp._fetchFromApi(`${endpoint}${params.join('&')}`);
  },

  /**
   * Fetches breach data for a single site by breach name.
   *
   * @param {string} breachName the name of a breach in the system
   * @returns {Promise} a Promise which resolves to an object representing a
   * breach (or null if no breach was found), or rejects with an Error
   * @example
   * hibp.breach('Adobe')
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   */
  breach: breachName => (
    hibp._fetchFromApi(`/breach/${encodeURIComponent(breachName)}`)
  ),

  /**
   * Fetches all data classes in the system.
   *
   * @returns {Promise} a Promise which resolves to an array of strings (or
   * null if no data classes were found), or rejects with an Error
   * @example
   * hibp.dataClasses()
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   */
  dataClasses: () => hibp._fetchFromApi('/dataclasses'),

  /**
   * Fetches all pastes for an account (email address).
   *
   * @param {string} email the email address to query
   * @returns {Promise} a Promise which resolves to an array of paste objects
   * (or null if no pastes were found), or rejects with an Error
   * @example
   * hibp.pasteAccount('foo@bar.com')
   *   .then((data) => {
   *     if (data) {
   *       // ...
   *     } else {
   *       // ...
   *     }
   *   })
   *   .catch((err) => {
   *     // ...
   *   });
   */
  pasteAccount: email => (
    hibp._fetchFromApi(`/pasteaccount/${encodeURIComponent(email)}`)
  ),
};

export default hibp;
<|endoftext|>


<commit_before>// Enable source map support
import 'source-map-support/register';

import fetch from 'node-fetch';
import * as pkg from '../package.json';

const API_URL = 'https://haveibeenpwned.com/api';
const REQ_HEADERS = {
  'Accept': 'application/vnd.haveibeenpwned.v2+json',
  'User-Agent': `${pkg.name} ${pkg.version}`
};

/**
 * Fetches data from the supplied API endpoint.
 *
 * HTTP status code 200 returns an Object (data found).
 * HTTP status code 404 returns undefined (no data found).
 * HTTP status code 400 throws an Error (bad request).
 * HTTP status code 403 throws an Error (forbidden).
 *
 * @param {string} endpoint the API endpoint to query
 * @returns {Promise} the Promise for this Fetch
 */
function fetchFromApi (endpoint) {
  return fetch(endpoint, {headers: REQ_HEADERS})
      .then((res) => {
        if (res.ok) {
          return res.text();
        } else if (res.status === 400) {
          throw new Error('Bad request — the account does not comply with an' +
              ' acceptable format.');
        } else if (res.status === 403) {
          throw new Error('Forbidden - no user agent has been specified in' +
              ' the request');
        }
      })
      .then((body) => {
        return body ? JSON.parse(body) : undefined;
      });
}

/**
 * HIBP - an interface to the haveibeenpwned.com API (version 2).
 */
export default {
  /**
   * Fetches breach data for the specified account.
   *
   * @param {string} account a username or email address
   * @param {string} [domain] a domain by which to filter the results
   * @param {boolean} [truncateResults] truncate the results to only include the
   * name of each breach (default: false)
   * @returns {Promise} a Promise which resolves to an Object representing a
   * breach or resolves to undefined if no breaches were found
   */
  breachedAccount: (account, domain, truncateResults) => {
    let endpoint = `${API_URL}/breachedaccount/${account}`;
    if (typeof domain === 'boolean') {
      truncateResults = domain;
      domain = undefined;
    }
    if (domain) {
      endpoint += `?domain=${domain}`;
      if (truncateResults) {
        endpoint += '&truncateResponse=true';
      }
    } else if (truncateResults) {
      endpoint += '?truncateResponse=true';
    }
    return fetchFromApi(endpoint);
  },

  /**
   * Fetches all breached sites in the system.
   *
   * @param {string} [domain] a domain by which to filter the results
   * @returns {Promise} a Promise which resolves to an array of breach Objects
   * or resolves to undefined if no breaches were found
   */
  breaches: (domain) => {
    let endpoint = `${API_URL}/breaches`;
    if (domain) {
      endpoint += `?domain=${domain}`;
    }
    return fetchFromApi(endpoint);
  },

  /**
   * Fetches breach data for a single site by breach name.
   *
   * @param {string} breachName the name of a breach in the system
   * @returns {Promise} a Promise which resolves to an Object representing a
   * breach or resolves to undefined if no breaches were found
   */
  breach: (breachName) => {
    return fetchFromApi(`${API_URL}/breach/${breachName}`);
  },

  /**
   * Fetches all data classes in the system.
   *
   * @returns {Promise} a Promise which resolves to an array of strings or
   * resolves to undefined if no data classes were found
   */
  dataClasses: () => {
    return fetchFromApi(`${API_URL}/dataclasses`);
  },

  /**
   * Fetches all pastes for an account (email address).
   *
   * @param {string} email the email address to query
   * @returns {Promise} a Promise which resolves to an array of paste Objects or
   * resolves to undefined if no pastes were found
   */
  pasteAccount: (email) => {
    return fetchFromApi(`${API_URL}/pasteaccount/${email}`);
  }
};
<commit_msg>Normalize the Promise returned from fetch<commit_after>// Enable source map support
import 'source-map-support/register';

import fetch from 'node-fetch';
import * as pkg from '../package.json';

const API_URL = 'https://haveibeenpwned.com/api';
const REQ_HEADERS = {
  'Accept': 'application/vnd.haveibeenpwned.v2+json',
  'User-Agent': `${pkg.name} ${pkg.version}`
};

/**
 * Fetches data from the supplied API endpoint.
 *
 * HTTP status code 200 returns an Object (data found).
 * HTTP status code 404 returns undefined (no data found).
 * HTTP status code 400 throws an Error (bad request).
 * HTTP status code 403 throws an Error (forbidden).
 *
 * @param {string} endpoint the API endpoint to query
 * @returns {Promise} the Promise for this Fetch
 */
function fetchFromApi (endpoint) {
  return Promise.resolve(fetch(endpoint, {headers: REQ_HEADERS}))
      .then((res) => {
        if (res.ok) {
          return res.text();
        } else if (res.status === 400) {
          throw new Error('Bad request — the account does not comply with an' +
              ' acceptable format.');
        } else if (res.status === 403) {
          throw new Error('Forbidden - no user agent has been specified in' +
              ' the request');
        }
      })
      .then((body) => {
        return body ? JSON.parse(body) : undefined;
      });
}

/**
 * HIBP - an interface to the haveibeenpwned.com API (version 2).
 */
export default {
  /**
   * Fetches breach data for the specified account.
   *
   * @param {string} account a username or email address
   * @param {string} [domain] a domain by which to filter the results
   * @param {boolean} [truncateResults] truncate the results to only include the
   * name of each breach (default: false)
   * @returns {Promise} a Promise which resolves to an Object representing a
   * breach or resolves to undefined if no breaches were found
   */
  breachedAccount: (account, domain, truncateResults) => {
    let endpoint = `${API_URL}/breachedaccount/${account}`;
    if (typeof domain === 'boolean') {
      truncateResults = domain;
      domain = undefined;
    }
    if (domain) {
      endpoint += `?domain=${domain}`;
      if (truncateResults) {
        endpoint += '&truncateResponse=true';
      }
    } else if (truncateResults) {
      endpoint += '?truncateResponse=true';
    }
    return fetchFromApi(endpoint);
  },

  /**
   * Fetches all breached sites in the system.
   *
   * @param {string} [domain] a domain by which to filter the results
   * @returns {Promise} a Promise which resolves to an array of breach Objects
   * or resolves to undefined if no breaches were found
   */
  breaches: (domain) => {
    let endpoint = `${API_URL}/breaches`;
    if (domain) {
      endpoint += `?domain=${domain}`;
    }
    return fetchFromApi(endpoint);
  },

  /**
   * Fetches breach data for a single site by breach name.
   *
   * @param {string} breachName the name of a breach in the system
   * @returns {Promise} a Promise which resolves to an Object representing a
   * breach or resolves to undefined if no breaches were found
   */
  breach: (breachName) => {
    return fetchFromApi(`${API_URL}/breach/${breachName}`);
  },

  /**
   * Fetches all data classes in the system.
   *
   * @returns {Promise} a Promise which resolves to an array of strings or
   * resolves to undefined if no data classes were found
   */
  dataClasses: () => {
    return fetchFromApi(`${API_URL}/dataclasses`);
  },

  /**
   * Fetches all pastes for an account (email address).
   *
   * @param {string} email the email address to query
   * @returns {Promise} a Promise which resolves to an array of paste Objects or
   * resolves to undefined if no pastes were found
   */
  pasteAccount: (email) => {
    return fetchFromApi(`${API_URL}/pasteaccount/${email}`);
  }
};
<|endoftext|>


<commit_before>
import funHooks from 'fun-hooks/no-eval/index.js';

export let hook = funHooks({
  ready: funHooks.SYNC | funHooks.ASYNC | funHooks.QUEUE
});

export const getHook = hook.get;

export function setupBeforeHookFnOnce(baseFn, hookFn, priority = 15) {
  let result = baseFn.getHooks({hook: hookFn});
  if (result.length === 0) {
    baseFn.before(hookFn, priority);
  }
}

export function module(name, install) {
  hook('async', function (submodules) {
    submodules.forEach(args => install(...args));
  }, name)([]); // will be queued until hook.ready() called in pbjs.processQueue();
}

export function submodule(name, ...args) {
  getHook(name).before((next, modules) => {
    modules.push(args);
    next(modules);
  });
}
<commit_msg>Prebid Core: async submodule loading (#7861)<commit_after>
import funHooks from 'fun-hooks/no-eval/index.js';

export let hook = funHooks({
  ready: funHooks.SYNC | funHooks.ASYNC | funHooks.QUEUE
});

export const getHook = hook.get;

export function setupBeforeHookFnOnce(baseFn, hookFn, priority = 15) {
  let result = baseFn.getHooks({hook: hookFn});
  if (result.length === 0) {
    baseFn.before(hookFn, priority);
  }
}
const submoduleInstallMap = {};

export function module(name, install, {postInstallAllowed = false} = {}) {
  hook('async', function (submodules) {
    submodules.forEach(args => install(...args));
    if (postInstallAllowed) submoduleInstallMap[name] = install;
  }, name)([]); // will be queued until hook.ready() called in pbjs.processQueue();
}

export function submodule(name, ...args) {
  const install = submoduleInstallMap[name];
  if (install) return install(...args);
  getHook(name).before((next, modules) => {
    modules.push(args);
    next(modules);
  });
}
<|endoftext|>


<commit_before>/**
 * @file Triggers host specific boot
 * @since 0.2.1
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_HOST*/ // Host types
/*global _gpfBootImplByHost*/ // Boot host specific implementation per host
/*global _gpfHost*/ // Host type
/*#endif*/

_gpfBootImplByHost[_gpfHost]();

/**
 * Host type enumeration
 *
 * @enum {String}
 * @readonly
 * @since 0.1.5
 */
gpf.hosts = {
    /**
     * Any browser (phantomjs is recognized separately)
     * @since 0.1.5
     */
    browser: _GPF_HOST.BROWSER,
    /**
     * [Nashorn](https://en.wikipedia.org/wiki/Nashorn_%28JavaScript_engine%29)
     * @since 0.2.4
     */
    nashorn: _GPF_HOST.NASHORN,
    /**
     * [NodeJs](http://nodejs.org/)
     * @since 0.1.5
     */
    nodejs: _GPF_HOST.NODEJS,
    /**
     * [PhantomJS](http://phantomjs.org/)
     * @since 0.1.5
     */
    phantomjs: _GPF_HOST.PHANTOMJS,
    /**
     * [Rhino](http://developer.mozilla.org/en/docs/Rhino)
     * @since 0.1.5
     */
    rhino: _GPF_HOST.RHINO,
    /**
     * Unknown (detection failed or the host is unknown)
     * @since 0.1.5
     */
    unknown: _GPF_HOST.UNKNOWN,
    /**
     * [cscript/wscript](http://technet.microsoft.com/en-us/library/bb490887.aspx)
     * @since 0.1.5
     */
    wscript: _GPF_HOST.WSCRIPT
};

/**
 * Returns the detected host type
 *
 * @return {gpf.hosts} Host type
 * @since 0.1.5
 */
gpf.host = function () {
    return _gpfHost;
};
<commit_msg>Removes _gpfBootImplByHost<commit_after>/**
 * @file Triggers host specific boot
 * @since 0.2.1
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_HOST*/ // Host types
/*global _gpfHost*/ // Host type
/*#endif*/

/**
 * Host type enumeration
 *
 * @enum {String}
 * @readonly
 * @since 0.1.5
 */
gpf.hosts = {
    /**
     * Any browser (phantomjs is recognized separately)
     * @since 0.1.5
     */
    browser: _GPF_HOST.BROWSER,
    /**
     * [Nashorn](https://en.wikipedia.org/wiki/Nashorn_%28JavaScript_engine%29)
     * @since 0.2.4
     */
    nashorn: _GPF_HOST.NASHORN,
    /**
     * [NodeJs](http://nodejs.org/)
     * @since 0.1.5
     */
    nodejs: _GPF_HOST.NODEJS,
    /**
     * [PhantomJS](http://phantomjs.org/)
     * @since 0.1.5
     */
    phantomjs: _GPF_HOST.PHANTOMJS,
    /**
     * [Rhino](http://developer.mozilla.org/en/docs/Rhino)
     * @since 0.1.5
     */
    rhino: _GPF_HOST.RHINO,
    /**
     * Unknown (detection failed or the host is unknown)
     * @since 0.1.5
     */
    unknown: _GPF_HOST.UNKNOWN,
    /**
     * [cscript/wscript](http://technet.microsoft.com/en-us/library/bb490887.aspx)
     * @since 0.1.5
     */
    wscript: _GPF_HOST.WSCRIPT
};

/**
 * Returns the detected host type
 *
 * @return {gpf.hosts} Host type
 * @since 0.1.5
 */
gpf.host = function () {
    return _gpfHost;
};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import Helmet from 'react-helmet'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'

export default function HTML (props) {
  const head = Helmet.rewind()
  const sheet = new ServerStyleSheet()
  const css = sheet.getStyleElement()

  return (

  )
}
<commit_msg>Use collectStyles function for server-side rendering of styles<commit_after>import React, { Component } from 'react'
import Helmet from 'react-helmet'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'

export default function HTML (props) {
  const head = Helmet.rewind()

  const sheet = new ServerStyleSheet()
  const main = sheet.collectStyles(

  )
  const css = sheet.getStyleElement()

  return (

        <meta charSet='utf-8' />
        { props.headComponents }
        { head.title.toComponent() }
        { head.meta.toComponent() }
        { head.link.toComponent() }
        <meta httpEquiv='X-UA-Compatible' content='IE=edge' />
        <meta name='viewport' content='width=device-width, initial-scale=1.0' />
        <link rel='icon' href='/favicon.ico' type='image/x-icon' />
        <link rel='apple-touch-icon' sizes='600x600' href='/icon.png' type='image/x-icon' />
        { process.env.NODE_ENV === 'production' && css }

        { main }
        { props.postBodyComponents }

  )
}
<|endoftext|>


<commit_before>import React from "react";
import PropTypes from "prop-types";

export default function HTML(props) {
  return (
    <html {...props.htmlAttributes}>
      <head>
        <meta charSet="utf-8" />
        <meta httpEquiv="x-ua-compatible" content="ie=edge" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1"
        />
        <link
          rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/0.5.0/modern-normalize.min.css"
        />
        {props.headComponents}
      </head>
      <body {...props.bodyAttributes}>
        {props.preBodyComponents}
        <noscript key="noscript" id="gatsby-noscript">
          This app works best with JavaScript enabled.
        </noscript>
        <div
          key={`body`}
          id="___gatsby"
          dangerouslySetInnerHTML={{ __html: props.body }}
        />
        {props.postBodyComponents}
      </body>
    </html>
  );
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array
};
<commit_msg>feat: add google ads<commit_after>import React from "react";
import PropTypes from "prop-types";

export default function HTML(props) {
  return (
    <html {...props.htmlAttributes}>
      <head>
        <meta charSet="utf-8" />
        <meta httpEquiv="x-ua-compatible" content="ie=edge" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1"
        />
        <link
          rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/0.5.0/modern-normalize.min.css"
        />
        <script
          data-ad-client="ca-pub-6098077505348522"
          async
          src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
        />
        {props.headComponents}
      </head>
      <body {...props.bodyAttributes}>
        {props.preBodyComponents}
        <noscript key="noscript" id="gatsby-noscript">
          This app works best with JavaScript enabled.
        </noscript>
        <div
          key={`body`}
          id="___gatsby"
          dangerouslySetInnerHTML={{ __html: props.body }}
        />
        {props.postBodyComponents}
      </body>
    </html>
  );
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array
};
<|endoftext|>


<commit_before>define([
  'jquery',
  'lodash',
  'backbone'/*,
  'text!templates/dashboard/page.html'*/
], function($, _, Backbone, dashboardPageTemplate){
  var DashboardPage = Backbone.View.extend({
    el: '.main',
    render: function () {
      var self = this;
      $('body .container header h1').html('Encuestas pendientes');

      require(["libs/widgets/widget.table"], function(){
        console.log('surveys table');
        var tSurveys = $('<div/>').table({
          columns:[
            {name:'name', label:'Nombre'},
            {name:'puesto', label:'Puesto'},
            {name:'surveyName', label:'Encuesta'},
            {name:'url', label:'ver encuesta', type:'link'}
          ],
          url:'userusersurvey/' + appView.user.get('id')
        });
        self.$el.empty().append(tSurveys);
      });
    }
  });
  return DashboardPage;
});
<commit_msg>No permite agregar nuevos elementos<commit_after>define([
  'jquery',
  'lodash',
  'backbone'/*,
  'text!templates/dashboard/page.html'*/
], function($, _, Backbone, dashboardPageTemplate){
  var DashboardPage = Backbone.View.extend({
    el: '.main',
    render: function () {
      var self = this;
      $('body .container header h1').html('Encuestas pendientes');

      require(["libs/widgets/widget.table"], function(){
        console.log('surveys table');
        var tSurveys = $('<div/>').table({
          canAdd: false,
          canEdit: false,
          columns:[
            {name:'name', label:'Nombre'},
            {name:'puesto', label:'Puesto'},
            {name:'surveyName', label:'Encuesta'},
            {name:'url', label:'ver encuesta', type:'link'}
          ],
          url:'userusersurvey/' + appView.user.get('id')
        });
        self.$el.empty().append(tSurveys);
      });
    }
  });
  return DashboardPage;
});
<|endoftext|>


<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

const path = require('path');
const fs = require('fs-extra');
const execa = require('execa');
const { osInfo } = require('systeminformation');
const { cordova, cordova_platforms: { getPlatformApi } } = require('cordova-lib');

const cdvLibUtil = require('cordova-lib/src/cordova/util');
const cdvPluginUtil = require('cordova-lib/src/cordova/plugin/util');

// Cache
let _installedPlatformsList = null;

/*
 * Sections
 */

async function getCordovaDependenciesInfo () {
    // get self "Cordova CLI"
    const cliPkg = require('../package');
    const cliDependencies = await _getLibDependenciesInfo(cliPkg.dependencies);

    const libPkg = require('cordova-lib/package');
    const cliLibDep = cliDependencies.find(({ key }) => key === 'lib');
    cliLibDep.children = await _getLibDependenciesInfo(libPkg.dependencies);

    return {
        key: 'Cordova Packages',
        children: [{
            key: 'cli',
            value: cliPkg.version,
            children: cliDependencies
        }]
    };
}

async function getInstalledPlatforms (projectRoot) {
    return _getInstalledPlatforms(projectRoot).then(platforms => {
        const key = 'Project Installed Platforms';
        const children = Object.entries(platforms)
            .map(([key, value]) => ({ key, value }));

        return { key, children };
    });
}

async function getInstalledPlugins (projectRoot) {
    const key = 'Project Installed Plugins';
    const children = cdvPluginUtil.getInstalledPlugins(projectRoot)
        .map(plugin => ({ key: plugin.id, value: plugin.version }));

    return { key, children };
}

async function getEnvironmentInfo () {
    const [npmVersion, osInfoResult] = await Promise.all([_getNpmVersion(), osInfo()]);
    const { platform, distro, release, codename, kernel, arch, build } = osInfoResult;

    const optionalBuildSuffix = build ? ` (${build})` : '';

    const osFormat = [
        platform === 'darwin' ? codename : distro,
        release + optionalBuildSuffix,
        `(${platform} ${kernel})`,
        `${arch}`
    ];

    return {
        key: 'Environment',
        children: [
            { key: 'OS', value: osFormat.join(' ') },
            { key: 'Node', value: process.version },
            { key: 'npm', value: npmVersion }
        ]
    };
}

async function getPlatformEnvironmentData (projectRoot) {
    const installedPlatforms = await _getInstalledPlatforms(projectRoot);

    return Object.keys(installedPlatforms)
        .map(platform => {
            const platformApi = getPlatformApi(platform);

            const getPlatformInfo = platformApi && platformApi.getEnvironmentInfo
                ? () => platformApi.getEnvironmentInfo()
                : _legacyPlatformInfo[platform];

            return { platform, getPlatformInfo };
        })
        .filter(o => o.getPlatformInfo)
        .map(async ({ platform, getPlatformInfo }) => ({
            key: `${platform} Environment`,
            children: await getPlatformInfo()
        }));
}

async function getProjectSettingsFiles (projectRoot) {
    const cfgXml = _fetchFileContents(cdvLibUtil.projectConfig(projectRoot));

    // Create package.json snippet
    const pkgJson = require(path.join(projectRoot, 'package'));
    const pkgSnippet = [
        '--- Start of Cordova JSON Snippet ---',
        JSON.stringify(pkgJson.cordova, null, 2),
        '--- End of Cordova JSON Snippet ---'
    ].join('\n');

    return {
        key: 'Project Setting Files',
        children: [
            { key: 'config.xml', value: `${cfgXml}` },
            { key: 'package.json', value: pkgSnippet }
        ]
    };
}

/*
 * Section Data Helpers
 */

async function _getLibDependenciesInfo (dependencies) {
    const cordovaPrefix = 'cordova-';
    const versionFor = name => require(`${name}/package`).version;

    return Object.keys(dependencies)
        .filter(name => name.startsWith(cordovaPrefix))
        .map(name => ({ key: name.slice(cordovaPrefix.length), value: versionFor(name) }));
}

async function _getInstalledPlatforms (projectRoot) {
    if (!_installedPlatformsList) {
        _installedPlatformsList = await cdvLibUtil.getInstalledPlatformsWithVersions(projectRoot);
    }
    return _installedPlatformsList;
}

async function _getNpmVersion () {
    return (await execa('npm', ['-v'])).stdout;
}

function _fetchFileContents (filePath) {
    if (!fs.existsSync(filePath)) return 'File Not Found';

    return fs.readFileSync(filePath, 'utf-8');
}

/**
 * @deprecated will be removed when platforms implement the calls.
 */
const _legacyPlatformInfo = {
    ios: async () => [{
        key: 'xcodebuild',
        value: await _failSafeSpawn('xcodebuild', ['-version'])
    }],
    android: async () => [{
        key: 'android',
        value: await _failSafeSpawn('android', ['list', 'target'])
    }]
};

const _failSafeSpawn = (command, args) => execa(command, args).then(
    ({ stdout }) => stdout,
    err => `ERROR: ${err.message}`
);

function _formatNodeList (list, level = 0) {
    const content = [];

    for (const item of list) {
        const indent = String.prototype.padStart((4 * level), ' ');
        let itemString = `${indent}${item.key}:`;

        if ('value' in item) {
            // Pad multi-line values with a new line on either end
            itemString += (/[\r\n]/.test(item.value))
                ? `\n${item.value.trim()}\n`
                : ` ${item.value}`;
        } else {
            // Start of section
            itemString = `\n${itemString}\n`;
        }

        content.push(itemString);

        if (item.children) {
            content.push(..._formatNodeList(item.children, level + 1));
        }
    }

    return content;
}

module.exports = async function () {
    const projectRoot = cdvLibUtil.cdProjectRoot();

    const results = await Promise.all([
        getCordovaDependenciesInfo(),
        getInstalledPlatforms(projectRoot),
        getInstalledPlugins(projectRoot),
        getEnvironmentInfo(),
        ...(await getPlatformEnvironmentData(projectRoot)),
        getProjectSettingsFiles(projectRoot)
    ]);

    const content = _formatNodeList(results);
    cordova.emit('results', content.join('\n'));
};
<commit_msg>(android) Replace deprecated `android` command with `avdmanager` (#533)<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

const path = require('path');
const fs = require('fs-extra');
const execa = require('execa');
const { osInfo } = require('systeminformation');
const { cordova, cordova_platforms: { getPlatformApi } } = require('cordova-lib');

const cdvLibUtil = require('cordova-lib/src/cordova/util');
const cdvPluginUtil = require('cordova-lib/src/cordova/plugin/util');

// Cache
let _installedPlatformsList = null;

/*
 * Sections
 */

async function getCordovaDependenciesInfo () {
    // get self "Cordova CLI"
    const cliPkg = require('../package');
    const cliDependencies = await _getLibDependenciesInfo(cliPkg.dependencies);

    const libPkg = require('cordova-lib/package');
    const cliLibDep = cliDependencies.find(({ key }) => key === 'lib');
    cliLibDep.children = await _getLibDependenciesInfo(libPkg.dependencies);

    return {
        key: 'Cordova Packages',
        children: [{
            key: 'cli',
            value: cliPkg.version,
            children: cliDependencies
        }]
    };
}

async function getInstalledPlatforms (projectRoot) {
    return _getInstalledPlatforms(projectRoot).then(platforms => {
        const key = 'Project Installed Platforms';
        const children = Object.entries(platforms)
            .map(([key, value]) => ({ key, value }));

        return { key, children };
    });
}

async function getInstalledPlugins (projectRoot) {
    const key = 'Project Installed Plugins';
    const children = cdvPluginUtil.getInstalledPlugins(projectRoot)
        .map(plugin => ({ key: plugin.id, value: plugin.version }));

    return { key, children };
}

async function getEnvironmentInfo () {
    const [npmVersion, osInfoResult] = await Promise.all([_getNpmVersion(), osInfo()]);
    const { platform, distro, release, codename, kernel, arch, build } = osInfoResult;

    const optionalBuildSuffix = build ? ` (${build})` : '';

    const osFormat = [
        platform === 'darwin' ? codename : distro,
        release + optionalBuildSuffix,
        `(${platform} ${kernel})`,
        `${arch}`
    ];

    return {
        key: 'Environment',
        children: [
            { key: 'OS', value: osFormat.join(' ') },
            { key: 'Node', value: process.version },
            { key: 'npm', value: npmVersion }
        ]
    };
}

async function getPlatformEnvironmentData (projectRoot) {
    const installedPlatforms = await _getInstalledPlatforms(projectRoot);

    return Object.keys(installedPlatforms)
        .map(platform => {
            const platformApi = getPlatformApi(platform);

            const getPlatformInfo = platformApi && platformApi.getEnvironmentInfo
                ? () => platformApi.getEnvironmentInfo()
                : _legacyPlatformInfo[platform];

            return { platform, getPlatformInfo };
        })
        .filter(o => o.getPlatformInfo)
        .map(async ({ platform, getPlatformInfo }) => ({
            key: `${platform} Environment`,
            children: await getPlatformInfo()
        }));
}

async function getProjectSettingsFiles (projectRoot) {
    const cfgXml = _fetchFileContents(cdvLibUtil.projectConfig(projectRoot));

    // Create package.json snippet
    const pkgJson = require(path.join(projectRoot, 'package'));
    const pkgSnippet = [
        '--- Start of Cordova JSON Snippet ---',
        JSON.stringify(pkgJson.cordova, null, 2),
        '--- End of Cordova JSON Snippet ---'
    ].join('\n');

    return {
        key: 'Project Setting Files',
        children: [
            { key: 'config.xml', value: `${cfgXml}` },
            { key: 'package.json', value: pkgSnippet }
        ]
    };
}

/*
 * Section Data Helpers
 */

async function _getLibDependenciesInfo (dependencies) {
    const cordovaPrefix = 'cordova-';
    const versionFor = name => require(`${name}/package`).version;

    return Object.keys(dependencies)
        .filter(name => name.startsWith(cordovaPrefix))
        .map(name => ({ key: name.slice(cordovaPrefix.length), value: versionFor(name) }));
}

async function _getInstalledPlatforms (projectRoot) {
    if (!_installedPlatformsList) {
        _installedPlatformsList = await cdvLibUtil.getInstalledPlatformsWithVersions(projectRoot);
    }
    return _installedPlatformsList;
}

async function _getNpmVersion () {
    return (await execa('npm', ['-v'])).stdout;
}

function _fetchFileContents (filePath) {
    if (!fs.existsSync(filePath)) return 'File Not Found';

    return fs.readFileSync(filePath, 'utf-8');
}

/**
 * @deprecated will be removed when platforms implement the calls.
 */
const _legacyPlatformInfo = {
    ios: async () => [{
        key: 'xcodebuild',
        value: await _failSafeSpawn('xcodebuild', ['-version'])
    }],
    android: async () => [{
        key: 'android',
        value: await _failSafeSpawn('avdmanager', ['list', 'target'])
    }]
};

const _failSafeSpawn = (command, args) => execa(command, args).then(
    ({ stdout }) => stdout,
    err => `ERROR: ${err.message}`
);

function _formatNodeList (list, level = 0) {
    const content = [];

    for (const item of list) {
        const indent = String.prototype.padStart((4 * level), ' ');
        let itemString = `${indent}${item.key}:`;

        if ('value' in item) {
            // Pad multi-line values with a new line on either end
            itemString += (/[\r\n]/.test(item.value))
                ? `\n${item.value.trim()}\n`
                : ` ${item.value}`;
        } else {
            // Start of section
            itemString = `\n${itemString}\n`;
        }

        content.push(itemString);

        if (item.children) {
            content.push(..._formatNodeList(item.children, level + 1));
        }
    }

    return content;
}

module.exports = async function () {
    const projectRoot = cdvLibUtil.cdProjectRoot();

    const results = await Promise.all([
        getCordovaDependenciesInfo(),
        getInstalledPlatforms(projectRoot),
        getInstalledPlugins(projectRoot),
        getEnvironmentInfo(),
        ...(await getPlatformEnvironmentData(projectRoot)),
        getProjectSettingsFiles(projectRoot)
    ]);

    const content = _formatNodeList(results);
    cordova.emit('results', content.join('\n'));
};
<|endoftext|>


<commit_before>/******************************************************************************
 *                                    ~fn~                                    *
 *                                  ‾‾‾‾‾‾‾‾                                  *
 * Function utilities.                                                        *
 *     _________________________________________________________________      *
 *        Copyright (c) 2011 Quildreen Motta // Licenced under MIT/X11        *
 ******************************************************************************/
void function (root) {

    var fn

    , slice = Array.prototype.slice

    ///// Function partial /////////////////////////////////////////////////////
    //
    //   (fn:Fn, args...) ↦ Fn
    //
    // Return a function that'll always have the given arguments
    // prepended to argument list passed to the function.
    //
    function partial(fn) {
        var args = slice.call(arguments, 1)
        return function() { return fn.apply(this, args.concat(slice.call(arguments))) }
    }

    ///// Function delay ///////////////////////////////////////////////////////
    //
    //   (fn:Fn, seconds:Num) ↦ Num
    //
    // Calls the function after the given number of seconds.
    //
    // Returns an ID to a timer, such that the call to the function can
    // be cancelled by passing that ID to `clearTimeout`.
    //
    function delay(fn, seconds) { var args
        args = slice.call(arguments, 2)
        if (args.length)  fn = fn.bind.apply(fn, args)

        return setTimeout(fn, seconds * 1000)
    }

    ///// Function defer ///////////////////////////////////////////////////////
    //
    //   (fn:Fn) ↦ Num
    //
    // Same as `delay`, but calls the function as soon as the engine is
    // not busy doing other things.
    //
    function defer(fn) { var args
        args = slice.call(arguments, 1)
        return delay.apply(this, [fn, 0].concat(args))
    }

    ///// Function wrap ////////////////////////////////////////////////////////
    //
    //   (fn:Fn[, wrapper:Fn]) ↦ Fn
    //
    // Returns a function that passes the given function as the first
    // argument for any other function.
    //
    function wrap(fn, wrapper) {
        if (!wrapper)
            wrapper = function(f){ f.apply(this, slice.call(arguments, 1)) }

        return partial(wrapper, fn)
    }

    ///// Exports //////////////////////////////////////////////////////////////
    fn = typeof exports == 'undefined'?  root.black.fn = { }
       :                                 exports

    fn.partial = partial
    fn.delay   = delay
    fn.defer   = defer
    fn.wrap    = wrap

    fn.$black_box    = Function
    fn.$black_proto  = Function.prototype
    fn.$black_utils  = { partial : partial
                       , delay   : delay
                       , defer   : defer
                       , wrap    : wrap }
}(this)
<commit_msg>src/fn: Fixes description for the `wrap` function.<commit_after>/******************************************************************************
 *                                    ~fn~                                    *
 *                                  ‾‾‾‾‾‾‾‾                                  *
 * Function utilities.                                                        *
 *     _________________________________________________________________      *
 *        Copyright (c) 2011 Quildreen Motta // Licenced under MIT/X11        *
 ******************************************************************************/
void function (root) {

    var fn

    , slice = Array.prototype.slice

    ///// Function partial /////////////////////////////////////////////////////
    //
    //   (fn:Fn, args...) ↦ Fn
    //
    // Return a function that'll always have the given arguments
    // prepended to argument list passed to the function.
    //
    function partial(fn) {
        var args = slice.call(arguments, 1)
        return function() { return fn.apply(this, args.concat(slice.call(arguments))) }
    }

    ///// Function delay ///////////////////////////////////////////////////////
    //
    //   (fn:Fn, seconds:Num) ↦ Num
    //
    // Calls the function after the given number of seconds.
    //
    // Returns an ID to a timer, such that the call to the function can
    // be cancelled by passing that ID to `clearTimeout`.
    //
    function delay(fn, seconds) { var args
        args = slice.call(arguments, 2)
        if (args.length)  fn = fn.bind.apply(fn, args)

        return setTimeout(fn, seconds * 1000)
    }

    ///// Function defer ///////////////////////////////////////////////////////
    //
    //   (fn:Fn) ↦ Num
    //
    // Same as `delay`, but calls the function as soon as the engine is
    // not busy doing other things.
    //
    function defer(fn) { var args
        args = slice.call(arguments, 1)
        return delay.apply(this, [fn, 0].concat(args))
    }

    ///// Function wrap ////////////////////////////////////////////////////////
    //
    //   (fn:Fn[, wrapper:Fn]) ↦ Fn
    //
    // Returns a function that passes the given `wrapper` as the first
    // argument for `fn`.
    //
    function wrap(fn, wrapper) {
        if (!wrapper)
            wrapper = function(f){ f.apply(this, slice.call(arguments, 1)) }

        return partial(wrapper, fn)
    }

    ///// Exports //////////////////////////////////////////////////////////////
    fn = typeof exports == 'undefined'?  root.black.fn = { }
       :                                 exports

    fn.partial = partial
    fn.delay   = delay
    fn.defer   = defer
    fn.wrap    = wrap

    fn.$black_box    = Function
    fn.$black_proto  = Function.prototype
    fn.$black_utils  = { partial : partial
                       , delay   : delay
                       , defer   : defer
                       , wrap    : wrap }
}(this)
<|endoftext|>


<commit_before>'use strict';

const getProjectOptions = require('./get-project-options');
const boilerplateUpdate = require('boilerplate-update');
const getStartAndEndCommands = require('./get-start-and-end-commands');
const parseBlueprintPackage = require('./parse-blueprint-package');
const downloadPackage = require('./download-package');
const saveBlueprint = require('./save-blueprint');
const loadDefaultBlueprint = require('./load-default-blueprint');
const loadDefaultBlueprintFromDisk = require('./load-default-blueprint-from-disk');
const loadSafeBlueprint = require('./load-safe-blueprint');
const loadSafeBlueprintFile = require('./load-safe-blueprint-file');
const stageBlueprintFile = require('./stage-blueprint-file');
const getBlueprintFilePath = require('./get-blueprint-file-path');
const isDefaultBlueprint = require('./is-default-blueprint');
const loadBlueprintFile = require('./load-blueprint-file');
const bootstrap = require('./bootstrap');
const findBlueprint = require('./find-blueprint');

module.exports = async function init({
  blueprint: _blueprint,
  to,
  resolveConflicts,
  reset,
  blueprintOptions,
  wasRunAsExecutable
}) {
  let cwd = process.cwd();

  let packageName;
  let name;
  let location;
  let url;
  if (_blueprint) {
    let parsedPackage = await parseBlueprintPackage({
      cwd,
      blueprint: _blueprint
    });
    packageName = parsedPackage.name;
    location = parsedPackage.location;
    url = parsedPackage.url;
  } else {
    let defaultBlueprint = await loadDefaultBlueprintFromDisk(cwd);
    packageName = defaultBlueprint.packageName;
    name = defaultBlueprint.name;
  }

  let downloadedPackage = await downloadPackage(packageName, url, to);
  packageName = downloadedPackage.name;

  // could be "app" or "addon" already
  // don't want to overwrite with "ember-cli"
  if (!name) {
    name = downloadedPackage.name;
  }

  let emberCliUpdateJson = await loadSafeBlueprintFile(cwd);

  let blueprint;

  let existingBlueprint = findBlueprint(emberCliUpdateJson, packageName, name);
  if (existingBlueprint) {
    blueprint = existingBlueprint;
  } else {
    blueprint = {
      packageName,
      name,
      location,
      path: downloadedPackage.path,
      options: blueprintOptions
    };
  }

  blueprint = loadSafeBlueprint(blueprint);

  blueprint.version = downloadedPackage.version;

  let isCustomBlueprint = !isDefaultBlueprint(blueprint);

  let result = await (await boilerplateUpdate({
    projectOptions: ({ packageJson }) => getProjectOptions(packageJson, blueprint),
    endVersion: blueprint.version,
    resolveConflicts,
    reset,
    createCustomDiff: true,
    customDiffOptions: ({
      packageJson,
      projectOptions
    }) => {
      if (!isCustomBlueprint) {
        blueprint = loadDefaultBlueprint(projectOptions, blueprint.version);
      }

      return getStartAndEndCommands({
        packageJson,
        endBlueprint: blueprint
      });
    },
    ignoredFiles: [await getBlueprintFilePath(cwd)],
    wasRunAsExecutable
  })).promise;

  if (!await loadBlueprintFile(cwd)) {
    await bootstrap();
  }

  await saveBlueprint({
    cwd,
    blueprint
  });

  if (!reset) {
    await stageBlueprintFile(cwd);
  }

  return result;
};
<commit_msg>remove unnecessary init code<commit_after>'use strict';

const boilerplateUpdate = require('boilerplate-update');
const getStartAndEndCommands = require('./get-start-and-end-commands');
const parseBlueprintPackage = require('./parse-blueprint-package');
const downloadPackage = require('./download-package');
const saveBlueprint = require('./save-blueprint');
const loadDefaultBlueprintFromDisk = require('./load-default-blueprint-from-disk');
const loadSafeBlueprint = require('./load-safe-blueprint');
const loadSafeBlueprintFile = require('./load-safe-blueprint-file');
const stageBlueprintFile = require('./stage-blueprint-file');
const getBlueprintFilePath = require('./get-blueprint-file-path');
const loadBlueprintFile = require('./load-blueprint-file');
const bootstrap = require('./bootstrap');
const findBlueprint = require('./find-blueprint');

module.exports = async function init({
  blueprint: _blueprint,
  to,
  resolveConflicts,
  reset,
  blueprintOptions,
  wasRunAsExecutable
}) {
  let cwd = process.cwd();

  let packageName;
  let name;
  let location;
  let url;
  if (_blueprint) {
    let parsedPackage = await parseBlueprintPackage({
      cwd,
      blueprint: _blueprint
    });
    packageName = parsedPackage.name;
    location = parsedPackage.location;
    url = parsedPackage.url;
  } else {
    let defaultBlueprint = await loadDefaultBlueprintFromDisk(cwd);
    packageName = defaultBlueprint.packageName;
    name = defaultBlueprint.name;
  }

  let downloadedPackage = await downloadPackage(packageName, url, to);
  packageName = downloadedPackage.name;

  // could be "app" or "addon" already
  // don't want to overwrite with "ember-cli"
  if (!name) {
    name = downloadedPackage.name;
  }

  let emberCliUpdateJson = await loadSafeBlueprintFile(cwd);

  let blueprint;

  let existingBlueprint = findBlueprint(emberCliUpdateJson, packageName, name);
  if (existingBlueprint) {
    blueprint = existingBlueprint;
  } else {
    blueprint = {
      packageName,
      name,
      location,
      path: downloadedPackage.path,
      options: blueprintOptions
    };
  }

  blueprint = loadSafeBlueprint(blueprint);

  blueprint.version = downloadedPackage.version;

  let result = await (await boilerplateUpdate({
    endVersion: blueprint.version,
    resolveConflicts,
    reset,
    createCustomDiff: true,
    customDiffOptions: ({
      packageJson
    }) => getStartAndEndCommands({
      packageJson,
      endBlueprint: blueprint
    }),
    ignoredFiles: [await getBlueprintFilePath(cwd)],
    wasRunAsExecutable
  })).promise;

  if (!await loadBlueprintFile(cwd)) {
    await bootstrap();
  }

  await saveBlueprint({
    cwd,
    blueprint
  });

  if (!reset) {
    await stageBlueprintFile(cwd);
  }

  return result;
};
<|endoftext|>


<commit_before>// Copyright (c) 2011-2012 UX Productivity Pty Ltd. All rights reserved.

function prettyPrintDocument()
{
    var clone = document.documentElement.cloneNode(true);
    removeRedundantWhitespace(clone,"");
    addIndentation(clone,"");
    return clone.outerHTML;

    function isWhitespaceChar(c)
    {
        return ((c == " ") || (c == "\t") || (c == "\r") || (c == "\n"));
    }

    // Note: This could potentially remove some whitespace that is important, e.g.
    // in the case of <b>one </b>two... it should only be used for debugging purposes
    function removeRedundantWhitespace(node,indent)
    {
        if (node.nodeType == Node.ELEMENT_NODE) {
            var next;
            for (var child = node.firstChild; child != null; child = next) {
                next = child.nextSibling;
                if (isWhitespaceTextNode(child)) {
                    node.removeChild(child);
                }
                else {
                    removeRedundantWhitespace(child,indent+"    ");
                }
            }
        }
        else if (node.nodeType == Node.TEXT_NODE) {
            var str = node.nodeValue;
            var start = 0;
            var end = str.length;
            while ((start < end) && isWhitespaceChar(str.charAt(start)))
                start++;
            while ((end > start) && isWhitespaceChar(str.charAt(end-1)))
                end--;
            node.nodeValue = str.slice(start,end);
        }
    }

    function addIndentation(node,indent)
    {
        if (node.nodeType == Node.ELEMENT_NODE) {
            var next;
            for (var child = node.firstChild; child != null; child = next) {
                next = child.nextSibling;
                var text = document.createTextNode("\n"+indent+"    ");
                node.insertBefore(text,child);
                addIndentation(child,indent+"    ");
            }
            var text = document.createTextNode("\n"+indent);
            node.appendChild(text);
        }
    }
}

function getDOMTree()
{
    var root = convertToObjects(document.documentElement);
    return JSON.stringify(root);

    function convertToObjects(node)
    {
        var obj = new Object();
        obj.nodeType = node.nodeType;
        if (node.nodeType == Node.ELEMENT_NODE) {
            obj.nodeName = node.nodeName;
            obj.attributes = new Object();
            for (var i = 0; i < node.attributes.length; i++) {
                var attr = node.attributes[i];
                obj.attributes[attr.nodeName] = attr.nodeValue;
            }
            obj.childNodes = new Array();
            for (var child = node.firstChild; child != null; child = child.nextSibling)
                obj.childNodes.push(convertToObjects(child));
        }
        else if (node.nodeType == Node.TEXT_NODE) {
            obj.nodeValue = node.nodeValue;
        }
        else {
            throw new Error("Unexpected node type: "+node.nodeType);
        }
        return obj;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                          General                                               //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////////////////////

function getStyles()
{
    var list = new Array();
    for (var i = 0; i < document.styleSheets.length; i++) {
        var sheet = document.styleSheets[i];
        var str = "";
        for (name in sheet)
            str += name+"\n";
        for (var j = 0; j < sheet.cssRules.length; j++) {
            var rule = sheet.cssRules[j];
            if (rule.type == CSSRule.STYLE_RULE) {
                var properties = new Object();
                for (k = 0; k < rule.style.length; k++)
                    properties[rule.style[k]] = rule.style.getPropertyValue(rule.style[k]);

                list.push({"selector": rule.selectorText,
                           "properties": properties });
            }
        }
    }
    editor.setStyles(list);
}

function jumpToSection(sectionId)
{
    var section = document.getElementById(sectionId);
    var location = webkitConvertPointFromNodeToPage(section,
                                                    new WebKitPoint(0,0));
    window.scrollTo(0,location.y);
}

function getHTML()
{
    try {
        var serializer = new XMLSerializer();
        var xml = serializer.serializeToString(document);
        editor.getHTMLResponse(xml);
    }
    catch (e) {
        editor.getHTMLError(e.toString());
    }
}

function keydown(e)
{
    if (e.keyCode == '\r'.charCodeAt(0)) {
        e.preventDefault();
        enterPressed();
    }
}

// Remove the temporary <script> element that was added to the document to execute this file
// so it's not saved with the document
var initscript = document.getElementById("initscript");
if (initscript != null) {
    initscript.parentNode.removeChild(initscript);
}

var jsInitOk = false;
try {
    document.onclick = reportSelectionFormatting;
//    document.body.contentEditable = true;
//    document.body.style.padding = "15%";
//    document.body.style.padding = "5%";
    document.body.style.textAlign = "justify";
    window.onkeydown = keydown;

    setupMutation();
    getOutline();
    getStyles();
    structure.examineDocument();
    jsInitOk = true;
}
catch (e) {
    editor.jsInterfaceInitError(e.stack);
}

if (jsInitOk)
    editor.jsInterfaceInitFinished();
<commit_msg>Call DOM.assignNodeIds() when the document is first loaded<commit_after>// Copyright (c) 2011-2012 UX Productivity Pty Ltd. All rights reserved.

function prettyPrintDocument()
{
    var clone = document.documentElement.cloneNode(true);
    removeRedundantWhitespace(clone,"");
    addIndentation(clone,"");
    return clone.outerHTML;

    function isWhitespaceChar(c)
    {
        return ((c == " ") || (c == "\t") || (c == "\r") || (c == "\n"));
    }

    // Note: This could potentially remove some whitespace that is important, e.g.
    // in the case of <b>one </b>two... it should only be used for debugging purposes
    function removeRedundantWhitespace(node,indent)
    {
        if (node.nodeType == Node.ELEMENT_NODE) {
            var next;
            for (var child = node.firstChild; child != null; child = next) {
                next = child.nextSibling;
                if (isWhitespaceTextNode(child)) {
                    node.removeChild(child);
                }
                else {
                    removeRedundantWhitespace(child,indent+"    ");
                }
            }
        }
        else if (node.nodeType == Node.TEXT_NODE) {
            var str = node.nodeValue;
            var start = 0;
            var end = str.length;
            while ((start < end) && isWhitespaceChar(str.charAt(start)))
                start++;
            while ((end > start) && isWhitespaceChar(str.charAt(end-1)))
                end--;
            node.nodeValue = str.slice(start,end);
        }
    }

    function addIndentation(node,indent)
    {
        if (node.nodeType == Node.ELEMENT_NODE) {
            var next;
            for (var child = node.firstChild; child != null; child = next) {
                next = child.nextSibling;
                var text = document.createTextNode("\n"+indent+"    ");
                node.insertBefore(text,child);
                addIndentation(child,indent+"    ");
            }
            var text = document.createTextNode("\n"+indent);
            node.appendChild(text);
        }
    }
}

function getDOMTree()
{
    var root = convertToObjects(document.documentElement);
    return JSON.stringify(root);

    function convertToObjects(node)
    {
        var obj = new Object();
        obj.nodeType = node.nodeType;
        if (node.nodeType == Node.ELEMENT_NODE) {
            obj.nodeName = node.nodeName;
            obj.attributes = new Object();
            for (var i = 0; i < node.attributes.length; i++) {
                var attr = node.attributes[i];
                obj.attributes[attr.nodeName] = attr.nodeValue;
            }
            obj.childNodes = new Array();
            for (var child = node.firstChild; child != null; child = child.nextSibling)
                obj.childNodes.push(convertToObjects(child));
        }
        else if (node.nodeType == Node.TEXT_NODE) {
            obj.nodeValue = node.nodeValue;
        }
        else {
            throw new Error("Unexpected node type: "+node.nodeType);
        }
        return obj;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                          General                                               //
//                                                                                //
////////////////////////////////////////////////////////////////////////////////////////////////////

function getStyles()
{
    var list = new Array();
    for (var i = 0; i < document.styleSheets.length; i++) {
        var sheet = document.styleSheets[i];
        var str = "";
        for (name in sheet)
            str += name+"\n";
        for (var j = 0; j < sheet.cssRules.length; j++) {
            var rule = sheet.cssRules[j];
            if (rule.type == CSSRule.STYLE_RULE) {
                var properties = new Object();
                for (k = 0; k < rule.style.length; k++)
                    properties[rule.style[k]] = rule.style.getPropertyValue(rule.style[k]);

                list.push({"selector": rule.selectorText,
                           "properties": properties });
            }
        }
    }
    editor.setStyles(list);
}

function jumpToSection(sectionId)
{
    var section = document.getElementById(sectionId);
    var location = webkitConvertPointFromNodeToPage(section,
                                                    new WebKitPoint(0,0));
    window.scrollTo(0,location.y);
}

function getHTML()
{
    try {
        var serializer = new XMLSerializer();
        var xml = serializer.serializeToString(document);
        editor.getHTMLResponse(xml);
    }
    catch (e) {
        editor.getHTMLError(e.toString());
    }
}

function keydown(e)
{
    if (e.keyCode == '\r'.charCodeAt(0)) {
        e.preventDefault();
        enterPressed();
    }
}

// Remove the temporary <script> element that was added to the document to execute this file
// so it's not saved with the document
var initscript = document.getElementById("initscript");
if (initscript != null) {
    initscript.parentNode.removeChild(initscript);
}

var jsInitOk = false;
try {
    DOM.assignNodeIds(document);
    document.onclick = reportSelectionFormatting;
//    document.body.contentEditable = true;
//    document.body.style.padding = "15%";
//    document.body.style.padding = "5%";
    document.body.style.textAlign = "justify";
    window.onkeydown = keydown;

    setupMutation();
    getOutline();
    getStyles();
    structure.examineDocument();
    jsInitOk = true;
}
catch (e) {
    editor.jsInterfaceInitError(e.stack);
}

if (jsInitOk)
    editor.jsInterfaceInitFinished();
<|endoftext|>


<commit_before>//     Zepto.js
//     (c) 2010-2015 Thomas Fuchs
//     Zepto.js may be freely distributed under the MIT license.

;(function($, undefined){
  var prefix = '', eventPrefix,
    vendors = { Webkit: 'webkit', Moz: '', O: 'o' },
    testEl = document.createElement('div'),
    supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,
    transform,
    transitionProperty, transitionDuration, transitionTiming, transitionDelay,
    animationName, animationDuration, animationTiming, animationDelay,
    cssReset = {}

  function dasherize(str) { return str.replace(/([a-z])([A-Z])/, '$1-$2').toLowerCase() }
  function normalizeEvent(name) { return eventPrefix ? eventPrefix + name : name.toLowerCase() }

  $.each(vendors, function(vendor, event){
    if (testEl.style[vendor + 'TransitionProperty'] !== undefined) {
      prefix = '-' + vendor.toLowerCase() + '-'
      eventPrefix = event
      return false
    }
  })

  transform = prefix + 'transform'
  cssReset[transitionProperty = prefix + 'transition-property'] =
  cssReset[transitionDuration = prefix + 'transition-duration'] =
  cssReset[transitionDelay    = prefix + 'transition-delay'] =
  cssReset[transitionTiming   = prefix + 'transition-timing-function'] =
  cssReset[animationName      = prefix + 'animation-name'] =
  cssReset[animationDuration  = prefix + 'animation-duration'] =
  cssReset[animationDelay     = prefix + 'animation-delay'] =
  cssReset[animationTiming    = prefix + 'animation-timing-function'] = ''

  $.fx = {
    off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined),
    speeds: { _default: 400, fast: 200, slow: 600 },
    cssPrefix: prefix,
    transitionEnd: normalizeEvent('TransitionEnd'),
    animationEnd: normalizeEvent('AnimationEnd')
  }

  $.fn.animate = function(properties, duration, ease, callback, delay){
    if ($.isFunction(duration))
      callback = duration, ease = undefined, duration = undefined
    if ($.isFunction(ease))
      callback = ease, ease = undefined
    if ($.isPlainObject(duration))
      ease = duration.easing, callback = duration.complete, delay = duration.delay, duration = duration.duration
    if (duration) duration = (typeof duration == 'number' ? duration :
                    ($.fx.speeds[duration] || $.fx.speeds._default)) / 1000
    if (delay) delay = parseFloat(delay) / 1000
    return this.anim(properties, duration, ease, callback, delay)
  }

  $.fn.anim = function(properties, duration, ease, callback, delay){
    var key, cssValues = {}, cssProperties, transforms = '',
        that = this, wrappedCallback, endEvent = $.fx.transitionEnd,
        fired = false

    if (duration === undefined) duration = $.fx.speeds._default / 1000
    if (delay === undefined) delay = 0
    if ($.fx.off) duration = 0

    if (typeof properties == 'string') {
      // keyframe animation
      cssValues[animationName] = properties
      cssValues[animationDuration] = duration + 's'
      cssValues[animationDelay] = delay + 's'
      cssValues[animationTiming] = (ease || 'linear')
      endEvent = $.fx.animationEnd
    } else {
      cssProperties = []
      // CSS transitions
      for (key in properties)
        if (supportedTransforms.test(key)) transforms += key + '(' + properties[key] + ') '
        else cssValues[key] = properties[key], cssProperties.push(dasherize(key))

      if (transforms) cssValues[transform] = transforms, cssProperties.push(transform)
      if (duration > 0 && typeof properties === 'object') {
        cssValues[transitionProperty] = cssProperties.join(', ')
        cssValues[transitionDuration] = duration + 's'
        cssValues[transitionDelay] = delay + 's'
        cssValues[transitionTiming] = (ease || 'linear')
      }
    }

    wrappedCallback = function(event){
      if (typeof event !== 'undefined') {
        if (event.target !== event.currentTarget) return // makes sure the event didn't bubble from "below"
        $(event.target).unbind(endEvent, wrappedCallback)
      } else
        $(this).unbind(endEvent, wrappedCallback) // triggered by setTimeout

      fired = true
      $(this).css(cssReset)
      callback && callback.call(this)
    }
    if (duration > 0){
      this.bind(endEvent, wrappedCallback)
      // transitionEnd is not always firing on older Android phones
      // so make sure it gets fired
      setTimeout(function(){
        if (fired) return
        wrappedCallback.call(that)
      }, ((duration + delay) * 1000) + 25)
    }

    // trigger page reflow so new elements can animate
    this.size() && this.get(0).clientLeft

    this.css(cssValues)

    if (duration <= 0) setTimeout(function() {
      that.each(function(){ wrappedCallback.call(this) })
    }, 0)

    return this
  }

  testEl = null
})(Zepto)
<commit_msg>add comment<commit_after>//     Zepto.js
//     (c) 2010-2015 Thomas Fuchs
//     Zepto.js may be freely distributed under the MIT license.

//css3动画
;(function($, undefined){
  var prefix = '', eventPrefix,
    vendors = { Webkit: 'webkit', Moz: '', O: 'o' },
    testEl = document.createElement('div'),
    supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,
    transform,
    transitionProperty, transitionDuration, transitionTiming, transitionDelay,
    animationName, animationDuration, animationTiming, animationDelay,
    cssReset = {};

  //将驼峰式的字符串转成用-分隔的小写形式，如borderWidth ==> border-width
  function dasherize(str) {
    return str.replace(/([a-z])([A-Z])/, '$1-$2').toLowerCase();
  }

  //加上前缀
  function normalizeEvent(name) {
    return eventPrefix ? eventPrefix + name : name.toLowerCase();
  }

  //
  $.each(vendors, function(vendor, event){
    if (testEl.style[vendor + 'TransitionProperty'] !== undefined) {
      prefix = '-' + vendor.toLowerCase() + '-';
      eventPrefix = event;
      return false;
    }
  });

  transform = prefix + 'transform';
  cssReset[transitionProperty = prefix + 'transition-property'] =
  cssReset[transitionDuration = prefix + 'transition-duration'] =
  cssReset[transitionDelay    = prefix + 'transition-delay'] =
  cssReset[transitionTiming   = prefix + 'transition-timing-function'] =
  cssReset[animationName      = prefix + 'animation-name'] =
  cssReset[animationDuration  = prefix + 'animation-duration'] =
  cssReset[animationDelay     = prefix + 'animation-delay'] =
  cssReset[animationTiming    = prefix + 'animation-timing-function'] = '';

  $.fx = {
    off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined),
    speeds: { _default: 400, fast: 200, slow: 600 },
    cssPrefix: prefix,
    transitionEnd: normalizeEvent('TransitionEnd'),
    animationEnd: normalizeEvent('AnimationEnd')
  }

  $.fn.animate = function(properties, duration, ease, callback, delay){
    if ($.isFunction(duration))
      callback = duration, ease = undefined, duration = undefined
    if ($.isFunction(ease))
      callback = ease, ease = undefined
    if ($.isPlainObject(duration))
      ease = duration.easing, callback = duration.complete, delay = duration.delay, duration = duration.duration
    if (duration) duration = (typeof duration == 'number' ? duration :
                    ($.fx.speeds[duration] || $.fx.speeds._default)) / 1000
    if (delay) delay = parseFloat(delay) / 1000
    return this.anim(properties, duration, ease, callback, delay)
  }

  $.fn.anim = function(properties, duration, ease, callback, delay){
    var key, cssValues = {}, cssProperties, transforms = '',
        that = this, wrappedCallback, endEvent = $.fx.transitionEnd,
        fired = false

    if (duration === undefined) duration = $.fx.speeds._default / 1000
    if (delay === undefined) delay = 0
    if ($.fx.off) duration = 0

    if (typeof properties == 'string') {
      // keyframe animation
      cssValues[animationName] = properties
      cssValues[animationDuration] = duration + 's'
      cssValues[animationDelay] = delay + 's'
      cssValues[animationTiming] = (ease || 'linear')
      endEvent = $.fx.animationEnd
    } else {
      cssProperties = []
      // CSS transitions
      for (key in properties)
        if (supportedTransforms.test(key)) transforms += key + '(' + properties[key] + ') '
        else cssValues[key] = properties[key], cssProperties.push(dasherize(key))

      if (transforms) cssValues[transform] = transforms, cssProperties.push(transform)
      if (duration > 0 && typeof properties === 'object') {
        cssValues[transitionProperty] = cssProperties.join(', ')
        cssValues[transitionDuration] = duration + 's'
        cssValues[transitionDelay] = delay + 's'
        cssValues[transitionTiming] = (ease || 'linear')
      }
    }

    wrappedCallback = function(event){
      if (typeof event !== 'undefined') {
        if (event.target !== event.currentTarget) return // makes sure the event didn't bubble from "below"
        $(event.target).unbind(endEvent, wrappedCallback)
      } else
        $(this).unbind(endEvent, wrappedCallback) // triggered by setTimeout

      fired = true
      $(this).css(cssReset)
      callback && callback.call(this)
    }
    if (duration > 0){
      this.bind(endEvent, wrappedCallback)
      // transitionEnd is not always firing on older Android phones
      // so make sure it gets fired
      setTimeout(function(){
        if (fired) return
        wrappedCallback.call(that)
      }, ((duration + delay) * 1000) + 25)
    }

    // trigger page reflow so new elements can animate
    this.size() && this.get(0).clientLeft

    this.css(cssValues)

    if (duration <= 0) setTimeout(function() {
      that.each(function(){ wrappedCallback.call(this) })
    }, 0)

    return this
  }

  testEl = null
})(Zepto);
<|endoftext|>