-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
216 lines (174 loc) · 5.92 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
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _http = require('http');
var _http2 = _interopRequireDefault(_http);
var _url = require('url');
var _url2 = _interopRequireDefault(_url);
var _portfinder = require('portfinder');
var _portfinder2 = _interopRequireDefault(_portfinder);
var _connect = require('connect');
var _connect2 = _interopRequireDefault(_connect);
var _lodash = require('lodash');
var ensureArray = function ensureArray(v) {
return Array.isArray(v) ? v : [v];
};
var makeConf = function makeConf() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var base = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
return (0, _lodash.defaults)(options, base, { status: 200, headers: {} });
};
var dataTypeToContentType = {
'string': 'text/plain; charset=utf-8',
'object': 'application/json; charset=utf-8'
};
var ensureContentTypeHeader = function ensureContentTypeHeader(payload, headers) {
var exists = Object.keys(headers).some(function (k) {
return k.toLowerCase() === 'content-type';
});
if (!exists) headers['Content-Type'] = dataTypeToContentType[typeof payload];
return headers;
};
var getUrl = function getUrl(server) {
return _url2['default'].format({
protocol: 'http',
hostname: server.address().address,
port: server.address().port,
pathname: '/'
});
};
var die = function die(msg) {
throw new Error('jort: ' + msg);
};
var serveSteps = function serveSteps(confs, baseOptions) {
if (!confs || confs.length === 0) {
die("You must supply at least one step to serveSteps().");
}
var steps = confs.map(function (c) {
var payload = undefined,
options = undefined;
if (Array.isArray(c)) {
var _c = _slicedToArray(c, 2);
payload = _c[0];
options = _c[1];
} else {
payload = c;
options = {};
}
if (payload === null || payload === undefined) {
payload = '';
} else if (typeof payload === 'object') {
try {
payload = JSON.stringify(payload);
} catch (e) {
die('Could not serialize supplied payload: ' + e);
}
}
return [payload, options];
});
var baseConf = makeConf(baseOptions);
return new Promise(function (resolve, reject) {
if (baseConf.port) {
doServe(baseConf.port);
} else {
_portfinder2['default'].getPort(function (err, port) {
if (err) reject(err);
doServe(port);
});
}
function doServe(port) {
var app = (0, _connect2['default'])();
var server = undefined;
// state changer
var current;
var currentStep;
function nextStep() {
if (steps.length === 0) {
if (!baseConf.leaveOpen) server.close();
} else {
currentStep = steps.shift();
var _ensureArray = ensureArray(currentStep);
var _ensureArray2 = _slicedToArray(_ensureArray, 2);
var payload = _ensureArray2[0];
var options = _ensureArray2[1];
current = makeConf(options, baseConf);
current.headers = ensureContentTypeHeader(payload, current.headers);
current.payload = payload;
}
}
// set up persistent middleware
// delayer
app.use(function (req, res, next) {
if (current.delay > 0) {
setTimeout(next, current.delay);
} else {
next();
}
});
// set up base middlewares
if (baseConf.use) {
ensureArray(baseConf.use).forEach(function (f) {
return app.use(f);
});
}
// set up all middlewares
steps.forEach(function (step) {
var options = step[1];
if (options && options.use) {
ensureArray(options.use).forEach(function (f) {
app.use(function (req, res, next) {
if (currentStep === step) {
f(req, res, next);
} else {
next();
}
});
});
}
});
// body resolver
app.use(function (req, res, next) {
res.writeHead(current.status, current.headers);
res.end(current.payload);
nextStep();
next();
});
// first step
nextStep();
// and deliver
var finish = function finish() {
return resolve({
server: server,
url: getUrl(server)
});
};
server = _http2['default'].createServer(app);
if (baseConf.ipv6 === false) {
server.listen(port, '127.0.0.1', finish);
} else {
server.listen(port, '::1', finish);
}
}
});
};
var serve = function serve(payload, options) {
return serveSteps([payload], options);
};
var steps = function steps(payloads, options) {
return serveSteps(payloads, (0, _lodash.defaults)(options, { leaveOpen: false })).then(function (r) {
return r.url;
});
};
var jort = function jort(payload, options) {
return serve(payload, (0, _lodash.defaults)(options, { leaveOpen: false })).then(function (r) {
return r.url;
});
};
jort.serve = serve;
jort.steps = steps;
jort.serveSteps = serveSteps;
exports['default'] = jort;
module.exports = exports['default'];