This repository has been archived by the owner on Aug 1, 2019. It is now read-only.
/
headers-parser-behavior.html
339 lines (329 loc) · 10.2 KB
/
headers-parser-behavior.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
<!--
@license
Copyright 2016 The Advanced REST client authors <arc@mulesoft.com>
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../arc-polyfills/arc-polyfills.html">
<link rel="import" href="../fetch-polyfill/fetch-polyfill.html">
<script>
(function(global) {
'use strict';
var ERROR_MESSAGES = {
CONTENT_TYPE_MISSING: 'Content-Type header is not defined',
HEADER_NAME_EMPTY: 'Header name can\'t be empty',
HEADER_NAME_WHITESPACES: 'Header name should not contain whitespaces',
HEADER_VALUE_EMPTY: 'Header value should not be empty'
};
global.ArcBehaviors = global.ArcBehaviors || {};
/**
* Headers parser behavior to be impplemented with elements that needs to parse headers data.
*
* In most cases function defined in this behavior can work with the headers defined as a string,
* array of objects (name, value keys) or as Header object.
*
* To calculate errors properly, set `isPayload` property when current request can carry a
* payload.
*
* @polymerBehavior ArcBehaviors.HeadersParserBehavior
*/
global.ArcBehaviors.HeadersParserBehavior = {
properties: {
/**
* Set to true when the request can carry a payload.
* It's required for calculating headers errors.
*/
isPayload: Boolean
},
/**
* Filter array of headers and return not duplicated array of the same headers.
* Duplicated headers should be appended to already found one using coma separator.
*
* @param {Array} headers
* Headers array to filter. All objects in headers array must have "name"
* and "value" keys.
* @return {Array} An array of filtered headers.
*/
filterHeaders: function(headers) {
var _tmp = {};
headers.forEach(function(header) {
if (header.name in _tmp) {
if (!!header.value) {
_tmp[header.name] += ', ' + header.value;
}
} else {
_tmp[header.name] = header.value;
}
});
var result = [];
for (var _key in _tmp) {
result[result.length] = {
'name': _key,
'value': _tmp[_key]
};
}
return result;
},
/**
* Parse headers array to Raw HTTP headers string.
*
* @param {Array|String|Headers} headersArray List of objects with "name" and "value"
* properties.
* @returns {String} A HTTP representation of the headers.
*/
headersToString: function(headersArray) {
if (typeof headersArray === 'string') {
return headersArray;
}
if (!(headersArray instanceof Array)) {
headersArray = this.headersToJSON(headersArray);
}
if (headersArray.length === 0) {
return '';
}
headersArray = this.filterHeaders(headersArray);
var result = '';
headersArray.forEach(function(header) {
if (result !== '') {
result += '\n';
}
var key = header.name;
var value = header.value;
if (key && key.trim() !== '') {
result += key + ': ';
if (value && value.trim() !== '') {
result += value;
}
}
});
return result;
},
/**
* Parse HTTP headers input from string to array of objects containing `name` and `value`
* properties.
*
* @param {String|Headers} headers Raw HTTP headers input or Headers object
* @returns {Array<Object>} The array of objects where properties are `name` as a header
* name and `value` as a header content.
*/
headersToJSON: function(headers) {
if (typeof headers === 'string') {
return this._headersStringToJSON(headers);
} else {
return this._hedersToJSON(headers);
}
},
/**
* Parse headers string to array of objects.
* See `#toJSON` for more info.
*/
_headersStringToJSON: function(headersString) {
if (!headersString || headersString.trim() === '') {
return [];
}
if (typeof headersString !== 'string') {
throw new Error('Headers must be an instance of String.');
}
var result = [];
var headers = headersString.split(/\n(?=[^ \t]+)/gim);
for (var i = 0, len = headers.length; i < len; i++) {
var line = headers[i].trim();
if (line === '') {
continue;
}
var sepPosition = line.indexOf(':');
if (sepPosition === -1) {
result[result.length] = {
name: line,
value: ''
};
continue;
}
var name = line.substr(0, sepPosition);
var value = line.substr(sepPosition + 1).trim();
var obj = {
name: name,
value: value
};
result.push(obj);
}
return result;
},
/**
* Parse Headers object to array of objects.
* See `#toJSON` for more info.
*/
_hedersToJSON: function(headers) {
var result = [];
if (!headers) {
return result;
}
var _tmp = {};
headers.forEach(function(value, name) {
if (_tmp[name]) {
_tmp[name] += ', ' + value;
} else {
_tmp[name] = value;
}
});
return Object.keys(_tmp).map(function(key) {
var value = _tmp[key];
if (value && value.indexOf(',') !== -1) {
value = value.split(',').map(function(part) {
return part.trim();
}).join(', ');
}
return {
name: key,
value: value
};
});
},
/**
* Helper method for old system: combine headers list with encoding value.
* Note that this function will update the original array.
*
* @param {Array} headers An array of headers
* @param {String} encoding An encoding string from the old request.
* @return {Boolean} True if encoding has been added to the array.
*/
_oldCombine: function(headers, encoding) {
if (!(headers instanceof Array)) {
throw new Error('Headers must be an array');
}
encoding = String(encoding);
var ct = headers.filter(function(item) {
return item.name.toLowerCase() === 'content-type';
});
if (ct.length === 0) {
headers.push({
'name': 'Content-Type',
'value': encoding.trim()
});
return true;
}
return false;
},
/**
* Get the Content-Type value from the headers.
*
* @param {Array|String} headers Either HTTP headers string or list of headers.
* @return {String|null} A content-type header value or null if not found
*/
getContentType: function(headers) {
if (typeof headers !== 'string') {
headers = this.headersToString(headers);
}
headers = headers.trim();
if (headers === '') {
return null;
}
var re = /^content-type:\s?(.*)$/im;
var match = headers.match(re);
if (!match) {
return null;
}
var ct = match[1].trim();
if (ct.indexOf('multipart') === -1) {
var index = ct.indexOf('; ');
if (index > 0) {
ct = ct.substr(0, index);
}
}
return ct;
},
/**
* Replace value for given header in the headers list.
*
* @param {Array|String|Object} headers A headers object. Can be string, array of objects or
* Headers object.
* @param {String} name Header name to be replaced.
* @param {String} value Header value to be repleced.
* @return {Array} Updated headers.
*/
replaceHeaderValue: function(headers, name, value) {
var origType = 'headers';
if (headers instanceof Array) {
origType = 'array';
} else if (typeof headers === 'string') {
origType = 'string';
}
if (origType !== 'array') {
headers = this.headersToJSON(headers);
}
var _name = name.toLowerCase();
var found = false;
headers.forEach(function(header) {
if (header.name.toLowerCase() === _name) {
header.value = value;
found = true;
}
});
if (!found) {
headers.push({
name: name,
value: value
});
}
if (origType === 'array') {
return headers;
} else if (origType === 'string') {
return this.headersToString(headers);
}
var obj = {};
headers.forEach(function(header) {
obj[header.name] = header.value;
});
return new Headers(obj);
},
/**
* Get error message for given header string.
* @param {Header|Array|String} input A headers to check.
* @return {?String} An error message or null if the headers are valid.
*/
getHeaderError: function(input) {
if (!input) {
if (this.isPayload) {
return ERROR_MESSAGES.CONTENT_TYPE_MISSING;
}
return null;
}
if (!(input instanceof Array)) {
input = this.headersToJSON(input);
}
var msg = [];
var hasContentType = false;
for (var i = 0, len = input.length; i < len; i++) {
var name = input[i].name;
var value = input[i].value;
if (name.toLowerCase() === 'content-type') {
hasContentType = true;
}
if (!name || !name.trim()) {
msg[msg.length] = ERROR_MESSAGES.HEADER_NAME_EMPTY;
} else if (/\s/.test(name)) {
msg[msg.length] = ERROR_MESSAGES.HEADER_NAME_WHITESPACES;
}
if (!value || !value.trim()) {
msg[msg.length] = ERROR_MESSAGES.HEADER_VALUE_EMPTY;
}
}
if (this.isPayload && !hasContentType) {
msg[msg.length] = ERROR_MESSAGES.CONTENT_TYPE_MISSING;
}
if (msg.length > 0) {
return msg.join('\n');
}
return null;
}
};
})(window);
</script>