-
Notifications
You must be signed in to change notification settings - Fork 2
/
veil.js
100 lines (84 loc) · 2.46 KB
/
veil.js
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
// Veil
//
// Copyright 2011 Iris Couch
//
// 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.
var defaultable = require('defaultable')
defaultable.def(module,
{ 'keys' : null
, 'dates' : false
, 'numbers': false
, 'breaks' : /\r?\n/
, 'newline': "\n"
, 'join' : true
, 'body_key': 'body'
, 'header_re': /^(.*?): +(.*)$/
, 'continued_header_re': /^(\s.+)$/
}, function(module, exports, DEFS, require) {
exports.parse = parse
var assert = require('assert')
function parse(message) {
assert.equal(typeof message, 'string', 'Must provide message as a string')
var result = message.split(DEFS.breaks).reduce(line, {})
if(DEFS.join)
result[DEFS.body_key] = result[DEFS.body_key].join(DEFS.newline)
return result
}
function line(message, line) {
if(DEFS.body_key in message)
body(message, line)
else if(line.length === 0)
message[DEFS.body_key] = []
else
header(message, line)
return message
}
function body(message, line) {
message[DEFS.body_key].push(line)
}
var last_key = null;
function header(message, line) {
var match = line.match(DEFS.header_re)
, key = match && match[1]
, val = match && match[2]
, append = false;
if(typeof key != 'string' || typeof val != 'string') {
if(last_key && (match = line.match(DEFS.continued_header_re))) {
key = last_key;
val = match[1];
append = true;
}
else
throw new Error('Bad header line: ' + JSON.stringify(line))
}
if(DEFS.keys === 'underscore')
key = key.toLowerCase().replace(/[^\w+]/g, '_')
var new_val
if(DEFS.dates && typeof val == 'string' && !val.match(/^\s*-?\d+\.?\d*\s*$/)) {
new_val = new Date(val)
if(! isNaN(new_val.getTime()))
val = new_val
}
if(DEFS.numbers && typeof val == 'string') {
new_val = +val
if(! isNaN(new_val))
val = new_val
}
if(append) {
message[key] += val;
} else {
message[key] = val
last_key = key;
}
}
}) // defaultable