This repository has been archived by the owner on Feb 17, 2023. It is now read-only.
forked from Kong/httpsnippet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
286 lines (230 loc) · 8.11 KB
/
index.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
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
'use strict'
var debug = require('debug')('httpsnippet')
var es = require('event-stream')
var MultiPartForm = require('form-data')
var qs = require('querystring')
var reducer = require('./helpers/reducer')
var targets = require('./targets')
var url = require('url')
var validate = require('har-validator/lib/async')
// constructor
var HTTPSnippet = function (data) {
var entries
var self = this
var input = Object.assign({}, data)
// prep the main container
self.requests = []
// is it har?
if (input.log && input.log.entries) {
entries = input.log.entries
} else {
entries = [{
request: input
}]
}
entries.forEach(function (entry) {
// add optional properties to make validation successful
entry.request.httpVersion = entry.request.httpVersion || 'HTTP/1.1'
entry.request.queryString = entry.request.queryString || []
entry.request.headers = entry.request.headers || []
entry.request.cookies = entry.request.cookies || []
entry.request.postData = entry.request.postData || {}
entry.request.postData.mimeType = entry.request.postData.mimeType || 'application/octet-stream'
entry.request.bodySize = 0
entry.request.headersSize = 0
entry.request.postData.size = 0
try {
validate.request(entry.request, function (err, valid) {
if (!valid) {
throw err
}
self.requests.push(self.prepare(entry.request))
})
} catch (e) {
console.warn('Error validating har object.', e)
// continue anyway
self.requests.push(self.prepare(entry.request))
}
})
}
HTTPSnippet.prototype.prepare = function (request) {
// construct utility properties
request.queryObj = {}
request.headersObj = {}
request.cookiesObj = {}
request.allHeaders = {}
request.postData.jsonObj = false
request.postData.paramsObj = false
// construct query objects
if (request.queryString && request.queryString.length) {
debug('queryString found, constructing queryString pair map')
request.queryObj = request.queryString.reduce(reducer, {})
}
// construct headers objects
if (request.headers && request.headers.length) {
// loweCase header keys
request.headersObj = request.headers.reduce(function (headers, header) {
headers[header.name.toLowerCase()] = header.value
return headers
}, {})
}
// construct headers objects
if (request.cookies && request.cookies.length) {
request.cookiesObj = request.cookies.reduceRight(function (cookies, cookie) {
cookies[cookie.name] = cookie.value
return cookies
}, {})
}
// construct Cookie header
var cookies = request.cookies.map(function (cookie) {
return encodeURIComponent(cookie.name) + '=' + encodeURIComponent(cookie.value)
})
if (cookies.length) {
request.allHeaders.cookie = cookies.join('; ')
}
switch (request.postData.mimeType) {
case 'multipart/mixed':
case 'multipart/related':
case 'multipart/form-data':
case 'multipart/alternative':
// reset values
request.postData.text = ''
request.postData.mimeType = 'multipart/form-data'
request.headersObj['content-type'] = 'multipart/form-data;'
if (request.postData.params) {
var form = new MultiPartForm()
// easter egg
form._boundary = '---011000010111000001101001'
request.postData.params.forEach(function (param) {
form.append(param.name, param.value || '', {
filename: param.fileName || null,
contentType: param.contentType || null
})
})
if (form.pipe) {
form.pipe(es.map(function (data, cb) {
request.postData.text += data
}))
}
if (form.getBoundary) {
request.postData.boundary = form.getBoundary()
}
request.headersObj['content-type'] = 'multipart/form-data; boundary=' + (request.postData.boundary || '')
}
break
case 'application/x-www-form-urlencoded':
if (!request.postData.params) {
request.postData.text = ''
} else {
request.postData.paramsObj = request.postData.params.reduce(reducer, {})
// always overwrite
request.postData.text = qs.stringify(request.postData.paramsObj)
}
break
case 'text/json':
case 'text/x-json':
case 'application/json':
case 'application/x-json':
request.postData.mimeType = 'application/json'
if (request.postData.text) {
try {
request.postData.jsonObj = JSON.parse(request.postData.text)
} catch (e) {
debug(e)
// force back to text/plain
// if headers have proper content-type value, then this should also work
request.postData.mimeType = 'text/plain'
}
}
break
}
// create allHeaders object
request.allHeaders = Object.assign(request.allHeaders, request.headersObj)
// deconstruct the uri
request.uriObj = url.parse(request.url, true, true)
// merge all possible queryString values
request.queryObj = Object.assign(request.queryObj, request.uriObj.query)
// reset uriObj values for a clean url
request.uriObj.query = null
request.uriObj.search = null
request.uriObj.path = request.uriObj.pathname
// keep the base url clean of queryString
request.url = url.format(request.uriObj)
// update the uri object
request.uriObj.query = request.queryObj
request.uriObj.search = qs.stringify(request.queryObj)
if (request.uriObj.search) {
request.uriObj.path = request.uriObj.pathname + '?' + request.uriObj.search
}
// construct a full url
request.fullUrl = url.format(request.uriObj)
return request
}
HTTPSnippet.prototype.convert = function (target, client, opts) {
if (!opts && client) {
opts = client
}
var func = this._matchTarget(target, client)
if (func) {
var results = this.requests.map(function (request) {
return func(request, opts)
})
return results.length === 1 ? results[0] : results
}
return false
}
HTTPSnippet.prototype._matchTarget = function (target, client) {
// does it exist?
if (!targets.hasOwnProperty(target)) {
return false
}
// shorthand
if (typeof client === 'string' && typeof targets[target][client] === 'function') {
return targets[target][client]
}
// default target
return targets[target][targets[target].info.default]
}
// exports
module.exports = HTTPSnippet
module.exports.addTarget = function (target) {
if (!('info' in target)) {
throw new Error('The supplied custom target must contain an `info` object.')
} else if (!('key' in target.info) || !('title' in target.info) || !('extname' in target.info) || !('default' in target.info)) {
throw new Error('The supplied custom target must have an `info` object with a `key`, `title`, `extname`, and `default` property.')
} else if (targets.hasOwnProperty(target.info.key)) {
throw new Error('The supplied custom target already exists.')
} else if (Object.keys(target).length === 1) {
throw new Error('A custom target must have a client defined on it.')
}
targets[target.info.key] = target
}
module.exports.addTargetClient = function (target, client) {
if (!targets.hasOwnProperty(target)) {
throw new Error(`Sorry, but no ${target} target exists to add clients to.`)
} else if (!('info' in client)) {
throw new Error('The supplied custom target client must contain an `info` object.')
} else if (!('key' in client.info) || !('title' in client.info)) {
throw new Error('The supplied custom target client must have an `info` object with a `key` and `title` property.')
}
targets[target][client.info.key] = client
}
module.exports.availableTargets = function () {
return Object.keys(targets).map(function (key) {
var target = Object.assign({}, targets[key].info)
var clients = Object.keys(targets[key])
.filter(function (prop) {
return !~['info', 'index'].indexOf(prop)
})
.map(function (client) {
return targets[key][client].info
})
if (clients.length) {
target.clients = clients
}
return target
})
}
module.exports.extname = function (target) {
return targets[target] ? targets[target].info.extname : ''
}