{"size": 1684, "ext": "js", "max_stars_repo_path": "node_modules/penthouse/lib/postformatting/embedded-base64-remover.js", "max_stars_repo_name": "jsoranno/PawPatrol", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "node_modules/penthouse/lib/postformatting/embedded-base64-remover.js", "max_issues_repo_name": "jsoranno/PawPatrol", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "node_modules/penthouse/lib/postformatting/embedded-base64-remover.js", "max_forks_repo_name": "jsoranno/PawPatrol", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.5438596491, "max_line_length": 121, "alphanum_fraction": 0.6894299287}
'use strict'

var cssAstFormatter = require('css')

var BASE64_ENCODE_PATTERN = /data:[^,]*base64,/

var _isTooLongBase64Encoded = function (declaration, maxEmbeddedBase64Length) {
  return BASE64_ENCODE_PATTERN.test(declaration.value) && declaration.value.length > maxEmbeddedBase64Length
}

var _removeDataUrisFromRule = function (rule, maxEmbeddedBase64Length) {
  if (rule.type === 'font-face') {
    var hasSrc = false
    rule.declarations = rule.declarations.filter(function (declaration) {
      if (_isTooLongBase64Encoded(declaration, maxEmbeddedBase64Length)) {
        return false
      } else if (declaration.property === 'src') {
        hasSrc = true
      }
      return true
    })
    if (!hasSrc) {
      return null
    }
  } else if (rule.type === 'rule') {
    rule.declarations = rule.declarations.filter(function (declaration) {
      if (_isTooLongBase64Encoded(declaration, maxEmbeddedBase64Length)) {
        return false
      }
      return true
    })
  } else if (rule.type === 'media') {
    var rules = rule.rules.map(function (rule) { return _removeDataUrisFromRule(rule, maxEmbeddedBase64Length) })
    rule.rules = rules.filter(function (rule) {
      return Boolean(rule)
    })
    return rule
  }
  return rule
}

var embeddedbase64Remover = function (css, maxEmbeddedBase64Length) {
  var ast = cssAstFormatter.parse(css)
  var rules = ast.stylesheet.rules.map(function (rule) { return _removeDataUrisFromRule(rule, maxEmbeddedBase64Length) })
  rules = rules.filter(function (rule) {
    return Boolean(rule)
  })

  return cssAstFormatter.stringify({
    stylesheet: {
      rules: rules
    }
  })
}

module.exports = embeddedbase64Remover
