| 48 | } |
| 49 | |
| 50 | export function createOpencodeClient(config?: Config & { directory?: string; experimental_workspaceID?: string }) { |
| 51 | if (!config?.fetch) { |
| 52 | const customFetch: any = (req: any) => { |
| 53 | // @ts-ignore |
| 54 | req.timeout = false |
| 55 | return fetch(req) |
| 56 | } |
| 57 | config = { |
| 58 | ...config, |
| 59 | fetch: customFetch, |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | if (config?.directory) { |
| 64 | config.headers = { |
| 65 | ...config.headers, |
| 66 | "x-opencode-directory": encodeURIComponent(config.directory), |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | if (config?.experimental_workspaceID) { |
| 71 | config.headers = { |
| 72 | ...config.headers, |
| 73 | "x-opencode-workspace": config.experimental_workspaceID, |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | const client = createClient(config) |
| 78 | client.interceptors.request.use((request) => |
| 79 | rewrite(request, { |
| 80 | directory: config?.directory, |
| 81 | workspace: config?.experimental_workspaceID, |
| 82 | }), |
| 83 | ) |
| 84 | client.interceptors.response.use((response) => { |
| 85 | const contentType = response.headers.get("content-type") |
| 86 | if (contentType === "text/html") |
| 87 | throw new Error("Request is not supported by this version of OpenCode Server (Server responded with text/html)") |
| 88 | |
| 89 | return response |
| 90 | }) |
| 91 | client.interceptors.error.use(wrapClientError) |
| 92 | return new OpencodeClient({ client }) |
| 93 | } |