libhyperproxy/dist/peer.js

74 lines
2.4 KiB
JavaScript
Raw Normal View History

2023-01-12 17:50:38 +00:00
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const socket_js_1 = __importDefault(require("./socket.js"));
2023-02-06 10:51:41 +00:00
const buffer_1 = require("buffer");
2023-01-12 17:50:38 +00:00
class Peer {
_proxy;
_peer;
_muxer;
_socket;
_onopen;
_onreceive;
_onsend;
_onclose;
constructor({ proxy, peer, muxer, onopen, onreceive, onsend, onclose, }) {
this._proxy = proxy;
this._peer = peer;
this._muxer = muxer;
this._onopen = onopen;
this._onreceive = onreceive;
this._onsend = onsend;
this._onclose = onclose;
}
async init() {
const write = async (data, cb) => {
pipe.send(data);
await this._onsend?.(data);
cb();
};
const self = this;
const channel = this._muxer.createChannel({
protocol: this._proxy.protocol,
async onopen(m) {
if (!m) {
2023-02-06 10:51:41 +00:00
m = buffer_1.Buffer.from([]);
}
if (m instanceof Uint8Array) {
m = buffer_1.Buffer.from(m);
2023-01-12 17:50:38 +00:00
}
self._socket = new socket_js_1.default({
remoteAddress: self._peer.rawStream.remoteHost,
remotePort: self._peer.rawStream.remotePort,
2023-02-25 04:14:57 +00:00
remotePublicKey: self._peer.remotePublicKey,
2023-01-12 17:50:38 +00:00
write,
});
self._socket.on("end", () => channel.close());
let ret = await self._onopen?.(self._socket, m);
if (!ret || (ret && ret.connect === false)) {
// @ts-ignore
self._socket.emit("connect");
}
self._socket.emit("data", m);
},
async onclose() {
2023-02-16 06:02:20 +00:00
self._socket?.destroy();
2023-01-12 17:50:38 +00:00
await self._onclose?.(self._socket);
},
});
const pipe = channel.addMessage({
async onmessage(m) {
2023-02-06 10:51:41 +00:00
if (m instanceof Uint8Array) {
m = buffer_1.Buffer.from(m);
}
2023-01-12 17:50:38 +00:00
self._socket.emit("data", m);
await self._onreceive?.(m);
},
});
await channel.open();
}
}
exports.default = Peer;