vite.node.config.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import path from "node:path"
  2. import { readFile } from "node:fs/promises"
  3. import { createRequire } from "node:module"
  4. import { defineConfig, type Plugin, type UserConfig } from "vite"
  5. import solid from "vite-plugin-solid"
  6. import { nodeExecArgv, nodeTarget, type NodeTarget, photonWasmAsset, shellParserWasmAssets } from "./src/node/target"
  7. const dir = import.meta.dirname
  8. function rawTextPlugin(): Plugin {
  9. return {
  10. name: "opencode:raw-text",
  11. async load(id) {
  12. if (!id.endsWith(".md")) return
  13. return `export default ${JSON.stringify(await readFile(id, "utf8"))}`
  14. },
  15. }
  16. }
  17. function runtimeRequirePlugin(): Plugin {
  18. return {
  19. name: "opencode:runtime-require",
  20. enforce: "pre",
  21. transform(code, id) {
  22. if (!id.endsWith("turndown/lib/turndown.es.js")) return
  23. const transformed = code.replace(" var domino = require('@mixmark-io/domino');", "")
  24. if (transformed === code) this.error("Failed to rewrite Turndown's Domino require")
  25. return `import domino from "@mixmark-io/domino"\n${transformed}`
  26. },
  27. }
  28. }
  29. function fffNodePlugin(): Plugin {
  30. return {
  31. name: "opencode:fff-node",
  32. enforce: "pre",
  33. transform(code, id) {
  34. const normalized = id.replaceAll("\\", "/")
  35. if (normalized.endsWith("/ffi-rs/index.js")) {
  36. const start = code.indexOf("if (!nativeBinding) {")
  37. if (start === -1) this.error("Failed to rewrite ffi-rs native binding loader")
  38. return `const unavailable = () => { throw new Error("ffi-rs native binding unavailable") }
  39. const nativeBinding = globalThis.__OPENCODE_FFF_FFI ?? {
  40. DataType: new Proxy({}, { get: (target, key) => target[key] ?? key }),
  41. PointerType: {},
  42. FFITypeTag: {},
  43. open: unavailable,
  44. close: unavailable,
  45. load: unavailable,
  46. isNullPointer: unavailable,
  47. createPointer: unavailable,
  48. restorePointer: unavailable,
  49. unwrapPointer: unavailable,
  50. wrapPointer: unavailable,
  51. freePointer: unavailable,
  52. }
  53. const loadError = undefined
  54. ${code.slice(start)}`
  55. }
  56. if (!normalized.endsWith("/fff-node/dist/src/binary.js")) return
  57. const transformed = code.replace(
  58. "export function findBinary() {",
  59. "export function findBinary() { if (process.env.FFF_BINARY_PATH) return process.env.FFF_BINARY_PATH;",
  60. )
  61. if (transformed === code) this.error("Failed to rewrite FFF binary loader")
  62. return transformed
  63. },
  64. }
  65. }
  66. const resolve = {
  67. alias: [
  68. { find: /^solid-js\/store$/, replacement: "solid-js/store/dist/store.js" },
  69. { find: /^solid-js$/, replacement: "solid-js/dist/solid.js" },
  70. {
  71. find: /^ws$/,
  72. replacement: path.join(path.dirname(createRequire(import.meta.url).resolve("ws/package.json")), "wrapper.mjs"),
  73. },
  74. ],
  75. conditions: ["node"],
  76. }
  77. const output = (entryFileNames: string, banner?: string) => ({
  78. format: "esm" as const,
  79. entryFileNames,
  80. inlineDynamicImports: true,
  81. banner,
  82. })
  83. function nodePrelude(input: NodeBuildInput) {
  84. const nodePtySpawnHelper =
  85. input.target.platform === "darwin"
  86. ? `${input.target.nodePtyPackage}/prebuilds/darwin-${input.target.arch}/spawn-helper`
  87. : undefined
  88. const promiseModule = `const sdk = globalThis[Symbol.for("opencode.plugin.v2.promise")]
  89. if (!sdk) throw new Error("OpenCode Promise plugin SDK is unavailable")
  90. export const Agent = sdk.Agent
  91. export const Command = sdk.Command
  92. export const Connection = sdk.Connection
  93. export const Credential = sdk.Credential
  94. export const Integration = sdk.Integration
  95. export const Model = sdk.Model
  96. export const Plugin = sdk.Plugin
  97. export const Provider = sdk.Provider
  98. export const Reference = sdk.Reference
  99. export const Skill = sdk.Skill`
  100. const effectModule = promiseModule
  101. .replace("opencode.plugin.v2.promise", "opencode.plugin.v2.effect")
  102. .replace("Promise plugin", "Effect plugin")
  103. const promisePluginModule = `const sdk = globalThis[Symbol.for("opencode.plugin.v2.promise")]
  104. if (!sdk) throw new Error("OpenCode Promise plugin SDK is unavailable")
  105. export const define = sdk.Plugin.define`
  106. const effectPluginModule = promisePluginModule
  107. .replace("opencode.plugin.v2.promise", "opencode.plugin.v2.effect")
  108. .replace("Promise plugin", "Effect plugin")
  109. const promiseToolModule = `export {}`
  110. const effectToolModule = `const sdk = globalThis[Symbol.for("opencode.plugin.v2.effect")]
  111. if (!sdk) throw new Error("OpenCode Effect plugin SDK is unavailable")
  112. export const Error = sdk.Tool.Error
  113. `
  114. return `#!/usr/bin/env -S node ${nodeExecArgv.join(" ")}
  115. import __cjs_mod__ from "node:module"
  116. import { chmodSync as __ocChmod, existsSync as __ocExists, lstatSync as __ocLstat, mkdirSync as __ocMkdir, renameSync as __ocRename, rmSync as __ocRm, writeFileSync as __ocWrite } from "node:fs"
  117. import { tmpdir as __ocTmpdir } from "node:os"
  118. import __ocPath from "node:path"
  119. import { getAssetKeys as __ocAssetKeys, getRawAsset as __ocRawAsset, isSea as __ocIsSea } from "node:sea"
  120. import { fileURLToPath as __ocFileURLToPath } from "node:url"
  121. const __filename = import.meta.filename
  122. const __dirname = import.meta.dirname
  123. const require = __cjs_mod__.createRequire(import.meta.url)
  124. const __ocPluginModules = ${JSON.stringify({
  125. "@opencode-ai/plugin": "opencode:plugin-v2",
  126. "@opencode-ai/plugin/promise/plugin": "opencode:plugin-promise-plugin",
  127. "@opencode-ai/plugin/promise/tool": "opencode:plugin-promise-tool",
  128. "@opencode-ai/plugin/effect": "opencode:plugin-v2-effect",
  129. "@opencode-ai/plugin/effect/plugin": "opencode:plugin-v2-effect-plugin",
  130. "@opencode-ai/plugin/effect/tool": "opencode:plugin-v2-effect-tool",
  131. })}
  132. const __ocPluginSources = ${JSON.stringify({
  133. "opencode:plugin-v2": promiseModule,
  134. "opencode:plugin-promise-plugin": promisePluginModule,
  135. "opencode:plugin-promise-tool": promiseToolModule,
  136. "opencode:plugin-v2-effect": effectModule,
  137. "opencode:plugin-v2-effect-plugin": effectPluginModule,
  138. "opencode:plugin-v2-effect-tool": effectToolModule,
  139. })}
  140. __cjs_mod__.registerHooks({
  141. resolve(__ocSpecifier, __ocContext, __ocNextResolve) {
  142. const __ocUrl = __ocPluginModules[__ocSpecifier]
  143. return __ocUrl ? { url: __ocUrl, shortCircuit: true } : __ocNextResolve(__ocSpecifier, __ocContext)
  144. },
  145. load(__ocUrl, __ocContext, __ocNextLoad) {
  146. const __ocSource = __ocPluginSources[__ocUrl]
  147. return __ocSource
  148. ? { format: "module", source: __ocSource, shortCircuit: true }
  149. : __ocNextLoad(__ocUrl, __ocContext)
  150. },
  151. })
  152. const __ocUid = typeof process.getuid === "function" ? process.getuid() : undefined
  153. const __ocCacheRoot = __ocPath.join(__ocTmpdir(), \`opencode-node-\${__ocUid ?? "user"}\`)
  154. if (__ocIsSea()) {
  155. try {
  156. __ocMkdir(__ocCacheRoot, { mode: 0o700 })
  157. } catch (__ocError) {
  158. if (!__ocExists(__ocCacheRoot)) throw __ocError
  159. }
  160. const __ocCacheInfo = __ocLstat(__ocCacheRoot)
  161. if (!__ocCacheInfo.isDirectory() || __ocCacheInfo.isSymbolicLink()) throw new Error("Unsafe Node asset cache path")
  162. if (__ocUid !== undefined && __ocCacheInfo.uid !== __ocUid) throw new Error("Node asset cache is owned by another user")
  163. if (__ocUid !== undefined) __ocChmod(__ocCacheRoot, 0o700)
  164. }
  165. const __ocAssetRoot = __ocIsSea()
  166. ? __ocPath.join(__ocCacheRoot, ${JSON.stringify(`${input.assetHash}-${input.target.platform}-${input.target.arch}`)})
  167. : __ocFileURLToPath(new URL("./assets/", import.meta.url))
  168. if (__ocIsSea()) {
  169. for (const __ocKey of __ocAssetKeys()) {
  170. const __ocTarget = __ocPath.join(__ocAssetRoot, __ocKey)
  171. if (__ocExists(__ocTarget)) continue
  172. __ocMkdir(__ocPath.dirname(__ocTarget), { recursive: true })
  173. const __ocTemporary = \`${"${__ocTarget}"}.${"${process.pid}"}.${"${crypto.randomUUID()}"}.tmp\`
  174. __ocWrite(__ocTemporary, new Uint8Array(__ocRawAsset(__ocKey)))
  175. try {
  176. __ocRename(__ocTemporary, __ocTarget)
  177. } catch (__ocError) {
  178. __ocRm(__ocTemporary, { force: true })
  179. if (!__ocExists(__ocTarget)) throw __ocError
  180. }
  181. }
  182. const __ocPtySpawnHelper = ${JSON.stringify(nodePtySpawnHelper)}
  183. if (__ocPtySpawnHelper) __ocChmod(__ocPath.join(__ocAssetRoot, __ocPtySpawnHelper), 0o755)
  184. }
  185. process.env.OPENCODE_NODE_ASSETS_DIR = __ocAssetRoot
  186. process.env.OTUI_ASSET_ROOT = __ocAssetRoot
  187. process.env.OPENCODE_NODE_PTY_PATH = __ocPath.join(__ocAssetRoot, ${JSON.stringify(input.target.nodePtyEntryAsset)})
  188. process.env.OPENCODE_PARCEL_WATCHER_PATH = __ocPath.join(__ocAssetRoot, ${JSON.stringify(input.target.parcelWatcherAsset)})
  189. process.env.OPENCODE_PHOTON_WASM_PATH = __ocPath.join(__ocAssetRoot, ${JSON.stringify(photonWasmAsset)})
  190. process.env.OPENCODE_TREE_SITTER_WASM_PATH = __ocPath.join(__ocAssetRoot, ${JSON.stringify(shellParserWasmAssets.runtime)})
  191. process.env.OPENCODE_TREE_SITTER_BASH_WASM_PATH = __ocPath.join(__ocAssetRoot, ${JSON.stringify(shellParserWasmAssets.bash)})
  192. process.env.OPENCODE_TREE_SITTER_POWERSHELL_WASM_PATH = __ocPath.join(__ocAssetRoot, ${JSON.stringify(shellParserWasmAssets.powershell)})
  193. process.env.FFF_BINARY_PATH = __ocPath.join(__ocAssetRoot, ${JSON.stringify(input.target.fffAsset)})
  194. process.env.OPENCODE_FFF_FFI_PATH = __ocPath.join(__ocAssetRoot, ${JSON.stringify(input.target.fffFfiAsset)})
  195. try {
  196. globalThis.__OPENCODE_FFF_FFI = require(process.env.OPENCODE_FFF_FFI_PATH)
  197. } catch {}
  198. globalThis.__OPENCODE_PHOTON_WASM_PATH = process.env.OPENCODE_PHOTON_WASM_PATH
  199. if (process.platform === "linux") process.env.OPENTUI_LIBC = "glibc"`
  200. }
  201. export type NodeBuildInput = {
  202. readonly version: string
  203. readonly channel: string
  204. readonly models: string
  205. readonly assetHash: string
  206. readonly target: NodeTarget
  207. }
  208. export function mainConfig(input: NodeBuildInput): UserConfig {
  209. return defineConfig({
  210. root: dir,
  211. plugins: [
  212. rawTextPlugin(),
  213. runtimeRequirePlugin(),
  214. fffNodePlugin(),
  215. solid({
  216. solid: {
  217. generate: "universal",
  218. moduleName: "@opentui/solid",
  219. },
  220. }),
  221. ],
  222. resolve,
  223. esbuild: { jsx: "automatic" },
  224. define: {
  225. OPENCODE_VERSION: JSON.stringify(input.version),
  226. OPENCODE_CLI_NAME: JSON.stringify("opencode2-node"),
  227. OPENCODE_MODELS_DEV: input.models,
  228. OPENCODE_CHANNEL: JSON.stringify(input.channel),
  229. OPENCODE_LIBC: input.target.platform === "linux" ? JSON.stringify("glibc") : "undefined",
  230. FFF_LIBC: input.target.platform === "linux" ? JSON.stringify("gnu") : "undefined",
  231. },
  232. ssr: { noExternal: true },
  233. build: {
  234. ssr: "src/node/index.ts",
  235. target: "node26",
  236. outDir: "dist-node",
  237. emptyOutDir: false,
  238. minify: true,
  239. rollupOptions: {
  240. external: [/^@opencode-ai\/simulation(?:\/|$)/],
  241. output: output("opencode.mjs", nodePrelude(input)),
  242. },
  243. },
  244. })
  245. }
  246. export default mainConfig({
  247. version: process.env.OPENCODE_VERSION ?? "local",
  248. channel: process.env.OPENCODE_CHANNEL ?? "local",
  249. models: "undefined",
  250. assetHash: "local",
  251. target: nodeTarget(process.platform, process.arch),
  252. })