opencode/packages/cli-rs/script/gen/js-host.ts
Simon Klee 6b1df0cceb
feat(cli-rs): add the native CLI and TUI (#63477)
Add packages/cli-rs, an OpenCode client written in Rust on OpenTUI's Rust crates. It is a client only.
2026-11-22 00:07:01 +01:00

115 lines
5.4 KiB
TypeScript

// Bundles the JS plugin compatibility layer and the client-side Solid runtime it serves.
import path from "node:path"
const root = new URL("../..", import.meta.url).pathname
const compat = path.join(root, "crates/plugin/src/pipe/compat")
await Bun.write(path.join(compat, "opentui.gen.ts"), await opentui())
await Bun.write(path.join(compat, "events.gen.ts"), await events())
const solid = path.dirname(Bun.resolveSync("solid-js/package.json", compat))
// Solid's client build, not the server one the `bun` condition picks: plugins render with it.
const builds: Record<string, string> = {
"solid-js": path.join(solid, "dist/solid.js"),
"solid-js/store": path.join(solid, "store/dist/store.js"),
"solid-js/universal": path.join(solid, "universal/dist/universal.js"),
}
const result = await Bun.build({
entrypoints: [path.join(compat, "index.ts")],
target: "bun",
format: "esm",
minify: true,
plugins: [
{
name: "solid-client",
setup(build) {
build.onResolve({ filter: /^solid-js(\/store|\/universal)?$/ }, (args) => ({ path: builds[args.path]! }))
},
},
],
})
if (!result.success) {
for (const log of result.logs) console.error(log)
process.exit(1)
}
const text = await result.outputs[0]!.text()
const file = path.join(root, "crates/plugin/src/pipe/compat.js")
await Bun.write(file, `// Generated by script/gen/js-host.ts from crates/plugin/src/pipe/compat; do not edit.\n${text}`)
console.log(`js-host: compat.js ${(text.length / 1024).toFixed(0)} KiB`)
async function opentui() {
const listed = async (name: string) => {
const module = await import(Bun.resolveSync(name, compat))
const names = Object.keys(module).sort()
// A value crosses as data when it is plain (JSON with nothing dropped) and small; the others are names.
const values = Object.fromEntries(
names.flatMap((key) => {
const value = module[key]
if (typeof value === "function" || value === undefined) return []
// Some exports are proxies that throw on a key they do not know (`env`): they are names.
const json = (() => {
try {
return plain(value) ? JSON.stringify(value) : undefined
} catch {
return undefined
}
})()
if (json === undefined || json.length > 2048) return []
return [[key, value]]
}),
)
return { names: names.filter((key) => !(key in values)), values }
}
const core = await listed("@opentui/core")
const module = await import(Bun.resolveSync("@opentui/core", compat))
const filetypes = { extensions: [...module.extensionToFiletype], basenames: [...module.basenameToFiletype] }
const solid = await listed("@opentui/solid")
const { CliRenderer } = await import(Bun.resolveSync("@opentui/core", compat))
const methods = new Set<string>()
for (let at = CliRenderer.prototype; at && at !== Object.prototype; at = Object.getPrototypeOf(at)) {
for (const key of Object.getOwnPropertyNames(at)) {
const descriptor = Object.getOwnPropertyDescriptor(at, key)!
if (key !== "constructor" && typeof descriptor.value === "function") methods.add(key)
}
}
// The methods its declarations say return a promise, which a stand-in answers with a resolved one.
const declared = await Bun.file(path.join(path.dirname(Bun.resolveSync("@opentui/core", compat)), "renderer.d.ts")).text()
const promised = [...declared.matchAll(/^\s+(\w+)\(.*\): Promise</gm)].map((match) => match[1]!)
// Inert implementations of async methods must still return a promise.
const root = path.dirname(Bun.resolveSync("@opentui/core", compat))
const promises = new Set<string>()
for await (const file of new Bun.Glob("**/*.d.ts").scan({ cwd: root }))
for (const match of (await Bun.file(path.join(root, file)).text()).matchAll(/^\s+(\w+)\(.*\): Promise</gm))
promises.add(match[1]!)
const header =
"// Generated by script/gen/js-host.ts from the installed @opentui/core and @opentui/solid; do not edit.\n"
const line = (name: string, value: unknown) => `export const ${name} = ${JSON.stringify(value)}\n`
return (
header +
line("core", core) +
line("solid", solid) +
line("rendererMethods", [...methods].sort()) +
line("rendererPromises", promised.filter((name) => methods.has(name)).sort()) +
line("promises", [...promises].sort()) +
line("filetypes", filetypes)
)
}
// The event types a client may subscribe to (`EventSubscribeInput.types` of the generated client), which `data.listen`
// hears all of.
async function events() {
const types = await Bun.file(path.join(root, "../client/src/promise/generated/types.ts")).text()
const start = types.indexOf("export type EventSubscribeInput")
const union = types.slice(start, types.indexOf("export type", start + 1))
const names = [...union.matchAll(/\| "([a-z0-9.-]+)"/g)].map((match) => match[1]!)
if (!names.length) throw new Error("no event types in EventSubscribeInput")
return (
"// Generated by script/gen/js-host.ts from the generated client's EventSubscribeInput; do not edit.\n" +
`export const eventTypes = ${JSON.stringify(names)}\n`
)
}
function plain(value: unknown): boolean {
if (value === null || ["string", "number", "boolean"].includes(typeof value)) return true
if (Array.isArray(value)) return value.every(plain)
if (typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) return false
return Object.values(value as object).every(plain)
}