crawlscope 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,217 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "csv"
4
+ require "json"
5
+ require "shellwords"
6
+
7
+ module Crawlscope
8
+ module LinkMap
9
+ class Report
10
+ VERSION = 1
11
+
12
+ CSV_FIELDS = {
13
+ nodes: %i[url sitemap inventory entry_root coverage click_depth outgoing_complete sitemap_reached inventory_reached inbound_sources contextual_inbound_sources sitemap_only priority page_type cluster status resolved_status resolved_url html canonical_url canonical_exclusion noncanonical indexable redirect redirect_exclusion],
14
+ occurrences: %i[source_url raw_href target_url anchor_text image_alt rel position contextual exclusion nofollow resolved_url canonical_url status resolved_status indexable coverage],
15
+ pairs: %i[source_url target_url occurrences contextual_occurrences followable_occurrences],
16
+ expected_edges: %i[source_url target_url type reason position approved_exception state],
17
+ issues: %i[code severity category url message details]
18
+ }.freeze
19
+
20
+ def initialize(**data)
21
+ @data = {version: VERSION, view: "all", **data}
22
+ end
23
+
24
+ def to_h(view: :all, cluster: nil, priority: false)
25
+ view = view.to_s
26
+ raise ConfigurationError, "Link map view must be all or contextual" unless %w[all contextual].include?(view)
27
+
28
+ result = @data.merge(view: view, filters: {cluster: cluster, priority: priority})
29
+ if view == "contextual"
30
+ result[:occurrences] = result[:occurrences].select { |edge| edge[:contextual] }
31
+ result[:pairs] = result[:pairs].filter_map do |pair|
32
+ count = pair[:contextual_occurrences]
33
+ next if count.zero?
34
+
35
+ pair.merge(occurrences: count)
36
+ end
37
+ followable = result[:occurrences].reject { |edge| edge[:nofollow] }
38
+ .map { |edge| edge.values_at(:source_url, :target_url) }.tally
39
+ result[:pairs] = result[:pairs].map do |pair|
40
+ pair.merge(followable_occurrences: followable.fetch(pair.values_at(:source_url, :target_url), 0))
41
+ end
42
+ end
43
+ return result unless cluster || priority
44
+
45
+ filter(result, cluster, priority)
46
+ end
47
+
48
+ def write(io, format: :json, table: :occurrences, sitemap_path: nil, invocation: :cli, **filters)
49
+ return write_summary(io, sitemap_path: sitemap_path, invocation: invocation, **filters) if format.to_s == "text"
50
+
51
+ data = to_h(**filters)
52
+ case format.to_s
53
+ when "json"
54
+ io.puts(JSON.generate(data))
55
+ when "csv"
56
+ write_csv(io, data, table.to_sym)
57
+ when "dot"
58
+ write_dot(io, data)
59
+ else
60
+ raise ConfigurationError, "Link map format must be json, csv, dot, or text"
61
+ end
62
+ end
63
+
64
+ def write_summary(io, sitemap_path: nil, source: "Public HTTP crawl", invocation: :cli, **filters)
65
+ data = to_h(**filters)
66
+ sitemap = data[:nodes].select { |node| node[:sitemap] }
67
+ html = sitemap.select { |node| node[:html] }
68
+ reached = html.count { |node| node[:sitemap_reached] }
69
+ no_context = data[:issues].count { |issue| issue[:code] == :no_contextual_inlinks }
70
+ partial = data[:exclusions].keys.any? { |key| key.start_with?("sitemap:", "page:") || key == "link:edge_limit" }
71
+
72
+ io.puts("Internal link map", " #{source}", " Entry roots: #{data[:roots].join(", ")}")
73
+ io.puts(" Entry root HTML unavailable in this snapshot.") unless @data[:nodes].any? { |node| node[:entry_root] && node[:html] }
74
+ rows = [
75
+ ["Sitemap URLs reached", "#{reached} / #{sitemap.size}"],
76
+ ["HTML URLs with no observed path", html.size - reached],
77
+ ["Sitemap URLs without verified HTML", sitemap.size - html.size],
78
+ ["Unique internal link pairs", data[:pairs].size],
79
+ ["Internal link occurrences", data[:occurrences].count { |edge| edge[:target_url] }],
80
+ ["Pages with no contextual inlinks", no_context],
81
+ ["Unreachable clusters", data[:unreachable_clusters].size]
82
+ ]
83
+ width = rows.map { |label, _| label.length }.max
84
+ io.puts("")
85
+ rows.each { |label, value| io.puts(" %-*s %s" % [width, label, value]) }
86
+ io.puts(" Coverage is partial. Review exclusions in the full report.") if partial || html.size < sitemap.size
87
+ write_export_commands(io, sitemap_path: sitemap_path, roots: data[:roots], invocation: invocation)
88
+ end
89
+
90
+ def self.diff(before, after)
91
+ before, after = [before, after].map do |snapshot|
92
+ snapshot = JSON.parse(JSON.generate(snapshot))
93
+ unless snapshot.is_a?(Hash) && snapshot["version"] == VERSION &&
94
+ %w[nodes occurrences pairs expected_edges].all? { |key| snapshot[key].is_a?(Array) }
95
+ raise ConfigurationError, "Diff requires version #{VERSION} link map snapshots"
96
+ end
97
+ snapshot
98
+ end
99
+ unless before.values_at("roots", "view", "filters") == after.values_at("roots", "view", "filters")
100
+ raise ConfigurationError, "Diff requires matching roots, view, and filters"
101
+ end
102
+
103
+ {
104
+ nodes: changes(before["nodes"], after["nodes"]) { |row| row.fetch("url") },
105
+ pairs: changes(*[before, after].map { |data| pair_records(data) }) { |row| row.values_at("source_url", "target_url") },
106
+ expected_edges: changes(before["expected_edges"], after["expected_edges"]) { |row| row.except("state").sort }
107
+ }
108
+ end
109
+
110
+ def self.pair_records(data)
111
+ by_pair = data.fetch("occurrences").group_by { |edge| edge.values_at("source_url", "target_url") }
112
+ data.fetch("pairs").map do |pair|
113
+ pair.merge("links" => by_pair.fetch(pair.values_at("source_url", "target_url"), []))
114
+ end
115
+ end
116
+ private_class_method :pair_records
117
+
118
+ def self.changes(before, after)
119
+ old = before.to_h { |row| [yield(row), row] }
120
+ new = after.to_h { |row| [yield(row), row] }
121
+ {
122
+ added: (new.keys - old.keys).map { |key| new.fetch(key) },
123
+ removed: (old.keys - new.keys).map { |key| old.fetch(key) },
124
+ changed: (old.keys & new.keys).filter_map do |key|
125
+ {before: old.fetch(key), after: new.fetch(key)} if old[key] != new[key]
126
+ end
127
+ }
128
+ end
129
+ private_class_method :changes
130
+
131
+ private
132
+
133
+ def write_export_commands(io, sitemap_path:, roots:, invocation:)
134
+ scope = Scope.new(roots.first, paths: ["/"], exclude_paths: [])
135
+ sitemap = sitemap_path.to_s
136
+ if sitemap.empty? || sitemap == "#{scope.origin}/sitemap.xml" ||
137
+ (Url.remote?(sitemap) && !scope.resolve(sitemap, control: true).first)
138
+ sitemap = nil
139
+ end
140
+
141
+ if invocation == :rake
142
+ arguments = "URL=#{scope.origin.shellescape}"
143
+ arguments += " SITEMAP=#{sitemap.shellescape}" if sitemap
144
+ json = "rake crawlscope:link_map #{arguments}"
145
+ csv = "rake 'crawlscope:link_map[,,csv,nodes]' #{arguments}"
146
+ dot = "rake 'crawlscope:link_map[,,dot]' #{arguments}"
147
+ else
148
+ argv = ["crawlscope", "link-map", "--url", scope.origin]
149
+ argv.concat(["--sitemap", sitemap]) if sitemap
150
+ roots.each { |root| argv.concat(["--root", root]) } unless roots == ["#{scope.origin}/"]
151
+ json = argv.shelljoin
152
+ csv = "#{json} --format csv --table nodes"
153
+ dot = "#{json} --format dot"
154
+ end
155
+
156
+ io.puts("", " Export from a public HTTP crawl")
157
+ io.puts(" JSON #{json} > links.json")
158
+ io.puts(" CSV #{csv} > nodes.csv")
159
+ io.puts(" DOT #{dot} > links.dot")
160
+ io.puts(" SVG sfdp -Gsplines=line -Tsvg links.dot -o links.svg")
161
+ end
162
+
163
+ def filter(data, cluster, priority)
164
+ selected = data[:nodes].filter_map do |node|
165
+ node[:url] if (!cluster || node[:cluster] == cluster) && (!priority || node[:priority])
166
+ end.to_set
167
+ visible = selected.dup
168
+ %i[occurrences pairs expected_edges].each do |table|
169
+ data[table] = data[table].select do |edge|
170
+ source, target = edge.values_at(:source_url, :target_url)
171
+ next false unless selected.include?(source) || selected.include?(target)
172
+
173
+ visible << source
174
+ visible << target if target
175
+ true
176
+ end
177
+ end
178
+ data[:nodes] = data[:nodes].select { |node| visible.include?(node[:url]) }
179
+ data[:issues] = data[:issues].select { |issue| visible.include?(issue[:url]) }
180
+ data[:unreachable_clusters] = data[:unreachable_clusters].select { |urls| urls.any? { |url| selected.include?(url) } }
181
+ data
182
+ end
183
+
184
+ def write_csv(io, data, table)
185
+ fields = CSV_FIELDS[table]
186
+ raise ConfigurationError, "Unknown link map CSV table" unless fields
187
+
188
+ csv = CSV.new(io)
189
+ csv << fields
190
+ data.fetch(table).each do |row|
191
+ csv << fields.map do |field|
192
+ value = row[field]
193
+ value = JSON.generate(value) if value.is_a?(Array) || value.is_a?(Hash)
194
+ (value.is_a?(String) && value.match?(/\A\s*[=+@-]|\A[\t\r\n]/)) ? "'#{value}" : value
195
+ end
196
+ end
197
+ end
198
+
199
+ def write_dot(io, data)
200
+ io.puts("digraph link_map {", " rankdir=LR;")
201
+ data[:nodes].each do |node|
202
+ url = JSON.generate(node[:url])
203
+ attributes = []
204
+ attributes << "shape=box" if node[:entry_root]
205
+ attributes << "style=dashed" if node[:click_depth].nil?
206
+ attributes << "peripheries=2" if node[:priority]
207
+ io.puts(" #{url} [#{attributes.join(", ")}];")
208
+ end
209
+ data[:pairs].each do |pair|
210
+ source, target = pair.values_at(:source_url, :target_url).map { |url| JSON.generate(url) }
211
+ io.puts(" #{source} -> #{target} [label=\"#{pair.fetch(:occurrences)}\"];")
212
+ end
213
+ io.puts("}")
214
+ end
215
+ end
216
+ end
217
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module LinkMap
5
+ class RobotsPolicy
6
+ MAX_BYTES = 512_000
7
+
8
+ attr_reader :state
9
+
10
+ def initialize(response)
11
+ body = response.body.to_s.dup.force_encoding(Encoding::UTF_8)
12
+ @state = if response.status == 200 && body.bytesize <= MAX_BYTES && body.valid_encoding? &&
13
+ !Documents::Robots.header_value(response.headers, "content-type").match?(/html/i)
14
+ "loaded"
15
+ elsif [404, 410].include?(response.status)
16
+ "absent"
17
+ else
18
+ "unavailable"
19
+ end
20
+ @rules = (@state == "loaded") ? parse(body.delete_prefix("\uFEFF")) : []
21
+ end
22
+
23
+ def exclusion(url)
24
+ return "robots_unavailable" if state == "unavailable"
25
+
26
+ path = URI.parse(url).path
27
+ rule = @rules.find { |pattern, _allow| pattern.match?(path) }
28
+ "robots_disallowed" if rule && !rule.last
29
+ rescue Regexp::TimeoutError
30
+ "robots_unavailable"
31
+ end
32
+
33
+ private
34
+
35
+ def parse(body)
36
+ groups = []
37
+ agents = []
38
+ rules = []
39
+ body.each_line do |line|
40
+ field, value = line.split("#", 2).first.to_s.split(":", 2).map(&:strip)
41
+ next if value.nil?
42
+
43
+ case field.downcase
44
+ when "user-agent"
45
+ unless rules.empty?
46
+ groups << [agents, rules]
47
+ agents = []
48
+ rules = []
49
+ end
50
+ agents << value.downcase
51
+ when "allow", "disallow"
52
+ rules << [value, field.casecmp?("allow")] unless agents.empty?
53
+ end
54
+ end
55
+ groups << [agents, rules]
56
+
57
+ matching = groups.select { |names, _| names.include?("crawlscope") }
58
+ matching = groups.select { |names, _| names.include?("*") } if matching.empty?
59
+ matching.flat_map(&:last).reject { |path, _| path.empty? }
60
+ .sort_by { |path, allow| [-path.bytesize, allow ? 0 : 1] }
61
+ .map { |path, allow| [compile(path), allow] }
62
+ end
63
+
64
+ def compile(path)
65
+ path = Scope.normalize_path(URI::DEFAULT_PARSER.escape(path, /[^\x00-\x7F]/))
66
+ anchored = path.end_with?("$")
67
+ pattern = Regexp.escape(path.delete_suffix("$")).gsub('\\*', ".*")
68
+ Regexp.new("\\A#{pattern}#{'\\z' if anchored}", timeout: 0.05)
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module LinkMap
5
+ class Scope
6
+ MAX_URL_BYTES = 2_048
7
+
8
+ attr_reader :origin
9
+
10
+ def initialize(base_url, paths:, exclude_paths:)
11
+ base = URI.parse(base_url.to_s)
12
+ unless base.is_a?(URI::HTTP) && base.host && !base.userinfo && !base.query && !base.fragment
13
+ raise ConfigurationError, "Link map requires a public HTTP(S) base URL without credentials, query, or fragment"
14
+ end
15
+
16
+ @origin = base.normalize.origin
17
+ @link_scope = Rules::Links::Scope.new
18
+ @paths = path_prefixes(paths)
19
+ @exclude_paths = path_prefixes(exclude_paths)
20
+ rescue URI::Error
21
+ raise ConfigurationError, "Invalid link map base URL"
22
+ end
23
+
24
+ def resolve(value, base: "#{origin}/", control: false)
25
+ return [nil, "invalid_url"] unless value.is_a?(String) && !value.empty? && value.bytesize <= MAX_URL_BYTES
26
+
27
+ uri = URI.join(base, value)
28
+ return [nil, "unsupported_scheme"] unless uri.is_a?(URI::HTTP)
29
+ return [nil, "credentials"] if uri.userinfo
30
+ return [nil, "outside_origin"] unless RequestHeaders.same_origin?(uri.normalize.to_s, base_url: origin)
31
+
32
+ uri = uri.normalize
33
+ path = self.class.normalize_path(uri.path)
34
+ return [nil, "unsafe_path"] if path.match?(%r{(?:\A|/)\.{1,2}(?:/|\z)|//|;|%(?:[01][\da-f]|2[35f]|3[bf]|5c|7f)}i)
35
+ return [nil, "outside_paths"] unless control || included_path?(path)
36
+ return [nil, "query"] if uri.query
37
+
38
+ uri.path = path
39
+ uri.fragment = nil
40
+ [uri.to_s, nil]
41
+ rescue URI::Error, ArgumentError
42
+ [nil, "invalid_url"]
43
+ end
44
+
45
+ def self.normalize_path(path)
46
+ path.gsub(/%([\da-f]{2})/i) do |escape|
47
+ byte = Regexp.last_match(1).hex.chr
48
+ byte.match?(/[a-z0-9._~-]/i) ? byte : escape.upcase
49
+ end
50
+ end
51
+
52
+ def document_base(doc, url)
53
+ href = doc&.at_css("base[href]")&.[]("href")
54
+ href ? URI.join(url, href.strip).to_s : url
55
+ rescue URI::Error
56
+ url
57
+ end
58
+
59
+ private
60
+
61
+ def path_prefixes(paths)
62
+ Array(paths).map do |path|
63
+ unless path.is_a?(String) && path.start_with?("/") && !path.match?(%r{[%?#]|//|(?:\A|/)\.{1,2}(?:/|\z)})
64
+ raise ConfigurationError, "Link map path prefixes must be absolute URL paths"
65
+ end
66
+
67
+ path.chomp("/")
68
+ end
69
+ end
70
+
71
+ def included_path?(path)
72
+ @link_scope.crawlable_source_path?(path) &&
73
+ @paths.any? { |prefix| within?(path, prefix) } &&
74
+ @exclude_paths.none? { |prefix| within?(path, prefix) }
75
+ end
76
+
77
+ def within?(path, prefix)
78
+ path == prefix || path.start_with?("#{prefix}/")
79
+ end
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module LinkMap
5
+ class SitemapUrls
6
+ MAX_SITEMAPS = 100
7
+ MAX_BYTES = 52_428_800
8
+ MAX_URLS = 100_000
9
+
10
+ def initialize(source:, http:, scope:, exclusions:)
11
+ @source = source.to_s
12
+ @http = http
13
+ @scope = scope
14
+ @exclusions = exclusions
15
+ end
16
+
17
+ def call
18
+ remote = @source.match?(%r{\A[a-z][a-z0-9+.-]*://}i)
19
+ root = remote ? remote_source(@source) : File.realpath(@source)
20
+ raise ConfigurationError, "Link map sitemap URL must be on the configured origin" unless root
21
+
22
+ directory = File.dirname(root)
23
+ pending = [root]
24
+ seen = Set.new(pending)
25
+ urls = Set.new
26
+ pending.each do |source|
27
+ name, locations = Sitemap.locations(read(source, remote: remote))
28
+ raise ValidationError, "Unexpected link map sitemap root" unless locations
29
+
30
+ if name == "urlset"
31
+ locations.each do |location|
32
+ url, reason = @scope.resolve(location.text.strip)
33
+ if reason
34
+ @exclusions["sitemap:#{reason}"] += 1
35
+ elsif urls.size < MAX_URLS || urls.include?(url)
36
+ urls.add(url)
37
+ else
38
+ @exclusions["sitemap:url_limit"] += 1
39
+ end
40
+ end
41
+ else
42
+ locations.each do |location|
43
+ child = remote ? remote_source(location.text.strip, base: source) : local_source(location.text.strip, source, directory)
44
+ if child && seen.include?(child)
45
+ next
46
+ elsif !child
47
+ @exclusions["sitemap:excluded_child"] += 1
48
+ elsif seen.size >= MAX_SITEMAPS
49
+ @exclusions["sitemap:limit"] += 1
50
+ else
51
+ seen.add(child)
52
+ pending << child
53
+ end
54
+ end
55
+ end
56
+ rescue ValidationError, SystemCallError
57
+ raise ValidationError, "Unable to read the link map sitemap" if source == root
58
+
59
+ @exclusions["sitemap:unavailable_child"] += 1
60
+ end
61
+ urls.to_a.sort
62
+ rescue SystemCallError
63
+ raise ValidationError, "Unable to read the link map sitemap"
64
+ end
65
+
66
+ private
67
+
68
+ def read(source, remote:)
69
+ if remote
70
+ response = @http.fetch(source, max_body_bytes: MAX_BYTES, parse_html: false)
71
+ raise ValidationError, "Sitemap fetch failed" unless response.status == 200
72
+
73
+ body = response.body
74
+ else
75
+ raise ValidationError, "Sitemap is not a regular file" unless File.file?(source)
76
+
77
+ body = File.binread(source, MAX_BYTES + 1)
78
+ end
79
+ raise ValidationError, "Sitemap exceeded its byte limit" if body.bytesize > MAX_BYTES
80
+
81
+ body
82
+ end
83
+
84
+ def remote_source(value, base: "#{@scope.origin}/")
85
+ @scope.resolve(value, base: base, control: true).first
86
+ end
87
+
88
+ def local_source(value, source, directory)
89
+ uri = URI.parse(value)
90
+ return if uri.query || uri.fragment || uri.userinfo || uri.path.to_s.empty?
91
+ return if uri.host && !remote_source(value)
92
+
93
+ path = uri.host ? File.basename(uri.path) : uri.path
94
+ return if Pathname.new(path).absolute?
95
+
96
+ candidate = File.realpath(path, File.dirname(source))
97
+ candidate if candidate.start_with?("#{directory.chomp("/")}/")
98
+ rescue URI::Error, SystemCallError
99
+ nil
100
+ end
101
+ end
102
+ end
103
+ end
@@ -12,12 +12,22 @@ module Crawlscope
12
12
  run("ldjson", argv: ldjson_argv(urls: urls))
13
13
  end
14
14
 
15
+ def link_map(url: nil, sitemap_path: nil, format: nil, table: nil)
16
+ argv = [
17
+ option_pair("--url", url),
18
+ option_pair("--sitemap", sitemap_path),
19
+ option_pair("--format", format),
20
+ option_pair("--table", table)
21
+ ].compact.flatten
22
+ run("link-map", argv: argv)
23
+ end
24
+
15
25
  def validate_rule(rule, url: nil, sitemap_path: nil)
16
26
  validate(url: url, sitemap_path: sitemap_path, rule_names: rule)
17
27
  end
18
28
 
19
29
  def run(command, argv: [], configuration: Crawlscope.configuration)
20
- status = Cli.start([command, *argv], out: $stdout, err: $stderr, configuration: configuration)
30
+ status = Cli.start([command, *argv], out: $stdout, err: $stderr, configuration: configuration, invocation: :rake)
21
31
  exit(status) unless status.zero?
22
32
  end
23
33
 
@@ -4,8 +4,10 @@ module Crawlscope
4
4
  class Reporter
5
5
  GROUP_LABELS = Reporting::IssuePresenter::GROUP_LABELS
6
6
 
7
- def initialize(io:)
7
+ def initialize(io:, link_map: true, invocation: :cli)
8
8
  @io = io
9
+ @link_map = link_map
10
+ @invocation = invocation
9
11
  end
10
12
 
11
13
  def report(result)
@@ -28,10 +30,19 @@ module Crawlscope
28
30
  end
29
31
 
30
32
  ServerTiming::Reporter.new(io: @io).report(result.server_timing_summary, base_url: result.base_url)
33
+ report_link_map(result) if @link_map
31
34
  end
32
35
 
33
36
  private
34
37
 
38
+ def report_link_map(result)
39
+ report = LinkMap::Audit.new(base_url: result.base_url).from_pages(urls: result.urls, pages: result.pages)
40
+ @io.puts("")
41
+ report.write_summary(@io, sitemap_path: result.sitemap_path, source: "HTML fetched during validation", invocation: @invocation)
42
+ rescue ConfigurationError => error
43
+ @io.puts("", "Internal link map", " Summary unavailable: #{error.message}")
44
+ end
45
+
35
46
  def status_for(issues)
36
47
  grouped = issues.by_severity
37
48
 
@@ -31,6 +31,22 @@ module Crawlscope
31
31
  )
32
32
  end
33
33
 
34
+ def link_map(base_url: nil, sitemap_path: nil, **options)
35
+ resolved_base_url = base_url || @configuration.base_url
36
+ if resolved_base_url.to_s.strip.empty?
37
+ raise ConfigurationError, "Link map requires an explicit site URL"
38
+ end
39
+
40
+ LinkMap::Audit.new(
41
+ base_url: resolved_base_url,
42
+ sitemap_path: sitemap_path || default_sitemap_path(base_url: resolved_base_url),
43
+ concurrency: @configuration.concurrency,
44
+ fetch_executor: @configuration.fetch_executor,
45
+ timeout_seconds: @configuration.timeout_seconds,
46
+ **options
47
+ ).call
48
+ end
49
+
34
50
  private
35
51
 
36
52
  def default_base_url
@@ -9,6 +9,18 @@ module Crawlscope
9
9
  class Sitemap
10
10
  SITEMAP_NAMESPACE = {"xmlns" => "http://www.sitemaps.org/schemas/sitemap/0.9"}.freeze
11
11
 
12
+ def self.locations(xml)
13
+ document = Nokogiri::XML(xml)
14
+ root = document.root&.name
15
+ case root
16
+ when "sitemapindex", "urlset"
17
+ element = (root == "sitemapindex") ? "sitemap" : "url"
18
+ [root, document.xpath("//xmlns:#{element}/xmlns:loc", SITEMAP_NAMESPACE)]
19
+ else
20
+ [root, nil]
21
+ end
22
+ end
23
+
12
24
  def initialize(path:, adapter: nil, concurrency: Configuration::DEFAULT_CONCURRENCY, fetch_executor: Configuration::DEFAULT_FETCH_EXECUTOR, profile_token: nil, timeout_seconds: Configuration::DEFAULT_TIMEOUT_SECONDS)
13
25
  @path = path
14
26
  @adapter = adapter
@@ -35,14 +47,13 @@ module Crawlscope
35
47
  end
36
48
  return [] if already_visited
37
49
 
38
- document = Nokogiri::XML(read(source, base_url: base_url))
39
- root_name = document.root&.name
40
- unless %w[sitemapindex urlset].include?(root_name)
50
+ root_name, locations = self.class.locations(read(source, base_url: base_url))
51
+ unless locations
41
52
  raise ValidationError, "Sitemap #{source} has unexpected root #{root_name.inspect}"
42
53
  end
43
54
 
44
55
  if root_name == "sitemapindex"
45
- child_sources = document.xpath("//xmlns:sitemap/xmlns:loc", SITEMAP_NAMESPACE).map do |node|
56
+ child_sources = locations.map do |node|
46
57
  resolve_child_source(source, node.text.to_s.strip, base_url: base_url)
47
58
  end
48
59
 
@@ -50,7 +61,7 @@ module Crawlscope
50
61
  collect_urls(child_source, base_url: base_url, visited: visited, visited_mutex: visited_mutex)
51
62
  end.flatten
52
63
  else
53
- document.xpath("//xmlns:url/xmlns:loc", SITEMAP_NAMESPACE).map do |node|
64
+ locations.map do |node|
54
65
  Url.normalize_for_base(node.text.to_s.strip, base_url: base_url)
55
66
  end
56
67
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Crawlscope
4
- VERSION = "0.10.2"
4
+ VERSION = "0.11.0"
5
5
  end
@@ -1,9 +1,14 @@
1
1
  namespace :crawlscope do
2
- desc "Validate URLs with all default Crawlscope rules. Args: [url,sitemap,rules]. ENV: URL, SITEMAP, RULES, JS=1, TIMEOUT, NETWORK_IDLE_TIMEOUT, CONCURRENCY, FETCH_EXECUTOR"
2
+ desc "Validate URLs with all default Crawlscope rules. Args: [url,sitemap,rules]. ENV: URL, SITEMAP, RULES, LINK_MAP=0, JS=1, TIMEOUT, NETWORK_IDLE_TIMEOUT, CONCURRENCY, FETCH_EXECUTOR"
3
3
  task :validate, [:url, :sitemap, :rules] => :environment do |_task, args|
4
4
  Crawlscope::RakeTasks.validate(url: args[:url], sitemap_path: args[:sitemap], rule_names: args[:rules])
5
5
  end
6
6
 
7
+ desc "Export the internal link map (JSON, CSV, DOT, or text). Args: [url,sitemap,format,table]. ENV: URL, SITEMAP"
8
+ task :link_map, [:url, :sitemap, :format, :table] => :environment do |_task, args|
9
+ Crawlscope::RakeTasks.link_map(url: args[:url], sitemap_path: args[:sitemap], format: args[:format], table: args[:table])
10
+ end
11
+
7
12
  namespace :validate do
8
13
  desc "Directly validate JSON-LD on one URL. Args: [url]. ENV: URL (semicolon-separated), DEBUG=1, JS=1, TIMEOUT, NETWORK_IDLE_TIMEOUT, REPORT_PATH, SUMMARY=1"
9
14
  task :ldjson, [:url] => :environment do |_task, args|