ludus-repl/listener.ts

77 lines
2.1 KiB
TypeScript
Raw Permalink Normal View History

import { run } from "@ludus/ludus-js-pure"
import { unlinkSync, readFileSync } from "node:fs"
2023-12-29 00:32:10 +00:00
function random_port () {
return Math.floor(Math.random() * 10000)
}
export async function listen () {
2023-12-29 00:32:10 +00:00
let id = random_port()
let unix_socket = `/tmp/ludus-${id}.sock`
// make sure the socket path isn't already taken
while (await Bun.file(unix_socket).exists()) {
id = random_port()
unix_socket = `/tmp/ludus-${id}.sock`
}
const repl_file_path = ".lrepl"
2023-12-27 17:07:24 +00:00
const repl_info = { unix_socket }
const repl_file = Bun.file(repl_file_path)
2023-12-26 22:54:34 +00:00
await Bun.write(repl_file, JSON.stringify(repl_info))
2023-12-29 00:29:04 +00:00
console.log(`Ludus REPL listening on unix://${unix_socket}`)
2023-12-26 22:54:34 +00:00
Bun.listen({
2023-12-27 17:07:24 +00:00
//hostname: "localhost",
//port,
unix: unix_socket,
2023-12-26 22:54:34 +00:00
socket: {
2023-12-27 17:07:24 +00:00
open: (_) => {console.log("=== === ===") },
data: (_, data) => {
2023-12-27 17:07:24 +00:00
const source = data.toString("utf-8")
const result = run(source)
if (!result.errors) console.log("=>", result.result)
2023-12-26 22:54:34 +00:00
else {
console.log("Ludus had some errors:")
console.log(result.errors)
}
},
error: (socket, error) => { console.log(error); socket.end() }
}
})
process.on("exit", async function () {
2023-12-27 17:07:24 +00:00
try { cleanup(repl_file_path, unix_socket) } catch (e) {}
console.log("\nGoodbye.")
})
process.on("SIGINT", () => process.exit())
// Below here, I'm trying to get ctrl-d to work to close the listener
// the while (true) loop locks the listener
// see: https://github.com/oven-sh/bun/issues/3255
// this should be doable with process.stdin.on("close"...)
//const mystdin = Bun.file("/dev/stdin").stream().getReader()
// while (true) {
// const {done, value} = await mystdin.read()
// if (done) process.exit()
// console.log(value)
// }
}
// Don't delete an .lrepl we don't own
2023-12-27 17:07:24 +00:00
function cleanup (path: string, my_socket: string) {
const repl_file = readFileSync(path).toString("utf-8")
2023-12-27 17:07:24 +00:00
let their_socket
try { their_socket = JSON.parse(repl_file).unix_socket } catch (e) { return }
if (their_socket === my_socket) {
unlinkSync(path)
unlinkSync(my_socket)
}
}
2023-12-27 17:07:24 +00:00
// await listen()