|
| 1 | +import { Server, type ServerOptions } from "@blink-sdk/compute-protocol/server"; |
| 2 | +import { Emitter } from "@blink-sdk/events"; |
| 3 | +import fs from "node:fs"; |
| 4 | +import os from "node:os"; |
| 5 | +import path from "node:path"; |
| 6 | +import { WebSocketServer } from "ws"; |
| 7 | + |
| 8 | +const defaultEnvVariables = { |
| 9 | + // These are so Blink can use commits to GitHub properly. |
| 10 | + GIT_TERMINAL_PROMPT: "0", |
| 11 | + GIT_PAGER: "cat", |
| 12 | + GIT_AUTHOR_NAME: "blink-so[bot]", |
| 13 | + GIT_AUTHOR_EMAIL: "211532188+blink-so[bot]@users.noreply.github.com", |
| 14 | + GIT_COMMITTER_NAME: "blink-so[bot]", |
| 15 | + GIT_COMMITTER_EMAIL: "211532188+blink-so[bot]@users.noreply.github.com", |
| 16 | + |
| 17 | + // The `gh` CLI is required to be in the workspace. |
| 18 | + // Eventually, we should move this credential helper to just be in the Blink CLI. |
| 19 | + GIT_CONFIG_COUNT: "1", |
| 20 | + GIT_CONFIG_KEY_0: "credential.https://github.com.helper", |
| 21 | + GIT_CONFIG_VALUE_0: "!gh auth git-credential", |
| 22 | +}; |
| 23 | + |
| 24 | +export default async function serveCompute() { |
| 25 | + for (const [key, value] of Object.entries(defaultEnvVariables)) { |
| 26 | + if (process.env[key] === undefined) { |
| 27 | + process.env[key] = value; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + const port = parseInt(process.env.PORT ?? "22137"); |
| 32 | + if (isNaN(port)) { |
| 33 | + throw new Error("PORT environment variable is not a number"); |
| 34 | + } |
| 35 | + |
| 36 | + const wss = new WebSocketServer({ port }); |
| 37 | + |
| 38 | + console.log(`Compute server running on port ${port}`); |
| 39 | + |
| 40 | + wss.on("connection", (ws) => { |
| 41 | + console.log("Client connected"); |
| 42 | + |
| 43 | + let nodePty: typeof import("@lydell/node-pty") | undefined; |
| 44 | + try { |
| 45 | + nodePty = require("@lydell/node-pty"); |
| 46 | + } catch (e) { |
| 47 | + // It's fine, we don't _need_ to use TTYs. |
| 48 | + } |
| 49 | + if (typeof Bun !== "undefined") { |
| 50 | + nodePty = undefined; |
| 51 | + } |
| 52 | + |
| 53 | + const server = new Server({ |
| 54 | + nodePty, |
| 55 | + send: (message: Uint8Array) => { |
| 56 | + // Send binary data to the WebSocket client |
| 57 | + ws.send(message); |
| 58 | + }, |
| 59 | + }); |
| 60 | + |
| 61 | + ws.on("message", (data: Buffer) => { |
| 62 | + // Forward WebSocket messages to the server |
| 63 | + server.handleMessage(new Uint8Array(data)); |
| 64 | + }); |
| 65 | + |
| 66 | + ws.on("close", () => { |
| 67 | + console.log("Client disconnected"); |
| 68 | + }); |
| 69 | + }); |
| 70 | +} |
0 commit comments