@opencode-ai/sdk 0.0.0-dev-202609040823 → 0.0.0-dev-19084

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +143 -0
  2. package/dist/contracts.d.ts +26 -0
  3. package/dist/contracts.js +26 -0
  4. package/dist/effect/index.d.ts +5 -0
  5. package/dist/effect/index.js +4 -0
  6. package/dist/effect/opencode.d.ts +31 -0
  7. package/dist/effect/opencode.js +23 -0
  8. package/dist/effect/tool.d.ts +3 -0
  9. package/dist/effect/tool.js +2 -0
  10. package/dist/effect/workerd.d.ts +15 -0
  11. package/dist/effect/workerd.js +8 -0
  12. package/dist/index.d.ts +5 -10
  13. package/dist/index.js +4 -16
  14. package/dist/internal/fetch.d.ts +7 -0
  15. package/dist/internal/fetch.js +106 -0
  16. package/dist/internal/host.d.ts +30 -0
  17. package/dist/internal/host.js +30 -0
  18. package/dist/internal/instances.d.ts +24 -0
  19. package/dist/internal/instances.js +45 -0
  20. package/dist/internal/workerd.d.ts +55 -0
  21. package/dist/internal/workerd.js +12 -0
  22. package/dist/logging.d.ts +15 -0
  23. package/dist/logging.js +46 -0
  24. package/dist/opencode.d.ts +7 -0
  25. package/dist/opencode.js +2 -0
  26. package/dist/promise.d.ts +26 -0
  27. package/dist/promise.js +30 -0
  28. package/dist/tool.d.ts +3 -0
  29. package/dist/tool.js +2 -0
  30. package/dist/workerd.d.ts +26 -0
  31. package/dist/workerd.js +7 -0
  32. package/package.json +41 -42
  33. package/dist/client.d.ts +0 -7
  34. package/dist/client.js +0 -53
  35. package/dist/error-interceptor.d.ts +0 -15
  36. package/dist/error-interceptor.js +0 -43
  37. package/dist/gen/client/client.gen.d.ts +0 -2
  38. package/dist/gen/client/client.gen.js +0 -165
  39. package/dist/gen/client/index.d.ts +0 -7
  40. package/dist/gen/client/index.js +0 -5
  41. package/dist/gen/client/types.gen.d.ts +0 -127
  42. package/dist/gen/client/types.gen.js +0 -2
  43. package/dist/gen/client/utils.gen.d.ts +0 -38
  44. package/dist/gen/client/utils.gen.js +0 -226
  45. package/dist/gen/client.gen.d.ts +0 -12
  46. package/dist/gen/client.gen.js +0 -5
  47. package/dist/gen/core/auth.gen.d.ts +0 -18
  48. package/dist/gen/core/auth.gen.js +0 -14
  49. package/dist/gen/core/bodySerializer.gen.d.ts +0 -17
  50. package/dist/gen/core/bodySerializer.gen.js +0 -57
  51. package/dist/gen/core/params.gen.d.ts +0 -33
  52. package/dist/gen/core/params.gen.js +0 -89
  53. package/dist/gen/core/pathSerializer.gen.d.ts +0 -33
  54. package/dist/gen/core/pathSerializer.gen.js +0 -106
  55. package/dist/gen/core/queryKeySerializer.gen.d.ts +0 -18
  56. package/dist/gen/core/queryKeySerializer.gen.js +0 -93
  57. package/dist/gen/core/serverSentEvents.gen.d.ts +0 -59
  58. package/dist/gen/core/serverSentEvents.gen.js +0 -117
  59. package/dist/gen/core/types.gen.d.ts +0 -78
  60. package/dist/gen/core/types.gen.js +0 -2
  61. package/dist/gen/core/utils.gen.d.ts +0 -14
  62. package/dist/gen/core/utils.gen.js +0 -69
  63. package/dist/gen/sdk.gen.d.ts +0 -403
  64. package/dist/gen/sdk.gen.js +0 -881
  65. package/dist/gen/types.gen.d.ts +0 -3383
  66. package/dist/gen/types.gen.js +0 -2
  67. package/dist/process.d.ts +0 -3
  68. package/dist/process.js +0 -33
  69. package/dist/server.d.ts +0 -23
  70. package/dist/server.js +0 -105
  71. package/dist/v2/client.d.ts +0 -9
  72. package/dist/v2/client.js +0 -80
  73. package/dist/v2/data.d.ts +0 -9
  74. package/dist/v2/data.js +0 -22
  75. package/dist/v2/gen/client/client.gen.d.ts +0 -2
  76. package/dist/v2/gen/client/client.gen.js +0 -232
  77. package/dist/v2/gen/client/index.d.ts +0 -8
  78. package/dist/v2/gen/client/index.js +0 -6
  79. package/dist/v2/gen/client/types.gen.d.ts +0 -117
  80. package/dist/v2/gen/client/types.gen.js +0 -2
  81. package/dist/v2/gen/client/utils.gen.d.ts +0 -33
  82. package/dist/v2/gen/client/utils.gen.js +0 -226
  83. package/dist/v2/gen/client.gen.d.ts +0 -12
  84. package/dist/v2/gen/client.gen.js +0 -3
  85. package/dist/v2/gen/core/auth.gen.d.ts +0 -18
  86. package/dist/v2/gen/core/auth.gen.js +0 -14
  87. package/dist/v2/gen/core/bodySerializer.gen.d.ts +0 -25
  88. package/dist/v2/gen/core/bodySerializer.gen.js +0 -57
  89. package/dist/v2/gen/core/params.gen.d.ts +0 -43
  90. package/dist/v2/gen/core/params.gen.js +0 -102
  91. package/dist/v2/gen/core/pathSerializer.gen.d.ts +0 -33
  92. package/dist/v2/gen/core/pathSerializer.gen.js +0 -106
  93. package/dist/v2/gen/core/queryKeySerializer.gen.d.ts +0 -18
  94. package/dist/v2/gen/core/queryKeySerializer.gen.js +0 -93
  95. package/dist/v2/gen/core/serverSentEvents.gen.d.ts +0 -71
  96. package/dist/v2/gen/core/serverSentEvents.gen.js +0 -133
  97. package/dist/v2/gen/core/types.gen.d.ts +0 -78
  98. package/dist/v2/gen/core/types.gen.js +0 -2
  99. package/dist/v2/gen/core/utils.gen.d.ts +0 -19
  100. package/dist/v2/gen/core/utils.gen.js +0 -87
  101. package/dist/v2/gen/sdk.gen.d.ts +0 -2302
  102. package/dist/v2/gen/sdk.gen.js +0 -4456
  103. package/dist/v2/gen/types.gen.d.ts +0 -11656
  104. package/dist/v2/gen/types.gen.js +0 -2
  105. package/dist/v2/index.d.ts +0 -11
  106. package/dist/v2/index.js +0 -17
  107. package/dist/v2/server.d.ts +0 -23
  108. package/dist/v2/server.js +0 -105
@@ -0,0 +1,12 @@
1
+ export * as WorkerdProfile from "./workerd";
2
+ import { ServerWorkerd } from "@opencode-ai/server/workerd";
3
+ export function make({ config, ...options }) {
4
+ const server = {
5
+ ...options,
6
+ config: config === void 0 ? void 0 : { content: JSON.stringify(config) }
7
+ };
8
+ return {
9
+ options: ServerWorkerd.serverOptions(server),
10
+ replacements: ServerWorkerd.replacements(server)
11
+ };
12
+ }
@@ -0,0 +1,15 @@
1
+ import { Context, Layer } from "effect";
2
+ export type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";
3
+ export type LogEntry = {
4
+ readonly level: LogLevel;
5
+ readonly message: string;
6
+ readonly attributes?: Readonly<Record<string, unknown>>;
7
+ readonly cause?: unknown;
8
+ };
9
+ export type LogWriter = (entry: LogEntry) => void;
10
+ export type LogOptions = {
11
+ readonly level?: LogLevel;
12
+ readonly emit: LogWriter;
13
+ };
14
+ export declare function layer(log?: LogOptions): Layer.Layer<never, never, never>;
15
+ export declare function context(source: Context.Context<never>): Context.Context<never>;
@@ -0,0 +1,46 @@
1
+ import { Context, Formatter, Layer, Logger, References } from "effect";
2
+ const levels = {
3
+ trace: "Trace",
4
+ debug: "Debug",
5
+ info: "Info",
6
+ warn: "Warn",
7
+ error: "Error",
8
+ fatal: "Fatal"
9
+ }, levelNames = new Map([
10
+ [levels.trace, "trace"],
11
+ [levels.debug, "debug"],
12
+ [levels.info, "info"],
13
+ [levels.warn, "warn"],
14
+ [levels.error, "error"],
15
+ [levels.fatal, "fatal"]
16
+ ]);
17
+ function normalizeLevel(level) {
18
+ return levelNames.get(level);
19
+ }
20
+ export function layer(log) {
21
+ const logger = Logger.make((options) => {
22
+ if (!log)
23
+ return;
24
+ const level = normalizeLevel(options.logLevel);
25
+ if (!level)
26
+ return;
27
+ const entry = Logger.formatStructured.log(options), values = Array.isArray(entry.message) ? entry.message : [entry.message], [message, ...data] = values, details = data.length === 1 && !Array.isArray(data[0]) ? data[0] : void 0, { cause: detailCause, ...detailAttributes } = details ?? {}, attributes = {
28
+ ...entry.annotations,
29
+ ...detailAttributes,
30
+ ...Object.keys(entry.spans).length > 0 ? { spans: entry.spans } : {},
31
+ ...!details && data.length > 0 ? { data: data.length === 1 ? data[0] : data } : {}
32
+ };
33
+ try {
34
+ log.emit({
35
+ level,
36
+ message: typeof message === "string" ? message : Formatter.format(message),
37
+ ...Object.keys(attributes).length > 0 ? { attributes } : {},
38
+ ...entry.cause === void 0 && detailCause === void 0 ? {} : { cause: entry.cause ?? detailCause }
39
+ });
40
+ } catch {}
41
+ });
42
+ return Layer.merge(Logger.layer([logger], { mergeWithExisting: !1 }), Layer.succeed(References.MinimumLogLevel, levels[log?.level ?? "info"]));
43
+ }
44
+ export function context(source) {
45
+ return Context.make(Logger.CurrentLoggers, Context.get(source, Logger.CurrentLoggers)).pipe(Context.add(References.MinimumLogLevel, Context.get(source, References.MinimumLogLevel)));
46
+ }
@@ -0,0 +1,7 @@
1
+ import { PromiseSdk } from "./promise";
2
+ export type { LogEntry, LogLevel, LogOptions, LogWriter } from "./logging";
3
+ export type CreateOptions = PromiseSdk.CreateOptions;
4
+ export type InstanceOptions = PromiseSdk.InstanceOptions;
5
+ export type InstanceConfiguration = PromiseSdk.InstanceConfiguration;
6
+ export type Interface = PromiseSdk.Interface;
7
+ export declare const create: (options?: CreateOptions) => Promise<PromiseSdk.Interface>;
@@ -0,0 +1,2 @@
1
+ import { PromiseSdk } from "./promise";
2
+ export const create = (options = {}) => PromiseSdk.create(options);
@@ -0,0 +1,26 @@
1
+ export * as PromiseSdk from "./promise";
2
+ import { type OpenCodeClient } from "@opencode-ai/client";
3
+ import type { Plugin } from "@opencode-ai/plugin";
4
+ import { Session } from "@opencode-ai/schema/session";
5
+ import { EmbeddedHost } from "./internal/host";
6
+ export interface InstanceConfiguration {
7
+ readonly plugins: ReadonlyArray<Plugin.Plugin>;
8
+ }
9
+ export interface InstanceOptions {
10
+ /** Select a sharing key within the Session's current Location. Must not initialize plugins. */
11
+ readonly key: (session: typeof Session.Info.Encoded) => string;
12
+ /** Reconstruct configuration on a cache miss, including after a host restart. */
13
+ readonly configure: (key: string) => InstanceConfiguration | Promise<InstanceConfiguration>;
14
+ }
15
+ export interface CreateOptions extends Omit<EmbeddedHost.CreateOptions, "workspaceProviders" | "instances"> {
16
+ readonly plugins?: ReadonlyArray<Plugin.Plugin>;
17
+ readonly instances?: InstanceOptions;
18
+ }
19
+ export type Interface = Omit<OpenCodeClient, "plugin"> & {
20
+ readonly sessions: OpenCodeClient["session"];
21
+ readonly events: OpenCodeClient["event"];
22
+ readonly plugin: ((plugin: Plugin.Plugin) => Promise<void>) & OpenCodeClient["plugin"];
23
+ readonly close: () => Promise<void>;
24
+ readonly [Symbol.asyncDispose]: () => Promise<void>;
25
+ };
26
+ export declare function create(options?: CreateOptions, embed?: EmbeddedHost.EmbedOptions): Promise<Interface>;
@@ -0,0 +1,30 @@
1
+ export * as PromiseSdk from "./promise";
2
+ import { OpenCode } from "@opencode-ai/client";
3
+ import { Session } from "@opencode-ai/schema/session";
4
+ import { Effect, Schema } from "effect";
5
+ import { EmbeddedHost } from "./internal/host";
6
+ export async function create(options = {}, embed = {}) {
7
+ const { plugins, instances, ...hostOptions } = options, host = await Effect.runPromise(EmbeddedHost.create({
8
+ ...hostOptions,
9
+ instances: instances ? {
10
+ key: (session) => instances.key(Schema.encodeSync(Session.Info)(session)),
11
+ configure: (key) => Effect.gen(function* () {
12
+ const { PluginPromise } = yield* Effect.promise(() => import("@opencode-ai/core/plugin/promise"));
13
+ return { plugins: (yield* Effect.tryPromise(async () => instances.configure(key))).plugins.map(PluginPromise.fromPromise) };
14
+ })
15
+ } : void 0
16
+ }, embed)), client = OpenCode.make({ baseUrl: "http://opencode.local", fetch: host.fetch }), register = async (plugin) => {
17
+ const { PluginPromise } = await import("@opencode-ai/core/plugin/promise");
18
+ return host.runtime.runPromise(host.plugins.register(PluginPromise.fromPromise(plugin)));
19
+ };
20
+ for (const plugin of plugins ?? [])
21
+ await register(plugin);
22
+ return {
23
+ ...client,
24
+ sessions: client.session,
25
+ events: client.event,
26
+ plugin: Object.assign(register, client.plugin),
27
+ close: host.close,
28
+ [Symbol.asyncDispose]: host.close
29
+ };
30
+ }
package/dist/tool.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { RegistrationError } from "@opencode-ai/core/tool";
2
+ export { Error } from "@opencode-ai/schema/tool";
3
+ export type { ToolContext as Context, Info } from "@opencode-ai/plugin/promise/tool";
package/dist/tool.js ADDED
@@ -0,0 +1,2 @@
1
+ export { RegistrationError } from "@opencode-ai/core/tool";
2
+ export { Error } from "@opencode-ai/schema/tool";
@@ -0,0 +1,26 @@
1
+ export * as OpenCodeWorkerd from "./workerd";
2
+ import { WorkerdProfile } from "./internal/workerd";
3
+ import type { LogOptions } from "./logging";
4
+ import { PromiseSdk } from "./promise";
5
+ export type Configuration = WorkerdProfile.Configuration;
6
+ export interface CreateOptions extends WorkerdProfile.Options {
7
+ readonly log?: LogOptions;
8
+ readonly plugins?: PromiseSdk.CreateOptions["plugins"];
9
+ readonly instances?: PromiseSdk.CreateOptions["instances"];
10
+ }
11
+ /**
12
+ * Boots the embedded opencode SDK on the workerd runtime profile: the full
13
+ * application graph inside a Cloudflare Durable Object, with the database on
14
+ * the injected `DurableObjectStorage` SQLite and every intentionally-local
15
+ * service replaced or disabled (see `ServerWorkerd.replacements`).
16
+ *
17
+ * Suspended Sessions resume on boot (as on every runtime) because a Durable
18
+ * Object can be evicted mid-turn with no teardown; the write-ahead execution
19
+ * claim marks the turn and the boot-time sweep replays it.
20
+ *
21
+ * Returns the same typed `OpenCode.Interface` as `OpenCode.create` — typed
22
+ * session operations plus the live `events.subscribe()` stream — served over
23
+ * an in-process fetch transport, so no request leaves the isolate.
24
+ */
25
+ export declare const create: ({ log, plugins, instances, ...options }: CreateOptions) => Promise<PromiseSdk.Interface>;
26
+ export type Interface = PromiseSdk.Interface;
@@ -0,0 +1,7 @@
1
+ export * as OpenCodeWorkerd from "./workerd";
2
+ import { WorkerdProfile } from "./internal/workerd";
3
+ import { PromiseSdk } from "./promise";
4
+ export const create = ({ log, plugins, instances, ...options }) => {
5
+ const profile = WorkerdProfile.make(options);
6
+ return PromiseSdk.create({ ...profile.options, log, plugins, instances }, { overrides: profile.replacements });
7
+ };
package/package.json CHANGED
@@ -1,60 +1,59 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
+ "version": "0.0.0-dev-19084",
3
4
  "name": "@opencode-ai/sdk",
4
- "version": "0.0.0-dev-202609040823",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
- "scripts": {
8
- "test": "bun test",
9
- "typecheck": "tsgo --noEmit",
10
- "build": "bun ./script/build.ts"
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/anomalyco/opencode.git",
10
+ "directory": "packages/sdk"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public"
11
14
  },
15
+ "files": [
16
+ "dist"
17
+ ],
12
18
  "exports": {
13
19
  ".": {
14
20
  "import": "./dist/index.js",
15
21
  "types": "./dist/index.d.ts"
16
22
  },
17
- "./client": {
18
- "import": "./dist/client.js",
19
- "types": "./dist/client.d.ts"
20
- },
21
- "./server": {
22
- "import": "./dist/server.js",
23
- "types": "./dist/server.d.ts"
24
- },
25
- "./v2": {
26
- "import": "./dist/v2/index.js",
27
- "types": "./dist/v2/index.d.ts"
28
- },
29
- "./v2/client": {
30
- "import": "./dist/v2/client.js",
31
- "types": "./dist/v2/client.d.ts"
23
+ "./effect": {
24
+ "import": "./dist/effect/index.js",
25
+ "types": "./dist/effect/index.d.ts"
32
26
  },
33
- "./v2/gen/client": {
34
- "import": "./dist/v2/gen/client/index.js",
35
- "types": "./dist/v2/gen/client/index.d.ts"
27
+ "./workerd": {
28
+ "import": "./dist/workerd.js",
29
+ "types": "./dist/workerd.d.ts"
36
30
  },
37
- "./v2/server": {
38
- "import": "./dist/v2/server.js",
39
- "types": "./dist/v2/server.d.ts"
40
- },
41
- "./v2/types": {
42
- "import": "./dist/v2/gen/types.gen.js",
43
- "types": "./dist/v2/gen/types.gen.d.ts"
31
+ "./workerd/effect": {
32
+ "import": "./dist/effect/workerd.js",
33
+ "types": "./dist/effect/workerd.d.ts"
44
34
  }
45
35
  },
46
- "files": [
47
- "dist"
48
- ],
49
- "devDependencies": {
50
- "@hey-api/openapi-ts": "0.90.10",
51
- "@tsconfig/node22": "22.0.2",
52
- "@types/cross-spawn": "6.0.6",
53
- "@types/node": "24.12.2",
54
- "@typescript/native-preview": "7.0.0-dev.20251207.1",
55
- "typescript": "5.8.2"
36
+ "scripts": {
37
+ "build": "bun run script/build.ts",
38
+ "test": "bun test --timeout 5000",
39
+ "typecheck": "tsgo -b",
40
+ "verify:package": "bun run script/verify-package.ts"
56
41
  },
57
42
  "dependencies": {
58
- "cross-spawn": "7.0.6"
43
+ "@opencode-ai/client": "0.0.0-dev-19084",
44
+ "@opencode-ai/core": "0.0.0-dev-19084",
45
+ "@opencode-ai/plugin": "0.0.0-dev-19084",
46
+ "@opencode-ai/schema": "0.0.0-dev-19084",
47
+ "@opencode-ai/server": "0.0.0-dev-19084",
48
+ "@opencode-ai/util": "0.0.0-dev-19084",
49
+ "effect": "4.0.0-rc.112"
50
+ },
51
+ "devDependencies": {
52
+ "@opencode-ai/ai": "0.0.0-dev-19084",
53
+ "@opencode-ai/httpapi-codegen": "0.0.0-dev-19084",
54
+ "@opencode-ai/protocol": "0.0.0-dev-19084",
55
+ "@tsconfig/bun": "1.0.9",
56
+ "@types/bun": "1.3.13",
57
+ "@typescript/native-preview": "7.0.0-dev.20251207.1"
59
58
  }
60
- }
59
+ }
package/dist/client.d.ts DELETED
@@ -1,7 +0,0 @@
1
- export * from "./gen/types.gen.js";
2
- import { type Config } from "./gen/client/types.gen.js";
3
- import { OpencodeClient } from "./gen/sdk.gen.js";
4
- export { type Config as OpencodeClientConfig, OpencodeClient };
5
- export declare function createOpencodeClient(config?: Config & {
6
- directory?: string;
7
- }): OpencodeClient;
package/dist/client.js DELETED
@@ -1,53 +0,0 @@
1
- export * from "./gen/types.gen.js";
2
- import { createClient } from "./gen/client/client.gen.js";
3
- import { OpencodeClient } from "./gen/sdk.gen.js";
4
- import { wrapClientError } from "./error-interceptor.js";
5
- export { OpencodeClient };
6
- function pick(value, fallback) {
7
- if (!value)
8
- return;
9
- if (!fallback)
10
- return value;
11
- if (value === fallback)
12
- return fallback;
13
- if (value === encodeURIComponent(fallback))
14
- return fallback;
15
- return value;
16
- }
17
- function rewrite(request, directory) {
18
- if (request.method !== "GET" && request.method !== "HEAD")
19
- return request;
20
- const value = pick(request.headers.get("x-opencode-directory"), directory);
21
- if (!value)
22
- return request;
23
- const url = new URL(request.url);
24
- if (!url.searchParams.has("directory")) {
25
- url.searchParams.set("directory", value);
26
- }
27
- const next = new Request(url, request);
28
- next.headers.delete("x-opencode-directory");
29
- return next;
30
- }
31
- export function createOpencodeClient(config) {
32
- if (!config?.fetch) {
33
- const customFetch = (req) => {
34
- // @ts-ignore
35
- req.timeout = false;
36
- return fetch(req);
37
- };
38
- config = {
39
- ...config,
40
- fetch: customFetch,
41
- };
42
- }
43
- if (config?.directory) {
44
- config.headers = {
45
- ...config.headers,
46
- "x-opencode-directory": encodeURIComponent(config.directory),
47
- };
48
- }
49
- const client = createClient(config);
50
- client.interceptors.request.use((request) => rewrite(request, config?.directory));
51
- client.interceptors.error.use(wrapClientError);
52
- return new OpencodeClient({ client });
53
- }
@@ -1,15 +0,0 @@
1
- /**
2
- * Wrap whatever the generated client decoded from a non-2xx error body
3
- * into a real `Error` so downstream formatters (TUI, plugins) get a
4
- * useful `.message` instead of `[object Object]` or blank. The original
5
- * parsed body and status live under `.cause` for callers that need
6
- * structured fields.
7
- *
8
- * Only fires when the caller used `{ throwOnError: true }`. Callers that
9
- * read `result.error` directly (the result-tuple path) get the parsed
10
- * body unchanged so existing field-level reads (`.error.name`,
11
- * `JSON.stringify(error)`, etc.) are byte-for-byte identical to before.
12
- */
13
- export declare function wrapClientError(error: unknown, response: Response | undefined, request: Request | undefined, opts: {
14
- throwOnError?: boolean;
15
- } | undefined): unknown;
@@ -1,43 +0,0 @@
1
- /**
2
- * Wrap whatever the generated client decoded from a non-2xx error body
3
- * into a real `Error` so downstream formatters (TUI, plugins) get a
4
- * useful `.message` instead of `[object Object]` or blank. The original
5
- * parsed body and status live under `.cause` for callers that need
6
- * structured fields.
7
- *
8
- * Only fires when the caller used `{ throwOnError: true }`. Callers that
9
- * read `result.error` directly (the result-tuple path) get the parsed
10
- * body unchanged so existing field-level reads (`.error.name`,
11
- * `JSON.stringify(error)`, etc.) are byte-for-byte identical to before.
12
- */
13
- export function wrapClientError(error, response, request, opts) {
14
- if (!opts?.throwOnError)
15
- return error;
16
- if (error instanceof Error)
17
- return error;
18
- // NamedError-shaped responses (the common case for opencode 4xx) come
19
- // through as POJOs — extract a useful message first, then wrap.
20
- if (typeof error === "object" && error !== null && Object.keys(error).length > 0) {
21
- const obj = error;
22
- const message = (typeof obj.data?.message === "string" && obj.data.message) ||
23
- (typeof obj.message === "string" && obj.message) ||
24
- (typeof obj.name === "string" && obj.name) ||
25
- describe(request, response);
26
- return new Error(message, { cause: { body: error, status: response?.status } });
27
- }
28
- if (typeof error === "string" && error.length > 0) {
29
- return new Error(error, { cause: { body: error, status: response?.status } });
30
- }
31
- // Empty body / network failure / undefined / null / empty object.
32
- const reason = response ? "(empty response body)" : "network error (no response)";
33
- return new Error(`opencode server ${describe(request, response)}: ${reason}`, {
34
- cause: { body: error, status: response?.status },
35
- });
36
- }
37
- function describe(request, response) {
38
- const method = request?.method ?? "?";
39
- const url = request?.url ?? "?";
40
- const status = response?.status;
41
- const statusText = response?.statusText;
42
- return `${method} ${url}${status ? " → " + status : ""}${statusText ? " " + statusText : ""}`;
43
- }
@@ -1,2 +0,0 @@
1
- import type { Client, Config } from "./types.gen.js";
2
- export declare const createClient: (config?: Config) => Client;
@@ -1,165 +0,0 @@
1
- // This file is auto-generated by @hey-api/openapi-ts
2
- import { createSseClient } from "../core/serverSentEvents.gen.js";
3
- import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from "./utils.gen.js";
4
- export const createClient = (config = {}) => {
5
- let _config = mergeConfigs(createConfig(), config);
6
- const getConfig = () => ({ ..._config });
7
- const setConfig = (config) => {
8
- _config = mergeConfigs(_config, config);
9
- return getConfig();
10
- };
11
- const interceptors = createInterceptors();
12
- const beforeRequest = async (options) => {
13
- const opts = {
14
- ..._config,
15
- ...options,
16
- fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
17
- headers: mergeHeaders(_config.headers, options.headers),
18
- serializedBody: undefined,
19
- };
20
- if (opts.security) {
21
- await setAuthParams({
22
- ...opts,
23
- security: opts.security,
24
- });
25
- }
26
- if (opts.requestValidator) {
27
- await opts.requestValidator(opts);
28
- }
29
- if (opts.body && opts.bodySerializer) {
30
- opts.serializedBody = opts.bodySerializer(opts.body);
31
- }
32
- // remove Content-Type header if body is empty to avoid sending invalid requests
33
- if (opts.serializedBody === undefined || opts.serializedBody === "") {
34
- opts.headers.delete("Content-Type");
35
- }
36
- const url = buildUrl(opts);
37
- return { opts, url };
38
- };
39
- const request = async (options) => {
40
- // @ts-expect-error
41
- const { opts, url } = await beforeRequest(options);
42
- const requestInit = {
43
- redirect: "follow",
44
- ...opts,
45
- body: opts.serializedBody,
46
- };
47
- let request = new Request(url, requestInit);
48
- for (const fn of interceptors.request._fns) {
49
- if (fn) {
50
- request = await fn(request, opts);
51
- }
52
- }
53
- // fetch must be assigned here, otherwise it would throw the error:
54
- // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
55
- const _fetch = opts.fetch;
56
- let response = await _fetch(request);
57
- for (const fn of interceptors.response._fns) {
58
- if (fn) {
59
- response = await fn(response, request, opts);
60
- }
61
- }
62
- const result = {
63
- request,
64
- response,
65
- };
66
- if (response.ok) {
67
- if (response.status === 204 || response.headers.get("Content-Length") === "0") {
68
- return opts.responseStyle === "data"
69
- ? {}
70
- : {
71
- data: {},
72
- ...result,
73
- };
74
- }
75
- const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
76
- let data;
77
- switch (parseAs) {
78
- case "arrayBuffer":
79
- case "blob":
80
- case "formData":
81
- case "json":
82
- case "text":
83
- data = await response[parseAs]();
84
- break;
85
- case "stream":
86
- return opts.responseStyle === "data"
87
- ? response.body
88
- : {
89
- data: response.body,
90
- ...result,
91
- };
92
- }
93
- if (parseAs === "json") {
94
- if (opts.responseValidator) {
95
- await opts.responseValidator(data);
96
- }
97
- if (opts.responseTransformer) {
98
- data = await opts.responseTransformer(data);
99
- }
100
- }
101
- return opts.responseStyle === "data"
102
- ? data
103
- : {
104
- data,
105
- ...result,
106
- };
107
- }
108
- const textError = await response.text();
109
- let jsonError;
110
- try {
111
- jsonError = JSON.parse(textError);
112
- }
113
- catch {
114
- // noop
115
- }
116
- const error = jsonError ?? textError;
117
- let finalError = error;
118
- for (const fn of interceptors.error._fns) {
119
- if (fn) {
120
- finalError = (await fn(error, response, request, opts));
121
- }
122
- }
123
- finalError = finalError || {};
124
- if (opts.throwOnError) {
125
- throw finalError;
126
- }
127
- // TODO: we probably want to return error and improve types
128
- return opts.responseStyle === "data"
129
- ? undefined
130
- : {
131
- error: finalError,
132
- ...result,
133
- };
134
- };
135
- const makeMethod = (method) => {
136
- const fn = (options) => request({ ...options, method });
137
- fn.sse = async (options) => {
138
- const { opts, url } = await beforeRequest(options);
139
- return createSseClient({
140
- ...opts,
141
- body: opts.body,
142
- headers: opts.headers,
143
- method,
144
- url,
145
- });
146
- };
147
- return fn;
148
- };
149
- return {
150
- buildUrl,
151
- connect: makeMethod("CONNECT"),
152
- delete: makeMethod("DELETE"),
153
- get: makeMethod("GET"),
154
- getConfig,
155
- head: makeMethod("HEAD"),
156
- interceptors,
157
- options: makeMethod("OPTIONS"),
158
- patch: makeMethod("PATCH"),
159
- post: makeMethod("POST"),
160
- put: makeMethod("PUT"),
161
- request,
162
- setConfig,
163
- trace: makeMethod("TRACE"),
164
- };
165
- };
@@ -1,7 +0,0 @@
1
- export type { Auth } from "../core/auth.gen.js";
2
- export type { QuerySerializerOptions } from "../core/bodySerializer.gen.js";
3
- export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from "../core/bodySerializer.gen.js";
4
- export { buildClientParams } from "../core/params.gen.js";
5
- export { createClient } from "./client.gen.js";
6
- export type { Client, ClientOptions, Config, CreateClientConfig, Options, OptionsLegacyParser, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from "./types.gen.js";
7
- export { createConfig, mergeHeaders } from "./utils.gen.js";
@@ -1,5 +0,0 @@
1
- // This file is auto-generated by @hey-api/openapi-ts
2
- export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from "../core/bodySerializer.gen.js";
3
- export { buildClientParams } from "../core/params.gen.js";
4
- export { createClient } from "./client.gen.js";
5
- export { createConfig, mergeHeaders } from "./utils.gen.js";