forked from sinonjs/nise
/
index.js
335 lines (268 loc) · 9.23 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
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
"use strict";
var fakeXhr = require("../fake-xhr");
var push = [].push;
var log = require("./log");
var configureLogError = require("../configure-logger");
var pathToRegexp = require("path-to-regexp");
var supportsArrayBuffer = typeof ArrayBuffer !== "undefined";
function responseArray(handler) {
var response = handler;
if (Object.prototype.toString.call(handler) !== "[object Array]") {
response = [200, {}, handler];
}
if (typeof response[2] !== "string") {
if (!supportsArrayBuffer) {
throw new TypeError(
"Fake server response body should be a string, but was " +
typeof response[2]
);
} else if (!(response[2] instanceof ArrayBuffer)) {
throw new TypeError(
"Fake server response body should be a string or ArrayBuffer, but was " +
typeof response[2]
);
}
}
return response;
}
function getDefaultWindowLocation() {
var winloc = {
hostname: "localhost",
port: process.env.PORT || 80,
protocol: "http:"
};
winloc.host =
winloc.hostname +
(String(winloc.port) === "80" ? "" : ":" + winloc.port);
return winloc;
}
function getWindowLocation() {
if (typeof window === "undefined") {
// Fallback
return getDefaultWindowLocation();
}
if (typeof window.location !== "undefined") {
// Browsers place location on window
return window.location;
}
if (
typeof window.window !== "undefined" &&
typeof window.window.location !== "undefined"
) {
// React Native on Android places location on window.window
return window.window.location;
}
return getDefaultWindowLocation();
}
function matchOne(response, reqMethod, reqUrl) {
var rmeth = response.method;
var matchMethod = !rmeth || rmeth.toLowerCase() === reqMethod.toLowerCase();
var url = response.url;
var matchUrl =
!url ||
url === reqUrl ||
(typeof url.test === "function" && url.test(reqUrl)) ||
(typeof url === "function" && url(reqUrl) === true);
return matchMethod && matchUrl;
}
function match(response, request) {
var wloc = getWindowLocation();
var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host + "/");
var requestUrl = request.url;
if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) {
requestUrl = requestUrl.replace(rCurrLoc, "/");
}
if (matchOne(response, this.getHTTPMethod(request), requestUrl)) {
if (typeof response.response === "function") {
var ru = response.url;
var args = [request].concat(
ru && typeof ru.exec === "function"
? ru.exec(requestUrl).slice(1)
: []
);
return response.response.apply(response, args);
}
return true;
}
return false;
}
function incrementRequestCount() {
var count = ++this.requestCount;
this.requested = true;
this.requestedOnce = count === 1;
this.requestedTwice = count === 2;
this.requestedThrice = count === 3;
this.firstRequest = this.getRequest(0);
this.secondRequest = this.getRequest(1);
this.thirdRequest = this.getRequest(2);
this.lastRequest = this.getRequest(count - 1);
}
var fakeServer = {
create: function(config) {
var server = Object.create(this);
server.configure(config);
this.xhr = fakeXhr.useFakeXMLHttpRequest();
server.requests = [];
server.requestCount = 0;
server.queue = [];
server.responses = [];
this.xhr.onCreate = function(xhrObj) {
xhrObj.unsafeHeadersEnabled = function() {
return !(server.unsafeHeadersEnabled === false);
};
server.addRequest(xhrObj);
};
return server;
},
configure: function(config) {
var self = this;
var allowlist = {
autoRespond: true,
autoRespondAfter: true,
respondImmediately: true,
fakeHTTPMethods: true,
logger: true,
unsafeHeadersEnabled: true
};
// eslint-disable-next-line no-param-reassign
config = config || {};
Object.keys(config).forEach(function(setting) {
if (setting in allowlist) {
self[setting] = config[setting];
}
});
self.logError = configureLogError(config);
},
addRequest: function addRequest(xhrObj) {
var server = this;
push.call(this.requests, xhrObj);
incrementRequestCount.call(this);
xhrObj.onSend = function() {
server.handleRequest(this);
if (server.respondImmediately) {
server.respond();
} else if (server.autoRespond && !server.responding) {
setTimeout(function() {
server.responding = false;
server.respond();
}, server.autoRespondAfter || 10);
server.responding = true;
}
};
},
getHTTPMethod: function getHTTPMethod(request) {
if (this.fakeHTTPMethods && /post/i.test(request.method)) {
var matches = (request.requestBody || "").match(
/_method=([^\b;]+)/
);
return matches ? matches[1] : request.method;
}
return request.method;
},
handleRequest: function handleRequest(xhr) {
if (xhr.async) {
push.call(this.queue, xhr);
} else {
this.processRequest(xhr);
}
},
logger: function() {
// no-op; override via configure()
},
logError: configureLogError({}),
log: log,
respondWith: function respondWith(method, url, body) {
if (arguments.length === 1 && typeof method !== "function") {
this.response = responseArray(method);
return;
}
if (arguments.length === 1) {
// eslint-disable-next-line no-param-reassign
body = method;
// eslint-disable-next-line no-param-reassign
url = method = null;
}
if (arguments.length === 2) {
// eslint-disable-next-line no-param-reassign
body = url;
// eslint-disable-next-line no-param-reassign
url = method;
// eslint-disable-next-line no-param-reassign
method = null;
}
// Escape port number to prevent "named" parameters in 'path-to-regexp' module
if (typeof url === "string" && url !== "" && /:[0-9]+\//.test(url)) {
var m = url.match(/^(https?:\/\/.*?):([0-9]+\/.*)$/);
// eslint-disable-next-line no-param-reassign
url = m[1] + "\\:" + m[2];
}
push.call(this.responses, {
method: method,
url:
typeof url === "string" && url !== "" ? pathToRegexp(url) : url,
response: typeof body === "function" ? body : responseArray(body)
});
},
respond: function respond() {
if (arguments.length > 0) {
this.respondWith.apply(this, arguments);
}
var queue = this.queue || [];
var requests = queue.splice(0, queue.length);
var self = this;
requests.forEach(function(request) {
self.processRequest(request);
});
},
respondAll: function respondAll() {
if (this.respondImmediately) {
return;
}
this.queue = this.requests.slice(0);
var request;
while ((request = this.queue.shift())) {
this.processRequest(request);
}
},
processRequest: function processRequest(request) {
try {
if (request.aborted) {
return;
}
var response = this.response || [404, {}, ""];
if (this.responses) {
for (var l = this.responses.length, i = l - 1; i >= 0; i--) {
if (match.call(this, this.responses[i], request)) {
response = this.responses[i].response;
break;
}
}
}
if (request.readyState !== 4) {
this.log(response, request);
request.respond(response[0], response[1], response[2]);
}
} catch (e) {
this.logError("Fake server request processing", e);
}
},
restore: function restore() {
return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments);
},
getRequest: function getRequest(index) {
return this.requests[index] || null;
},
reset: function reset() {
this.resetBehavior();
this.resetHistory();
},
resetBehavior: function resetBehavior() {
this.responses.length = this.queue.length = 0;
},
resetHistory: function resetHistory() {
this.requests.length = this.requestCount = 0;
this.requestedOnce = this.requestedTwice = this.requestedThrice = this.requested = false;
this.firstRequest = this.secondRequest = this.thirdRequest = this.lastRequest = null;
}
};
module.exports = fakeServer;