Skip to content

Commit

Permalink
Merge pull request #289 from keanu-delgado/patch-2
Browse files Browse the repository at this point in the history
Disallow invalid literals
  • Loading branch information
rodneyrehm committed Mar 30, 2016
2 parents 670ea0d + 442e186 commit d37c326
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/URITemplate.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@
URITemplate.VARIABLE_PATTERN = /^([^*:.](?:\.?[^*:.])*)((\*)|:(\d+))?$/;
// pattern to verify variable name integrity
URITemplate.VARIABLE_NAME_PATTERN = /[^a-zA-Z0-9%_.]/;
// pattern to verify literal integrity
URITemplate.LITERAL_PATTERN = /[<>{}'"`^| \\]/;

// expand parsed expression (expression, not template!)
URITemplate.expand = function(expression, data) {
Expand Down Expand Up @@ -346,12 +348,20 @@
var ePattern = URITemplate.EXPRESSION_PATTERN;
var vPattern = URITemplate.VARIABLE_PATTERN;
var nPattern = URITemplate.VARIABLE_NAME_PATTERN;
var lPattern = URITemplate.LITERAL_PATTERN;
// token result buffer
var parts = [];
// position within source template
var pos = 0;
var variables, eMatch, vMatch;

var checkLiteral = function(literal) {
if (literal.match(lPattern)) {
throw new Error('Invalid Literal "' + literal + '"');
}
return literal;
};

// RegExp is shared accross all templates,
// which requires a manual reset
ePattern.lastIndex = 0;
Expand All @@ -361,11 +371,11 @@
eMatch = ePattern.exec(expression);
if (eMatch === null) {
// push trailing literal
parts.push(expression.substring(pos));
parts.push(checkLiteral(expression.substring(pos)));
break;
} else {
// push leading literal
parts.push(expression.substring(pos, eMatch.index));
parts.push(checkLiteral(expression.substring(pos, eMatch.index)));
pos = eMatch.index + eMatch[0].length;
}

Expand Down Expand Up @@ -407,7 +417,7 @@
// template doesn't contain any expressions
// so it is a simple literal string
// this probably should fire a warning or something?
parts.push(expression);
parts.push(checkLiteral(expression));
}

this.parts = parts;
Expand Down
6 changes: 6 additions & 0 deletions test/test_template.js
Original file line number Diff line number Diff line change
Expand Up @@ -395,4 +395,10 @@
equal(expansion, literal, 'period in varname');
});

test('Invalid literals', function () {
raises(function() {
URITemplate('invalid.char}acter').parse();
}, Error, 'Failing invalid literal');
});

})();

0 comments on commit d37c326

Please sign in to comment.