Class: Importmap::Npm

Inherits:
Object
  • Object
show all
Defined in:
lib/importmap/npm.rb

Defined Under Namespace

Classes: OutdatedPackage, VulnerablePackage

Constant Summary collapse

PIN_REGEX =

:nodoc:

/#{Importmap::Map::PIN_REGEX}.*/.freeze
Error =
Class.new(StandardError)
HTTPError =
Class.new(Error)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(importmap_path = "config/importmap.rb", vendor_path: "vendor/javascript") ⇒ Npm

Returns a new instance of Npm.



14
15
16
17
# File 'lib/importmap/npm.rb', line 14

def initialize(importmap_path = "config/importmap.rb", vendor_path: "vendor/javascript")
  @importmap_path = Pathname.new(importmap_path)
  @vendor_path    = Pathname.new(vendor_path)
end

Instance Attribute Details

#base_uriObject

Returns the value of attribute base_uri.



11
12
13
# File 'lib/importmap/npm.rb', line 11

def base_uri
  @base_uri
end

Instance Method Details

#outdated_packagesObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/importmap/npm.rb', line 19

def outdated_packages
  packages_with_versions.each_with_object([]) do |(package, current_version), outdated_packages|
    outdated_package = OutdatedPackage.new(name: package, current_version: current_version)

    if !(response = get_package(package))
      outdated_package.error = 'Response error'
    elsif (error = response['error'])
      outdated_package.error = error
    else
      latest_version = find_latest_version(response)
      next unless outdated?(current_version, latest_version)

      outdated_package.latest_version = latest_version
    end

    outdated_packages << outdated_package
  end.sort_by(&:name)
end

#packages_with_versionsObject



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/importmap/npm.rb', line 51

def packages_with_versions
  # We cannot use the name after "pin" because some dependencies are loaded from inside packages
  # Eg. pin "buffer", to: "https://ga.jspm.io/npm:@jspm/[email protected]/nodelibs/browser/buffer.js"
  with_versions = importmap.scan(/^pin .*(?<=npm:|npm\/|skypack\.dev\/|unpkg\.com\/)([^@\/]+)@(\d+\.\d+\.\d+(?:[^\/\s"']*))/) |
    importmap.scan(/#{PIN_REGEX} #.*@(\d+\.\d+\.\d+(?:[^\s]*)).*$/)

  vendored_packages_without_version(with_versions).each do |package, path|
    $stdout.puts "Ignoring #{package} (#{path}) since no version is specified in the importmap"
  end

  with_versions
end

#vulnerable_packagesObject



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/importmap/npm.rb', line 38

def vulnerable_packages
  get_audit.flat_map do |package, vulnerabilities|
    vulnerabilities.map do |vulnerability|
      VulnerablePackage.new(
        name: package,
        severity: vulnerability['severity'],
        vulnerable_versions: vulnerability['vulnerable_versions'],
        vulnerability: vulnerability['title']
      )
    end
  end.sort_by { |p| [p.name, p.severity] }
end