crawlscope 0.10.0 → 0.10.2

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.
Files changed (56) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +29 -0
  3. data/README.md +51 -260
  4. data/UPGRADE.md +76 -0
  5. data/docs/architecture.md +73 -0
  6. data/docs/rails.md +121 -0
  7. data/docs/rules.md +144 -0
  8. data/docs/server-timing.md +59 -0
  9. data/lib/crawlscope/configuration.rb +2 -1
  10. data/lib/crawlscope/crawl.rb +11 -79
  11. data/lib/crawlscope/crawling/fetcher_factory.rb +31 -0
  12. data/lib/crawlscope/crawling/target.rb +45 -0
  13. data/lib/crawlscope/crawling/target_resolver.rb +75 -0
  14. data/lib/crawlscope/documents/canonical.rb +22 -0
  15. data/lib/crawlscope/documents/robots.rb +57 -0
  16. data/lib/crawlscope/page.rb +4 -0
  17. data/lib/crawlscope/reporter.rb +6 -160
  18. data/lib/crawlscope/reporting/issue_presenter.rb +162 -0
  19. data/lib/crawlscope/reporting/url_formatter.rb +29 -0
  20. data/lib/crawlscope/rule_registry.rb +2 -2
  21. data/lib/crawlscope/rules/content_quality.rb +18 -0
  22. data/lib/crawlscope/rules/indexability.rb +9 -14
  23. data/lib/crawlscope/rules/links/canonical_checks.rb +102 -0
  24. data/lib/crawlscope/rules/links/extractor.rb +100 -0
  25. data/lib/crawlscope/rules/links/graph.rb +39 -0
  26. data/lib/crawlscope/rules/links/inbound_checks.rb +124 -0
  27. data/lib/crawlscope/rules/links/outgoing_checks.rb +104 -0
  28. data/lib/crawlscope/rules/links/resolution_check.rb +88 -0
  29. data/lib/crawlscope/rules/links/scope.rb +23 -0
  30. data/lib/crawlscope/rules/links/target_lookup.rb +38 -0
  31. data/lib/crawlscope/rules/links/url_checks.rb +54 -0
  32. data/lib/crawlscope/rules/links.rb +18 -600
  33. data/lib/crawlscope/rules/metadata.rb +2 -2
  34. data/lib/crawlscope/rules/structured_data.rb +26 -77
  35. data/lib/crawlscope/rules/uniqueness.rb +1 -1
  36. data/lib/crawlscope/schemas.rb +10 -2
  37. data/lib/crawlscope/server_timing/reporter.rb +2 -13
  38. data/lib/crawlscope/structured_data/audit.rb +17 -76
  39. data/lib/crawlscope/structured_data/check.rb +2 -0
  40. data/lib/crawlscope/structured_data/document.rb +14 -1
  41. data/lib/crawlscope/structured_data/entry.rb +31 -0
  42. data/lib/crawlscope/structured_data/outcome.rb +11 -0
  43. data/lib/crawlscope/structured_data/report.rb +6 -14
  44. data/lib/crawlscope/structured_data/reporter.rb +6 -11
  45. data/lib/crawlscope/structured_data/validator.rb +64 -0
  46. data/lib/crawlscope/version.rb +1 -1
  47. data/test/crawlscope/cli_test.rb +21 -0
  48. data/test/crawlscope/content_quality_rule_test.rb +51 -0
  49. data/test/crawlscope/links_rule_test.rb +16 -0
  50. data/test/crawlscope/reporter_test.rb +12 -0
  51. data/test/crawlscope/schema_registry_test.rb +22 -0
  52. data/test/crawlscope/structured_data_audit_test.rb +60 -0
  53. data/test/crawlscope/structured_data_report_test.rb +32 -0
  54. data/test/crawlscope/structured_data_rule_test.rb +11 -1
  55. data/test/crawlscope/structured_data_validator_test.rb +24 -0
  56. metadata +26 -2
data/docs/rails.md ADDED
@@ -0,0 +1,121 @@
1
+ # Rails integration
2
+
3
+ [README](../README.md) · [Project guide](https://www.ethos-link.com/opensource/crawlscope)
4
+
5
+ Install Rails 8 in the host application; Crawlscope does not install Railties.
6
+ For a process that loads Crawlscope before Rails, require `crawlscope/rails`
7
+ after Rails is available. The Ruby and CLI entry points remain independent of Rails.
8
+
9
+ Run the install generator after adding the gem:
10
+
11
+ ```bash
12
+ bin/rails generate crawlscope:install
13
+ ```
14
+
15
+ The generator creates `config/initializers/crawlscope.rb` with an idempotent
16
+ `CrawlscopeConfiguration.apply` loader and adds conditional `crawlscope/tasks`
17
+ loading to the application's `Rakefile`. This preserves `bin/rails --tasks` and
18
+ the `crawlscope:*` tasks without loading Crawlscope during normal Rails boot.
19
+
20
+ Customize the `Crawlscope.configure` block inside the generated initializer:
21
+
22
+ ```ruby
23
+ Crawlscope.configure do |config|
24
+ config.base_url = -> { ENV.fetch("CRAWLSCOPE_BASE_URL", "http://localhost:3000") }
25
+ config.sitemap_path = lambda {
26
+ ENV.fetch("SITEMAP", "#{config.base_url.to_s.chomp("/")}/sitemap.xml")
27
+ }
28
+ config.site_name = ENV.fetch("CRAWLSCOPE_SITE_NAME", "Application")
29
+ end
30
+ ```
31
+
32
+ Runtime callers must apply the generated configuration before using
33
+ Crawlscope:
34
+
35
+ ```ruby
36
+ CrawlscopeConfiguration.apply
37
+ Crawlscope.configuration.audit.call
38
+ ```
39
+
40
+ Rake tasks apply it automatically because `crawlscope/tasks` loads the gem
41
+ before Rails evaluates the initializer. Each Rake entry point passes the shared
42
+ `Crawlscope.configuration` object to the CLI, so configured base URLs, sitemap
43
+ paths, registries, and runtime settings are preserved unless a task argument or
44
+ environment override replaces them.
45
+
46
+ Then run:
47
+
48
+ ```bash
49
+ bin/rails crawlscope:validate
50
+ ```
51
+
52
+ Available environment overrides:
53
+
54
+ - `URL`
55
+ - `SITEMAP`
56
+ - `CRAWLSCOPE_PROFILE_TOKEN`
57
+ - `RULES=metadata,links`
58
+ - `JS=1` or `RENDERER=browser`
59
+ - `TIMEOUT=30`
60
+ - `NETWORK_IDLE_TIMEOUT=10`
61
+ - `CONCURRENCY=5`
62
+ - `FETCH_EXECUTOR=threaded` or `FETCH_EXECUTOR=async`
63
+
64
+ Available tasks:
65
+
66
+ ```bash
67
+ bin/rails crawlscope:validate
68
+ bin/rails crawlscope:validate:indexability
69
+ bin/rails crawlscope:validate:metadata
70
+ bin/rails crawlscope:validate:structured_data
71
+ bin/rails crawlscope:validate:uniqueness
72
+ bin/rails crawlscope:validate:content_quality
73
+ bin/rails crawlscope:validate:links
74
+ bin/rails crawlscope:validate:ldjson
75
+ ```
76
+
77
+ The same validation surface is also available in the gem repository itself through plain `rake`:
78
+
79
+ ```bash
80
+ bundle exec rake crawlscope:validate URL=https://example.com
81
+ bundle exec rake 'crawlscope:validate[https://example.com]'
82
+ bundle exec rake crawlscope:validate:metadata URL=https://example.com
83
+ bundle exec rake 'crawlscope:validate:metadata[https://example.com]'
84
+ bundle exec rake crawlscope:validate:ldjson URL=https://example.com/article
85
+ bundle exec rake 'crawlscope:validate:ldjson[https://example.com/article]'
86
+ ```
87
+
88
+ `crawlscope:validate` runs all default sitemap rules: indexability, metadata,
89
+ structured data, uniqueness, content quality, and links. `URL` is the site
90
+ base. Without `SITEMAP`, Crawlscope uses the configured sitemap URL, then fetches
91
+ `/sitemap.xml` from `URL` over HTTP. With `SITEMAP`, Crawlscope uses `URL` as
92
+ the site base and validates URLs from that sitemap. `SITEMAP` may be a full URL
93
+ or an explicitly selected local file path.
94
+
95
+ Plain `rake` does not pass `--url` style flags to tasks. Use `URL=...` or the
96
+ task-argument form above instead.
97
+
98
+ `FETCH_EXECUTOR=async` is the default for HTTP crawling. It uses Ruby's fiber
99
+ scheduler and Async::HTTP through Faraday, preserving the same `CONCURRENCY`
100
+ bound. Use `FETCH_EXECUTOR=threaded` or `--fetch-executor threaded` for the
101
+ thread-pool executor. Browser rendering uses the threaded executor by default
102
+ because async fetch execution is only supported with HTTP rendering.
103
+
104
+ `crawlscope:validate:ldjson` is separate because it directly checks the URL or semicolon-separated URLs in `URL`; it does not crawl the sitemap. Without `URL`, it checks the configured base URL, falling back to `http://localhost:3000`.
105
+
106
+ ## Structured Data URL Audit
107
+
108
+ For one-off structured-data checks:
109
+
110
+ ```bash
111
+ bin/rails crawlscope:validate:ldjson URL=https://example.com/article
112
+ bin/rails crawlscope:validate:ldjson URL='https://example.com/a;https://example.com/b' SUMMARY=1
113
+ bin/rails crawlscope:validate:ldjson URL=https://example.com/article REPORT_PATH=tmp/structured-data.json
114
+ ```
115
+
116
+ Optional flags:
117
+
118
+ - `DEBUG=1`: print detected items
119
+ - `SUMMARY=1`: print grouped failures
120
+ - `REPORT_PATH=...`: write a JSON report. Treat this as trusted operator input; Crawlscope writes to the path the task process can access.
121
+ - `JS=1` or `RENDERER=browser`: render with Ferrum
data/docs/rules.md ADDED
@@ -0,0 +1,144 @@
1
+ # Rules and schemas
2
+
3
+ [README](../README.md) · [Project guide](https://www.ethos-link.com/opensource/crawlscope)
4
+
5
+ Built-in rules:
6
+
7
+ - `indexability`
8
+ - `metadata`
9
+ - `structured_data`
10
+ - `uniqueness`
11
+ - `content_quality`
12
+ - `links`
13
+
14
+ ## Indexability
15
+
16
+ Checks:
17
+
18
+ - page-level meta robots `noindex`
19
+ - `X-Robots-Tag: noindex`
20
+
21
+ ## Metadata
22
+
23
+ Checks:
24
+
25
+ - missing `<h1>`
26
+ - missing `<title>`
27
+ - title length
28
+ - repeated site name in the title
29
+ - missing meta description
30
+ - meta description length
31
+ - missing canonical link
32
+ - canonical mismatch
33
+
34
+ ## Structured Data
35
+
36
+ Checks:
37
+
38
+ - malformed JSON-LD
39
+ - missing required fields for supported schema types
40
+ - schema validation failures from the configured registry
41
+ - direct URL structured-data audits through `crawlscope:validate:ldjson`
42
+
43
+ Sitemap and direct URL audits share the same document validator, including
44
+ missing `@type` checks. Direct URL audits treat missing markup as a failure;
45
+ sitemap audits retain their warning severity for structured-data findings.
46
+
47
+ ### Required types by URL
48
+
49
+ Schema validation checks the markup a page contains. To detect a missing type
50
+ even when other valid markup exists, configure a URL policy:
51
+
52
+ ```ruby
53
+ Crawlscope.configure do |config|
54
+ config.required_structured_data_types = ->(url) {
55
+ case URI(url).path
56
+ when %r{\A/guides/[^/]+/?\z}
57
+ [["Article", "BlogPosting", "NewsArticle"]]
58
+ when "/guides"
59
+ ["CollectionPage", "ItemList"]
60
+ when %r{/benchmark/?\z}
61
+ ["WebPage", "Dataset"]
62
+ else
63
+ []
64
+ end
65
+ }
66
+ end
67
+ ```
68
+
69
+ Each string requires that type. A nested array accepts any of its types.
70
+ Return an empty array for URLs without a type requirement. The callback receives
71
+ the full URL; the host owns the route policy and content classification.
72
+
73
+ The default sitemap rule and direct URL audits use this policy. A missing
74
+ requirement produces `structured_data_missing_required_type` in sitemap
75
+ findings and a validation failure in direct audits, including their reports and
76
+ exit status. Top-level items, JSON-LD type arrays and `@graph` nodes count;
77
+ an article linked inside an ItemList does not satisfy an article-page requirement.
78
+ Microdata items also count. Custom rule registries must pass the callback to
79
+ `Rules::StructuredData.new(required_types: callback)` themselves.
80
+
81
+ This checks type presence; the schema registry still validates supported types.
82
+ An index, product page or dataset should not acquire Article markup solely
83
+ because an external crawler classified its prose as an article.
84
+
85
+ Job detail pages can opt into an exactly-one-JobPosting policy with
86
+ `Rules::StructuredData.new(job_posting_path: your_path_pattern)` in a custom
87
+ rule registry. No host route patterns are assumed by default. See
88
+ [UPGRADE](../UPGRADE.md) for an example registry configuration.
89
+
90
+ ## Uniqueness
91
+
92
+ Checks:
93
+
94
+ - duplicate titles
95
+ - duplicate meta descriptions
96
+ - duplicate content fingerprints
97
+ - near-duplicate visible content for up to 250 HTML pages
98
+
99
+ For larger crawls, exact duplicate checks still run and Crawlscope reports
100
+ `near_duplicate_scan_skipped`. Configure `Rules::Uniqueness` with
101
+ `max_near_duplicate_pages:` in a custom rule registry to change the limit.
102
+
103
+ ## Content Quality
104
+
105
+ Checks:
106
+
107
+ - missing `alt` attributes on `<img>` elements throughout the page, including
108
+ headers and footers (empty `alt=""` is allowed for decorative images)
109
+ - thin visible text
110
+ - low visible-text-to-HTML ratio
111
+ - low unique-token ratio
112
+
113
+ ## Links
114
+
115
+ Checks:
116
+
117
+ - broken internal links
118
+ - unresolved internal links
119
+ - low inbound anchor-link counts
120
+
121
+ ## Schema Registry
122
+
123
+ `crawlscope` ships with a default schema registry for common types such as:
124
+
125
+ - `Article`
126
+ - `FAQPage`
127
+ - `Organization`
128
+ - `Product`
129
+ - `Review`
130
+ - `SoftwareApplication`
131
+ - `WebApplication`
132
+ - `WebSite`
133
+
134
+ The default schema definitions live in `Crawlscope::Schemas`; `Crawlscope::SchemaRegistry` owns registration and validation.
135
+
136
+ Host apps can replace or extend the registry:
137
+
138
+ ```ruby
139
+ Crawlscope.configure do |config|
140
+ config.schema_registry = -> { MyApp::StructuredData::SchemaRegistry.new }
141
+ end
142
+ ```
143
+
144
+ That makes `crawlscope` useful as the audit engine while the app remains the owner of stricter product-specific schema rules.
@@ -0,0 +1,59 @@
1
+ # Server timing
2
+
3
+ [README](../README.md) · [Project guide](https://www.ethos-link.com/opensource/crawlscope)
4
+
5
+ Crawlscope parses the
6
+ [`Server-Timing`](https://www.w3.org/TR/server-timing/) response header for both
7
+ HTTP and browser-rendered crawls. Each page exposes its parsed header through
8
+ `page.server_timing`:
9
+
10
+ ```ruby
11
+ page.server_timing.each do |metric|
12
+ puts [metric.name, metric.duration, metric.description].compact.join(": ")
13
+ end
14
+ ```
15
+
16
+ The validation report adds a `Server Timing` section only when at least one page
17
+ publishes the header. It includes:
18
+
19
+ - header coverage and the number of pages publishing durations
20
+ - sample and page counts with average, p50, p95, and maximum per metric
21
+ - non-duration signals, including cache status and routing descriptions
22
+ - the ten pages with the largest individual metric
23
+ - the number of malformed entries ignored during parsing
24
+
25
+ `dur` values are reported as milliseconds, as recommended by the specification.
26
+ Crawlscope does not add durations together because metrics such as `total`,
27
+ `app`, and `db` may overlap. A page's worst-offender entry is its largest
28
+ individual metric instead.
29
+
30
+ The current HTTP and browser transports expose response headers, not response
31
+ trailers. Metrics published only in a `Server-Timing` trailer are therefore not
32
+ available to Crawlscope.
33
+
34
+ Rails 8 applications can enable `ActionDispatch::ServerTiming` with:
35
+
36
+ ```ruby
37
+ config.server_timing = true
38
+ ```
39
+
40
+ Applications that expose timing only to authenticated diagnostics can set
41
+ `config.profile_token`. When this value is present, Crawlscope sends it as
42
+ `X-Profile-Token` on same-origin sitemap, HTTP, and browser document requests.
43
+ The header survives same-origin redirects but is removed before a cross-origin
44
+ redirect, and browser subresources never receive it. Keep the token in the host
45
+ application's secret store rather than a URL, command argument, report, or
46
+ checked-in configuration.
47
+
48
+ `CRAWLSCOPE_PROFILE_TOKEN` is the portable default for Rails, the standalone
49
+ CLI, Rake tasks, and plain Ruby callers. Rails applications may instead assign
50
+ `config.profile_token` from encrypted credentials when that is their established
51
+ secret-management boundary; explicit configuration takes precedence over the
52
+ environment.
53
+
54
+ New Rails applications enable Server-Timing in development by default;
55
+ production remains opt-in. Rails publishes the Active Support notification names observed during
56
+ each request and sums repeated events with the same name. The exact metrics
57
+ therefore depend on the application and request, but commonly include controller,
58
+ view, database, and cache instrumentation. Crawlscope accepts Rails' dotted
59
+ metric names and reports each metric independently.
@@ -12,6 +12,7 @@ module Crawlscope
12
12
  DEFAULT_TIMEOUT_SECONDS = 20
13
13
 
14
14
  attr_writer :allowed_statuses, :base_url, :browser_factory, :concurrency, :fetch_executor, :network_idle_timeout_seconds, :output, :profile_token, :renderer, :rule_registry, :schema_registry, :scroll_page, :site_name, :sitemap_path, :timeout_seconds
15
+ attr_accessor :required_structured_data_types
15
16
 
16
17
  def allowed_statuses
17
18
  value = resolve(@allowed_statuses)
@@ -78,7 +79,7 @@ module Crawlscope
78
79
  value = resolve(@rule_registry)
79
80
  return value unless value.nil?
80
81
 
81
- RuleRegistry.default(site_name: site_name)
82
+ RuleRegistry.default(site_name: site_name, required_types: required_structured_data_types)
82
83
  end
83
84
 
84
85
  def audit(base_url: self.base_url, sitemap_path: self.sitemap_path, rule_names: nil)
@@ -28,7 +28,10 @@ module Crawlscope
28
28
  issues = IssueCollection.new
29
29
 
30
30
  collect(pages, issues)
31
- cache(pages)
31
+ @target_resolver = Crawling::TargetResolver.new(
32
+ base_url: @base_url, pages: pages,
33
+ crawler: Crawler.new(page_fetcher: @page_fetcher, concurrency: @concurrency, fetch_executor: @fetch_executor)
34
+ )
32
35
  scan(urls, pages, issues)
33
36
 
34
37
  Result.new(
@@ -58,24 +61,13 @@ module Crawlscope
58
61
  urls
59
62
  end
60
63
 
61
- def browser
62
- Browser.new(
63
- base_url: @base_url,
64
- timeout_seconds: @timeout_seconds,
65
- network_idle_timeout_seconds: @network_idle_timeout_seconds,
66
- profile_token: @profile_token,
67
- scroll_page: @scroll_page
68
- )
69
- rescue LoadError => error
70
- raise ConfigurationError, "Browser rendering requires the ferrum gem (#{error.message})"
71
- end
72
-
73
64
  def page
74
- if @renderer == :browser
75
- (@browser_factory || method(:browser)).call
76
- else
77
- Http.new(base_url: @base_url, timeout_seconds: @timeout_seconds, adapter: http_adapter, profile_token: @profile_token)
78
- end
65
+ Crawling::FetcherFactory.new(
66
+ base_url: @base_url, renderer: @renderer, timeout_seconds: @timeout_seconds,
67
+ browser_factory: @browser_factory, profile_token: @profile_token,
68
+ network_idle_timeout_seconds: @network_idle_timeout_seconds,
69
+ scroll_page: @scroll_page, adapter: http_adapter
70
+ ).call
79
71
  end
80
72
 
81
73
  def http_adapter
@@ -119,20 +111,6 @@ module Crawlscope
119
111
  end
120
112
  end
121
113
 
122
- def cache(pages)
123
- @pages = {}
124
- @targets = {}
125
-
126
- pages.each do |page|
127
- cache_page(page)
128
- end
129
- end
130
-
131
- def cache_page(page)
132
- @pages[page.normalized_url] = page unless page.normalized_url.to_s.empty?
133
- @pages[page.normalized_final_url] = page unless page.normalized_final_url.to_s.empty?
134
- end
135
-
136
114
  def scan(urls, pages, issues)
137
115
  @rules.each do |rule|
138
116
  rule.call(urls: urls, pages: pages, issues: issues, context: context)
@@ -144,53 +122,7 @@ module Crawlscope
144
122
  end
145
123
 
146
124
  def resolve_all(target_urls)
147
- normalized_by_url = Array(target_urls).to_h do |target_url|
148
- [target_url, Url.normalize(target_url, base_url: @base_url)]
149
- end
150
- normalized_urls = normalized_by_url.values.compact.uniq
151
- missing_urls = []
152
-
153
- normalized_urls.each do |normalized_url|
154
- next if @targets.key?(normalized_url)
155
-
156
- resolved = resolved_page(normalized_url)
157
- if resolved
158
- @targets[normalized_url] = resolved
159
- else
160
- missing_urls << normalized_url
161
- end
162
- end
163
-
164
- fetched_pages(missing_urls).each do |page|
165
- normalized_url = Url.normalize(page.url, base_url: @base_url)
166
- cache_page(page)
167
- @targets[normalized_url] = resolution(page, normalized_url, crawled: false)
168
- end
169
-
170
- normalized_by_url.to_h { |target_url, normalized_url| [target_url, @targets[normalized_url]] }
171
- end
172
-
173
- def fetched_pages(normalized_urls)
174
- return [] if normalized_urls.empty?
175
-
176
- Crawler.new(page_fetcher: @page_fetcher, concurrency: @concurrency, fetch_executor: @fetch_executor).call(normalized_urls)
177
- end
178
-
179
- def resolved_page(normalized_url)
180
- page = @pages[normalized_url]
181
- resolution(page, normalized_url, crawled: true) if page
182
- end
183
-
184
- def resolution(page, normalized_url, crawled:)
185
- {
186
- crawled: crawled,
187
- doc: page.doc,
188
- error: page.error,
189
- final_url: page.normalized_final_url || normalized_url,
190
- headers: page.headers,
191
- html: page.html?,
192
- status: page.status
193
- }
125
+ @target_resolver.call(target_urls)
194
126
  end
195
127
 
196
128
  def redirected?(page)
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module Crawling
5
+ class FetcherFactory
6
+ def initialize(base_url:, renderer:, timeout_seconds:, browser_factory: nil,
7
+ network_idle_timeout_seconds: Configuration::DEFAULT_BROWSER_NETWORK_IDLE_TIMEOUT_SECONDS,
8
+ scroll_page: Configuration::DEFAULT_BROWSER_SCROLL_PAGE, profile_token: nil, adapter: nil)
9
+ @base_url = base_url
10
+ @renderer = renderer
11
+ @timeout_seconds = timeout_seconds
12
+ @browser_factory = browser_factory
13
+ @network_idle_timeout_seconds = network_idle_timeout_seconds
14
+ @scroll_page = scroll_page
15
+ @profile_token = profile_token
16
+ @adapter = adapter
17
+ end
18
+
19
+ def call
20
+ return Http.new(base_url: @base_url, timeout_seconds: @timeout_seconds, adapter: @adapter, profile_token: @profile_token) unless @renderer == :browser
21
+ return @browser_factory.call if @browser_factory
22
+
23
+ Browser.new(base_url: @base_url, timeout_seconds: @timeout_seconds,
24
+ network_idle_timeout_seconds: @network_idle_timeout_seconds,
25
+ scroll_page: @scroll_page, profile_token: @profile_token)
26
+ rescue LoadError => error
27
+ raise ConfigurationError, "Browser rendering requires the ferrum gem (#{error.message})"
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module Crawling
5
+ Target = Data.define(:target_url, :resolution) do
6
+ def allowed?(statuses)
7
+ statuses.include?(status)
8
+ end
9
+
10
+ def final_path
11
+ Url.path(final_url)
12
+ end
13
+
14
+ def final_url
15
+ value = resolution[:final_url].to_s
16
+ value.empty? ? target_url : value
17
+ end
18
+
19
+ def ignored_error?
20
+ resolution && status.nil? && resolution[:crawled] && resolution[:error]
21
+ end
22
+
23
+ def html?
24
+ resolution && resolution[:html]
25
+ end
26
+
27
+ def noindex?
28
+ Documents::Robots.noindex_header?(resolution[:headers] || {}) ||
29
+ Documents::Robots.noindex_meta?(resolution[:doc])
30
+ end
31
+
32
+ def status
33
+ resolution && resolution[:status]
34
+ end
35
+
36
+ def redirect?
37
+ (status && (300..399).cover?(status.to_i)) || final_url != target_url
38
+ end
39
+
40
+ def unresolved?
41
+ resolution.nil? || (status.nil? && !ignored_error?)
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module Crawling
5
+ class TargetResolver
6
+ def initialize(base_url:, crawler:, pages:)
7
+ @base_url = base_url
8
+ @crawler = crawler
9
+ @pages = {}
10
+ @targets = {}
11
+
12
+ pages.each do |page|
13
+ cache_page(page)
14
+ end
15
+ end
16
+
17
+ def call(target_urls)
18
+ normalized_by_url = Array(target_urls).to_h do |target_url|
19
+ [target_url, Url.normalize(target_url, base_url: @base_url)]
20
+ end
21
+ normalized_urls = normalized_by_url.values.compact.uniq
22
+ missing_urls = []
23
+
24
+ normalized_urls.each do |normalized_url|
25
+ next if @targets.key?(normalized_url)
26
+
27
+ resolved = resolved_page(normalized_url)
28
+ if resolved
29
+ @targets[normalized_url] = resolved
30
+ else
31
+ missing_urls << normalized_url
32
+ end
33
+ end
34
+
35
+ fetched_pages(missing_urls).each do |page|
36
+ normalized_url = Url.normalize(page.url, base_url: @base_url)
37
+ cache_page(page)
38
+ @targets[normalized_url] = resolution(page, normalized_url, crawled: false)
39
+ end
40
+
41
+ normalized_by_url.to_h { |target_url, normalized_url| [target_url, @targets[normalized_url]] }
42
+ end
43
+
44
+ private
45
+
46
+ def cache_page(page)
47
+ @pages[page.normalized_url] = page unless page.normalized_url.to_s.empty?
48
+ @pages[page.normalized_final_url] = page unless page.normalized_final_url.to_s.empty?
49
+ end
50
+
51
+ def fetched_pages(normalized_urls)
52
+ return [] if normalized_urls.empty?
53
+
54
+ @crawler.call(normalized_urls)
55
+ end
56
+
57
+ def resolved_page(normalized_url)
58
+ page = @pages[normalized_url]
59
+ resolution(page, normalized_url, crawled: true) if page
60
+ end
61
+
62
+ def resolution(page, normalized_url, crawled:)
63
+ {
64
+ crawled: crawled,
65
+ doc: page.doc,
66
+ error: page.error,
67
+ final_url: page.normalized_final_url || normalized_url,
68
+ headers: page.headers,
69
+ html: page.html?,
70
+ status: page.status
71
+ }
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module Documents
5
+ class Canonical
6
+ attr_reader :href
7
+
8
+ def initialize(doc:, base_url:)
9
+ @href = doc&.at_css('link[rel="canonical"]')&.[]("href").to_s.strip
10
+ @base_url = base_url
11
+ end
12
+
13
+ def present?
14
+ !href.empty?
15
+ end
16
+
17
+ def url
18
+ Url.normalize(href, base_url: @base_url) if present?
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module Documents
5
+ class Robots
6
+ ROBOTS_META_SELECTOR = 'meta[name="robots"], meta[name="googlebot"]'
7
+ X_ROBOTS_TAG_HEADER = "x-robots-tag"
8
+
9
+ def self.noindex_header?(headers)
10
+ noindex?(header_value(headers, X_ROBOTS_TAG_HEADER))
11
+ end
12
+
13
+ def self.noindex_meta?(doc)
14
+ return false unless doc
15
+
16
+ doc.css(ROBOTS_META_SELECTOR).any? { |tag| noindex?(tag["content"].to_s) }
17
+ end
18
+
19
+ def self.header_value(headers, name)
20
+ headers.find { |key, _value| key.to_s.casecmp?(name) }&.last.to_s
21
+ end
22
+
23
+ def self.directives(value)
24
+ value
25
+ .split(",")
26
+ .map { |directive| directive.split(":", 2).last.to_s.strip }
27
+ .reject(&:empty?)
28
+ end
29
+
30
+ def self.noindex?(value)
31
+ new(value).noindex?
32
+ end
33
+
34
+ def initialize(value)
35
+ @directives = self.class.directives(value)
36
+ end
37
+
38
+ def noindex?
39
+ include?("noindex") || include?("none")
40
+ end
41
+
42
+ def nofollow?
43
+ include?("nofollow") || include?("none")
44
+ end
45
+
46
+ def follow?
47
+ include?("follow")
48
+ end
49
+
50
+ private
51
+
52
+ def include?(value)
53
+ @directives.any? { |directive| directive.casecmp?(value) }
54
+ end
55
+ end
56
+ end
57
+ end