robots-parser 2.1.1 → 3.0.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.
package/.gitignore ADDED
@@ -0,0 +1,4 @@
1
+ node_modules
2
+ coverage
3
+ .nyc_output
4
+ .vscode
package/CHANGELOG.md ADDED
@@ -0,0 +1,75 @@
1
+ # Changelog
2
+
3
+ ## Version 3.0.0
4
+
5
+ - Changed to using global URL object instead of importing. – Thanks to @brendankenny
6
+
7
+ ## Version 2.4.0:
8
+
9
+ - Added Typescript definitions. – Thanks to @danhab99 for creating
10
+ - Added SECURITY.md policy and CodeQL scanning
11
+
12
+ ## Version 2.3.0:
13
+
14
+ - Fixed bug where if the user-agent passed to `isAllowed()` / `isDisallowed()` is called "constructor" it would throw an error.
15
+ - Added support for relative URLs. This does not affect the default behavior so can safely be upgraded.
16
+
17
+ Relative matching is only allowed if both the robots.txt URL and the URLs being checked are relative.
18
+
19
+ For example:
20
+
21
+ ```js
22
+ var robots = robotsParser('/robots.txt', [
23
+ 'User-agent: *',
24
+ 'Disallow: /dir/',
25
+ 'Disallow: /test.html',
26
+ 'Allow: /dir/test.html',
27
+ 'Allow: /test.html'
28
+ ].join('\n'));
29
+
30
+ robots.isAllowed('/test.html', 'Sams-Bot/1.0'); // false
31
+ robots.isAllowed('/dir/test.html', 'Sams-Bot/1.0'); // true
32
+ robots.isDisallowed('/dir/test2.html', 'Sams-Bot/1.0'); // true
33
+ ```
34
+
35
+ ## Version 2.2.0:
36
+
37
+ - Fixed bug that with matching wildcard patterns with some URLs
38
+ – Thanks to @ckylape for reporting and fixing
39
+ - Changed matching algorithm to match Google's implementation in google/robotstxt
40
+ - Changed order of precedence to match current spec
41
+
42
+ ## Version 2.1.1:
43
+
44
+ - Fix bug that could be used to causing rule checking to take a long time
45
+ – Thanks to @andeanfog
46
+
47
+ ## Version 2.1.0:
48
+
49
+ - Removed use of punycode module API's as new URL API handles it
50
+ - Improved test coverage
51
+ - Added tests for percent encoded paths and improved support
52
+ - Added `getMatchingLineNumber()` method
53
+ - Fixed bug with comments on same line as directive
54
+
55
+ ## Version 2.0.0:
56
+
57
+ This release is not 100% backwards compatible as it now uses the new URL APIs which are not supported in Node < 7.
58
+
59
+ - Update code to not use deprecated URL module API's.
60
+ &ndash; Thanks to @kdzwinel
61
+
62
+ ## Version 1.0.2:
63
+
64
+ - Fixed error caused by invalid URLs missing the protocol.
65
+
66
+ ## Version 1.0.1:
67
+
68
+ - Fixed bug with the "user-agent" rule being treated as case sensitive.
69
+ &ndash; Thanks to @brendonboshell
70
+ - Improved test coverage.
71
+ &ndash; Thanks to @schornio
72
+
73
+ ## Version 1.0.0:
74
+
75
+ - Initial release.
File without changes
package/README.md ADDED
@@ -0,0 +1,194 @@
1
+ # Robots Parser [![NPM downloads](https://img.shields.io/npm/dm/robots-parser)](https://www.npmjs.com/package/robots-parser) [![DeepScan grade](https://deepscan.io/api/teams/457/projects/16277/branches/344939/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=457&pid=16277&bid=344939) [![GitHub license](https://img.shields.io/github/license/samclarke/robots-parser.svg)](https://github.com/samclarke/robots-parser/blob/master/license.md) [![Coverage Status](https://coveralls.io/repos/github/samclarke/robots-parser/badge.svg?branch=master)](https://coveralls.io/github/samclarke/robots-parser?branch=master)
2
+
3
+ A robots.txt parser which aims to be complaint with the [draft specification](https://datatracker.ietf.org/doc/html/draft-koster-rep).
4
+
5
+ The parser currently supports:
6
+
7
+ - User-agent:
8
+ - Allow:
9
+ - Disallow:
10
+ - Sitemap:
11
+ - Crawl-delay:
12
+ - Host:
13
+ - Paths with wildcards (\*) and EOL matching ($)
14
+
15
+ ## Installation
16
+
17
+ Via NPM:
18
+
19
+ npm install robots-parser
20
+
21
+ or via Yarn:
22
+
23
+ yarn add robots-parser
24
+
25
+ ## Usage
26
+
27
+ ```js
28
+ var robotsParser = require('robots-parser');
29
+
30
+ var robots = robotsParser('http://www.example.com/robots.txt', [
31
+ 'User-agent: *',
32
+ 'Disallow: /dir/',
33
+ 'Disallow: /test.html',
34
+ 'Allow: /dir/test.html',
35
+ 'Allow: /test.html',
36
+ 'Crawl-delay: 1',
37
+ 'Sitemap: http://example.com/sitemap.xml',
38
+ 'Host: example.com'
39
+ ].join('\n'));
40
+
41
+ robots.isAllowed('http://www.example.com/test.html', 'Sams-Bot/1.0'); // true
42
+ robots.isAllowed('http://www.example.com/dir/test.html', 'Sams-Bot/1.0'); // true
43
+ robots.isDisallowed('http://www.example.com/dir/test2.html', 'Sams-Bot/1.0'); // true
44
+ robots.getCrawlDelay('Sams-Bot/1.0'); // 1
45
+ robots.getSitemaps(); // ['http://example.com/sitemap.xml']
46
+ robots.getPreferredHost(); // example.com
47
+ ```
48
+
49
+ ### isAllowed(url, [ua])
50
+
51
+ **boolean or undefined**
52
+
53
+ Returns true if crawling the specified URL is allowed for the specified user-agent.
54
+
55
+ This will return `undefined` if the URL isn't valid for this robots.txt.
56
+
57
+ ### isDisallowed(url, [ua])
58
+
59
+ **boolean or undefined**
60
+
61
+ Returns true if crawling the specified URL is not allowed for the specified user-agent.
62
+
63
+ This will return `undefined` if the URL isn't valid for this robots.txt.
64
+
65
+ ### getMatchingLineNumber(url, [ua])
66
+
67
+ **number or undefined**
68
+
69
+ Returns the line number of the matching directive for the specified URL and user-agent if any.
70
+
71
+ Line numbers start at 1 and go up (1-based indexing).
72
+
73
+ Returns -1 if there is no matching directive. If a rule is manually added without a lineNumber then this will return undefined for that rule.
74
+
75
+ ### getCrawlDelay([ua])
76
+
77
+ **number or undefined**
78
+
79
+ Returns the number of seconds the specified user-agent should wait between requests.
80
+
81
+ Returns undefined if no crawl delay has been specified for this user-agent.
82
+
83
+ ### getSitemaps()
84
+
85
+ **array**
86
+
87
+ Returns an array of sitemap URLs specified by the `sitemap:` directive.
88
+
89
+ ### getPreferredHost()
90
+
91
+ **string or null**
92
+
93
+ Returns the preferred host name specified by the `host:` directive or null if there isn't one.
94
+
95
+ # Changes
96
+
97
+ ### Version 3.0.0
98
+
99
+ - Changed to using global URL object instead of importing. &ndash; Thanks to @brendankenny
100
+
101
+ ### Version 2.4.0:
102
+
103
+ - Added Typescript definitions
104
+ &ndash; Thanks to @danhab99 for creating
105
+ - Added SECURITY.md policy and CodeQL scanning
106
+
107
+ ### Version 2.3.0:
108
+
109
+ - Fixed bug where if the user-agent passed to `isAllowed()` / `isDisallowed()` is called "constructor" it would throw an error.
110
+ - Added support for relative URLs. This does not affect the default behavior so can safely be upgraded.
111
+
112
+ Relative matching is only allowed if both the robots.txt URL and the URLs being checked are relative.
113
+
114
+ For example:
115
+
116
+ ```js
117
+ var robots = robotsParser('/robots.txt', [
118
+ 'User-agent: *',
119
+ 'Disallow: /dir/',
120
+ 'Disallow: /test.html',
121
+ 'Allow: /dir/test.html',
122
+ 'Allow: /test.html'
123
+ ].join('\n'));
124
+
125
+ robots.isAllowed('/test.html', 'Sams-Bot/1.0'); // false
126
+ robots.isAllowed('/dir/test.html', 'Sams-Bot/1.0'); // true
127
+ robots.isDisallowed('/dir/test2.html', 'Sams-Bot/1.0'); // true
128
+ ```
129
+
130
+ ### Version 2.2.0:
131
+
132
+ - Fixed bug that with matching wildcard patterns with some URLs
133
+ &ndash; Thanks to @ckylape for reporting and fixing
134
+ - Changed matching algorithm to match Google's implementation in google/robotstxt
135
+ - Changed order of precedence to match current spec
136
+
137
+ ### Version 2.1.1:
138
+
139
+ - Fix bug that could be used to causing rule checking to take a long time
140
+ &ndash; Thanks to @andeanfog
141
+
142
+ ### Version 2.1.0:
143
+
144
+ - Removed use of punycode module API's as new URL API handles it
145
+ - Improved test coverage
146
+ - Added tests for percent encoded paths and improved support
147
+ - Added `getMatchingLineNumber()` method
148
+ - Fixed bug with comments on same line as directive
149
+
150
+ ### Version 2.0.0:
151
+
152
+ This release is not 100% backwards compatible as it now uses the new URL APIs which are not supported in Node < 7.
153
+
154
+ - Update code to not use deprecated URL module API's.
155
+ &ndash; Thanks to @kdzwinel
156
+
157
+ ### Version 1.0.2:
158
+
159
+ - Fixed error caused by invalid URLs missing the protocol.
160
+
161
+ ### Version 1.0.1:
162
+
163
+ - Fixed bug with the "user-agent" rule being treated as case sensitive.
164
+ &ndash; Thanks to @brendonboshell
165
+ - Improved test coverage.
166
+ &ndash; Thanks to @schornio
167
+
168
+ ### Version 1.0.0:
169
+
170
+ - Initial release.
171
+
172
+ # License
173
+
174
+ The MIT License (MIT)
175
+
176
+ Copyright (c) 2014 Sam Clarke
177
+
178
+ Permission is hereby granted, free of charge, to any person obtaining a copy
179
+ of this software and associated documentation files (the "Software"), to deal
180
+ in the Software without restriction, including without limitation the rights
181
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
182
+ copies of the Software, and to permit persons to whom the Software is
183
+ furnished to do so, subject to the following conditions:
184
+
185
+ The above copyright notice and this permission notice shall be included in
186
+ all copies or substantial portions of the Software.
187
+
188
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
189
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
190
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
191
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
192
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
193
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
194
+ THE SOFTWARE.
package/Robots.js CHANGED
@@ -1,5 +1,3 @@
1
- var URL = require('url').URL;
2
-
3
1
  /**
4
2
  * Trims the white space from the start and end of the line.
5
3
  *
@@ -78,7 +76,7 @@ function formatUserAgent(userAgent) {
78
76
  /**
79
77
  * Normalises the URL encoding of a path by encoding
80
78
  * unicode characters.
81
- *
79
+ *
82
80
  * @param {string} path
83
81
  * @return {string}
84
82
  * @private
@@ -86,7 +84,7 @@ function formatUserAgent(userAgent) {
86
84
  function normaliseEncoding(path) {
87
85
  try {
88
86
  return urlEncodeToUpper(encodeURI(path).replace(/%25/g, '%'));
89
- } catch(e) {
87
+ } catch (e) {
90
88
  return path;
91
89
  }
92
90
  }
@@ -107,33 +105,72 @@ function urlEncodeToUpper(path) {
107
105
  }
108
106
 
109
107
  /**
110
- * Converts the pattern into a regexp if it is a wildcard
111
- * pattern.
108
+ * Matches a pattern with the specified path
112
109
  *
113
- * Returns a string if the pattern isn't a wildcard pattern
110
+ * Uses same algorithm to match patterns as the Google implementation in
111
+ * google/robotstxt so it should be consistent with the spec.
114
112
  *
115
- * @param {string} pattern
116
- * @return {string|RegExp}
113
+ * @see https://github.com/google/robotstxt/blob/f465f0ede81099dd8bc4aeb2966b3a892bd488b3/robots.cc#L74
114
+ * @param {string} pattern
115
+ * @param {string} path
116
+ * @return {boolean}
117
117
  * @private
118
118
  */
119
- function parsePattern(pattern) {
120
- var regexSpecialChars = /[\-\[\]\/\{\}\(\)\+\?\.\\\^\$\|]/g;
121
- // Treat consecutive wildcards as one (#12)
122
- var wildCardPattern = /\*+/g;
123
- var endOfLinePattern = /\\\$$/;
119
+ function matches(pattern, path) {
120
+ // I've added extra comments to try make this easier to understand
121
+
122
+ // Stores the lengths of all the current matching substrings.
123
+ // Maximum number of possible matching lengths is every length in path plus
124
+ // 1 to handle 0 length too (if pattern starts with * which is zero or more)
125
+ var matchingLengths = new Array(path.length + 1);
126
+ var numMatchingLengths = 1;
127
+
128
+ // Initially longest match is 0
129
+ matchingLengths[0] = 0;
130
+
131
+ for (var p = 0; p < pattern.length; p++) {
132
+ // If $ is at the end of pattern then we must match the whole path.
133
+ // Which is true if the longest matching length matches path length
134
+ if (pattern[p] === '$' && p + 1 === pattern.length) {
135
+ return matchingLengths[numMatchingLengths - 1] === path.length;
136
+ }
124
137
 
125
- pattern = normaliseEncoding(pattern)
138
+ // Handle wildcards
139
+ if (pattern[p] == '*') {
140
+ // Wildcard so all substrings minus the current smallest matching
141
+ // length are matches
142
+ numMatchingLengths = path.length - matchingLengths[0] + 1;
143
+
144
+ // Update matching lengths to include the smallest all the way up
145
+ // to numMatchingLengths
146
+ // Don't update smallest possible match as * matches zero or more
147
+ // so the smallest current match is also valid
148
+ for (var i = 1; i < numMatchingLengths; i++) {
149
+ matchingLengths[i] = matchingLengths[i - 1] + 1;
150
+ }
151
+ } else {
152
+ // Check the char at the matching length matches the pattern, if it
153
+ // does increment it and add it as a valid length, ignore if not.
154
+ var numMatches = 0;
155
+ for (var i = 0; i < numMatchingLengths; i++) {
156
+ if (
157
+ matchingLengths[i] < path.length &&
158
+ path[matchingLengths[i]] === pattern[p]
159
+ ) {
160
+ matchingLengths[numMatches++] = matchingLengths[i] + 1;
161
+ }
162
+ }
126
163
 
127
- if (pattern.indexOf('*') < 0 && pattern.indexOf('$') < 0) {
128
- return pattern;
129
- }
164
+ // No paths matched the current pattern char so not a match
165
+ if (numMatches == 0) {
166
+ return false;
167
+ }
130
168
 
131
- pattern = pattern
132
- .replace(regexSpecialChars, '\\$&')
133
- .replace(wildCardPattern, '(?:.*)')
134
- .replace(endOfLinePattern, '$');
169
+ numMatchingLengths = numMatches;
170
+ }
171
+ }
135
172
 
136
- return new RegExp(pattern);
173
+ return true;
137
174
  }
138
175
 
139
176
  function parseRobots(contents, robots) {
@@ -146,7 +183,7 @@ function parseRobots(contents, robots) {
146
183
 
147
184
  var currentUserAgents = [];
148
185
  var isNoneUserAgentState = true;
149
- for (var i=0; i < lines.length; i++) {
186
+ for (var i = 0; i < lines.length; i++) {
150
187
  var line = lines[i];
151
188
 
152
189
  if (!line || !line[0]) {
@@ -197,53 +234,57 @@ function parseRobots(contents, robots) {
197
234
  * @private
198
235
  */
199
236
  function findRule(path, rules) {
200
- var matchingRule = null;
201
-
202
- for (var i=0; i < rules.length; i++) {
203
- var rule = rules[i];
204
-
205
- if (typeof rule.pattern === 'string') {
206
- if (path.indexOf(rule.pattern) !== 0) {
207
- continue;
208
- }
209
-
210
- // The longest matching rule takes precedence
211
- if (!matchingRule || rule.pattern.length > matchingRule.pattern.length) {
212
- matchingRule = rule;
213
- }
214
- // The first matching pattern takes precedence
215
- // over all other rules including other patterns
216
- } else if (rule.pattern.test(path)) {
217
- return rule;
218
- }
219
- }
220
-
221
- return matchingRule;
237
+ var matchedRule = null;
238
+
239
+ for (var i = 0; i < rules.length; i++) {
240
+ var rule = rules[i];
241
+
242
+ if (!matches(rule.pattern, path)) {
243
+ continue;
244
+ }
245
+
246
+ // The longest matching rule takes precedence
247
+ // If rules are the same length then allow takes precedence
248
+ if (!matchedRule || rule.pattern.length > matchedRule.pattern.length) {
249
+ matchedRule = rule;
250
+ } else if (
251
+ rule.pattern.length == matchedRule.pattern.length &&
252
+ rule.allow &&
253
+ !matchedRule.allow
254
+ ) {
255
+ matchedRule = rule;
256
+ }
257
+ }
258
+
259
+ return matchedRule;
222
260
  }
223
261
 
224
262
  /**
225
263
  * Converts provided string into an URL object.
226
- *
264
+ *
227
265
  * Will return null if provided string is not a valid URL.
228
- *
229
- * @param {string} url
266
+ *
267
+ * @param {string} url
230
268
  * @return {?URL}
231
269
  * @private
232
270
  */
233
271
  function parseUrl(url) {
234
272
  try {
235
- return new URL(url);
236
- } catch(e) {
273
+ // Specify a URL to be used with relative paths
274
+ // Using non-existent subdomain so can never cause conflict unless
275
+ // trying to crawl it but doesn't exist and even if tried worst that can
276
+ // happen is it allows relative URLs on it.
277
+ return new URL(url, 'http://robots-relative.samclarke.com/');
278
+ } catch (e) {
237
279
  return null;
238
280
  }
239
281
  }
240
282
 
241
-
242
283
  function Robots(url, contents) {
243
284
  this._url = parseUrl(url) || {};
244
285
  this._url.port = this._url.port || 80;
245
286
 
246
- this._rules = {};
287
+ this._rules = Object.create(null);
247
288
  this._sitemaps = [];
248
289
  this._preferredHost = null;
249
290
 
@@ -270,7 +311,7 @@ Robots.prototype.addRule = function (userAgents, pattern, allow, lineNumber) {
270
311
  }
271
312
 
272
313
  rules[userAgent].push({
273
- pattern: parsePattern(pattern),
314
+ pattern: normaliseEncoding(pattern),
274
315
  allow: allow,
275
316
  lineNumber: lineNumber
276
317
  });
@@ -320,17 +361,19 @@ Robots.prototype._getRule = function (url, ua) {
320
361
  var parsedUrl = parseUrl(url) || {};
321
362
  var userAgent = formatUserAgent(ua || '*');
322
363
 
323
- parsedUrl.port = parsedUrl.port || '80';
364
+ parsedUrl.port = parsedUrl.port || 80;
324
365
 
325
366
  // The base URL must match otherwise this robots.txt is not valid for it.
326
- if (parsedUrl.protocol !== this._url.protocol ||
367
+ if (
368
+ parsedUrl.protocol !== this._url.protocol ||
327
369
  parsedUrl.hostname !== this._url.hostname ||
328
- parsedUrl.port !== this._url.port) {
370
+ parsedUrl.port !== this._url.port
371
+ ) {
329
372
  return;
330
373
  }
331
374
 
332
375
  var rules = this._rules[userAgent] || this._rules['*'] || [];
333
- var path = urlEncodeToUpper(parsedUrl.pathname + parsedUrl.search)
376
+ var path = urlEncodeToUpper(parsedUrl.pathname + parsedUrl.search);
334
377
  var rule = findRule(path, rules);
335
378
 
336
379
  return rule;
package/SECURITY.md ADDED
@@ -0,0 +1,11 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ The latest version is supported.
6
+
7
+ ## Reporting a Vulnerability
8
+
9
+ If you find or suspect a security vulnerability, please report it to sam@samclarke.com, and I will try to respond as quickly as possible.
10
+
11
+ If possible, please include "Security vulnerability report:" in the subject line.
package/index.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ declare module 'robots-parser';
2
+
3
+ interface Robot {
4
+ isAllowed(url: string, ua?: string): boolean | undefined;
5
+ isDisallowed(url: string, ua?: string): boolean | undefined;
6
+ getMatchingLineNumber(url: string, ua?: string): number;
7
+ getCrawlDelay(ua?: string): number | undefined;
8
+ getSitemaps(): string[];
9
+ getPreferredHost(): string | null;
10
+ }
11
+
12
+ export default function robotsParser(url: string, robotstxt: string): Robot;
package/package.json CHANGED
@@ -1,23 +1,57 @@
1
1
  {
2
- "name": "robots-parser",
3
- "version": "2.1.1",
4
- "description": "Robots.txt parser.",
5
- "main": "index.js",
6
- "directories": {
7
- "test": "tests"
8
- },
9
- "scripts": {
10
- "test": "istanbul cover _mocha --print detail --report html --dir ./report/coverage"
11
- },
12
- "repository": {
13
- "type": "git",
14
- "url": "https://github.com/samclarke/robots-parser.git"
15
- },
16
- "author": "Sam Clarke <sam@samclarke.com>",
17
- "license": "MIT",
18
- "devDependencies": {
19
- "chai": "^3.5.0",
20
- "istanbul": "^0.4.5",
21
- "mocha": "^3.1.2"
22
- }
2
+ "name": "robots-parser",
3
+ "version": "3.0.0",
4
+ "description": "A specification compliant robots.txt parser with wildcard (*) matching support.",
5
+ "keywords": [
6
+ "robots.txt",
7
+ "parser",
8
+ "user-agent",
9
+ "scraper",
10
+ "spider",
11
+ "bot",
12
+ "robots-exclusion-standard"
13
+ ],
14
+ "main": "index.js",
15
+ "directories": {
16
+ "test": "tests"
17
+ },
18
+ "homepage": "https://github.com/samclarke/robots-parser",
19
+ "bugs": {
20
+ "url": "https://github.com/samclarke/robots-parser/issues"
21
+ },
22
+ "scripts": {
23
+ "test": "nyc --reporter=text-summary --reporter=html --reporter=lcovonly mocha"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "https://github.com/samclarke/robots-parser.git"
28
+ },
29
+ "author": "Sam Clarke <sam@samclarke.com>",
30
+ "license": "MIT",
31
+ "files": [
32
+ "/Robots.js",
33
+ "/index.js",
34
+ "/index.d.ts",
35
+ "/README.md",
36
+ "/LICENSE.md",
37
+ "/CHANGELOG.md",
38
+ "/SECURITY.md",
39
+ "test/*.js",
40
+ ".gitignore"
41
+ ],
42
+ "engines": {
43
+ "node": ">=0.10"
44
+ },
45
+ "prettier": {
46
+ "tabWidth": 4,
47
+ "useTabs": true,
48
+ "singleQuote": true,
49
+ "trailingComma": "none"
50
+ },
51
+ "devDependencies": {
52
+ "chai": "^4.3.4",
53
+ "mocha": "^9.1.3",
54
+ "nyc": "^15.1.0"
55
+ },
56
+ "types": "./index.d.ts"
23
57
  }
package/test/Robots.js CHANGED
@@ -48,13 +48,13 @@ describe('Robots', function () {
48
48
  var allowed = [
49
49
  'http://www.example.com/fish',
50
50
  'http://www.example.com/fish/test.html',
51
- 'http://www.example.com/Test.html'
51
+ 'http://www.example.com/Test.html',
52
+ 'http://www.example.com/test.html'
52
53
  ];
53
54
 
54
55
  var disallowed = [
55
56
  'http://www.example.com/fish/index.php',
56
57
  'http://www.example.com/fish/',
57
- 'http://www.example.com/test.html'
58
58
  ];
59
59
 
60
60
  testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
@@ -64,48 +64,146 @@ describe('Robots', function () {
64
64
  var contents = [
65
65
  'User-agent: *',
66
66
  'Disallow: /fish*.php',
67
- 'Disallow: /*.dext$'
67
+ 'Disallow: /*.dext$',
68
+ 'Disallow: /dir*'
68
69
  ].join('\n');
69
70
 
70
71
  var allowed = [
71
72
  'http://www.example.com/Fish.PHP',
72
- 'http://www.example.com/Fish.dext1'
73
+ 'http://www.example.com/Fish.dext1',
74
+ 'http://www.example.com/folder/dir.html',
75
+ 'http://www.example.com/folder/dir/test.html'
73
76
  ];
74
77
 
75
78
  var disallowed = [
76
79
  'http://www.example.com/fish.php',
77
80
  'http://www.example.com/fishheads/catfish.php?parameters',
78
81
  'http://www.example.com/AnYthInG.dext',
79
- 'http://www.example.com/Fish.dext.dext'
82
+ 'http://www.example.com/Fish.dext.dext',
83
+ 'http://www.example.com/dir/test.html',
84
+ 'http://www.example.com/directory.html'
80
85
  ];
81
86
 
82
87
  testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
83
88
  });
84
89
 
85
- it('should have the correct order presidence for allow and disallow', function () {
90
+ it('should have the correct order precedence for allow and disallow', function () {
86
91
  var contents = [
87
92
  'User-agent: *',
88
93
  'Disallow: /fish*.php',
89
94
  'Allow: /fish/index.php',
90
95
  'Disallow: /test',
91
96
  'Allow: /test/',
97
+ 'Disallow: /aa/',
98
+ 'Allow: /aa/',
99
+ 'Allow: /bb/',
100
+ 'Disallow: /bb/',
92
101
  ].join('\n');
93
102
 
94
103
  var allowed = [
95
104
  'http://www.example.com/test/index.html',
96
- 'http://www.example.com/test/'
105
+ 'http://www.example.com/fish/index.php',
106
+ 'http://www.example.com/test/',
107
+ 'http://www.example.com/aa/',
108
+ 'http://www.example.com/bb/',
109
+ 'http://www.example.com/x/'
97
110
  ];
98
111
 
99
112
  var disallowed = [
100
113
  'http://www.example.com/fish.php',
101
114
  'http://www.example.com/fishheads/catfish.php?parameters',
102
- 'http://www.example.com/fish/index.php',
103
115
  'http://www.example.com/test'
104
116
  ];
105
117
 
106
118
  testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
107
119
  });
108
120
 
121
+ it('should have the correct order precedence for wildcards', function () {
122
+ var contents = [
123
+ 'User-agent: *',
124
+ 'Disallow: /*/',
125
+ 'Allow: /x/',
126
+ ].join('\n');
127
+
128
+ var allowed = [
129
+ 'http://www.example.com/x/',
130
+ 'http://www.example.com/fish.php',
131
+ 'http://www.example.com/test'
132
+ ];
133
+
134
+ var disallowed = [
135
+ 'http://www.example.com/a/',
136
+ 'http://www.example.com/xx/',
137
+ 'http://www.example.com/test/index.html'
138
+ ];
139
+
140
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
141
+ });
142
+
143
+ it('should parse lines delimitated by \\r', function () {
144
+ var contents = [
145
+ 'User-agent: *',
146
+ 'Disallow: /fish/',
147
+ 'Disallow: /test.html'
148
+ ].join('\r');
149
+
150
+ var allowed = [
151
+ 'http://www.example.com/fish',
152
+ 'http://www.example.com/Test.html'
153
+ ];
154
+
155
+ var disallowed = [
156
+ 'http://www.example.com/fish/index.php',
157
+ 'http://www.example.com/fish/',
158
+ 'http://www.example.com/test.html'
159
+ ];
160
+
161
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
162
+ });
163
+
164
+ it('should parse lines delimitated by \\r\\n', function () {
165
+ var contents = [
166
+ 'User-agent: *',
167
+ 'Disallow: /fish/',
168
+ 'Disallow: /test.html'
169
+ ].join('\r\n');
170
+
171
+ var allowed = [
172
+ 'http://www.example.com/fish',
173
+ 'http://www.example.com/Test.html'
174
+ ];
175
+
176
+ var disallowed = [
177
+ 'http://www.example.com/fish/index.php',
178
+ 'http://www.example.com/fish/',
179
+ 'http://www.example.com/test.html'
180
+ ];
181
+
182
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
183
+ });
184
+
185
+
186
+ it('should parse lines delimitated by mixed line endings', function () {
187
+ var contents = [
188
+ 'User-agent: *\r',
189
+ 'Disallow: /fish/\r\n',
190
+ 'Disallow: /test.html\n\n'
191
+ ].join('');
192
+
193
+ var allowed = [
194
+ 'http://www.example.com/fish',
195
+ 'http://www.example.com/Test.html'
196
+ ];
197
+
198
+ var disallowed = [
199
+ 'http://www.example.com/fish/index.php',
200
+ 'http://www.example.com/fish/',
201
+ 'http://www.example.com/test.html'
202
+ ];
203
+
204
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
205
+ });
206
+
109
207
  it('should ignore rules that are not in a group', function () {
110
208
  var contents = [
111
209
  'Disallow: /secret.html',
@@ -213,6 +311,7 @@ describe('Robots', function () {
213
311
 
214
312
  var invalidUrls = [
215
313
  'http://example.com/secret.html',
314
+ 'http://ex ample.com/secret.html',
216
315
  'http://www.example.net/test/index.html',
217
316
  'http://www.examsple.com/test/',
218
317
  'example.com/test/',
@@ -339,6 +438,54 @@ describe('Robots', function () {
339
438
  testRobots('http://www.eXample.com/robots.txt', contents, allowed, disallowed);
340
439
  });
341
440
 
441
+ it('should handle relative paths', function () {
442
+ var contents = [
443
+ 'User-agent: *',
444
+ 'Disallow: /fish',
445
+ 'Allow: /fish/test',
446
+ ].join('\n');
447
+
448
+ var robots = robotsParser('/robots.txt', contents);
449
+ expect(robots.isAllowed('/fish/test')).to.equal(true);
450
+ expect(robots.isAllowed('/fish')).to.equal(false);
451
+ });
452
+
453
+ it('should not allow relative paths if domain specified', function () {
454
+ var contents = [
455
+ 'User-agent: *',
456
+ 'Disallow: /fish',
457
+ 'Allow: /fish/test',
458
+ ].join('\n');
459
+
460
+ var robots = robotsParser('http://www.example.com/robots.txt', contents);
461
+ expect(robots.isAllowed('/fish/test')).to.equal(undefined);
462
+ expect(robots.isAllowed('/fish')).to.equal(undefined);
463
+ });
464
+
465
+ it('should not treat invalid robots.txt URLs as relative', function () {
466
+ var contents = [
467
+ 'User-agent: *',
468
+ 'Disallow: /fish',
469
+ 'Allow: /fish/test',
470
+ ].join('\n');
471
+
472
+ var robots = robotsParser('https://ex ample.com/robots.txt', contents);
473
+ expect(robots.isAllowed('/fish/test')).to.equal(undefined);
474
+ expect(robots.isAllowed('/fish')).to.equal(undefined);
475
+ });
476
+
477
+ it('should not allow URls if domain specified and robots.txt is relative', function () {
478
+ var contents = [
479
+ 'User-agent: *',
480
+ 'Disallow: /fish',
481
+ 'Allow: /fish/test',
482
+ ].join('\n');
483
+
484
+ var robots = robotsParser('/robots.txt', contents);
485
+ expect(robots.isAllowed('http://www.example.com/fish/test')).to.equal(undefined);
486
+ expect(robots.isAllowed('http://www.example.com/fish')).to.equal(undefined);
487
+ });
488
+
342
489
  it('should allow all if empty robots.txt', function () {
343
490
  var allowed = [
344
491
  'http://www.example.com/secret.html',
@@ -551,6 +698,17 @@ describe('Robots', function () {
551
698
  expect(robots.getCrawlDelay('b')).to.equal(undefined);
552
699
  });
553
700
 
701
+ it('should handle UAs with object property names', function () {
702
+ var contents = [
703
+ 'User-agent: *',
704
+ 'Disallow: /fish',
705
+ ].join('\n');
706
+
707
+ var robots = robotsParser('http://www.example.com/robots.txt', contents);
708
+ expect(robots.isAllowed('http://www.example.com/fish', 'constructor')).to.equal(false);
709
+ expect(robots.isAllowed('http://www.example.com/fish', '__proto__')).to.equal(false);
710
+ });
711
+
554
712
  it('should ignore version numbers in the UA string', function () {
555
713
  var contents = [
556
714
  'user-agent: *',
@@ -589,7 +747,10 @@ describe('Robots', function () {
589
747
  'User-agent: b',
590
748
  'disallow: /test',
591
749
  'disallow: /t*t',
592
- // check UA returns -1 if no matching UA and also handles patterns both allow and disaloow
750
+ '',
751
+ 'User-agent: c',
752
+ 'Disallow: /fish*.php',
753
+ 'Allow: /fish/index.php'
593
754
  ].join('\n');
594
755
 
595
756
  var robots = robotsParser('http://www.example.com/robots.txt', contents);
@@ -600,10 +761,34 @@ describe('Robots', function () {
600
761
 
601
762
  expect(robots.getMatchingLineNumber('http://www.example.com/fish/index.php')).to.equal(4);
602
763
  expect(robots.getMatchingLineNumber('http://www.example.com/fish/')).to.equal(4);
603
- expect(robots.getMatchingLineNumber('http://www.example.com/test.html')).to.equal(5);
764
+ expect(robots.getMatchingLineNumber('http://www.example.com/test.html')).to.equal(7);
604
765
 
605
766
  expect(robots.getMatchingLineNumber('http://www.example.com/test.html', 'a')).to.equal(10);
606
- expect(robots.getMatchingLineNumber('http://www.example.com/test.html', 'b')).to.equal(14);
767
+
768
+ expect(robots.getMatchingLineNumber('http://www.example.com/fish.php', 'c')).to.equal(17);
769
+ expect(robots.getMatchingLineNumber('http://www.example.com/fish/index.php', 'c')).to.equal(18);
607
770
  });
608
- });
609
771
 
772
+ it('should handle large wildcards efficiently', function () {
773
+ var contents = [
774
+ 'User-agent: *',
775
+ 'Disallow: /' + '*'.repeat(2048) + '.html',
776
+ ].join('\n');
777
+
778
+ var allowed = [
779
+ 'http://www.example.com/' + 'sub'.repeat(2048) + 'folder/index.php',
780
+ ];
781
+
782
+ var disallowed = [
783
+ 'http://www.example.com/secret.html'
784
+ ];
785
+
786
+ const start = Date.now();
787
+ testRobots('http://www.eXample.com/robots.txt', contents, allowed, disallowed);
788
+ const end = Date.now();
789
+
790
+ // Should take less than 500 ms (high to allow for variableness of
791
+ // machines running the test, should normally be much less)
792
+ expect(end - start).to.be.lessThan(500);
793
+ });
794
+ });
package/readme.md DELETED
@@ -1,156 +0,0 @@
1
- # Robots Parser [![DeepScan Grade](https://deepscan.io/api/projects/1275/branches/3378/badge/grade.svg)](https://deepscan.io/dashboard/#view=project&pid=1275&bid=3378) [![GitHub license](https://img.shields.io/github/license/samclarke/robots-parser.svg)](https://github.com/samclarke/robots-parser/blob/master/license.md)
2
-
3
- NodeJS robots.txt parser.
4
-
5
- It currently supports:
6
-
7
- * User-agent:
8
- * Allow:
9
- * Disallow:
10
- * Sitemap:
11
- * Crawl-delay:
12
- * Host:
13
- * Paths with wildcards (*) and EOL matching ($)
14
-
15
- ## Installation
16
-
17
- Via NPM:
18
-
19
- npm install robots-parser
20
-
21
- or via Yarn:
22
-
23
- yarn add robots-parser
24
-
25
- ## Usage
26
-
27
- ```js
28
- var robotsParser = require('robots-parser');
29
-
30
- var robots = robotsParser('http://www.example.com/robots.txt', [
31
- 'User-agent: *',
32
- 'Disallow: /dir/',
33
- 'Disallow: /test.html',
34
- 'Allow: /dir/test.html',
35
- 'Allow: /test.html',
36
- 'Crawl-delay: 1',
37
- 'Sitemap: http://example.com/sitemap.xml',
38
- 'Host: example.com'
39
- ].join('\n'));
40
-
41
- robots.isAllowed('http://www.example.com/test.html', 'Sams-Bot/1.0'); // false
42
- robots.isAllowed('http://www.example.com/dir/test.html', 'Sams-Bot/1.0'); // true
43
- robots.isDisallowed('http://www.example.com/dir/test2.html', 'Sams-Bot/1.0'); // true
44
- robots.getCrawlDelay('Sams-Bot/1.0'); // 1
45
- robots.getSitemaps(); // ['http://example.com/sitemap.xml']
46
- robots.getPreferedHost(); // example.com
47
- ```
48
-
49
-
50
- ### isAllowed(url, [ua])
51
- **boolean or undefined**
52
-
53
- Returns true if crawling the specified URL is allowed for the specified user-agent.
54
-
55
- This will return `undefined` if the URL isn't valid for this robots.txt.
56
-
57
-
58
- ### isDisallowed(url, [ua])
59
- **boolean or undefined**
60
-
61
- Returns true if crawling the specified URL is not allowed for the specified user-agent.
62
-
63
- This will return `undefined` if the URL isn't valid for this robots.txt.
64
-
65
-
66
- ### getMatchingLineNumber(url, [ua])
67
- **number or undefined**
68
-
69
- Returns the line number of the matching directive for the specified URL and user-agent if any.
70
-
71
- Line numbers start at 1 and go up (1-based indexing).
72
-
73
- Returns -1 if there is no matching directive. If a rule is manually added without a lineNumber then this will return undefined for that rule.
74
-
75
-
76
- ### getCrawlDelay([ua])
77
- **number or undefined**
78
-
79
- Returns the number of seconds the specified user-agent should wait between requests.
80
-
81
- Returns undefined if no crawl delay has been specified for this user-agent.
82
-
83
-
84
- ### getSitemaps()
85
- **array**
86
-
87
- Returns an array of sitemap URLs specified by the `sitemap:` directive.
88
-
89
-
90
- ### getPreferredHost()
91
- **string or null**
92
-
93
- Returns the preferred host name specified by the `host:` directive or null if there isn't one.
94
-
95
-
96
- # Changes
97
-
98
- ### Version 2.1.1:
99
-
100
- * Fix bug that could be used to causing rule checking to take a long time
101
- &ndash; Thanks to @andeanfog
102
-
103
- ### Version 2.1.0:
104
-
105
- * Removed use of punycode module API's as new URL API handles it
106
- * Improved test coverage
107
- * Added tests for percent encoded paths and improved support
108
- * Added `getMatchingLineNumber()` method
109
- * Fixed bug with comments on same line as directive
110
-
111
- ### Version 2.0.0:
112
-
113
- This release is not 100% backwards compatible as it now uses the new URL APIs which are not supported in Node < 7.
114
-
115
- * Update code to not use deprecated URL module API's.
116
- &ndash; Thanks to @kdzwinel
117
-
118
- ### Version 1.0.2:
119
-
120
- * Fixed error caused by invalid URLs missing the protocol.
121
-
122
- ### Version 1.0.1:
123
-
124
- * Fixed bug with the "user-agent" rule being treated as case sensitive.
125
- &ndash; Thanks to @brendonboshell
126
- * Improved test coverage.
127
- &ndash; Thanks to @schornio
128
-
129
- ### Version 1.0.0:
130
-
131
- * Initial release.
132
-
133
-
134
- # License
135
-
136
- The MIT License (MIT)
137
-
138
- Copyright (c) 2014 Sam Clarke
139
-
140
- Permission is hereby granted, free of charge, to any person obtaining a copy
141
- of this software and associated documentation files (the "Software"), to deal
142
- in the Software without restriction, including without limitation the rights
143
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
144
- copies of the Software, and to permit persons to whom the Software is
145
- furnished to do so, subject to the following conditions:
146
-
147
- The above copyright notice and this permission notice shall be included in
148
- all copies or substantial portions of the Software.
149
-
150
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
151
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
152
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
153
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
154
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
155
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
156
- THE SOFTWARE.