/
electron-http-transport.js
589 lines (563 loc) · 16.3 KB
/
electron-http-transport.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
/**
* `electron-http-transport`
*
* A web comonent to work with @advanced-rest-client/electron-request
* node package in web components environment
*
* @customElement
* @memberof LogicElements
*/
class ElectronHttpTransport extends HTMLElement {
/* global SocketRequest, ElectronRequest */
get requestTimeout() {
const rt = this.getAttribute('request-timeout');
if (!rt || isNaN(rt)) {
return null;
}
return Number(rt);
}
set requestTimeout(value) {
if (!value) {
this.removeAttribute('request-timeout');
} else {
this.setAttribute('request-timeout', value);
}
}
get nativeTransport() {
return this.hasAttribute('native-transport');
}
set nativeTransport(value) {
if (!value) {
this.removeAttribute('native-transport');
} else {
this.setAttribute('native-transport', '');
}
}
get validateCertificates() {
return this.hasAttribute('validate-certificates');
}
/**
* When set it validates certificates during request.
* @param {Boolean} value
*/
set validateCertificates(value) {
if (!value) {
this.removeAttribute('validate-certificates');
} else {
this.setAttribute('validate-certificates', '');
}
}
/**
* When not set the request object won't follow redirects.
* @param {Boolean} value
*/
set followRedirects(value) {
if (!value) {
this.removeAttribute('follow-redirects');
} else {
this.setAttribute('follow-redirects', '');
}
}
get followRedirects() {
return this.hasAttribute('follow-redirects');
}
/**
* A limit of characters to include into the `sentHttpMessage` property
* of the request object. 0 to disable limit. Default to 2048.
* @param {Number} value
*/
set sentMessageLimit(value) {
if (!value) {
this.removeAttribute('sent-message-limit');
} else {
this.setAttribute('sent-message-limit', value);
}
}
get sentMessageLimit() {
const v = this.getAttribute('sent-message-limit');
if (!v || isNaN(v)) {
return null;
}
return Number(v);
}
constructor() {
super();
// Socket handlers
this._loadStartHandler = this._loadStartHandler.bind(this);
this._firstByteHandler = this._firstByteHandler.bind(this);
this._loadEndHandler = this._loadEndHandler.bind(this);
this._beforeRedirectHandler = this._beforeRedirectHandler.bind(this);
this._headersReceivedHandler = this._headersReceivedHandler.bind(this);
this._loadHandler = this._loadHandler.bind(this);
this._errorHandler = this._errorHandler.bind(this);
// Host data handlers
this._ruleUpdated = this._ruleUpdated.bind(this);
this._ruleDeleted = this._ruleDeleted.bind(this);
// Transport control
this._onTransportRequested = this._onTransportRequested.bind(this);
this._abortHandler = this._abortHandler.bind(this);
// Local properties
this._connections = {};
}
connectedCallback() {
document.body.addEventListener('transport-request', this._onTransportRequested);
document.body.addEventListener('abort-api-request', this._abortHandler);
window.addEventListener('host-rules-changed', this._ruleUpdated);
window.addEventListener('host-rules-deleted', this._ruleDeleted);
}
disconnectedCallback() {
document.body.removeEventListener('transport-request', this._onTransportRequested);
document.body.removeEventListener('abort-api-request', this._abortHandler);
window.addEventListener('host-rules-changed', this._ruleUpdated);
window.addEventListener('host-rules-deleted', this._ruleDeleted);
}
_abortHandler(e) {
const id = e.detail.id;
const info = this._connections[id];
if (!info) {
return;
}
e.preventDefault();
info.connection.abort();
info.aborted = true;
}
_onTransportRequested(e) {
if (e.defaultPrevented) {
return;
}
e.preventDefault();
e.stopPropagation();
this.run(e.detail);
}
/**
* Runs the request with Electron's `SocketRequest` class.
* @param {Object} request ARC request object
* @param {?Object} opts Additional request options:
* - timeout {Number} - Timeout in milliseconds
* - followRedirects {Boolean} Note, as of ARC 13 this object is part of
* the request object under `config` property.
* @return {Promise} A promise when the request is started with the socket
* library
*/
run(request, opts) {
opts = this._prepareRequestOptions(request, opts);
return this._readHosts()
.then((hosts) => {
opts.hosts = hosts;
return this._prepareRequest(request, opts);
})
.then((connection) => this._makeConnection(connection))
.catch((cause) => this._errorHandler(cause, request.id));
}
_prepareRequestOptions(request, opts) {
let rConfig;
if (request.config && request.config.enabled !== false) {
rConfig = Object.assign(request.config);
} else {
rConfig = {};
}
opts = Object.assign({}, opts || {});
opts = Object.assign(rConfig, opts);
if (typeof opts.timeout === 'undefined') {
const time = this.requestTimeout;
if (time) {
opts.timeout = time;
}
}
if (opts.timeout) {
if (opts.timeout < 500) {
opts.timeout = opts.timeout * 1000;
}
} else {
opts.timeout = 0;
}
if (!opts.validateCertificates) {
opts.validateCertificates = this.validateCertificates;
}
if (typeof opts.followRedirects === 'undefined') {
opts.followRedirects = this.followRedirects;
}
if (typeof opts.sentMessageLimit === 'undefined') {
opts.sentMessageLimit = this.sentMessageLimit;
}
if (opts.sentMessageLimit) {
opts.sentMessageLimit = Number(opts.sentMessageLimit);
}
return opts;
}
/**
* Reads application hosts configuration and returns it.
* It returns empty array of hosts couldn't be read.
* @return {Promise<Array>}
*/
async _readHosts() {
if (this.hosts !== undefined) {
return this.hosts;
}
const e = new CustomEvent('host-rules-list', {
bubbles: true,
composed: true,
cancelable: true,
detail: {}
});
this.dispatchEvent(e);
if (!e.defaultPrevented) {
this.hosts = [];
return this.hosts;
}
const rules = await e.detail.result;
this.hosts = rules || [];
return rules;
}
_isNative(opts) {
if (opts && typeof opts.nativeTransport === 'boolean') {
return opts.nativeTransport;
}
return this.nativeTransport;
}
_prepareRequest(request, opts) {
return this._isNative(opts) ?
this._prepareNativeRequest(request, opts) :
this._prepareArcRequest(request, opts);
}
_prepareArcRequest(request, opts) {
let conn;
// In ARC electron the browser window is created without node integration
// and therefore require is disabled. In tests node is enabled.
if (typeof SocketRequest === 'undefined') {
const { SocketRequest } = require('@advanced-rest-client/electron-request');
conn = new SocketRequest(request, opts);
} else {
conn = new SocketRequest(request, opts);
}
this._connections[request.id] = {
connection: conn,
aborted: false
};
conn.on('loadstart', this._loadStartHandler);
conn.on('firstbyte', this._firstByteHandler);
conn.on('loadend', this._loadEndHandler);
conn.on('beforeredirect', this._beforeRedirectHandler);
conn.on('headersreceived', this._headersReceivedHandler);
conn.on('load', this._loadHandler);
conn.on('error', this._errorHandler);
return conn;
}
_prepareNativeRequest(request, opts) {
let conn;
// In ARC electron the browser window is created without node integration
// and therefore require is disabled. In tests node is enabled.
if (typeof ElectronRequest === 'undefined') {
const { ElectronRequest } = require('@advanced-rest-client/electron-request');
conn = new ElectronRequest(request, opts);
} else {
conn = new ElectronRequest(request, opts);
}
this._connections[request.id] = {
connection: conn,
aborted: false
};
conn.on('loadstart', this._loadStartHandler);
conn.on('firstbyte', this._firstByteHandler);
conn.on('loadend', this._loadEndHandler);
conn.on('beforeredirect', this._beforeRedirectHandler);
conn.on('headersreceived', this._headersReceivedHandler);
conn.on('load', this._loadHandler);
conn.on('error', this._errorHandler);
return conn;
}
_makeConnection(connection) {
return connection.send()
.catch((cause) => {
this._errorHandler(cause, connection.id);
});
}
_removeConnectionHandlers(connection) {
connection.removeListener('loadstart', this._loadStartHandler);
connection.removeListener('firstbyte', this._firstByteHandler);
connection.removeListener('loadend', this._loadEndHandler);
connection.removeListener('beforeredirect', this._beforeRedirectHandler);
connection.removeListener('headersreceived', this._headersReceivedHandler);
connection.removeListener('load', this._loadHandler);
connection.removeListener('error', this._errorHandler);
}
_informStatus(type, id) {
const info = this._connections[id];
if (!info || info.aborted) {
return;
}
this.dispatchEvent(new CustomEvent(type, {
composed: true,
bubbles: true,
detail: {
id
}
}));
}
_loadStartHandler(id) {
this._informStatus('request-load-start', id);
}
_firstByteHandler(id) {
this._informStatus('request-first-byte-received', id);
}
_loadEndHandler(id) {
this._informStatus('request-load-end', id);
}
_beforeRedirectHandler(id, detail) {
const info = this._connections[id];
if (!info || info.aborted) {
return;
}
const e = new CustomEvent('before-redirect', {
composed: true,
bubbles: true,
cancelable: true,
detail: {
id,
url: detail.location
}
});
this.dispatchEvent(e);
if (e.defaultPrevented) {
detail.returnValue = false;
}
}
_headersReceivedHandler(id, detail) {
const info = this._connections[id];
if (!info || info.aborted) {
return;
}
const e = new CustomEvent('headers-received', {
composed: true,
bubbles: true,
cancelable: true,
detail: {
id,
value: detail.value
}
});
this.dispatchEvent(e);
if (e.defaultPrevented) {
detail.returnValue = false;
}
}
_loadHandler(id, response, request) {
const info = this._connections[id];
if (!info || info.aborted) {
return;
}
this._removeConnectionHandlers(info.connection);
delete this._connections[id];
this._processResponse(id, response, request);
}
_errorHandler(cause, id, request, response) {
const info = this._connections[id];
if (info) {
this._removeConnectionHandlers(info.connection);
delete this._connections[id];
}
if (info && info.aborted) {
return;
}
if (!response) {
response = {};
}
const data = Object.assign({}, response, {
isError: true,
error: cause
});
this._processResponse(id, data, request);
}
/**
* Processes response data and creates ARC response object.
* @param {String} id Request ID
* @param {Object} data Response data
* @param {Object} requestInfo Request data
*/
_processResponse(id, data, requestInfo) {
const detail = {
isXhr: false,
request: requestInfo
};
const redirects = this._processRedirects(data.redirects);
if (redirects.timings.length) {
detail.redirectsTiming = redirects.timings;
detail.redirects = redirects.redirects;
}
if (data.error && typeof data.error !== 'function') {
detail.isError = true;
detail.error = data.error;
} else {
const stats = this._cleanTimings(data.stats);
detail.isError = false;
detail.response = data;
detail.sentHttpMessage = data.sentHttpMessage;
detail.loadingTime = this._computeLoadingTime(stats);
detail.timing = stats;
detail.auth = data.auth;
delete detail.response.sentHttpMessage;
delete detail.request.sentHttpMessage;
}
detail.id = id;
this._beforeResponse(detail);
}
/**
* Processes redirects data from the socket library.
* @param {Set} set A set of redirects
* @return {Object} Map of arrays of timings and redirects information.
*/
_processRedirects(set) {
const result = {
timings: [],
redirects: []
};
if (!set) {
return result;
}
set.forEach((item) => {
result.redirects.push(item);
result.timings.push(item.stats);
delete item.stats;
});
return result;
}
/**
* Computes a request / response loading time from the stats object
* @param {Objject} stats A stats property of the socket client response.
* @return {Number} A time to full response in miliseconds. 0 if stats unavailable.
*/
_computeLoadingTime(stats) {
if (!stats) {
return 0;
}
let value = 0;
if (stats.dns && stats.dns > 0) {
value += stats.dns;
}
if (stats.connect && stats.connect > 0) {
value += stats.connect;
}
if (stats.receive && stats.receive > 0) {
value += stats.receive;
}
if (stats.send && stats.send > 0) {
value += stats.send;
}
if (stats.ssl && stats.ssl > 0) {
value += stats.ssl;
}
if (stats.wait && stats.wait > 0) {
value += stats.wait;
}
return value;
}
/**
* Creates HAR 1.2 object from timing data
* @param {Object} stats
* @return {Object}
*/
_cleanTimings(stats) {
const result = {
dns: stats.dns || -1,
connect: stats.connect || -1,
receive: stats.receive || -1,
send: stats.send || -1,
ssl: stats.ssl || -1,
wait: stats.wait || -1
};
return result;
}
/**
* Dispatches `response-ready` event with request data.
* If the event is not caneled then it dispatches `report-response`
* event.
*
* @param {Object} detail The request detail
*/
_beforeResponse(detail) {
const e = new CustomEvent('response-ready', {
composed: true,
bubbles: true,
cancelable: true,
detail
});
this.dispatchEvent(e);
if (e.defaultPrevented) {
return;
}
this._reportResponse(e.detail);
}
/**
* Fires the `report-response` custom event with immutable response data.
* @param {Object} detail The event detail object.
*/
_reportResponse(detail) {
detail = this._prepareTransportObject(detail);
const e = new CustomEvent('report-response', {
composed: true,
bubbles: true,
cancelable: false,
detail
});
this.dispatchEvent(e);
}
/**
* Creates an immutable `detail` object for the `report-response` custom
* event.
* @param {Object} detail
* @return {Object} Immutable object.
*/
_prepareTransportObject(detail) {
const configuration = {};
Object.keys(detail).forEach((key) => {
configuration[key] = {
value: detail[key],
writable: false,
enumerable: true
};
});
return Object.create(Object.prototype, configuration);
}
/**
* Updates a rule from the `host-rules-changed` custom event.
* The event should contain `rule` property on the event's detail object
* containing the rule object.
* @param {CustomEvent} e
*/
_ruleUpdated(e) {
if (e.cancelable || !this.hosts) {
// Don't update rules if there's no local hosts array. Let the component
// ask for all rules first.
return;
}
const updatedValue = e.detail.rule;
const index = this.hosts.findIndex((item) => item._id === updatedValue._id);
if (index === -1) {
this.hosts.push(updatedValue);
} else {
this.hosts[index] = updatedValue;
}
}
/**
* Deletes the rule from the `host-rules-deleted` custom event.
* The event should contain `rule` property on the event's detail object
* containing the rule object.
*
* @param {CustomEvent} e
*/
_ruleDeleted(e) {
if (e.cancelable) {
return;
}
if (!this.hosts || !this.hosts.length) {
return;
}
const id = e.detail.id;
const index = this.hosts.findIndex((item) => item._id === id);
if (index === -1) {
return;
}
this.hosts.splice(index, 1);
}
}
window.customElements.define('electron-http-transport', ElectronHttpTransport);