2
0

build.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. #!/usr/bin/env bun
  2. import solidPlugin from "./solid-plugin"
  3. import path from "path"
  4. import { $ } from "bun"
  5. import { fileURLToPath } from "url"
  6. import { createRequire } from "module"
  7. const __filename = fileURLToPath(import.meta.url)
  8. const __dirname = path.dirname(__filename)
  9. const require = createRequire(import.meta.url)
  10. const dir = path.resolve(__dirname, "..")
  11. process.chdir(dir)
  12. import pkg from "../package.json"
  13. import { Script } from "@opencode-ai/script"
  14. import fs from "fs/promises"
  15. import nodefs from "fs"
  16. await $`bun run build:webgui`
  17. const webGuiDir = path.join(dir, "webgui-dist")
  18. const embedOutput = path.join(dir, "src/webgui/embed.generated.ts")
  19. async function listWebGuiFiles(current: string) {
  20. const entries = await fs.readdir(current, { withFileTypes: true })
  21. const files: { path: string; data: string }[] = []
  22. for (const entry of entries) {
  23. const absolute = path.join(current, entry.name)
  24. if (entry.isDirectory()) {
  25. const nested = await listWebGuiFiles(absolute)
  26. files.push(...nested)
  27. continue
  28. }
  29. const relative = path.relative(webGuiDir, absolute).split(path.sep).join("/")
  30. const file = Bun.file(absolute)
  31. const buffer = Buffer.from(await file.arrayBuffer())
  32. files.push({ path: relative, data: buffer.toString("base64") })
  33. }
  34. return files
  35. }
  36. async function generateEmbeddedWebGui() {
  37. const indexFile = Bun.file(path.join(webGuiDir, "index.html"))
  38. if (!(await indexFile.exists())) {
  39. await Bun.write(embedOutput, "export const embeddedWebGui = [] as const\n")
  40. return
  41. }
  42. const items = await listWebGuiFiles(webGuiDir)
  43. const lines = [
  44. "export const embeddedWebGui = [",
  45. ...items.map((item) => ` { path: ${JSON.stringify(item.path)}, data: ${JSON.stringify(item.data)} },`),
  46. "] as const",
  47. "",
  48. ]
  49. await Bun.write(embedOutput, lines.join("\n"))
  50. }
  51. await generateEmbeddedWebGui()
  52. const modelsUrl = process.env.OPENCODE_MODELS_URL || "https://models.dev"
  53. // Fetch and generate models.dev snapshot
  54. const modelsData = process.env.MODELS_DEV_API_JSON
  55. ? await Bun.file(process.env.MODELS_DEV_API_JSON).text()
  56. : await fetch(`${modelsUrl}/api.json`).then((x) => x.text())
  57. await Bun.write(
  58. path.join(dir, "src/provider/models-snapshot.ts"),
  59. `// Auto-generated by build.ts - do not edit\nexport const snapshot = ${modelsData} as const\n`,
  60. )
  61. console.log("Generated models-snapshot.ts")
  62. const singleFlag = process.argv.includes("--single")
  63. const baselineFlag = process.argv.includes("--baseline")
  64. const skipInstall = process.argv.includes("--skip-install")
  65. const allTargets: {
  66. os: string
  67. arch: "arm64" | "x64"
  68. abi?: "musl"
  69. avx2?: false
  70. }[] = [
  71. {
  72. os: "linux",
  73. arch: "arm64",
  74. },
  75. {
  76. os: "linux",
  77. arch: "x64",
  78. },
  79. {
  80. os: "darwin",
  81. arch: "arm64",
  82. },
  83. {
  84. os: "darwin",
  85. arch: "x64",
  86. },
  87. {
  88. os: "win32",
  89. arch: "x64",
  90. },
  91. ]
  92. const targets = singleFlag
  93. ? allTargets.filter((item) => {
  94. if (item.os !== process.platform || item.arch !== process.arch) {
  95. return false
  96. }
  97. // When building for the current platform, prefer a single native binary by default.
  98. // Baseline binaries require additional Bun artifacts and can be flaky to download.
  99. if (item.avx2 === false) {
  100. return baselineFlag
  101. }
  102. // also skip abi-specific builds for the same reason
  103. if (item.abi !== undefined) {
  104. return false
  105. }
  106. return true
  107. })
  108. : allTargets
  109. await fs.rm("dist", { recursive: true, force: true })
  110. const binaries: Record<string, string> = {}
  111. if (!skipInstall) {
  112. await $`bun install --os="*" --cpu="*" @opentui/core@${pkg.dependencies["@opentui/core"]}`
  113. await $`bun install --os="*" --cpu="*" @parcel/watcher@${pkg.dependencies["@parcel/watcher"]}`
  114. }
  115. for (const item of targets) {
  116. const name = [
  117. pkg.name,
  118. // changing to win32 flags npm for some reason
  119. item.os === "win32" ? "windows" : item.os,
  120. item.arch,
  121. item.avx2 === false ? "baseline" : undefined,
  122. item.abi === undefined ? undefined : item.abi,
  123. ]
  124. .filter(Boolean)
  125. .join("-")
  126. console.log(`building ${name}`)
  127. await fs.mkdir(`dist/${name}/bin`, { recursive: true })
  128. const opentuiCoreEntry = require.resolve("@opentui/core")
  129. const parserWorker = nodefs.realpathSync(path.join(path.dirname(opentuiCoreEntry), "parser.worker.js"))
  130. const workerPath = "./src/cli/cmd/tui/worker.ts"
  131. // Use platform-specific bunfs root path based on target OS
  132. const bunfsRoot = item.os === "win32" ? "B:/~BUN/root/" : "/$bunfs/root/"
  133. const workerRelativePath = path.relative(dir, parserWorker).replaceAll("\\", "/")
  134. await Bun.build({
  135. conditions: ["browser"],
  136. tsconfig: "./tsconfig.json",
  137. plugins: [solidPlugin],
  138. sourcemap: "external",
  139. compile: {
  140. autoloadBunfig: false,
  141. autoloadDotenv: false,
  142. //@ts-ignore (bun types aren't up to date)
  143. autoloadTsconfig: true,
  144. autoloadPackageJson: true,
  145. target: name.replace(pkg.name, "bun") as any,
  146. outfile: `dist/${name}/bin/opencode`,
  147. execArgv: [`--user-agent=opencode/${Script.version}`, "--use-system-ca", "--"],
  148. windows: {},
  149. },
  150. entrypoints: ["./src/index.ts", parserWorker, workerPath],
  151. define: {
  152. OPENCODE_VERSION: `'${Script.version}'`,
  153. OTUI_TREE_SITTER_WORKER_PATH: bunfsRoot + workerRelativePath,
  154. OPENCODE_WORKER_PATH: workerPath,
  155. OPENCODE_CHANNEL: `'${Script.channel}'`,
  156. OPENCODE_LIBC: item.os === "linux" ? `'${item.abi ?? "glibc"}'` : "",
  157. },
  158. })
  159. await fs.rm(`./dist/${name}/bin/tui`, { recursive: true, force: true })
  160. await Bun.file(`dist/${name}/package.json`).write(
  161. JSON.stringify(
  162. {
  163. name,
  164. version: Script.version,
  165. os: [item.os],
  166. cpu: [item.arch],
  167. },
  168. null,
  169. 2,
  170. ),
  171. )
  172. binaries[name] = Script.version
  173. }
  174. if (Script.release) {
  175. for (const key of Object.keys(binaries)) {
  176. if (key.includes("linux")) {
  177. await $`tar -czf ../../${key}.tar.gz *`.cwd(`dist/${key}/bin`)
  178. } else {
  179. await $`zip -r ../../${key}.zip *`.cwd(`dist/${key}/bin`)
  180. }
  181. }
  182. await $`gh release upload v${Script.version} ./dist/*.zip ./dist/*.tar.gz --clobber`
  183. }
  184. export { binaries }