robots-parser 2.0.0 → 2.3.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.
Files changed (4) hide show
  1. package/Robots.js +194 -70
  2. package/package.json +31 -21
  3. package/readme.md +58 -5
  4. package/test/Robots.js +0 -459
package/Robots.js CHANGED
@@ -1,5 +1,4 @@
1
- var URL = require('url').URL;
2
- var punycode = require('punycode');
1
+ var URL = require('url').URL;
3
2
 
4
3
  /**
5
4
  * Trims the white space from the start and end of the line.
@@ -23,6 +22,22 @@ function trimLine(line) {
23
22
  return String(line).trim();
24
23
  }
25
24
 
25
+ /**
26
+ * Remove comments from lines
27
+ *
28
+ * @param {string} line
29
+ * @return {string}
30
+ * @private
31
+ */
32
+ function removeComments(line) {
33
+ var commentStartIndex = line.indexOf('#');
34
+ if (commentStartIndex > -1) {
35
+ return line.substr(0, commentStartIndex);
36
+ }
37
+
38
+ return line;
39
+ }
40
+
26
41
  /**
27
42
  * Splits a line at the first occurrence of :
28
43
  *
@@ -42,7 +57,7 @@ function splitLine(line) {
42
57
 
43
58
  /**
44
59
  * Normalises the user-agent string by converting it to
45
- * lowercase and removing any version numbers.
60
+ * lower case and removing any version numbers.
46
61
  *
47
62
  * @param {string} userAgent
48
63
  * @return {string}
@@ -61,45 +76,119 @@ function formatUserAgent(userAgent) {
61
76
  }
62
77
 
63
78
  /**
64
- * Converts the pattern into a regexp if it is a wildcard
65
- * pattern.
79
+ * Normalises the URL encoding of a path by encoding
80
+ * unicode characters.
81
+ *
82
+ * @param {string} path
83
+ * @return {string}
84
+ * @private
85
+ */
86
+ function normaliseEncoding(path) {
87
+ try {
88
+ return urlEncodeToUpper(encodeURI(path).replace(/%25/g, '%'));
89
+ } catch (e) {
90
+ return path;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Convert URL encodings to support case.
96
+ *
97
+ * e.g.: %2a%ef becomes %2A%EF
98
+ *
99
+ * @param {string} path
100
+ * @return {string}
101
+ * @private
102
+ */
103
+ function urlEncodeToUpper(path) {
104
+ return path.replace(/%[0-9a-fA-F]{2}/g, function (match) {
105
+ return match.toUpperCase();
106
+ });
107
+ }
108
+
109
+ /**
110
+ * Matches a pattern with the specified path
66
111
  *
67
- * Returns a string if the pattern isn't a wildcard pattern
112
+ * Uses same algorithm to match patterns as the Google implementation in
113
+ * google/robotstxt so it should be consistent with the spec.
68
114
  *
69
- * @param {string} pattern
70
- * @return {string|RegExp}
115
+ * @see https://github.com/google/robotstxt/blob/f465f0ede81099dd8bc4aeb2966b3a892bd488b3/robots.cc#L74
116
+ * @param {string} pattern
117
+ * @param {string} path
118
+ * @return {boolean}
71
119
  * @private
72
120
  */
73
- function parsePattern(pattern) {
74
- var regexSpecialChars = /[\-\[\]\/\{\}\(\)\+\?\.\\\^\$\|]/g;
75
- var wildCardPattern = /\*/g;
76
- var endOfLinePattern = /\\\$$/;
121
+ function matches(pattern, path) {
122
+ // I've added extra comments to try make this easier to understand
123
+
124
+ // Stores the lengths of all the current matching substrings.
125
+ // Maximum number of possible matching lengths is every length in path plus
126
+ // 1 to handle 0 length too (if pattern starts with * which is zero or more)
127
+ var matchingLengths = new Array(path.length + 1);
128
+ var numMatchingLengths = 1;
129
+
130
+ // Initially longest match is 0
131
+ matchingLengths[0] = 0;
132
+
133
+ for (var p = 0; p < pattern.length; p++) {
134
+ // If $ is at the end of pattern then we must match the whole path.
135
+ // Which is true if the longest matching length matches path length
136
+ if (pattern[p] === '$' && p + 1 === pattern.length) {
137
+ return matchingLengths[numMatchingLengths - 1] === path.length;
138
+ }
77
139
 
78
- if (pattern.indexOf('*') < 0 && pattern.indexOf('$') < 0) {
79
- return pattern;
80
- }
140
+ // Handle wildcards
141
+ if (pattern[p] == '*') {
142
+ // Wildcard so all substrings minus the current smallest matching
143
+ // length are matches
144
+ numMatchingLengths = path.length - matchingLengths[0] + 1;
145
+
146
+ // Update matching lengths to include the smallest all the way up
147
+ // to numMatchingLengths
148
+ // Don't update smallest possible match as * matches zero or more
149
+ // so the smallest current match is also valid
150
+ for (var i = 1; i < numMatchingLengths; i++) {
151
+ matchingLengths[i] = matchingLengths[i - 1] + 1;
152
+ }
153
+ } else {
154
+ // Check the char at the matching length matches the pattern, if it
155
+ // does increment it and add it as a valid length, ignore if not.
156
+ var numMatches = 0;
157
+ for (var i = 0; i < numMatchingLengths; i++) {
158
+ if (
159
+ matchingLengths[i] < path.length &&
160
+ path[matchingLengths[i]] === pattern[p]
161
+ ) {
162
+ matchingLengths[numMatches++] = matchingLengths[i] + 1;
163
+ }
164
+ }
165
+
166
+ // No paths matched the current pattern char so not a match
167
+ if (numMatches == 0) {
168
+ return false;
169
+ }
81
170
 
82
- pattern = pattern
83
- .replace(regexSpecialChars, '\\$&')
84
- .replace(wildCardPattern, '(?:.*)')
85
- .replace(endOfLinePattern, '$');
171
+ numMatchingLengths = numMatches;
172
+ }
173
+ }
86
174
 
87
- return new RegExp(pattern);
175
+ return true;
88
176
  }
89
177
 
90
178
  function parseRobots(contents, robots) {
91
179
  var newlineRegex = /\r\n|\r|\n/;
92
180
  var lines = contents
93
181
  .split(newlineRegex)
182
+ .map(removeComments)
94
183
  .map(splitLine)
95
184
  .map(trimLine);
96
185
 
97
186
  var currentUserAgents = [];
98
187
  var isNoneUserAgentState = true;
99
- for (var i=0; i < lines.length; i++) {
188
+ for (var i = 0; i < lines.length; i++) {
100
189
  var line = lines[i];
101
190
 
102
- if (!line || !line[0] || line[0].indexOf('#') === 0) {
191
+ if (!line || !line[0]) {
103
192
  continue;
104
193
  }
105
194
 
@@ -114,10 +203,10 @@ function parseRobots(contents, robots) {
114
203
  }
115
204
  break;
116
205
  case 'disallow':
117
- robots.addRule(currentUserAgents, line[1], false);
206
+ robots.addRule(currentUserAgents, line[1], false, i + 1);
118
207
  break;
119
208
  case 'allow':
120
- robots.addRule(currentUserAgents, line[1], true);
209
+ robots.addRule(currentUserAgents, line[1], true, i + 1);
121
210
  break;
122
211
  case 'crawl-delay':
123
212
  robots.setCrawlDelay(currentUserAgents, line[1]);
@@ -141,64 +230,65 @@ function parseRobots(contents, robots) {
141
230
  /**
142
231
  * Returns if a pattern is allowed by the specified rules.
143
232
  *
144
- * @param {strnig} path
233
+ * @param {string} path
145
234
  * @param {Array.<Object>} rules
146
- * @return {boolean?}
235
+ * @return {Object?}
147
236
  * @private
148
237
  */
149
- function isPathAllowed(path, rules) {
150
- var result = true;
151
- var resultRuleLength = 0;
238
+ function findRule(path, rules) {
239
+ var matchedRule = null;
152
240
 
153
- for (var i=0; i < rules.length; i++) {
241
+ for (var i = 0; i < rules.length; i++) {
154
242
  var rule = rules[i];
155
243
 
156
- if (typeof rule.pattern === 'string') {
157
- if (path.indexOf(rule.pattern) !== 0) {
158
- continue;
159
- }
244
+ if (!matches(rule.pattern, path)) {
245
+ continue;
246
+ }
160
247
 
161
- // The longest matching rule takes precedence
162
- if (rule.pattern.length > resultRuleLength) {
163
- resultRuleLength = rule.pattern.length;
164
- result = rule.allow;
165
- }
166
- // The first matching pattern takes precedence
167
- // over all other rules including other patterns
168
- } else if (rule.pattern.test(path)) {
169
- return rule.allow;
248
+ // The longest matching rule takes precedence
249
+ // If rules are the same length then allow takes precedence
250
+ if (!matchedRule || rule.pattern.length > matchedRule.pattern.length) {
251
+ matchedRule = rule;
252
+ } else if (
253
+ rule.pattern.length == matchedRule.pattern.length &&
254
+ rule.allow &&
255
+ !matchedRule.allow
256
+ ) {
257
+ matchedRule = rule;
170
258
  }
171
259
  }
172
260
 
173
- return result;
261
+ return matchedRule;
174
262
  }
175
263
 
176
264
  /**
177
265
  * Converts provided string into an URL object.
178
- *
266
+ *
179
267
  * Will return null if provided string is not a valid URL.
180
- *
181
- * @param {string} url
268
+ *
269
+ * @param {string} url
182
270
  * @return {?URL}
183
271
  * @private
184
272
  */
185
273
  function parseUrl(url) {
186
274
  try {
187
- return new URL(url);
188
- } catch(e) {
275
+ // Specify a URL to be used with relative paths
276
+ // Using non-existent subdomain so can never cause conflict unless
277
+ // trying to crawl it but doesn't exist and even if tried worst that can
278
+ // happen is it allows relative URLs on it.
279
+ return new URL(url, 'http://robots-relative.samclarke.com/');
280
+ } catch (e) {
189
281
  return null;
190
282
  }
191
283
  }
192
284
 
193
-
194
285
  function Robots(url, contents) {
195
286
  this._url = parseUrl(url) || {};
196
287
  this._url.port = this._url.port || 80;
197
- this._url.hostname = punycode.toUnicode(this._url.hostname);
198
288
 
199
- this._rules = {};
289
+ this._rules = Object.create(null);
200
290
  this._sitemaps = [];
201
- this._preferedHost = null;
291
+ this._preferredHost = null;
202
292
 
203
293
  parseRobots(contents || '', this);
204
294
  }
@@ -210,8 +300,9 @@ function Robots(url, contents) {
210
300
  * @param {Array.<string>} userAgents
211
301
  * @param {string} pattern
212
302
  * @param {boolean} allow
303
+ * @param {number} [lineNumber] Should use 1-based indexing
213
304
  */
214
- Robots.prototype.addRule = function (userAgents, pattern, allow) {
305
+ Robots.prototype.addRule = function (userAgents, pattern, allow, lineNumber) {
215
306
  var rules = this._rules;
216
307
 
217
308
  userAgents.forEach(function (userAgent) {
@@ -222,8 +313,9 @@ Robots.prototype.addRule = function (userAgents, pattern, allow) {
222
313
  }
223
314
 
224
315
  rules[userAgent].push({
225
- pattern: parsePattern(pattern),
226
- allow: allow
316
+ pattern: normaliseEncoding(pattern),
317
+ allow: allow,
318
+ lineNumber: lineNumber
227
319
  });
228
320
  });
229
321
  };
@@ -264,7 +356,29 @@ Robots.prototype.addSitemap = function (url) {
264
356
  * @param {string} url
265
357
  */
266
358
  Robots.prototype.setPreferredHost = function (url) {
267
- this._preferedHost = url;
359
+ this._preferredHost = url;
360
+ };
361
+
362
+ Robots.prototype._getRule = function (url, ua) {
363
+ var parsedUrl = parseUrl(url) || {};
364
+ var userAgent = formatUserAgent(ua || '*');
365
+
366
+ parsedUrl.port = parsedUrl.port || 80;
367
+
368
+ // The base URL must match otherwise this robots.txt is not valid for it.
369
+ if (
370
+ parsedUrl.protocol !== this._url.protocol ||
371
+ parsedUrl.hostname !== this._url.hostname ||
372
+ parsedUrl.port !== this._url.port
373
+ ) {
374
+ return;
375
+ }
376
+
377
+ var rules = this._rules[userAgent] || this._rules['*'] || [];
378
+ var path = urlEncodeToUpper(parsedUrl.pathname + parsedUrl.search);
379
+ var rule = findRule(path, rules);
380
+
381
+ return rule;
268
382
  };
269
383
 
270
384
  /**
@@ -278,22 +392,33 @@ Robots.prototype.setPreferredHost = function (url) {
278
392
  * @return {boolean?}
279
393
  */
280
394
  Robots.prototype.isAllowed = function (url, ua) {
281
- var parsedUrl = parseUrl(url) || {};
282
- var userAgent = formatUserAgent(ua || '*');
283
-
284
- parsedUrl.port = parsedUrl.port || 80;
285
- parsedUrl.hostname = parsedUrl.hostname && punycode.toUnicode(parsedUrl.hostname);
395
+ var rule = this._getRule(url, ua);
286
396
 
287
- // The base URL must match otherwise this robots.txt is not valid for it.
288
- if (parsedUrl.protocol !== this._url.protocol ||
289
- parsedUrl.hostname !== this._url.hostname ||
290
- parsedUrl.port !== this._url.port) {
397
+ if (typeof rule === 'undefined') {
291
398
  return;
292
399
  }
293
400
 
294
- var rules = this._rules[userAgent] || this._rules['*'] || [];
401
+ return !rule || rule.allow;
402
+ };
295
403
 
296
- return isPathAllowed(parsedUrl.pathname + parsedUrl.search, rules);
404
+ /**
405
+ * Returns the line number of the matching directive for the specified
406
+ * URL and user-agent if any.
407
+ *
408
+ * The line numbers start at 1 and go up (1-based indexing).
409
+ *
410
+ * Return -1 if there is no matching directive. If a rule is manually
411
+ * added without a lineNumber then this will return undefined for that
412
+ * rule.
413
+ *
414
+ * @param {string} url
415
+ * @param {string?} ua
416
+ * @return {number?}
417
+ */
418
+ Robots.prototype.getMatchingLineNumber = function (url, ua) {
419
+ var rule = this._getRule(url, ua);
420
+
421
+ return rule ? rule.lineNumber : -1;
297
422
  };
298
423
 
299
424
  /**
@@ -327,7 +452,7 @@ Robots.prototype.getCrawlDelay = function (ua) {
327
452
  * @return {string?}
328
453
  */
329
454
  Robots.prototype.getPreferredHost = function () {
330
- return this._preferedHost;
455
+ return this._preferredHost;
331
456
  };
332
457
 
333
458
  /**
@@ -340,4 +465,3 @@ Robots.prototype.getSitemaps = function () {
340
465
  };
341
466
 
342
467
  module.exports = Robots;
343
-
package/package.json CHANGED
@@ -1,23 +1,33 @@
1
1
  {
2
- "name": "robots-parser",
3
- "version": "2.0.0",
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": "2.3.0",
4
+ "description": "Robots.txt parser.",
5
+ "main": "index.js",
6
+ "directories": {
7
+ "test": "tests"
8
+ },
9
+ "scripts": {
10
+ "test": "nyc --reporter=text-summary --reporter=html --reporter=lcovonly mocha"
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
+ "files": [
19
+ "/Robots.js",
20
+ "/index.js"
21
+ ],
22
+ "prettier": {
23
+ "tabWidth": 4,
24
+ "useTabs": true,
25
+ "singleQuote": true,
26
+ "trailingComma": "none"
27
+ },
28
+ "devDependencies": {
29
+ "chai": "^4.2.0",
30
+ "mocha": "^6.1.4",
31
+ "nyc": "^14.1.1"
32
+ }
23
33
  }
package/readme.md CHANGED
@@ -1,4 +1,4 @@
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)
1
+ # 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
2
 
3
3
  NodeJS robots.txt parser.
4
4
 
@@ -43,7 +43,7 @@ robots.isAllowed('http://www.example.com/dir/test.html', 'Sams-Bot/1.0'); // tru
43
43
  robots.isDisallowed('http://www.example.com/dir/test2.html', 'Sams-Bot/1.0'); // true
44
44
  robots.getCrawlDelay('Sams-Bot/1.0'); // 1
45
45
  robots.getSitemaps(); // ['http://example.com/sitemap.xml']
46
- robots.getPreferedHost(); // example.com
46
+ robots.getPreferredHost(); // example.com
47
47
  ```
48
48
 
49
49
 
@@ -63,6 +63,16 @@ Returns true if crawling the specified URL is not allowed for the specified user
63
63
  This will return `undefined` if the URL isn't valid for this robots.txt.
64
64
 
65
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
+
66
76
  ### getCrawlDelay([ua])
67
77
  **number or undefined**
68
78
 
@@ -85,11 +95,54 @@ Returns the preferred host name specified by the `host:` directive or null if th
85
95
 
86
96
  # Changes
87
97
 
98
+ ### Version 2.3.0:
99
+
100
+ * Fixed bug where if the user-agent passed to `isAllowed()` / `isDisallowed()` is called "constructor" it would throw an error.
101
+ * Added support for relative URLs. This does not affect the default behavior so can safely be upgraded.
102
+
103
+ Relative matching is only allowed if both the robots.txt URL and the URLs being checked are relative.
104
+
105
+ For example:
106
+ ```js
107
+ var robots = robotsParser('/robots.txt', [
108
+ 'User-agent: *',
109
+ 'Disallow: /dir/',
110
+ 'Disallow: /test.html',
111
+ 'Allow: /dir/test.html',
112
+ 'Allow: /test.html'
113
+ ].join('\n'));
114
+
115
+ robots.isAllowed('/test.html', 'Sams-Bot/1.0'); // false
116
+ robots.isAllowed('/dir/test.html', 'Sams-Bot/1.0'); // true
117
+ robots.isDisallowed('/dir/test2.html', 'Sams-Bot/1.0'); // true
118
+ ```
119
+
120
+
121
+ ### Version 2.2.0:
122
+
123
+ * Fixed bug that with matching wildcard patterns with some URLs
124
+ &ndash; Thanks to @ckylape for reporting and fixing
125
+ * Changed matching algorithm to match Google's implementation in google/robotstxt
126
+ * Changed order of precedence to match current spec
127
+
128
+ ### Version 2.1.1:
129
+
130
+ * Fix bug that could be used to causing rule checking to take a long time
131
+ &ndash; Thanks to @andeanfog
132
+
133
+ ### Version 2.1.0:
134
+
135
+ * Removed use of punycode module API's as new URL API handles it
136
+ * Improved test coverage
137
+ * Added tests for percent encoded paths and improved support
138
+ * Added `getMatchingLineNumber()` method
139
+ * Fixed bug with comments on same line as directive
140
+
88
141
  ### Version 2.0.0:
89
142
 
90
143
  This release is not 100% backwards compatible as it now uses the new URL APIs which are not supported in Node < 7.
91
144
 
92
- * Update code to not use deprecated URL module API's.
145
+ * Update code to not use deprecated URL module API's.
93
146
  &ndash; Thanks to @kdzwinel
94
147
 
95
148
  ### Version 1.0.2:
@@ -98,9 +151,9 @@ This release is not 100% backwards compatible as it now uses the new URL APIs wh
98
151
 
99
152
  ### Version 1.0.1:
100
153
 
101
- * Fixed bug with the "user-agent" rule being treated as case sensitive.
154
+ * Fixed bug with the "user-agent" rule being treated as case sensitive.
102
155
  &ndash; Thanks to @brendonboshell
103
- * Improved test coverage.
156
+ * Improved test coverage.
104
157
  &ndash; Thanks to @schornio
105
158
 
106
159
  ### Version 1.0.0:
package/test/Robots.js DELETED
@@ -1,459 +0,0 @@
1
- var robotsParser = require('../index');
2
- var expect = require('chai').expect;
3
- var punycode = require('punycode');
4
-
5
-
6
- function testRobots(url, contents, allowed, disallowed) {
7
- var robots = robotsParser(url, contents);
8
-
9
- allowed.forEach(function (url) {
10
- expect(robots.isAllowed(url)).to.equal(true);
11
- });
12
-
13
- disallowed.forEach(function (url) {
14
- expect(robots.isDisallowed(url)).to.equal(true);
15
- });
16
- }
17
-
18
- describe('Robots', function () {
19
- it('should parse the disallow directive', function () {
20
- var contents = [
21
- 'User-agent: *',
22
- 'Disallow: /fish/',
23
- 'Disallow: /test.html'
24
- ].join('\n');
25
-
26
- var allowed = [
27
- 'http://www.example.com/fish',
28
- 'http://www.example.com/Test.html'
29
- ];
30
-
31
- var disallowed = [
32
- 'http://www.example.com/fish/index.php',
33
- 'http://www.example.com/fish/',
34
- 'http://www.example.com/test.html'
35
- ];
36
-
37
- testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
38
- });
39
-
40
- it('should parse the allow directive', function () {
41
- var contents = [
42
- 'User-agent: *',
43
- 'Disallow: /fish/',
44
- 'Disallow: /test.html',
45
- 'Allow: /fish/test.html',
46
- 'Allow: /test.html'
47
- ].join('\n');
48
-
49
- var allowed = [
50
- 'http://www.example.com/fish',
51
- 'http://www.example.com/fish/test.html',
52
- 'http://www.example.com/Test.html'
53
- ];
54
-
55
- var disallowed = [
56
- 'http://www.example.com/fish/index.php',
57
- 'http://www.example.com/fish/',
58
- 'http://www.example.com/test.html'
59
- ];
60
-
61
- testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
62
- });
63
-
64
- it('should parse patterns', function () {
65
- var contents = [
66
- 'User-agent: *',
67
- 'Disallow: /fish*.php',
68
- 'Disallow: /*.dext$'
69
- ].join('\n');
70
-
71
- var allowed = [
72
- 'http://www.example.com/Fish.PHP',
73
- 'http://www.example.com/Fish.dext1'
74
- ];
75
-
76
- var disallowed = [
77
- 'http://www.example.com/fish.php',
78
- 'http://www.example.com/fishheads/catfish.php?parameters',
79
- 'http://www.example.com/AnYthInG.dext',
80
- 'http://www.example.com/Fish.dext.dext'
81
- ];
82
-
83
- testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
84
- });
85
-
86
- it('should have the correct order presidence for allow and disallow', function () {
87
- var contents = [
88
- 'User-agent: *',
89
- 'Disallow: /fish*.php',
90
- 'Allow: /fish/index.php',
91
- 'Disallow: /test',
92
- 'Allow: /test/',
93
- ].join('\n');
94
-
95
- var allowed = [
96
- 'http://www.example.com/test/index.html',
97
- 'http://www.example.com/test/'
98
- ];
99
-
100
- var disallowed = [
101
- 'http://www.example.com/fish.php',
102
- 'http://www.example.com/fishheads/catfish.php?parameters',
103
- 'http://www.example.com/fish/index.php',
104
- 'http://www.example.com/test'
105
- ];
106
-
107
- testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
108
- });
109
-
110
- it('should ignore rules that are not in a group', function () {
111
- var contents = [
112
- 'Disallow: /secret.html',
113
- 'Disallow: /test',
114
- ].join('\n');
115
-
116
- var allowed = [
117
- 'http://www.example.com/secret.html',
118
- 'http://www.example.com/test/index.html',
119
- 'http://www.example.com/test/'
120
- ];
121
-
122
- testRobots('http://www.example.com/robots.txt', contents, allowed, []);
123
- });
124
-
125
-
126
- it('should ignore comments', function () {
127
- var contents = [
128
- '#',
129
- '# This is a comment',
130
- '#',
131
- 'User-agent: *',
132
- '# This is a comment',
133
- 'Disallow: /fish/',
134
- '# Disallow: fish',
135
- 'Disallow: /test.html'
136
- ].join('\n');
137
-
138
- var allowed = [
139
- 'http://www.example.com/fish',
140
- 'http://www.example.com/Test.html'
141
- ];
142
-
143
- var disallowed = [
144
- 'http://www.example.com/fish/index.php',
145
- 'http://www.example.com/fish/',
146
- 'http://www.example.com/test.html'
147
- ];
148
-
149
- testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
150
- });
151
-
152
- it('should ignore invalid lines', function () {
153
- var contents = [
154
- 'invalid line',
155
- 'User-agent: *',
156
- 'Disallow: /fish/',
157
- ':::::another invalid line:::::',
158
- 'Disallow: /test.html',
159
- 'Unknown: tule'
160
- ].join('\n');
161
-
162
- var allowed = [
163
- 'http://www.example.com/fish',
164
- 'http://www.example.com/Test.html'
165
- ];
166
-
167
- var disallowed = [
168
- 'http://www.example.com/fish/index.php',
169
- 'http://www.example.com/fish/',
170
- 'http://www.example.com/test.html'
171
- ];
172
-
173
- testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
174
- });
175
-
176
- it('should ignore empty user-agent lines', function () {
177
- var contents = [
178
- 'User-agent:',
179
- 'Disallow: /fish/',
180
- 'Disallow: /test.html'
181
- ].join('\n');
182
-
183
- var allowed = [
184
- 'http://www.example.com/fish',
185
- 'http://www.example.com/Test.html',
186
- 'http://www.example.com/fish/index.php',
187
- 'http://www.example.com/fish/',
188
- 'http://www.example.com/test.html'
189
- ];
190
-
191
- var disallowed = [];
192
-
193
- testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
194
- });
195
-
196
- it('should support groups with multiple user agents (case insensitive)', function () {
197
- var contents = [
198
- 'User-agent: agenta',
199
- 'User-agent: agentb',
200
- 'Disallow: /fish',
201
- ].join('\n');
202
-
203
- var robots = robotsParser('http://www.example.com/robots.txt', contents);
204
-
205
- expect(robots.isAllowed("http://www.example.com/fish", "agenta")).to.equal(false);
206
- });
207
-
208
- it('should return undefined for invalid urls', function () {
209
- var contents = [
210
- 'User-agent: *',
211
- 'Disallow: /secret.html',
212
- 'Disallow: /test',
213
- ].join('\n');
214
-
215
- var invalidUrls = [
216
- 'http://example.com/secret.html',
217
- 'http://www.example.net/test/index.html',
218
- 'http://www.examsple.com/test/',
219
- 'example.com/test/',
220
- ':::::;;`\\|/.example.com/test/'
221
- ];
222
-
223
- var robots = robotsParser('http://www.example.com/robots.txt', contents);
224
-
225
- invalidUrls.forEach(function (url) {
226
- expect(robots.isAllowed(url)).to.equal(undefined);
227
- });
228
- });
229
-
230
- it('should handle Unicode and punycode URLs', function () {
231
- var contents = [
232
- 'User-agent: *',
233
- 'Disallow: /secret.html',
234
- 'Disallow: /test',
235
- ].join('\n');
236
-
237
- var allowed = [
238
- 'http://www.münich.com/index.html',
239
- 'http://www.xn--mnich-kva.com/index.html'
240
- ];
241
-
242
- var disallowed = [
243
- 'http://www.münich.com/secret.html',
244
- 'http://www.xn--mnich-kva.com/secret.html'
245
- ];
246
-
247
- testRobots('http://www.münich.com/robots.txt', contents, allowed, disallowed);
248
- });
249
-
250
- it('should allow all if empty robots.txt', function () {
251
- var allowed = [
252
- 'http://www.example.com/secret.html',
253
- 'http://www.example.com/test/index.html',
254
- 'http://www.example.com/test/'
255
- ];
256
-
257
- var robots = robotsParser('http://www.example.com/robots.txt', '');
258
-
259
- allowed.forEach(function (url) {
260
- expect(robots.isAllowed(url)).to.equal(true);
261
- });
262
- });
263
-
264
- it('should treat null as allowing all', function () {
265
- var robots = robotsParser('http://www.example.com/robots.txt', null);
266
-
267
- expect(robots.isAllowed("http://www.example.com/", "userAgent")).to.equal(true);
268
- expect(robots.isAllowed("http://www.example.com/")).to.equal(true);
269
- });
270
-
271
- it('should parse the crawl-delay directive', function () {
272
- var contents = [
273
- 'user-agent: a',
274
- 'crawl-delay: 1',
275
-
276
- 'user-agent: b',
277
- 'disallow: /d',
278
-
279
- 'user-agent: c',
280
- 'user-agent: d',
281
- 'crawl-delay: 10'
282
- ].join('\n');
283
-
284
- var robots = robotsParser('http://www.example.com/robots.txt', contents);
285
-
286
- expect(robots.getCrawlDelay('a')).to.equal(1);
287
- expect(robots.getCrawlDelay('b')).to.equal(undefined);
288
- expect(robots.getCrawlDelay('c')).to.equal(10);
289
- expect(robots.getCrawlDelay('d')).to.equal(10);
290
- expect(robots.getCrawlDelay()).to.equal(undefined);
291
- });
292
-
293
- it('should ignore invalid crawl-delay directives', function () {
294
- var contents = [
295
- 'user-agent: a',
296
- 'crawl-delay: 1.2.1',
297
-
298
- 'user-agent: b',
299
- 'crawl-delay: 1.a0',
300
-
301
- 'user-agent: c',
302
- 'user-agent: d',
303
- 'crawl-delay: 10a'
304
- ].join('\n');
305
-
306
- var robots = robotsParser('http://www.example.com/robots.txt', contents);
307
-
308
- expect(robots.getCrawlDelay('a')).to.equal(undefined);
309
- expect(robots.getCrawlDelay('b')).to.equal(undefined);
310
- expect(robots.getCrawlDelay('c')).to.equal(undefined);
311
- expect(robots.getCrawlDelay('d')).to.equal(undefined);
312
- });
313
-
314
- it('should parse the sitemap directive', function () {
315
- var contents = [
316
- 'user-agent: a',
317
- 'crawl-delay: 1',
318
- 'sitemap: http://example.com/test.xml',
319
-
320
- 'user-agent: b',
321
- 'disallow: /d',
322
-
323
- 'sitemap: /sitemap.xml',
324
- 'sitemap: http://example.com/test/sitemap.xml '
325
- ].join('\n');
326
-
327
- var robots = robotsParser('http://www.example.com/robots.txt', contents);
328
-
329
- expect(robots.getSitemaps()).to.eql([
330
- 'http://example.com/test.xml',
331
- '/sitemap.xml',
332
- 'http://example.com/test/sitemap.xml'
333
- ]);
334
- });
335
-
336
- it('should parse the host directive', function () {
337
- var contents = [
338
- 'user-agent: a',
339
- 'crawl-delay: 1',
340
- 'host: www.example.net',
341
-
342
- 'user-agent: b',
343
- 'disallow: /d',
344
-
345
- 'host: example.com'
346
- ].join('\n');
347
-
348
- var robots = robotsParser('http://www.example.com/robots.txt', contents);
349
-
350
- expect(robots.getPreferredHost()).to.equal('example.com');
351
- });
352
-
353
- it('should parse empty and invalid directives', function () {
354
- var contents = [
355
- 'user-agent:',
356
- 'user-agent:::: a::',
357
- 'crawl-delay:',
358
- 'crawl-delay:::: 0:',
359
- 'host:',
360
- 'host:: example.com',
361
- 'sitemap:',
362
- 'sitemap:: site:map.xml',
363
- 'disallow:',
364
- 'disallow::: /:',
365
- 'allow:',
366
- 'allow::: /:',
367
- ].join('\n');
368
-
369
- robotsParser('http://www.example.com/robots.txt', contents);
370
- });
371
-
372
- it('should treat only the last host directive as valid', function () {
373
- var contents = [
374
- 'user-agent: a',
375
- 'crawl-delay: 1',
376
- 'host: www.example.net',
377
-
378
- 'user-agent: b',
379
- 'disallow: /d',
380
-
381
- 'host: example.net',
382
- 'host: example.com'
383
- ].join('\n');
384
-
385
- var robots = robotsParser('http://www.example.com/robots.txt', contents);
386
-
387
- expect(robots.getPreferredHost()).to.equal('example.com');
388
- });
389
-
390
- it('should return null when there is no host directive', function () {
391
- var contents = [
392
- 'user-agent: a',
393
- 'crawl-delay: 1',
394
-
395
- 'user-agent: b',
396
- 'disallow: /d',
397
- ].join('\n');
398
-
399
- var robots = robotsParser('http://www.example.com/robots.txt', contents);
400
-
401
- expect(robots.getPreferredHost()).to.equal(null);
402
- });
403
-
404
- it('should fallback to * when a UA has no rules of its own', function () {
405
- var contents = [
406
- 'user-agent: *',
407
- 'crawl-delay: 1',
408
-
409
- 'user-agent: b',
410
- 'crawl-delay: 12',
411
-
412
- 'user-agent: c',
413
- 'user-agent: d',
414
- 'crawl-delay: 10'
415
- ].join('\n');
416
-
417
- var robots = robotsParser('http://www.example.com/robots.txt', contents);
418
-
419
- expect(robots.getCrawlDelay('should-fall-back')).to.equal(1);
420
- expect(robots.getCrawlDelay('d')).to.equal(10);
421
- expect(robots.getCrawlDelay('dd')).to.equal(1);
422
- });
423
-
424
- it('should not fallback to * when a UA has rules', function () {
425
- var contents = [
426
- 'user-agent: *',
427
- 'crawl-delay: 1',
428
-
429
- 'user-agent: b',
430
- 'disallow:'
431
- ].join('\n');
432
-
433
- var robots = robotsParser('http://www.example.com/robots.txt', contents);
434
-
435
- expect(robots.getCrawlDelay('b')).to.equal(undefined);
436
- });
437
-
438
- it('should ignore version numbers in the UA string', function () {
439
- var contents = [
440
- 'user-agent: *',
441
- 'crawl-delay: 1',
442
-
443
- 'user-agent: b',
444
- 'crawl-delay: 12',
445
-
446
- 'user-agent: c',
447
- 'user-agent: d',
448
- 'crawl-delay: 10'
449
- ].join('\n');
450
-
451
- var robots = robotsParser('http://www.example.com/robots.txt', contents);
452
-
453
- expect(robots.getCrawlDelay('should-fall-back/1.0.0')).to.equal(1);
454
- expect(robots.getCrawlDelay('d/12')).to.equal(10);
455
- expect(robots.getCrawlDelay('dd / 0-32-3')).to.equal(1);
456
- expect(robots.getCrawlDelay('b / 1.0')).to.equal(12);
457
- });
458
- });
459
-