42 lines
813 B
JavaScript
42 lines
813 B
JavaScript
'use strict';
|
|
const tls = require('tls');
|
|
|
|
module.exports = (options = {}, connect = tls.connect) => new Promise((resolve, reject) => {
|
|
let timeout = false;
|
|
|
|
let socket;
|
|
|
|
const callback = async () => {
|
|
socket.off('timeout', onTimeout);
|
|
socket.off('error', reject);
|
|
|
|
if (options.resolveSocket) {
|
|
resolve({alpnProtocol: socket.alpnProtocol, socket, timeout});
|
|
|
|
if (timeout) {
|
|
await Promise.resolve();
|
|
socket.emit('timeout');
|
|
}
|
|
} else {
|
|
socket.destroy();
|
|
resolve({alpnProtocol: socket.alpnProtocol, timeout});
|
|
}
|
|
};
|
|
|
|
const onTimeout = async () => {
|
|
timeout = true;
|
|
callback();
|
|
};
|
|
|
|
(async () => {
|
|
try {
|
|
socket = await connect(options, callback);
|
|
|
|
socket.on('error', reject);
|
|
socket.once('timeout', onTimeout);
|
|
} catch (error) {
|
|
reject(error);
|
|
}
|
|
})();
|
|
});
|