Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disallow invalid literals #289

Merged
merged 1 commit into from
Mar 30, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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');
});

})();