File size: 5,545 Bytes
84c1942 | 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 | import { EventEmitter } from 'events';
import { commonPostMessage } from '@codesandbox/common/lib/utils/global';
import { protocolAndHost } from '@codesandbox/common/lib/utils/url-generator';
const SOCKET_IDENTIFIER = 'node-socket';
export class Socket extends EventEmitter {
public destroyed = false;
// @ts-ignore
private encoding: string;
constructor(
private target: Window | MessageEventSource,
private channel: string,
private isWorker: boolean
) {
super();
this.emit('connect');
this.startListening();
}
setEncoding(encoding: string) {
this.encoding = encoding;
}
defaultListener(e: Event) {
const evt = e as MessageEvent;
if ((evt.source || self) !== this.target) {
return;
}
const data = evt.data.$data;
if (!data) {
return;
}
if (data.$type === SOCKET_IDENTIFIER && data.$channel === this.channel) {
this.emit('data', Buffer.from(JSON.parse(data.data)));
}
}
startListening() {
self.addEventListener('message', this.defaultListener.bind(this));
}
end() {
self.removeEventListener('message', this.defaultListener.bind(this));
this.destroyed = true;
// @ts-ignore
if (typeof this.target.terminate !== 'undefined') {
// @ts-ignore
this.target.terminate();
}
}
unref() {}
write(buffer: Buffer) {
if (this.destroyed) {
return;
}
const message = {
$type: SOCKET_IDENTIFIER,
$channel: this.channel,
data: JSON.stringify(buffer),
};
if (this.isWorker) {
((this.target as unknown) as Worker).postMessage(message);
} else {
(this.target as Window).postMessage(message, protocolAndHost());
}
}
}
export class Server extends EventEmitter {
public connected = false;
public closed = false;
private socket: Socket | null = null;
private listenerFunctions: Array<(e: MessageEvent) => void> = [];
listen(listenPath: string, listenCallback?: Function) {
const listenerFunction = (e: MessageEvent) => {
const data = e.data.$data || e.data;
if (this.closed) {
return;
}
if (
data.$type === 'node-server' &&
data.$channel === listenPath &&
data.$event === 'init'
) {
this.connected = true;
this.socket = new Socket(e.source || self, listenPath, false);
this.emit('connection', this.socket);
}
};
this.listenerFunctions.push(listenerFunction);
self.addEventListener('message', listenerFunction as EventListener);
if (listenCallback) {
listenCallback();
}
}
close(cb?: Function) {
this.closed = true;
this.removeAllListeners();
// This is not according to spec, but we do this anyways for clean cleanup
this.listenerFunctions.forEach(func => {
self.removeEventListener('message', func);
});
if (cb) {
cb();
}
}
}
function blobToBuffer(
blob: Blob,
cb: (err: any | undefined | null, result?: Buffer) => void
) {
if (typeof Blob === 'undefined' || !(blob instanceof Blob)) {
throw new Error('first argument must be a Blob');
}
if (typeof cb !== 'function') {
throw new Error('second argument must be a function');
}
const reader = new FileReader();
function onLoadEnd(e: any) {
reader.removeEventListener('loadend', onLoadEnd, false);
if (e.error) {
cb(e.error);
} else {
// @ts-ignore
cb(null, Buffer.from(reader.result));
}
}
reader.addEventListener('loadend', onLoadEnd, false);
reader.readAsArrayBuffer(blob);
}
export class WebSocketServer extends EventEmitter {
public connected = false;
public closed = false;
private socket: WebSocket | null = null;
private listenerFunctions: Array<(e: MessageEvent) => void> = [];
constructor(public url: string) {
super();
}
listen(listenPath: string, listenCallback?: Function) {
this.socket = new WebSocket(this.url);
this.socket.onmessage = message => {
blobToBuffer(message.data, (err, r) => {
this.emit('data', r);
});
};
this.socket.onclose = () => {
this.emit('close');
};
if (listenCallback) {
listenCallback();
}
this.socket.onopen = () => {
this.connected = true;
this.emit('connection', this);
};
}
public write(buffer: Buffer) {
this.socket!.send(buffer);
}
public end() {
this.socket!.close();
}
close(cb?: Function) {
this.closed = true;
this.removeAllListeners();
// This is not according to spec, but we do this anyways for clean cleanup
this.listenerFunctions.forEach(func => {
self.removeEventListener('message', func);
});
if (cb) {
cb();
}
}
}
let socketUrl: string = '';
function setSocketURL(url: string) {
socketUrl = url;
}
function createServerWS() {
return new WebSocketServer(socketUrl);
}
function createServerLocal() {
return new Server();
}
function createServer(...args: any[]) {
if (socketUrl) {
return createServerWS();
} else {
return createServerLocal();
}
}
function createConnection(pipeName: string, cb?: Function) {
commonPostMessage({
$type: 'node-server',
$channel: pipeName,
$event: 'init',
});
const socket = new Socket(self, pipeName, true);
setTimeout(() => {
if (cb) {
cb();
}
}, 0);
// TODO: Fix this to initialize properly
return socket;
}
const connect = createConnection;
export { setSocketURL, createServer, createConnection, connect };
|