UNPKG

1.71 kBJavaScriptView Raw
1/*!
2 * Robots
3 * Copyright(c) 2011 Eugene Kalinin
4 * MIT Licensed
5 */
6
7var ut = require('./utils');
8
9exports.Rule = Rule;
10
11/**
12 * A rule line is a single
13 * - "Allow:" (allowance==True) or
14 * - "Disallow:" (allowance==False)
15 * followed by a path.
16 *
17 * @constructor
18 * @param {String} path URL-string
19 * @param {Boolean} allowance Is path allowed
20 */
21function Rule (path, allowance) {
22
23 this.path = ut.quote(ut.unquote(path));
24 this.allowance = allowance;
25
26 // an empty value means allow all
27 if( path === '' && !allowance) {
28 this.allowance = true;
29 }
30}
31
32var end_char = ut.quote('$');
33/**
34 * Check if this rule applies to the specified url
35 *
36 * @param {String} url
37 * @return {Boolean}
38 */
39Rule.prototype.appliesTo = function(url) {
40 var url = ut.quote(ut.unquote(url));
41 ut.d(' * Rule.appliesTo, url: '+url+', path: '+this.path);
42
43 if (this.path === '*' || url.indexOf(this.path) === 0)
44 return true;
45 else if (this.path.indexOf('*') === -1)
46 return false;
47 else {
48 // we have globed match
49 var have_strict_end = this.path.indexOf(end_char) + end_char.length === this.path.length;
50 var parts_to_match = this.path.split('*');
51 url = url + end_char;
52
53 var last_matched_index = 0;
54 for (var i = 0; i < parts_to_match.length; i++) {
55 last_matched_index = url.indexOf(parts_to_match[i], last_matched_index);
56 if (last_matched_index === -1)
57 break;
58 }
59
60 if (have_strict_end && last_matched_index === (this.path.length + end_char.length)) {
61 return true;
62 }
63 else {
64 return last_matched_index !== -1;
65 }
66 }
67};
68
69Rule.prototype.toString = function() {
70 return (this.allowance ? 'Allow' : 'Disallow') + ": " + this.path
71};