3 var TOKEN = /([!#\$%&'\*\+\-\.\^_`\|~0-9a-z]+)/,
4 NOTOKEN = /([^!#\$%&'\*\+\-\.\^_`\|~0-9a-z])/g,
5 QUOTED = /"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"])*)"/,
6 PARAM = new RegExp(TOKEN.source + '(?:=(?:' + TOKEN.source + '|' + QUOTED.source + '))?'),
7 EXT = new RegExp(TOKEN.source + '(?: *; *' + PARAM.source + ')*', 'g'),
8 EXT_LIST = new RegExp('^' + EXT.source + '(?: *, *' + EXT.source + ')*$'),
9 NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/;
12 parseHeader: function(header) {
13 var offers = new Offers();
14 if (header === '' || header === undefined) return offers;
16 if (!EXT_LIST.test(header))
17 throw new SyntaxError('Invalid Sec-WebSocket-Extensions header: ' + header);
19 var values = header.match(EXT);
21 values.forEach(function(value) {
22 var params = value.match(new RegExp(PARAM.source, 'g')),
23 name = params.shift(),
26 params.forEach(function(param) {
27 var args = param.match(PARAM), key = args[1], data;
29 if (args[2] !== undefined) {
31 } else if (args[3] !== undefined) {
32 data = args[3].replace(/\\/g, '');
36 if (NUMBER.test(data)) data = parseFloat(data);
38 if (offer.hasOwnProperty(key)) {
39 offer[key] = [].concat(offer[key]);
40 offer[key].push(data);
45 offers.push(name, offer);
51 serializeParams: function(name, params) {
54 var print = function(key, value) {
55 if (value instanceof Array) {
56 value.forEach(function(v) { print(key, v) });
57 } else if (value === true) {
59 } else if (typeof value === 'number') {
60 values.push(key + '=' + value);
61 } else if (NOTOKEN.test(value)) {
62 values.push(key + '="' + value.replace(/"/g, '\\"') + '"');
64 values.push(key + '=' + value);
68 for (var key in params) print(key, params[key]);
70 return [name].concat(values).join('; ');
74 var Offers = function() {
79 Offers.prototype.push = function(name, params) {
80 this._byName[name] = this._byName[name] || [];
81 this._byName[name].push(params);
82 this._inOrder.push({name: name, params: params});
85 Offers.prototype.eachOffer = function(callback, context) {
86 var list = this._inOrder;
87 for (var i = 0, n = list.length; i < n; i++)
88 callback.call(context, list[i].name, list[i].params);
91 Offers.prototype.byName = function(name) {
92 return this._byName[name] || [];
95 Offers.prototype.toArray = function() {
96 return this._inOrder.slice();
99 module.exports = Parser;