2019-01-16 01:36:09 +07:00
|
|
|
import { ReadWriteConnection } from "@coder/protocol";
|
|
|
|
import { Server, ServerOptions } from "@coder/protocol/src/node/server";
|
|
|
|
import * as express from "express";
|
|
|
|
import * as http from "http";
|
|
|
|
import * as ws from "ws";
|
2019-01-19 04:46:40 +07:00
|
|
|
import * as url from "url";
|
|
|
|
import { ClientMessage, SharedProcessInitMessage } from '@coder/protocol/src/proto';
|
2019-01-16 01:36:09 +07:00
|
|
|
|
|
|
|
export const createApp = (registerMiddleware?: (app: express.Application) => void, options?: ServerOptions): {
|
|
|
|
readonly express: express.Application;
|
|
|
|
readonly server: http.Server;
|
|
|
|
readonly wss: ws.Server;
|
2019-01-19 04:46:40 +07:00
|
|
|
} => {
|
2019-01-16 01:36:09 +07:00
|
|
|
const app = express();
|
|
|
|
if (registerMiddleware) {
|
|
|
|
registerMiddleware(app);
|
|
|
|
}
|
|
|
|
const server = http.createServer(app);
|
|
|
|
const wss = new ws.Server({ server });
|
2019-01-19 04:46:40 +07:00
|
|
|
|
|
|
|
wss.shouldHandle = (req): boolean => {
|
|
|
|
if (typeof req.url === "undefined") {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
const parsedUrl = url.parse(req.url, true);
|
|
|
|
const sharedProcessInit = parsedUrl.query["shared_process_init"];
|
|
|
|
if (typeof sharedProcessInit === "undefined" || Array.isArray(sharedProcessInit)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
const msg = ClientMessage.deserializeBinary(Buffer.from(sharedProcessInit, "base64"));
|
|
|
|
if (!msg.hasSharedProcessInit()) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
const spm = msg.getSharedProcessInit()!;
|
|
|
|
(<any>req).sharedProcessInit = spm;
|
|
|
|
} catch (ex) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
|
|
|
|
wss.on("connection", (ws: WebSocket, req) => {
|
|
|
|
const spm = (<any>req).sharedProcessInit as SharedProcessInitMessage;
|
|
|
|
if (!spm) {
|
|
|
|
ws.close();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-01-16 01:36:09 +07:00
|
|
|
const connection: ReadWriteConnection = {
|
2019-01-19 04:46:40 +07:00
|
|
|
onMessage: (cb): void => {
|
2019-01-16 01:36:09 +07:00
|
|
|
ws.addEventListener("message", (event) => cb(event.data));
|
|
|
|
},
|
2019-01-19 04:46:40 +07:00
|
|
|
close: (): void => ws.close(),
|
|
|
|
send: (data): void => ws.send(data),
|
|
|
|
onClose: (cb): void => ws.addEventListener("close", () => cb()),
|
2019-01-16 01:36:09 +07:00
|
|
|
};
|
2019-01-19 04:46:40 +07:00
|
|
|
|
2019-01-16 01:36:09 +07:00
|
|
|
const server = new Server(connection, options);
|
|
|
|
});
|
|
|
|
|
|
|
|
/**
|
2019-01-19 04:46:40 +07:00
|
|
|
* We should static-serve the `web` package at this point.
|
2019-01-16 01:36:09 +07:00
|
|
|
*/
|
|
|
|
app.get("/", (req, res, next) => {
|
|
|
|
res.write("Example! :)");
|
|
|
|
res.status(200);
|
|
|
|
res.end();
|
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
|
|
|
express: app,
|
|
|
|
server,
|
|
|
|
wss,
|
|
|
|
};
|
|
|
|
};
|