🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@opencode-ai/sdk

Package Overview
Dependencies
Maintainers
2
Versions
9480
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@opencode-ai/sdk - npm Package Compare versions

Comparing version
0.0.0-next-15065
to
0.0.1
+2
dist/gen/client/client.d.ts
import type { Client, Config } from './types';
export declare const createClient: (config?: Config) => Client;
import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils';
export const createClient = (config = {}) => {
let _config = mergeConfigs(createConfig(), config);
const getConfig = () => ({ ..._config });
const setConfig = (config) => {
_config = mergeConfigs(_config, config);
return getConfig();
};
const interceptors = createInterceptors();
const request = async (options) => {
const opts = {
..._config,
...options,
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
headers: mergeHeaders(_config.headers, options.headers),
};
if (opts.security) {
await setAuthParams({
...opts,
security: opts.security,
});
}
if (opts.requestValidator) {
await opts.requestValidator(opts);
}
if (opts.body && opts.bodySerializer) {
opts.body = opts.bodySerializer(opts.body);
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.body === undefined || opts.body === '') {
opts.headers.delete('Content-Type');
}
const url = buildUrl(opts);
const requestInit = {
redirect: 'follow',
...opts,
};
let request = new Request(url, requestInit);
for (const fn of interceptors.request._fns) {
if (fn) {
request = await fn(request, opts);
}
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = opts.fetch;
let response = await _fetch(request);
for (const fn of interceptors.response._fns) {
if (fn) {
response = await fn(response, request, opts);
}
}
const result = {
request,
response,
};
if (response.ok) {
if (response.status === 204 ||
response.headers.get('Content-Length') === '0') {
return opts.responseStyle === 'data'
? {}
: {
data: {},
...result,
};
}
const parseAs = (opts.parseAs === 'auto'
? getParseAs(response.headers.get('Content-Type'))
: opts.parseAs) ?? 'json';
let data;
switch (parseAs) {
case 'arrayBuffer':
case 'blob':
case 'formData':
case 'json':
case 'text':
data = await response[parseAs]();
break;
case 'stream':
return opts.responseStyle === 'data'
? response.body
: {
data: response.body,
...result,
};
}
if (parseAs === 'json') {
if (opts.responseValidator) {
await opts.responseValidator(data);
}
if (opts.responseTransformer) {
data = await opts.responseTransformer(data);
}
}
return opts.responseStyle === 'data'
? data
: {
data,
...result,
};
}
const textError = await response.text();
let jsonError;
try {
jsonError = JSON.parse(textError);
}
catch {
// noop
}
const error = jsonError ?? textError;
let finalError = error;
for (const fn of interceptors.error._fns) {
if (fn) {
finalError = (await fn(error, response, request, opts));
}
}
finalError = finalError || {};
if (opts.throwOnError) {
throw finalError;
}
// TODO: we probably want to return error and improve types
return opts.responseStyle === 'data'
? undefined
: {
error: finalError,
...result,
};
};
return {
buildUrl,
connect: (options) => request({ ...options, method: 'CONNECT' }),
delete: (options) => request({ ...options, method: 'DELETE' }),
get: (options) => request({ ...options, method: 'GET' }),
getConfig,
head: (options) => request({ ...options, method: 'HEAD' }),
interceptors,
options: (options) => request({ ...options, method: 'OPTIONS' }),
patch: (options) => request({ ...options, method: 'PATCH' }),
post: (options) => request({ ...options, method: 'POST' }),
put: (options) => request({ ...options, method: 'PUT' }),
request,
setConfig,
trace: (options) => request({ ...options, method: 'TRACE' }),
};
};
import type { Auth } from '../core/auth';
import type { Client as CoreClient, Config as CoreConfig } from '../core/types';
import type { Middleware } from './utils';
export type ResponseStyle = 'data' | 'fields';
export interface Config<T extends ClientOptions = ClientOptions> extends Omit<RequestInit, 'body' | 'headers' | 'method'>, CoreConfig {
/**
* Base URL for all requests made by this client.
*/
baseUrl?: T['baseUrl'];
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: (request: Request) => ReturnType<typeof fetch>;
/**
* Please don't use the Fetch client for Next.js applications. The `next`
* options won't have any effect.
*
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
*/
next?: never;
/**
* Return the response data parsed in a specified format. By default, `auto`
* will infer the appropriate method from the `Content-Type` response header.
* You can override this behavior with any of the {@link Body} methods.
* Select `stream` if you don't want to parse response data at all.
*
* @default 'auto'
*/
parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text';
/**
* Should we return only data or multiple fields (data, error, response, etc.)?
*
* @default 'fields'
*/
responseStyle?: ResponseStyle;
/**
* Throw an error instead of returning it in the response?
*
* @default false
*/
throwOnError?: T['throwOnError'];
}
export interface RequestOptions<TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string> extends Config<{
responseStyle: TResponseStyle;
throwOnError: ThrowOnError;
}> {
/**
* Any body that you want to add to your request.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
*/
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
/**
* Security mechanism(s) to use for the request.
*/
security?: ReadonlyArray<Auth>;
url: Url;
}
export type RequestResult<TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields'> = ThrowOnError extends true ? Promise<TResponseStyle extends 'data' ? TData extends Record<string, unknown> ? TData[keyof TData] : TData : {
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
request: Request;
response: Response;
}> : Promise<TResponseStyle extends 'data' ? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined : ({
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
error: undefined;
} | {
data: undefined;
error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
}) & {
request: Request;
response: Response;
}>;
export interface ClientOptions {
baseUrl?: string;
responseStyle?: ResponseStyle;
throwOnError?: boolean;
}
type MethodFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, 'method'>) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type RequestFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, 'method'> & Pick<Required<RequestOptions<TResponseStyle, ThrowOnError>>, 'method'>) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type BuildUrlFn = <TData extends {
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
url: string;
}>(options: Pick<TData, 'url'> & Options<TData>) => string;
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
interceptors: Middleware<Request, Response, unknown, RequestOptions>;
};
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
export interface TDataShape {
body?: unknown;
headers?: unknown;
path?: unknown;
query?: unknown;
url: string;
}
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields'> = OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'body' | 'path' | 'query' | 'url'> & Omit<TData, 'url'>;
export type OptionsLegacyParser<TData = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields'> = TData extends {
body?: any;
} ? TData extends {
headers?: any;
} ? OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'body' | 'headers' | 'url'> & TData : OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'body' | 'url'> & TData & Pick<RequestOptions<TResponseStyle, ThrowOnError>, 'headers'> : TData extends {
headers?: any;
} ? OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'headers' | 'url'> & TData & Pick<RequestOptions<TResponseStyle, ThrowOnError>, 'body'> : OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'url'> & TData;
export {};
import type { QuerySerializer, QuerySerializerOptions } from '../core/bodySerializer';
import type { Client, ClientOptions, Config, RequestOptions } from './types';
export declare const createQuerySerializer: <T = unknown>({ allowReserved, array, object, }?: QuerySerializerOptions) => (queryParams: T) => string;
/**
* Infers parseAs value from provided Content-Type header.
*/
export declare const getParseAs: (contentType: string | null) => Exclude<Config["parseAs"], "auto">;
export declare const setAuthParams: ({ security, ...options }: Pick<Required<RequestOptions>, "security"> & Pick<RequestOptions, "auth" | "query"> & {
headers: Headers;
}) => Promise<void>;
export declare const buildUrl: Client['buildUrl'];
export declare const getUrl: ({ baseUrl, path, query, querySerializer, url: _url, }: {
baseUrl?: string;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
querySerializer: QuerySerializer;
url: string;
}) => string;
export declare const mergeConfigs: (a: Config, b: Config) => Config;
export declare const mergeHeaders: (...headers: Array<Required<Config>["headers"] | undefined>) => Headers;
type ErrInterceptor<Err, Res, Req, Options> = (error: Err, response: Res, request: Req, options: Options) => Err | Promise<Err>;
type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;
type ResInterceptor<Res, Req, Options> = (response: Res, request: Req, options: Options) => Res | Promise<Res>;
declare class Interceptors<Interceptor> {
_fns: (Interceptor | null)[];
constructor();
clear(): void;
getInterceptorIndex(id: number | Interceptor): number;
exists(id: number | Interceptor): boolean;
eject(id: number | Interceptor): void;
update(id: number | Interceptor, fn: Interceptor): number | false | Interceptor;
use(fn: Interceptor): number;
}
export interface Middleware<Req, Res, Err, Options> {
error: Pick<Interceptors<ErrInterceptor<Err, Res, Req, Options>>, 'eject' | 'use'>;
request: Pick<Interceptors<ReqInterceptor<Req, Options>>, 'eject' | 'use'>;
response: Pick<Interceptors<ResInterceptor<Res, Req, Options>>, 'eject' | 'use'>;
}
export declare const createInterceptors: <Req, Res, Err, Options>() => {
error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
request: Interceptors<ReqInterceptor<Req, Options>>;
response: Interceptors<ResInterceptor<Res, Req, Options>>;
};
export declare const createConfig: <T extends ClientOptions = ClientOptions>(override?: Config<Omit<ClientOptions, keyof T> & T>) => Config<Omit<ClientOptions, keyof T> & T>;
export {};
import { getAuthToken } from '../core/auth';
import { jsonBodySerializer } from '../core/bodySerializer';
import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer';
const PATH_PARAM_RE = /\{[^{}]+\}/g;
const defaultPathSerializer = ({ path, url: _url }) => {
let url = _url;
const matches = _url.match(PATH_PARAM_RE);
if (matches) {
for (const match of matches) {
let explode = false;
let name = match.substring(1, match.length - 1);
let style = 'simple';
if (name.endsWith('*')) {
explode = true;
name = name.substring(0, name.length - 1);
}
if (name.startsWith('.')) {
name = name.substring(1);
style = 'label';
}
else if (name.startsWith(';')) {
name = name.substring(1);
style = 'matrix';
}
const value = path[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
continue;
}
if (typeof value === 'object') {
url = url.replace(match, serializeObjectParam({
explode,
name,
style,
value: value,
valueOnly: true,
}));
continue;
}
if (style === 'matrix') {
url = url.replace(match, `;${serializePrimitiveParam({
name,
value: value,
})}`);
continue;
}
const replaceValue = encodeURIComponent(style === 'label' ? `.${value}` : value);
url = url.replace(match, replaceValue);
}
}
return url;
};
export const createQuerySerializer = ({ allowReserved, array, object, } = {}) => {
const querySerializer = (queryParams) => {
const search = [];
if (queryParams && typeof queryParams === 'object') {
for (const name in queryParams) {
const value = queryParams[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
const serializedArray = serializeArrayParam({
allowReserved,
explode: true,
name,
style: 'form',
value,
...array,
});
if (serializedArray)
search.push(serializedArray);
}
else if (typeof value === 'object') {
const serializedObject = serializeObjectParam({
allowReserved,
explode: true,
name,
style: 'deepObject',
value: value,
...object,
});
if (serializedObject)
search.push(serializedObject);
}
else {
const serializedPrimitive = serializePrimitiveParam({
allowReserved,
name,
value: value,
});
if (serializedPrimitive)
search.push(serializedPrimitive);
}
}
}
return search.join('&');
};
return querySerializer;
};
/**
* Infers parseAs value from provided Content-Type header.
*/
export const getParseAs = (contentType) => {
if (!contentType) {
// If no Content-Type header is provided, the best we can do is return the raw response body,
// which is effectively the same as the 'stream' option.
return 'stream';
}
const cleanContent = contentType.split(';')[0]?.trim();
if (!cleanContent) {
return;
}
if (cleanContent.startsWith('application/json') ||
cleanContent.endsWith('+json')) {
return 'json';
}
if (cleanContent === 'multipart/form-data') {
return 'formData';
}
if (['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))) {
return 'blob';
}
if (cleanContent.startsWith('text/')) {
return 'text';
}
return;
};
export const setAuthParams = async ({ security, ...options }) => {
for (const auth of security) {
const token = await getAuthToken(auth, options.auth);
if (!token) {
continue;
}
const name = auth.name ?? 'Authorization';
switch (auth.in) {
case 'query':
if (!options.query) {
options.query = {};
}
options.query[name] = token;
break;
case 'cookie':
options.headers.append('Cookie', `${name}=${token}`);
break;
case 'header':
default:
options.headers.set(name, token);
break;
}
return;
}
};
export const buildUrl = (options) => {
const url = getUrl({
baseUrl: options.baseUrl,
path: options.path,
query: options.query,
querySerializer: typeof options.querySerializer === 'function'
? options.querySerializer
: createQuerySerializer(options.querySerializer),
url: options.url,
});
return url;
};
export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }) => {
const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
let url = (baseUrl ?? '') + pathUrl;
if (path) {
url = defaultPathSerializer({ path, url });
}
let search = query ? querySerializer(query) : '';
if (search.startsWith('?')) {
search = search.substring(1);
}
if (search) {
url += `?${search}`;
}
return url;
};
export const mergeConfigs = (a, b) => {
const config = { ...a, ...b };
if (config.baseUrl?.endsWith('/')) {
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
}
config.headers = mergeHeaders(a.headers, b.headers);
return config;
};
export const mergeHeaders = (...headers) => {
const mergedHeaders = new Headers();
for (const header of headers) {
if (!header || typeof header !== 'object') {
continue;
}
const iterator = header instanceof Headers ? header.entries() : Object.entries(header);
for (const [key, value] of iterator) {
if (value === null) {
mergedHeaders.delete(key);
}
else if (Array.isArray(value)) {
for (const v of value) {
mergedHeaders.append(key, v);
}
}
else if (value !== undefined) {
// assume object headers are meant to be JSON stringified, i.e. their
// content value in OpenAPI specification is 'application/json'
mergedHeaders.set(key, typeof value === 'object' ? JSON.stringify(value) : value);
}
}
}
return mergedHeaders;
};
class Interceptors {
_fns;
constructor() {
this._fns = [];
}
clear() {
this._fns = [];
}
getInterceptorIndex(id) {
if (typeof id === 'number') {
return this._fns[id] ? id : -1;
}
else {
return this._fns.indexOf(id);
}
}
exists(id) {
const index = this.getInterceptorIndex(id);
return !!this._fns[index];
}
eject(id) {
const index = this.getInterceptorIndex(id);
if (this._fns[index]) {
this._fns[index] = null;
}
}
update(id, fn) {
const index = this.getInterceptorIndex(id);
if (this._fns[index]) {
this._fns[index] = fn;
return id;
}
else {
return false;
}
}
use(fn) {
this._fns = [...this._fns, fn];
return this._fns.length - 1;
}
}
// do not add `Middleware` as return type so we can use _fns internally
export const createInterceptors = () => ({
error: new Interceptors(),
request: new Interceptors(),
response: new Interceptors(),
});
const defaultQuerySerializer = createQuerySerializer({
allowReserved: false,
array: {
explode: true,
style: 'form',
},
object: {
explode: true,
style: 'deepObject',
},
});
const defaultHeaders = {
'Content-Type': 'application/json',
};
export const createConfig = (override = {}) => ({
...jsonBodySerializer,
headers: defaultHeaders,
parseAs: 'auto',
querySerializer: defaultQuerySerializer,
...override,
});
export type AuthToken = string | undefined;
export interface Auth {
/**
* Which part of the request do we use to send the auth?
*
* @default 'header'
*/
in?: 'header' | 'query' | 'cookie';
/**
* Header or query parameter name.
*
* @default 'Authorization'
*/
name?: string;
scheme?: 'basic' | 'bearer';
type: 'apiKey' | 'http';
}
export declare const getAuthToken: (auth: Auth, callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken) => Promise<string | undefined>;
export const getAuthToken = async (auth, callback) => {
const token = typeof callback === 'function' ? await callback(auth) : callback;
if (!token) {
return;
}
if (auth.scheme === 'bearer') {
return `Bearer ${token}`;
}
if (auth.scheme === 'basic') {
return `Basic ${btoa(token)}`;
}
return token;
};
import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer';
export type QuerySerializer = (query: Record<string, unknown>) => string;
export type BodySerializer = (body: any) => any;
export interface QuerySerializerOptions {
allowReserved?: boolean;
array?: SerializerOptions<ArrayStyle>;
object?: SerializerOptions<ObjectStyle>;
}
export declare const formDataBodySerializer: {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T) => FormData;
};
export declare const jsonBodySerializer: {
bodySerializer: <T>(body: T) => string;
};
export declare const urlSearchParamsBodySerializer: {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T) => string;
};
const serializeFormDataPair = (data, key, value) => {
if (typeof value === 'string' || value instanceof Blob) {
data.append(key, value);
}
else {
data.append(key, JSON.stringify(value));
}
};
const serializeUrlSearchParamsPair = (data, key, value) => {
if (typeof value === 'string') {
data.append(key, value);
}
else {
data.append(key, JSON.stringify(value));
}
};
export const formDataBodySerializer = {
bodySerializer: (body) => {
const data = new FormData();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeFormDataPair(data, key, v));
}
else {
serializeFormDataPair(data, key, value);
}
});
return data;
},
};
export const jsonBodySerializer = {
bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === 'bigint' ? value.toString() : value),
};
export const urlSearchParamsBodySerializer = {
bodySerializer: (body) => {
const data = new URLSearchParams();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
}
else {
serializeUrlSearchParamsPair(data, key, value);
}
});
return data.toString();
},
};
type Slot = 'body' | 'headers' | 'path' | 'query';
export type Field = {
in: Exclude<Slot, 'body'>;
/**
* Field name. This is the name we want the user to see and use.
*/
key: string;
/**
* Field mapped name. This is the name we want to use in the request.
* If omitted, we use the same value as `key`.
*/
map?: string;
} | {
in: Extract<Slot, 'body'>;
/**
* Key isn't required for bodies.
*/
key?: string;
map?: string;
};
export interface Fields {
allowExtra?: Partial<Record<Slot, boolean>>;
args?: ReadonlyArray<Field>;
}
export type FieldsConfig = ReadonlyArray<Field | Fields>;
interface Params {
body: unknown;
headers: Record<string, unknown>;
path: Record<string, unknown>;
query: Record<string, unknown>;
}
export declare const buildClientParams: (args: ReadonlyArray<unknown>, fields: FieldsConfig) => Params;
export {};
const extraPrefixesMap = {
$body_: 'body',
$headers_: 'headers',
$path_: 'path',
$query_: 'query',
};
const extraPrefixes = Object.entries(extraPrefixesMap);
const buildKeyMap = (fields, map) => {
if (!map) {
map = new Map();
}
for (const config of fields) {
if ('in' in config) {
if (config.key) {
map.set(config.key, {
in: config.in,
map: config.map,
});
}
}
else if (config.args) {
buildKeyMap(config.args, map);
}
}
return map;
};
const stripEmptySlots = (params) => {
for (const [slot, value] of Object.entries(params)) {
if (value && typeof value === 'object' && !Object.keys(value).length) {
delete params[slot];
}
}
};
export const buildClientParams = (args, fields) => {
const params = {
body: {},
headers: {},
path: {},
query: {},
};
const map = buildKeyMap(fields);
let config;
for (const [index, arg] of args.entries()) {
if (fields[index]) {
config = fields[index];
}
if (!config) {
continue;
}
if ('in' in config) {
if (config.key) {
const field = map.get(config.key);
const name = field.map || config.key;
params[field.in][name] = arg;
}
else {
params.body = arg;
}
}
else {
for (const [key, value] of Object.entries(arg ?? {})) {
const field = map.get(key);
if (field) {
const name = field.map || key;
params[field.in][name] = value;
}
else {
const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));
if (extra) {
const [prefix, slot] = extra;
params[slot][key.slice(prefix.length)] = value;
}
else {
for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) {
if (allowed) {
params[slot][key] = value;
break;
}
}
}
}
}
}
}
stripEmptySlots(params);
return params;
};
interface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {
}
interface SerializePrimitiveOptions {
allowReserved?: boolean;
name: string;
}
export interface SerializerOptions<T> {
/**
* @default true
*/
explode: boolean;
style: T;
}
export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
type MatrixStyle = 'label' | 'matrix' | 'simple';
export type ObjectStyle = 'form' | 'deepObject';
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
value: string;
}
export declare const separatorArrayExplode: (style: ArraySeparatorStyle) => "." | ";" | "," | "&";
export declare const separatorArrayNoExplode: (style: ArraySeparatorStyle) => "," | "|" | "%20";
export declare const separatorObjectExplode: (style: ObjectSeparatorStyle) => "." | ";" | "," | "&";
export declare const serializeArrayParam: ({ allowReserved, explode, name, style, value, }: SerializeOptions<ArraySeparatorStyle> & {
value: unknown[];
}) => string;
export declare const serializePrimitiveParam: ({ allowReserved, name, value, }: SerializePrimitiveParam) => string;
export declare const serializeObjectParam: ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions<ObjectSeparatorStyle> & {
value: Record<string, unknown> | Date;
valueOnly?: boolean;
}) => string;
export {};
export const separatorArrayExplode = (style) => {
switch (style) {
case 'label':
return '.';
case 'matrix':
return ';';
case 'simple':
return ',';
default:
return '&';
}
};
export const separatorArrayNoExplode = (style) => {
switch (style) {
case 'form':
return ',';
case 'pipeDelimited':
return '|';
case 'spaceDelimited':
return '%20';
default:
return ',';
}
};
export const separatorObjectExplode = (style) => {
switch (style) {
case 'label':
return '.';
case 'matrix':
return ';';
case 'simple':
return ',';
default:
return '&';
}
};
export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }) => {
if (!explode) {
const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
switch (style) {
case 'label':
return `.${joinedValues}`;
case 'matrix':
return `;${name}=${joinedValues}`;
case 'simple':
return joinedValues;
default:
return `${name}=${joinedValues}`;
}
}
const separator = separatorArrayExplode(style);
const joinedValues = value
.map((v) => {
if (style === 'label' || style === 'simple') {
return allowReserved ? v : encodeURIComponent(v);
}
return serializePrimitiveParam({
allowReserved,
name,
value: v,
});
})
.join(separator);
return style === 'label' || style === 'matrix'
? separator + joinedValues
: joinedValues;
};
export const serializePrimitiveParam = ({ allowReserved, name, value, }) => {
if (value === undefined || value === null) {
return '';
}
if (typeof value === 'object') {
throw new Error('Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.');
}
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
};
export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }) => {
if (value instanceof Date) {
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
}
if (style !== 'deepObject' && !explode) {
let values = [];
Object.entries(value).forEach(([key, v]) => {
values = [
...values,
key,
allowReserved ? v : encodeURIComponent(v),
];
});
const joinedValues = values.join(',');
switch (style) {
case 'form':
return `${name}=${joinedValues}`;
case 'label':
return `.${joinedValues}`;
case 'matrix':
return `;${name}=${joinedValues}`;
default:
return joinedValues;
}
}
const separator = separatorObjectExplode(style);
const joinedValues = Object.entries(value)
.map(([key, v]) => serializePrimitiveParam({
allowReserved,
name: style === 'deepObject' ? `${name}[${key}]` : key,
value: v,
}))
.join(separator);
return style === 'label' || style === 'matrix'
? separator + joinedValues
: joinedValues;
};
import type { Auth, AuthToken } from './auth';
import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer';
export interface Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never> {
/**
* Returns the final request URL.
*/
buildUrl: BuildUrlFn;
connect: MethodFn;
delete: MethodFn;
get: MethodFn;
getConfig: () => Config;
head: MethodFn;
options: MethodFn;
patch: MethodFn;
post: MethodFn;
put: MethodFn;
request: RequestFn;
setConfig: (config: Config) => Config;
trace: MethodFn;
}
export interface Config {
/**
* Auth token or a function returning auth token. The resolved value will be
* added to the request payload as defined by its `security` array.
*/
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
/**
* A function for serializing request body parameter. By default,
* {@link JSON.stringify()} will be used.
*/
bodySerializer?: BodySerializer | null;
/**
* An object containing any HTTP headers that you want to pre-populate your
* `Headers` object with.
*
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
*/
headers?: RequestInit['headers'] | Record<string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown>;
/**
* The request method.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
*/
method?: 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE';
/**
* A function for serializing request query parameters. By default, arrays
* will be exploded in form style, objects will be exploded in deepObject
* style, and reserved characters are percent-encoded.
*
* This method will have no effect if the native `paramsSerializer()` Axios
* API function is used.
*
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
*/
querySerializer?: QuerySerializer | QuerySerializerOptions;
/**
* A function validating request data. This is useful if you want to ensure
* the request conforms to the desired shape, so it can be safely sent to
* the server.
*/
requestValidator?: (data: unknown) => Promise<unknown>;
/**
* A function transforming response data before it's returned. This is useful
* for post-processing data, e.g. converting ISO strings into Date objects.
*/
responseTransformer?: (data: unknown) => Promise<unknown>;
/**
* A function validating response data. This is useful if you want to ensure
* the response conforms to the desired shape, so it can be safely passed to
* the transformers and returned to the user.
*/
responseValidator?: (data: unknown) => Promise<unknown>;
}
type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false;
export type OmitNever<T extends Record<string, unknown>> = {
[K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true ? never : K]: T[K];
};
export {};
#!/usr/bin/env bun
import { $ } from "bun";
import fs from "fs/promises";
import path from "path";
console.log("=== Generating JS SDK ===");
console.log();
import { createClient } from "@hey-api/openapi-ts";
const dir = new URL("..", import.meta.url).pathname;
await fs.rm(path.join(dir, "src/gen"), { recursive: true, force: true });
await $ `bun run ../../opencode/src/index.ts generate > openapi.json`.cwd(dir);
await createClient({
input: "./openapi.json",
output: "./src/gen",
plugins: [
{
name: "@hey-api/typescript",
exportFromIndex: false,
},
{
name: "@hey-api/sdk",
instance: "OpencodeClient",
exportFromIndex: false,
auth: false,
},
{
name: "@hey-api/client-fetch",
exportFromIndex: false,
baseUrl: "http://localhost:4096",
},
],
});
#!/usr/bin/env bun
import { $ } from "bun";
await import("./generate.js");
await $ `bun tsc`;
// This file is auto-generated by @hey-api/openapi-ts
import { createClient, createConfig } from './client';
export const client = createClient(createConfig({
baseUrl: 'http://localhost:4096'
}));
import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils';
export const createClient = (config = {}) => {
let _config = mergeConfigs(createConfig(), config);
const getConfig = () => ({ ..._config });
const setConfig = (config) => {
_config = mergeConfigs(_config, config);
return getConfig();
};
const interceptors = createInterceptors();
const request = async (options) => {
const opts = {
..._config,
...options,
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
headers: mergeHeaders(_config.headers, options.headers),
};
if (opts.security) {
await setAuthParams({
...opts,
security: opts.security,
});
}
if (opts.requestValidator) {
await opts.requestValidator(opts);
}
if (opts.body && opts.bodySerializer) {
opts.body = opts.bodySerializer(opts.body);
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.body === undefined || opts.body === '') {
opts.headers.delete('Content-Type');
}
const url = buildUrl(opts);
const requestInit = {
redirect: 'follow',
...opts,
};
let request = new Request(url, requestInit);
for (const fn of interceptors.request._fns) {
if (fn) {
request = await fn(request, opts);
}
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = opts.fetch;
let response = await _fetch(request);
for (const fn of interceptors.response._fns) {
if (fn) {
response = await fn(response, request, opts);
}
}
const result = {
request,
response,
};
if (response.ok) {
if (response.status === 204 ||
response.headers.get('Content-Length') === '0') {
return opts.responseStyle === 'data'
? {}
: {
data: {},
...result,
};
}
const parseAs = (opts.parseAs === 'auto'
? getParseAs(response.headers.get('Content-Type'))
: opts.parseAs) ?? 'json';
let data;
switch (parseAs) {
case 'arrayBuffer':
case 'blob':
case 'formData':
case 'json':
case 'text':
data = await response[parseAs]();
break;
case 'stream':
return opts.responseStyle === 'data'
? response.body
: {
data: response.body,
...result,
};
}
if (parseAs === 'json') {
if (opts.responseValidator) {
await opts.responseValidator(data);
}
if (opts.responseTransformer) {
data = await opts.responseTransformer(data);
}
}
return opts.responseStyle === 'data'
? data
: {
data,
...result,
};
}
const textError = await response.text();
let jsonError;
try {
jsonError = JSON.parse(textError);
}
catch {
// noop
}
const error = jsonError ?? textError;
let finalError = error;
for (const fn of interceptors.error._fns) {
if (fn) {
finalError = (await fn(error, response, request, opts));
}
}
finalError = finalError || {};
if (opts.throwOnError) {
throw finalError;
}
// TODO: we probably want to return error and improve types
return opts.responseStyle === 'data'
? undefined
: {
error: finalError,
...result,
};
};
return {
buildUrl,
connect: (options) => request({ ...options, method: 'CONNECT' }),
delete: (options) => request({ ...options, method: 'DELETE' }),
get: (options) => request({ ...options, method: 'GET' }),
getConfig,
head: (options) => request({ ...options, method: 'HEAD' }),
interceptors,
options: (options) => request({ ...options, method: 'OPTIONS' }),
patch: (options) => request({ ...options, method: 'PATCH' }),
post: (options) => request({ ...options, method: 'POST' }),
put: (options) => request({ ...options, method: 'PUT' }),
request,
setConfig,
trace: (options) => request({ ...options, method: 'TRACE' }),
};
};
export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer';
export { buildClientParams } from '../core/params';
export { createClient } from './client';
export { createConfig, mergeHeaders } from './utils';
import { getAuthToken } from '../core/auth';
import { jsonBodySerializer } from '../core/bodySerializer';
import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer';
const PATH_PARAM_RE = /\{[^{}]+\}/g;
const defaultPathSerializer = ({ path, url: _url }) => {
let url = _url;
const matches = _url.match(PATH_PARAM_RE);
if (matches) {
for (const match of matches) {
let explode = false;
let name = match.substring(1, match.length - 1);
let style = 'simple';
if (name.endsWith('*')) {
explode = true;
name = name.substring(0, name.length - 1);
}
if (name.startsWith('.')) {
name = name.substring(1);
style = 'label';
}
else if (name.startsWith(';')) {
name = name.substring(1);
style = 'matrix';
}
const value = path[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
continue;
}
if (typeof value === 'object') {
url = url.replace(match, serializeObjectParam({
explode,
name,
style,
value: value,
valueOnly: true,
}));
continue;
}
if (style === 'matrix') {
url = url.replace(match, `;${serializePrimitiveParam({
name,
value: value,
})}`);
continue;
}
const replaceValue = encodeURIComponent(style === 'label' ? `.${value}` : value);
url = url.replace(match, replaceValue);
}
}
return url;
};
export const createQuerySerializer = ({ allowReserved, array, object, } = {}) => {
const querySerializer = (queryParams) => {
const search = [];
if (queryParams && typeof queryParams === 'object') {
for (const name in queryParams) {
const value = queryParams[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
const serializedArray = serializeArrayParam({
allowReserved,
explode: true,
name,
style: 'form',
value,
...array,
});
if (serializedArray)
search.push(serializedArray);
}
else if (typeof value === 'object') {
const serializedObject = serializeObjectParam({
allowReserved,
explode: true,
name,
style: 'deepObject',
value: value,
...object,
});
if (serializedObject)
search.push(serializedObject);
}
else {
const serializedPrimitive = serializePrimitiveParam({
allowReserved,
name,
value: value,
});
if (serializedPrimitive)
search.push(serializedPrimitive);
}
}
}
return search.join('&');
};
return querySerializer;
};
/**
* Infers parseAs value from provided Content-Type header.
*/
export const getParseAs = (contentType) => {
if (!contentType) {
// If no Content-Type header is provided, the best we can do is return the raw response body,
// which is effectively the same as the 'stream' option.
return 'stream';
}
const cleanContent = contentType.split(';')[0]?.trim();
if (!cleanContent) {
return;
}
if (cleanContent.startsWith('application/json') ||
cleanContent.endsWith('+json')) {
return 'json';
}
if (cleanContent === 'multipart/form-data') {
return 'formData';
}
if (['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))) {
return 'blob';
}
if (cleanContent.startsWith('text/')) {
return 'text';
}
return;
};
export const setAuthParams = async ({ security, ...options }) => {
for (const auth of security) {
const token = await getAuthToken(auth, options.auth);
if (!token) {
continue;
}
const name = auth.name ?? 'Authorization';
switch (auth.in) {
case 'query':
if (!options.query) {
options.query = {};
}
options.query[name] = token;
break;
case 'cookie':
options.headers.append('Cookie', `${name}=${token}`);
break;
case 'header':
default:
options.headers.set(name, token);
break;
}
return;
}
};
export const buildUrl = (options) => {
const url = getUrl({
baseUrl: options.baseUrl,
path: options.path,
query: options.query,
querySerializer: typeof options.querySerializer === 'function'
? options.querySerializer
: createQuerySerializer(options.querySerializer),
url: options.url,
});
return url;
};
export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }) => {
const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
let url = (baseUrl ?? '') + pathUrl;
if (path) {
url = defaultPathSerializer({ path, url });
}
let search = query ? querySerializer(query) : '';
if (search.startsWith('?')) {
search = search.substring(1);
}
if (search) {
url += `?${search}`;
}
return url;
};
export const mergeConfigs = (a, b) => {
const config = { ...a, ...b };
if (config.baseUrl?.endsWith('/')) {
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
}
config.headers = mergeHeaders(a.headers, b.headers);
return config;
};
export const mergeHeaders = (...headers) => {
const mergedHeaders = new Headers();
for (const header of headers) {
if (!header || typeof header !== 'object') {
continue;
}
const iterator = header instanceof Headers ? header.entries() : Object.entries(header);
for (const [key, value] of iterator) {
if (value === null) {
mergedHeaders.delete(key);
}
else if (Array.isArray(value)) {
for (const v of value) {
mergedHeaders.append(key, v);
}
}
else if (value !== undefined) {
// assume object headers are meant to be JSON stringified, i.e. their
// content value in OpenAPI specification is 'application/json'
mergedHeaders.set(key, typeof value === 'object' ? JSON.stringify(value) : value);
}
}
}
return mergedHeaders;
};
class Interceptors {
_fns;
constructor() {
this._fns = [];
}
clear() {
this._fns = [];
}
getInterceptorIndex(id) {
if (typeof id === 'number') {
return this._fns[id] ? id : -1;
}
else {
return this._fns.indexOf(id);
}
}
exists(id) {
const index = this.getInterceptorIndex(id);
return !!this._fns[index];
}
eject(id) {
const index = this.getInterceptorIndex(id);
if (this._fns[index]) {
this._fns[index] = null;
}
}
update(id, fn) {
const index = this.getInterceptorIndex(id);
if (this._fns[index]) {
this._fns[index] = fn;
return id;
}
else {
return false;
}
}
use(fn) {
this._fns = [...this._fns, fn];
return this._fns.length - 1;
}
}
// do not add `Middleware` as return type so we can use _fns internally
export const createInterceptors = () => ({
error: new Interceptors(),
request: new Interceptors(),
response: new Interceptors(),
});
const defaultQuerySerializer = createQuerySerializer({
allowReserved: false,
array: {
explode: true,
style: 'form',
},
object: {
explode: true,
style: 'deepObject',
},
});
const defaultHeaders = {
'Content-Type': 'application/json',
};
export const createConfig = (override = {}) => ({
...jsonBodySerializer,
headers: defaultHeaders,
parseAs: 'auto',
querySerializer: defaultQuerySerializer,
...override,
});
export const getAuthToken = async (auth, callback) => {
const token = typeof callback === 'function' ? await callback(auth) : callback;
if (!token) {
return;
}
if (auth.scheme === 'bearer') {
return `Bearer ${token}`;
}
if (auth.scheme === 'basic') {
return `Basic ${btoa(token)}`;
}
return token;
};
const serializeFormDataPair = (data, key, value) => {
if (typeof value === 'string' || value instanceof Blob) {
data.append(key, value);
}
else {
data.append(key, JSON.stringify(value));
}
};
const serializeUrlSearchParamsPair = (data, key, value) => {
if (typeof value === 'string') {
data.append(key, value);
}
else {
data.append(key, JSON.stringify(value));
}
};
export const formDataBodySerializer = {
bodySerializer: (body) => {
const data = new FormData();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeFormDataPair(data, key, v));
}
else {
serializeFormDataPair(data, key, value);
}
});
return data;
},
};
export const jsonBodySerializer = {
bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === 'bigint' ? value.toString() : value),
};
export const urlSearchParamsBodySerializer = {
bodySerializer: (body) => {
const data = new URLSearchParams();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
}
else {
serializeUrlSearchParamsPair(data, key, value);
}
});
return data.toString();
},
};
const extraPrefixesMap = {
$body_: 'body',
$headers_: 'headers',
$path_: 'path',
$query_: 'query',
};
const extraPrefixes = Object.entries(extraPrefixesMap);
const buildKeyMap = (fields, map) => {
if (!map) {
map = new Map();
}
for (const config of fields) {
if ('in' in config) {
if (config.key) {
map.set(config.key, {
in: config.in,
map: config.map,
});
}
}
else if (config.args) {
buildKeyMap(config.args, map);
}
}
return map;
};
const stripEmptySlots = (params) => {
for (const [slot, value] of Object.entries(params)) {
if (value && typeof value === 'object' && !Object.keys(value).length) {
delete params[slot];
}
}
};
export const buildClientParams = (args, fields) => {
const params = {
body: {},
headers: {},
path: {},
query: {},
};
const map = buildKeyMap(fields);
let config;
for (const [index, arg] of args.entries()) {
if (fields[index]) {
config = fields[index];
}
if (!config) {
continue;
}
if ('in' in config) {
if (config.key) {
const field = map.get(config.key);
const name = field.map || config.key;
params[field.in][name] = arg;
}
else {
params.body = arg;
}
}
else {
for (const [key, value] of Object.entries(arg ?? {})) {
const field = map.get(key);
if (field) {
const name = field.map || key;
params[field.in][name] = value;
}
else {
const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));
if (extra) {
const [prefix, slot] = extra;
params[slot][key.slice(prefix.length)] = value;
}
else {
for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) {
if (allowed) {
params[slot][key] = value;
break;
}
}
}
}
}
}
}
stripEmptySlots(params);
return params;
};
export const separatorArrayExplode = (style) => {
switch (style) {
case 'label':
return '.';
case 'matrix':
return ';';
case 'simple':
return ',';
default:
return '&';
}
};
export const separatorArrayNoExplode = (style) => {
switch (style) {
case 'form':
return ',';
case 'pipeDelimited':
return '|';
case 'spaceDelimited':
return '%20';
default:
return ',';
}
};
export const separatorObjectExplode = (style) => {
switch (style) {
case 'label':
return '.';
case 'matrix':
return ';';
case 'simple':
return ',';
default:
return '&';
}
};
export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }) => {
if (!explode) {
const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
switch (style) {
case 'label':
return `.${joinedValues}`;
case 'matrix':
return `;${name}=${joinedValues}`;
case 'simple':
return joinedValues;
default:
return `${name}=${joinedValues}`;
}
}
const separator = separatorArrayExplode(style);
const joinedValues = value
.map((v) => {
if (style === 'label' || style === 'simple') {
return allowReserved ? v : encodeURIComponent(v);
}
return serializePrimitiveParam({
allowReserved,
name,
value: v,
});
})
.join(separator);
return style === 'label' || style === 'matrix'
? separator + joinedValues
: joinedValues;
};
export const serializePrimitiveParam = ({ allowReserved, name, value, }) => {
if (value === undefined || value === null) {
return '';
}
if (typeof value === 'object') {
throw new Error('Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.');
}
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
};
export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }) => {
if (value instanceof Date) {
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
}
if (style !== 'deepObject' && !explode) {
let values = [];
Object.entries(value).forEach(([key, v]) => {
values = [
...values,
key,
allowReserved ? v : encodeURIComponent(v),
];
});
const joinedValues = values.join(',');
switch (style) {
case 'form':
return `${name}=${joinedValues}`;
case 'label':
return `.${joinedValues}`;
case 'matrix':
return `;${name}=${joinedValues}`;
default:
return joinedValues;
}
}
const separator = separatorObjectExplode(style);
const joinedValues = Object.entries(value)
.map(([key, v]) => serializePrimitiveParam({
allowReserved,
name: style === 'deepObject' ? `${name}[${key}]` : key,
value: v,
}))
.join(separator);
return style === 'label' || style === 'matrix'
? separator + joinedValues
: joinedValues;
};
// This file is auto-generated by @hey-api/openapi-ts
import { client as _heyApiClient } from './client.gen';
class _HeyApiClient {
_client = _heyApiClient;
constructor(args) {
if (args?.client) {
this._client = args.client;
}
}
}
class Event extends _HeyApiClient {
/**
* Get events
*/
subscribe(options) {
return (options?.client ?? this._client).get({
url: '/event',
...options
});
}
}
class App extends _HeyApiClient {
/**
* Get app info
*/
get(options) {
return (options?.client ?? this._client).get({
url: '/app',
...options
});
}
/**
* Initialize the app
*/
init(options) {
return (options?.client ?? this._client).post({
url: '/app/init',
...options
});
}
/**
* Write a log entry to the server logs
*/
log(options) {
return (options?.client ?? this._client).post({
url: '/log',
...options,
headers: {
'Content-Type': 'application/json',
...options?.headers
}
});
}
/**
* List all modes
*/
modes(options) {
return (options?.client ?? this._client).get({
url: '/mode',
...options
});
}
}
class Config extends _HeyApiClient {
/**
* Get config info
*/
get(options) {
return (options?.client ?? this._client).get({
url: '/config',
...options
});
}
/**
* List all providers
*/
providers(options) {
return (options?.client ?? this._client).get({
url: '/config/providers',
...options
});
}
}
class Session extends _HeyApiClient {
/**
* List all sessions
*/
list(options) {
return (options?.client ?? this._client).get({
url: '/session',
...options
});
}
/**
* Create a new session
*/
create(options) {
return (options?.client ?? this._client).post({
url: '/session',
...options
});
}
/**
* Delete a session and all its data
*/
delete(options) {
return (options.client ?? this._client).delete({
url: '/session/{id}',
...options
});
}
/**
* Analyze the app and create an AGENTS.md file
*/
init(options) {
return (options.client ?? this._client).post({
url: '/session/{id}/init',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
}
/**
* Abort a session
*/
abort(options) {
return (options.client ?? this._client).post({
url: '/session/{id}/abort',
...options
});
}
/**
* Unshare the session
*/
unshare(options) {
return (options.client ?? this._client).delete({
url: '/session/{id}/share',
...options
});
}
/**
* Share a session
*/
share(options) {
return (options.client ?? this._client).post({
url: '/session/{id}/share',
...options
});
}
/**
* Summarize the session
*/
summarize(options) {
return (options.client ?? this._client).post({
url: '/session/{id}/summarize',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
}
/**
* List messages for a session
*/
messages(options) {
return (options.client ?? this._client).get({
url: '/session/{id}/message',
...options
});
}
/**
* Create and send a new message to a session
*/
chat(options) {
return (options.client ?? this._client).post({
url: '/session/{id}/message',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
}
/**
* Revert a message
*/
revert(options) {
return (options.client ?? this._client).post({
url: '/session/{id}/revert',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
}
/**
* Restore all reverted messages
*/
unrevert(options) {
return (options.client ?? this._client).post({
url: '/session/{id}/unrevert',
...options
});
}
}
class Find extends _HeyApiClient {
/**
* Find text in files
*/
text(options) {
return (options.client ?? this._client).get({
url: '/find',
...options
});
}
/**
* Find files
*/
files(options) {
return (options.client ?? this._client).get({
url: '/find/file',
...options
});
}
/**
* Find workspace symbols
*/
symbols(options) {
return (options.client ?? this._client).get({
url: '/find/symbol',
...options
});
}
}
class File extends _HeyApiClient {
/**
* Read a file
*/
read(options) {
return (options.client ?? this._client).get({
url: '/file',
...options
});
}
/**
* Get file status
*/
status(options) {
return (options?.client ?? this._client).get({
url: '/file/status',
...options
});
}
}
class Tui extends _HeyApiClient {
/**
* Append prompt to the TUI
*/
appendPrompt(options) {
return (options?.client ?? this._client).post({
url: '/tui/append-prompt',
...options,
headers: {
'Content-Type': 'application/json',
...options?.headers
}
});
}
/**
* Open the help dialog
*/
openHelp(options) {
return (options?.client ?? this._client).post({
url: '/tui/open-help',
...options
});
}
}
export class OpencodeClient extends _HeyApiClient {
event = new Event({ client: this._client });
app = new App({ client: this._client });
config = new Config({ client: this._client });
session = new Session({ client: this._client });
find = new Find({ client: this._client });
file = new File({ client: this._client });
tui = new Tui({ client: this._client });
}
// This file is auto-generated by @hey-api/openapi-ts
import { createClient } from "./gen/client/client";
import { OpencodeClient } from "./gen/sdk.gen";
export function createOpencodeClient(config) {
const client = createClient(config);
return new OpencodeClient({ client });
}
+3
-3

@@ -1,3 +0,3 @@

import type { ClientOptions } from "./types.gen.js";
import { type Config, type ClientOptions as DefaultClientOptions } from "./client/index.js";
import type { ClientOptions } from './types.gen';
import { type Config, type ClientOptions as DefaultClientOptions } from './client';
/**

@@ -12,2 +12,2 @@ * The `createClientConfig()` function will be called on client initialization

export type CreateClientConfig<T extends DefaultClientOptions = ClientOptions> = (override?: Config<DefaultClientOptions & T>) => Config<Required<DefaultClientOptions> & T>;
export declare const client: import("./client/types.gen.js").Client;
export declare const client: import("./client").Client;
// This file is auto-generated by @hey-api/openapi-ts
import { createClient, createConfig } from "./client/index.js";
import { createClient, createConfig } from './client';
export const client = createClient(createConfig({
baseUrl: "http://localhost:4096",
baseUrl: 'http://localhost:4096'
}));

@@ -1,7 +0,7 @@

export type { Auth } from "../core/auth.gen.js";
export type { QuerySerializerOptions } from "../core/bodySerializer.gen.js";
export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from "../core/bodySerializer.gen.js";
export { buildClientParams } from "../core/params.gen.js";
export { createClient } from "./client.gen.js";
export type { Client, ClientOptions, Config, CreateClientConfig, Options, OptionsLegacyParser, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from "./types.gen.js";
export { createConfig, mergeHeaders } from "./utils.gen.js";
export type { Auth } from '../core/auth';
export type { QuerySerializerOptions } from '../core/bodySerializer';
export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer';
export { buildClientParams } from '../core/params';
export { createClient } from './client';
export type { Client, ClientOptions, Config, CreateClientConfig, Options, OptionsLegacyParser, RequestOptions, RequestResult, ResponseStyle, TDataShape, } from './types';
export { createConfig, mergeHeaders } from './utils';

@@ -1,5 +0,4 @@

// This file is auto-generated by @hey-api/openapi-ts
export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from "../core/bodySerializer.gen.js";
export { buildClientParams } from "../core/params.gen.js";
export { createClient } from "./client.gen.js";
export { createConfig, mergeHeaders } from "./utils.gen.js";
export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer';
export { buildClientParams } from '../core/params';
export { createClient } from './client';
export { createConfig, mergeHeaders } from './utils';

@@ -1,3 +0,3 @@

import type { Options as ClientOptions, TDataShape, Client } from "./client/index.js";
import type { GlobalEventData, GlobalEventResponses, ProjectListData, ProjectListResponses, ProjectCurrentData, ProjectCurrentResponses, PtyListData, PtyListResponses, PtyCreateData, PtyCreateResponses, PtyCreateErrors, PtyRemoveData, PtyRemoveResponses, PtyRemoveErrors, PtyGetData, PtyGetResponses, PtyGetErrors, PtyUpdateData, PtyUpdateResponses, PtyUpdateErrors, PtyConnectData, PtyConnectResponses, PtyConnectErrors, ConfigGetData, ConfigGetResponses, ConfigUpdateData, ConfigUpdateResponses, ConfigUpdateErrors, ToolIdsData, ToolIdsResponses, ToolIdsErrors, ToolListData, ToolListResponses, ToolListErrors, InstanceDisposeData, InstanceDisposeResponses, PathGetData, PathGetResponses, VcsGetData, VcsGetResponses, SessionListData, SessionListResponses, SessionCreateData, SessionCreateResponses, SessionCreateErrors, SessionStatusData, SessionStatusResponses, SessionStatusErrors, SessionDeleteData, SessionDeleteResponses, SessionDeleteErrors, SessionGetData, SessionGetResponses, SessionGetErrors, SessionUpdateData, SessionUpdateResponses, SessionUpdateErrors, SessionChildrenData, SessionChildrenResponses, SessionChildrenErrors, SessionTodoData, SessionTodoResponses, SessionTodoErrors, SessionInitData, SessionInitResponses, SessionInitErrors, SessionForkData, SessionForkResponses, SessionAbortData, SessionAbortResponses, SessionAbortErrors, SessionUnshareData, SessionUnshareResponses, SessionUnshareErrors, SessionShareData, SessionShareResponses, SessionShareErrors, SessionDiffData, SessionDiffResponses, SessionDiffErrors, SessionSummarizeData, SessionSummarizeResponses, SessionSummarizeErrors, SessionMessagesData, SessionMessagesResponses, SessionMessagesErrors, SessionPromptData, SessionPromptResponses, SessionPromptErrors, SessionMessageData, SessionMessageResponses, SessionMessageErrors, SessionPromptAsyncData, SessionPromptAsyncResponses, SessionPromptAsyncErrors, SessionCommandData, SessionCommandResponses, SessionCommandErrors, SessionShellData, SessionShellResponses, SessionShellErrors, SessionRevertData, SessionRevertResponses, SessionRevertErrors, SessionUnrevertData, SessionUnrevertResponses, SessionUnrevertErrors, PostSessionIdPermissionsPermissionIdData, PostSessionIdPermissionsPermissionIdResponses, PostSessionIdPermissionsPermissionIdErrors, CommandListData, CommandListResponses, ConfigProvidersData, ConfigProvidersResponses, ProviderListData, ProviderListResponses, ProviderAuthData, ProviderAuthResponses, ProviderOauthAuthorizeData, ProviderOauthAuthorizeResponses, ProviderOauthAuthorizeErrors, ProviderOauthCallbackData, ProviderOauthCallbackResponses, ProviderOauthCallbackErrors, FindTextData, FindTextResponses, FindFilesData, FindFilesResponses, FindSymbolsData, FindSymbolsResponses, FileListData, FileListResponses, FileReadData, FileReadResponses, FileStatusData, FileStatusResponses, AppLogData, AppLogResponses, AppLogErrors, AppAgentsData, AppAgentsResponses, McpStatusData, McpStatusResponses, McpAddData, McpAddResponses, McpAddErrors, McpAuthRemoveData, McpAuthRemoveResponses, McpAuthRemoveErrors, McpAuthStartData, McpAuthStartResponses, McpAuthStartErrors, McpAuthCallbackData, McpAuthCallbackResponses, McpAuthCallbackErrors, McpAuthAuthenticateData, McpAuthAuthenticateResponses, McpAuthAuthenticateErrors, McpConnectData, McpConnectResponses, McpDisconnectData, McpDisconnectResponses, LspStatusData, LspStatusResponses, FormatterStatusData, FormatterStatusResponses, TuiAppendPromptData, TuiAppendPromptResponses, TuiAppendPromptErrors, TuiOpenHelpData, TuiOpenHelpResponses, TuiOpenSessionsData, TuiOpenSessionsResponses, TuiOpenThemesData, TuiOpenThemesResponses, TuiOpenModelsData, TuiOpenModelsResponses, TuiSubmitPromptData, TuiSubmitPromptResponses, TuiClearPromptData, TuiClearPromptResponses, TuiExecuteCommandData, TuiExecuteCommandResponses, TuiExecuteCommandErrors, TuiShowToastData, TuiShowToastResponses, TuiPublishData, TuiPublishResponses, TuiPublishErrors, TuiControlNextData, TuiControlNextResponses, TuiControlResponseData, TuiControlResponseResponses, AuthSetData, AuthSetResponses, AuthSetErrors, EventSubscribeData, EventSubscribeResponses } from "./types.gen.js";
import type { Options as ClientOptions, TDataShape, Client } from './client';
import type { EventSubscribeData, EventSubscribeResponses, AppGetData, AppGetResponses, AppInitData, AppInitResponses, ConfigGetData, ConfigGetResponses, SessionListData, SessionListResponses, SessionCreateData, SessionCreateResponses, SessionCreateErrors, SessionDeleteData, SessionDeleteResponses, SessionInitData, SessionInitResponses, SessionAbortData, SessionAbortResponses, SessionUnshareData, SessionUnshareResponses, SessionShareData, SessionShareResponses, SessionSummarizeData, SessionSummarizeResponses, SessionMessagesData, SessionMessagesResponses, SessionChatData, SessionChatResponses, SessionRevertData, SessionRevertResponses, SessionUnrevertData, SessionUnrevertResponses, ConfigProvidersData, ConfigProvidersResponses, FindTextData, FindTextResponses, FindFilesData, FindFilesResponses, FindSymbolsData, FindSymbolsResponses, FileReadData, FileReadResponses, FileStatusData, FileStatusResponses, AppLogData, AppLogResponses, AppModesData, AppModesResponses, TuiAppendPromptData, TuiAppendPromptResponses, TuiOpenHelpData, TuiOpenHelpResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = ClientOptions<TData, ThrowOnError> & {

@@ -22,43 +22,25 @@ /**

}
declare class Global extends _HeyApiClient {
declare class Event extends _HeyApiClient {
/**
* Get events
*/
event<ThrowOnError extends boolean = false>(options?: Options<GlobalEventData, ThrowOnError>): Promise<import("./core/serverSentEvents.gen.js").ServerSentEventsResult<GlobalEventResponses, unknown>>;
subscribe<ThrowOnError extends boolean = false>(options?: Options<EventSubscribeData, ThrowOnError>): import("./client").RequestResult<EventSubscribeResponses, unknown, ThrowOnError, "fields">;
}
declare class Project extends _HeyApiClient {
declare class App extends _HeyApiClient {
/**
* List all projects
* Get app info
*/
list<ThrowOnError extends boolean = false>(options?: Options<ProjectListData, ThrowOnError>): import("./client/types.gen.js").RequestResult<ProjectListResponses, unknown, ThrowOnError, "fields">;
get<ThrowOnError extends boolean = false>(options?: Options<AppGetData, ThrowOnError>): import("./client").RequestResult<AppGetResponses, unknown, ThrowOnError, "fields">;
/**
* Get the current project
* Initialize the app
*/
current<ThrowOnError extends boolean = false>(options?: Options<ProjectCurrentData, ThrowOnError>): import("./client/types.gen.js").RequestResult<ProjectCurrentResponses, unknown, ThrowOnError, "fields">;
}
declare class Pty extends _HeyApiClient {
init<ThrowOnError extends boolean = false>(options?: Options<AppInitData, ThrowOnError>): import("./client").RequestResult<AppInitResponses, unknown, ThrowOnError, "fields">;
/**
* List all PTY sessions
* Write a log entry to the server logs
*/
list<ThrowOnError extends boolean = false>(options?: Options<PtyListData, ThrowOnError>): import("./client/types.gen.js").RequestResult<PtyListResponses, unknown, ThrowOnError, "fields">;
log<ThrowOnError extends boolean = false>(options?: Options<AppLogData, ThrowOnError>): import("./client").RequestResult<AppLogResponses, unknown, ThrowOnError, "fields">;
/**
* Create a new PTY session
* List all modes
*/
create<ThrowOnError extends boolean = false>(options?: Options<PtyCreateData, ThrowOnError>): import("./client/types.gen.js").RequestResult<PtyCreateResponses, PtyCreateErrors, ThrowOnError, "fields">;
/**
* Remove a PTY session
*/
remove<ThrowOnError extends boolean = false>(options: Options<PtyRemoveData, ThrowOnError>): import("./client/types.gen.js").RequestResult<PtyRemoveResponses, PtyRemoveErrors, ThrowOnError, "fields">;
/**
* Get PTY session info
*/
get<ThrowOnError extends boolean = false>(options: Options<PtyGetData, ThrowOnError>): import("./client/types.gen.js").RequestResult<PtyGetResponses, PtyGetErrors, ThrowOnError, "fields">;
/**
* Update PTY session
*/
update<ThrowOnError extends boolean = false>(options: Options<PtyUpdateData, ThrowOnError>): import("./client/types.gen.js").RequestResult<PtyUpdateResponses, PtyUpdateErrors, ThrowOnError, "fields">;
/**
* Connect to a PTY session
*/
connect<ThrowOnError extends boolean = false>(options: Options<PtyConnectData, ThrowOnError>): import("./client/types.gen.js").RequestResult<PtyConnectResponses, PtyConnectErrors, ThrowOnError, "fields">;
modes<ThrowOnError extends boolean = false>(options?: Options<AppModesData, ThrowOnError>): import("./client").RequestResult<AppModesResponses, unknown, ThrowOnError, "fields">;
}

@@ -69,40 +51,8 @@ declare class Config extends _HeyApiClient {

*/
get<ThrowOnError extends boolean = false>(options?: Options<ConfigGetData, ThrowOnError>): import("./client/types.gen.js").RequestResult<ConfigGetResponses, unknown, ThrowOnError, "fields">;
get<ThrowOnError extends boolean = false>(options?: Options<ConfigGetData, ThrowOnError>): import("./client").RequestResult<ConfigGetResponses, unknown, ThrowOnError, "fields">;
/**
* Update config
*/
update<ThrowOnError extends boolean = false>(options?: Options<ConfigUpdateData, ThrowOnError>): import("./client/types.gen.js").RequestResult<ConfigUpdateResponses, ConfigUpdateErrors, ThrowOnError, "fields">;
/**
* List all providers
*/
providers<ThrowOnError extends boolean = false>(options?: Options<ConfigProvidersData, ThrowOnError>): import("./client/types.gen.js").RequestResult<ConfigProvidersResponses, unknown, ThrowOnError, "fields">;
providers<ThrowOnError extends boolean = false>(options?: Options<ConfigProvidersData, ThrowOnError>): import("./client").RequestResult<ConfigProvidersResponses, unknown, ThrowOnError, "fields">;
}
declare class Tool extends _HeyApiClient {
/**
* List all tool IDs (including built-in and dynamically registered)
*/
ids<ThrowOnError extends boolean = false>(options?: Options<ToolIdsData, ThrowOnError>): import("./client/types.gen.js").RequestResult<ToolIdsResponses, ToolIdsErrors, ThrowOnError, "fields">;
/**
* List tools with JSON schema parameters for a provider/model
*/
list<ThrowOnError extends boolean = false>(options: Options<ToolListData, ThrowOnError>): import("./client/types.gen.js").RequestResult<ToolListResponses, ToolListErrors, ThrowOnError, "fields">;
}
declare class Instance extends _HeyApiClient {
/**
* Dispose the current instance
*/
dispose<ThrowOnError extends boolean = false>(options?: Options<InstanceDisposeData, ThrowOnError>): import("./client/types.gen.js").RequestResult<InstanceDisposeResponses, unknown, ThrowOnError, "fields">;
}
declare class Path extends _HeyApiClient {
/**
* Get the current path
*/
get<ThrowOnError extends boolean = false>(options?: Options<PathGetData, ThrowOnError>): import("./client/types.gen.js").RequestResult<PathGetResponses, unknown, ThrowOnError, "fields">;
}
declare class Vcs extends _HeyApiClient {
/**
* Get VCS info for the current instance
*/
get<ThrowOnError extends boolean = false>(options?: Options<VcsGetData, ThrowOnError>): import("./client/types.gen.js").RequestResult<VcsGetResponses, unknown, ThrowOnError, "fields">;
}
declare class Session extends _HeyApiClient {

@@ -112,119 +62,48 @@ /**

*/
list<ThrowOnError extends boolean = false>(options?: Options<SessionListData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionListResponses, unknown, ThrowOnError, "fields">;
list<ThrowOnError extends boolean = false>(options?: Options<SessionListData, ThrowOnError>): import("./client").RequestResult<SessionListResponses, unknown, ThrowOnError, "fields">;
/**
* Create a new session
*/
create<ThrowOnError extends boolean = false>(options?: Options<SessionCreateData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionCreateResponses, SessionCreateErrors, ThrowOnError, "fields">;
create<ThrowOnError extends boolean = false>(options?: Options<SessionCreateData, ThrowOnError>): import("./client").RequestResult<SessionCreateResponses, SessionCreateErrors, ThrowOnError, "fields">;
/**
* Get session status
*/
status<ThrowOnError extends boolean = false>(options?: Options<SessionStatusData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionStatusResponses, SessionStatusErrors, ThrowOnError, "fields">;
/**
* Delete a session and all its data
*/
delete<ThrowOnError extends boolean = false>(options: Options<SessionDeleteData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionDeleteResponses, SessionDeleteErrors, ThrowOnError, "fields">;
delete<ThrowOnError extends boolean = false>(options: Options<SessionDeleteData, ThrowOnError>): import("./client").RequestResult<SessionDeleteResponses, unknown, ThrowOnError, "fields">;
/**
* Get session
*/
get<ThrowOnError extends boolean = false>(options: Options<SessionGetData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionGetResponses, SessionGetErrors, ThrowOnError, "fields">;
/**
* Update session properties
*/
update<ThrowOnError extends boolean = false>(options: Options<SessionUpdateData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionUpdateResponses, SessionUpdateErrors, ThrowOnError, "fields">;
/**
* Get a session's children
*/
children<ThrowOnError extends boolean = false>(options: Options<SessionChildrenData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionChildrenResponses, SessionChildrenErrors, ThrowOnError, "fields">;
/**
* Get the todo list for a session
*/
todo<ThrowOnError extends boolean = false>(options: Options<SessionTodoData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionTodoResponses, SessionTodoErrors, ThrowOnError, "fields">;
/**
* Analyze the app and create an AGENTS.md file
*/
init<ThrowOnError extends boolean = false>(options: Options<SessionInitData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionInitResponses, SessionInitErrors, ThrowOnError, "fields">;
init<ThrowOnError extends boolean = false>(options: Options<SessionInitData, ThrowOnError>): import("./client").RequestResult<SessionInitResponses, unknown, ThrowOnError, "fields">;
/**
* Fork an existing session at a specific message
*/
fork<ThrowOnError extends boolean = false>(options: Options<SessionForkData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionForkResponses, unknown, ThrowOnError, "fields">;
/**
* Abort a session
*/
abort<ThrowOnError extends boolean = false>(options: Options<SessionAbortData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionAbortResponses, SessionAbortErrors, ThrowOnError, "fields">;
abort<ThrowOnError extends boolean = false>(options: Options<SessionAbortData, ThrowOnError>): import("./client").RequestResult<SessionAbortResponses, unknown, ThrowOnError, "fields">;
/**
* Unshare the session
*/
unshare<ThrowOnError extends boolean = false>(options: Options<SessionUnshareData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionUnshareResponses, SessionUnshareErrors, ThrowOnError, "fields">;
unshare<ThrowOnError extends boolean = false>(options: Options<SessionUnshareData, ThrowOnError>): import("./client").RequestResult<SessionUnshareResponses, unknown, ThrowOnError, "fields">;
/**
* Share a session
*/
share<ThrowOnError extends boolean = false>(options: Options<SessionShareData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionShareResponses, SessionShareErrors, ThrowOnError, "fields">;
share<ThrowOnError extends boolean = false>(options: Options<SessionShareData, ThrowOnError>): import("./client").RequestResult<SessionShareResponses, unknown, ThrowOnError, "fields">;
/**
* Get the diff for this session
*/
diff<ThrowOnError extends boolean = false>(options: Options<SessionDiffData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionDiffResponses, SessionDiffErrors, ThrowOnError, "fields">;
/**
* Summarize the session
*/
summarize<ThrowOnError extends boolean = false>(options: Options<SessionSummarizeData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionSummarizeResponses, SessionSummarizeErrors, ThrowOnError, "fields">;
summarize<ThrowOnError extends boolean = false>(options: Options<SessionSummarizeData, ThrowOnError>): import("./client").RequestResult<SessionSummarizeResponses, unknown, ThrowOnError, "fields">;
/**
* List messages for a session
*/
messages<ThrowOnError extends boolean = false>(options: Options<SessionMessagesData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionMessagesResponses, SessionMessagesErrors, ThrowOnError, "fields">;
messages<ThrowOnError extends boolean = false>(options: Options<SessionMessagesData, ThrowOnError>): import("./client").RequestResult<SessionMessagesResponses, unknown, ThrowOnError, "fields">;
/**
* Create and send a new message to a session
*/
prompt<ThrowOnError extends boolean = false>(options: Options<SessionPromptData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionPromptResponses, SessionPromptErrors, ThrowOnError, "fields">;
chat<ThrowOnError extends boolean = false>(options: Options<SessionChatData, ThrowOnError>): import("./client").RequestResult<SessionChatResponses, unknown, ThrowOnError, "fields">;
/**
* Get a message from a session
*/
message<ThrowOnError extends boolean = false>(options: Options<SessionMessageData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionMessageResponses, SessionMessageErrors, ThrowOnError, "fields">;
/**
* Create and send a new message to a session, start if needed and return immediately
*/
promptAsync<ThrowOnError extends boolean = false>(options: Options<SessionPromptAsyncData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionPromptAsyncResponses, SessionPromptAsyncErrors, ThrowOnError, "fields">;
/**
* Send a new command to a session
*/
command<ThrowOnError extends boolean = false>(options: Options<SessionCommandData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionCommandResponses, SessionCommandErrors, ThrowOnError, "fields">;
/**
* Run a shell command
*/
shell<ThrowOnError extends boolean = false>(options: Options<SessionShellData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionShellResponses, SessionShellErrors, ThrowOnError, "fields">;
/**
* Revert a message
*/
revert<ThrowOnError extends boolean = false>(options: Options<SessionRevertData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionRevertResponses, SessionRevertErrors, ThrowOnError, "fields">;
revert<ThrowOnError extends boolean = false>(options: Options<SessionRevertData, ThrowOnError>): import("./client").RequestResult<SessionRevertResponses, unknown, ThrowOnError, "fields">;
/**
* Restore all reverted messages
*/
unrevert<ThrowOnError extends boolean = false>(options: Options<SessionUnrevertData, ThrowOnError>): import("./client/types.gen.js").RequestResult<SessionUnrevertResponses, SessionUnrevertErrors, ThrowOnError, "fields">;
unrevert<ThrowOnError extends boolean = false>(options: Options<SessionUnrevertData, ThrowOnError>): import("./client").RequestResult<SessionUnrevertResponses, unknown, ThrowOnError, "fields">;
}
declare class Command extends _HeyApiClient {
/**
* List all commands
*/
list<ThrowOnError extends boolean = false>(options?: Options<CommandListData, ThrowOnError>): import("./client/types.gen.js").RequestResult<CommandListResponses, unknown, ThrowOnError, "fields">;
}
declare class Oauth extends _HeyApiClient {
/**
* Authorize a provider using OAuth
*/
authorize<ThrowOnError extends boolean = false>(options: Options<ProviderOauthAuthorizeData, ThrowOnError>): import("./client/types.gen.js").RequestResult<ProviderOauthAuthorizeResponses, ProviderOauthAuthorizeErrors, ThrowOnError, "fields">;
/**
* Handle OAuth callback for a provider
*/
callback<ThrowOnError extends boolean = false>(options: Options<ProviderOauthCallbackData, ThrowOnError>): import("./client/types.gen.js").RequestResult<ProviderOauthCallbackResponses, ProviderOauthCallbackErrors, ThrowOnError, "fields">;
}
declare class Provider extends _HeyApiClient {
/**
* List all providers
*/
list<ThrowOnError extends boolean = false>(options?: Options<ProviderListData, ThrowOnError>): import("./client/types.gen.js").RequestResult<ProviderListResponses, unknown, ThrowOnError, "fields">;
/**
* Get provider authentication methods
*/
auth<ThrowOnError extends boolean = false>(options?: Options<ProviderAuthData, ThrowOnError>): import("./client/types.gen.js").RequestResult<ProviderAuthResponses, unknown, ThrowOnError, "fields">;
oauth: Oauth;
}
declare class Find extends _HeyApiClient {

@@ -234,99 +113,22 @@ /**

*/
text<ThrowOnError extends boolean = false>(options: Options<FindTextData, ThrowOnError>): import("./client/types.gen.js").RequestResult<FindTextResponses, unknown, ThrowOnError, "fields">;
text<ThrowOnError extends boolean = false>(options: Options<FindTextData, ThrowOnError>): import("./client").RequestResult<FindTextResponses, unknown, ThrowOnError, "fields">;
/**
* Find files
*/
files<ThrowOnError extends boolean = false>(options: Options<FindFilesData, ThrowOnError>): import("./client/types.gen.js").RequestResult<FindFilesResponses, unknown, ThrowOnError, "fields">;
files<ThrowOnError extends boolean = false>(options: Options<FindFilesData, ThrowOnError>): import("./client").RequestResult<FindFilesResponses, unknown, ThrowOnError, "fields">;
/**
* Find workspace symbols
*/
symbols<ThrowOnError extends boolean = false>(options: Options<FindSymbolsData, ThrowOnError>): import("./client/types.gen.js").RequestResult<FindSymbolsResponses, unknown, ThrowOnError, "fields">;
symbols<ThrowOnError extends boolean = false>(options: Options<FindSymbolsData, ThrowOnError>): import("./client").RequestResult<FindSymbolsResponses, unknown, ThrowOnError, "fields">;
}
declare class File extends _HeyApiClient {
/**
* List files and directories
*/
list<ThrowOnError extends boolean = false>(options: Options<FileListData, ThrowOnError>): import("./client/types.gen.js").RequestResult<FileListResponses, unknown, ThrowOnError, "fields">;
/**
* Read a file
*/
read<ThrowOnError extends boolean = false>(options: Options<FileReadData, ThrowOnError>): import("./client/types.gen.js").RequestResult<FileReadResponses, unknown, ThrowOnError, "fields">;
read<ThrowOnError extends boolean = false>(options: Options<FileReadData, ThrowOnError>): import("./client").RequestResult<FileReadResponses, unknown, ThrowOnError, "fields">;
/**
* Get file status
*/
status<ThrowOnError extends boolean = false>(options?: Options<FileStatusData, ThrowOnError>): import("./client/types.gen.js").RequestResult<FileStatusResponses, unknown, ThrowOnError, "fields">;
status<ThrowOnError extends boolean = false>(options?: Options<FileStatusData, ThrowOnError>): import("./client").RequestResult<FileStatusResponses, unknown, ThrowOnError, "fields">;
}
declare class App extends _HeyApiClient {
/**
* Write a log entry to the server logs
*/
log<ThrowOnError extends boolean = false>(options?: Options<AppLogData, ThrowOnError>): import("./client/types.gen.js").RequestResult<AppLogResponses, AppLogErrors, ThrowOnError, "fields">;
/**
* List all agents
*/
agents<ThrowOnError extends boolean = false>(options?: Options<AppAgentsData, ThrowOnError>): import("./client/types.gen.js").RequestResult<AppAgentsResponses, unknown, ThrowOnError, "fields">;
}
declare class Auth extends _HeyApiClient {
/**
* Remove OAuth credentials for an MCP server
*/
remove<ThrowOnError extends boolean = false>(options: Options<McpAuthRemoveData, ThrowOnError>): import("./client/types.gen.js").RequestResult<McpAuthRemoveResponses, McpAuthRemoveErrors, ThrowOnError, "fields">;
/**
* Start OAuth authentication flow for an MCP server
*/
start<ThrowOnError extends boolean = false>(options: Options<McpAuthStartData, ThrowOnError>): import("./client/types.gen.js").RequestResult<McpAuthStartResponses, McpAuthStartErrors, ThrowOnError, "fields">;
/**
* Complete OAuth authentication with authorization code
*/
callback<ThrowOnError extends boolean = false>(options: Options<McpAuthCallbackData, ThrowOnError>): import("./client/types.gen.js").RequestResult<McpAuthCallbackResponses, McpAuthCallbackErrors, ThrowOnError, "fields">;
/**
* Start OAuth flow and wait for callback (opens browser)
*/
authenticate<ThrowOnError extends boolean = false>(options: Options<McpAuthAuthenticateData, ThrowOnError>): import("./client/types.gen.js").RequestResult<McpAuthAuthenticateResponses, McpAuthAuthenticateErrors, ThrowOnError, "fields">;
/**
* Set authentication credentials
*/
set<ThrowOnError extends boolean = false>(options: Options<AuthSetData, ThrowOnError>): import("./client/types.gen.js").RequestResult<AuthSetResponses, AuthSetErrors, ThrowOnError, "fields">;
}
declare class Mcp extends _HeyApiClient {
/**
* Get MCP server status
*/
status<ThrowOnError extends boolean = false>(options?: Options<McpStatusData, ThrowOnError>): import("./client/types.gen.js").RequestResult<McpStatusResponses, unknown, ThrowOnError, "fields">;
/**
* Add MCP server dynamically
*/
add<ThrowOnError extends boolean = false>(options?: Options<McpAddData, ThrowOnError>): import("./client/types.gen.js").RequestResult<McpAddResponses, McpAddErrors, ThrowOnError, "fields">;
/**
* Connect an MCP server
*/
connect<ThrowOnError extends boolean = false>(options: Options<McpConnectData, ThrowOnError>): import("./client/types.gen.js").RequestResult<McpConnectResponses, unknown, ThrowOnError, "fields">;
/**
* Disconnect an MCP server
*/
disconnect<ThrowOnError extends boolean = false>(options: Options<McpDisconnectData, ThrowOnError>): import("./client/types.gen.js").RequestResult<McpDisconnectResponses, unknown, ThrowOnError, "fields">;
auth: Auth;
}
declare class Lsp extends _HeyApiClient {
/**
* Get LSP server status
*/
status<ThrowOnError extends boolean = false>(options?: Options<LspStatusData, ThrowOnError>): import("./client/types.gen.js").RequestResult<LspStatusResponses, unknown, ThrowOnError, "fields">;
}
declare class Formatter extends _HeyApiClient {
/**
* Get formatter status
*/
status<ThrowOnError extends boolean = false>(options?: Options<FormatterStatusData, ThrowOnError>): import("./client/types.gen.js").RequestResult<FormatterStatusResponses, unknown, ThrowOnError, "fields">;
}
declare class Control extends _HeyApiClient {
/**
* Get the next TUI request from the queue
*/
next<ThrowOnError extends boolean = false>(options?: Options<TuiControlNextData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiControlNextResponses, unknown, ThrowOnError, "fields">;
/**
* Submit a response to the TUI request queue
*/
response<ThrowOnError extends boolean = false>(options?: Options<TuiControlResponseData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiControlResponseResponses, unknown, ThrowOnError, "fields">;
}
declare class Tui extends _HeyApiClient {

@@ -336,73 +138,17 @@ /**

*/
appendPrompt<ThrowOnError extends boolean = false>(options?: Options<TuiAppendPromptData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiAppendPromptResponses, TuiAppendPromptErrors, ThrowOnError, "fields">;
appendPrompt<ThrowOnError extends boolean = false>(options?: Options<TuiAppendPromptData, ThrowOnError>): import("./client").RequestResult<TuiAppendPromptResponses, unknown, ThrowOnError, "fields">;
/**
* Open the help dialog
*/
openHelp<ThrowOnError extends boolean = false>(options?: Options<TuiOpenHelpData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiOpenHelpResponses, unknown, ThrowOnError, "fields">;
/**
* Open the session dialog
*/
openSessions<ThrowOnError extends boolean = false>(options?: Options<TuiOpenSessionsData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiOpenSessionsResponses, unknown, ThrowOnError, "fields">;
/**
* Open the theme dialog
*/
openThemes<ThrowOnError extends boolean = false>(options?: Options<TuiOpenThemesData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiOpenThemesResponses, unknown, ThrowOnError, "fields">;
/**
* Open the model dialog
*/
openModels<ThrowOnError extends boolean = false>(options?: Options<TuiOpenModelsData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiOpenModelsResponses, unknown, ThrowOnError, "fields">;
/**
* Submit the prompt
*/
submitPrompt<ThrowOnError extends boolean = false>(options?: Options<TuiSubmitPromptData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiSubmitPromptResponses, unknown, ThrowOnError, "fields">;
/**
* Clear the prompt
*/
clearPrompt<ThrowOnError extends boolean = false>(options?: Options<TuiClearPromptData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiClearPromptResponses, unknown, ThrowOnError, "fields">;
/**
* Execute a TUI command (e.g. agent_cycle)
*/
executeCommand<ThrowOnError extends boolean = false>(options?: Options<TuiExecuteCommandData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiExecuteCommandResponses, TuiExecuteCommandErrors, ThrowOnError, "fields">;
/**
* Show a toast notification in the TUI
*/
showToast<ThrowOnError extends boolean = false>(options?: Options<TuiShowToastData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiShowToastResponses, unknown, ThrowOnError, "fields">;
/**
* Publish a TUI event
*/
publish<ThrowOnError extends boolean = false>(options?: Options<TuiPublishData, ThrowOnError>): import("./client/types.gen.js").RequestResult<TuiPublishResponses, TuiPublishErrors, ThrowOnError, "fields">;
control: Control;
openHelp<ThrowOnError extends boolean = false>(options?: Options<TuiOpenHelpData, ThrowOnError>): import("./client").RequestResult<TuiOpenHelpResponses, unknown, ThrowOnError, "fields">;
}
declare class Event extends _HeyApiClient {
/**
* Get events
*/
subscribe<ThrowOnError extends boolean = false>(options?: Options<EventSubscribeData, ThrowOnError>): Promise<import("./core/serverSentEvents.gen.js").ServerSentEventsResult<EventSubscribeResponses, unknown>>;
}
export declare class OpencodeClient extends _HeyApiClient {
/**
* Respond to a permission request
*/
postSessionIdPermissionsPermissionId<ThrowOnError extends boolean = false>(options: Options<PostSessionIdPermissionsPermissionIdData, ThrowOnError>): import("./client/types.gen.js").RequestResult<PostSessionIdPermissionsPermissionIdResponses, PostSessionIdPermissionsPermissionIdErrors, ThrowOnError, "fields">;
global: Global;
project: Project;
pty: Pty;
event: Event;
app: App;
config: Config;
tool: Tool;
instance: Instance;
path: Path;
vcs: Vcs;
session: Session;
command: Command;
provider: Provider;
find: Find;
file: File;
app: App;
mcp: Mcp;
lsp: Lsp;
formatter: Formatter;
tui: Tui;
auth: Auth;
event: Event;
}
export {};
// This file is auto-generated by @hey-api/openapi-ts
import { client as _heyApiClient } from "./client.gen.js";
import { client as _heyApiClient } from './client.gen';
class _HeyApiClient {

@@ -11,94 +11,52 @@ _client = _heyApiClient;

}
class Global extends _HeyApiClient {
class Event extends _HeyApiClient {
/**
* Get events
*/
event(options) {
return (options?.client ?? this._client).get.sse({
url: "/global/event",
...options,
});
}
}
class Project extends _HeyApiClient {
/**
* List all projects
*/
list(options) {
subscribe(options) {
return (options?.client ?? this._client).get({
url: "/project",
...options,
url: '/event',
...options
});
}
/**
* Get the current project
*/
current(options) {
return (options?.client ?? this._client).get({
url: "/project/current",
...options,
});
}
}
class Pty extends _HeyApiClient {
class App extends _HeyApiClient {
/**
* List all PTY sessions
* Get app info
*/
list(options) {
get(options) {
return (options?.client ?? this._client).get({
url: "/pty",
...options,
url: '/app',
...options
});
}
/**
* Create a new PTY session
* Initialize the app
*/
create(options) {
init(options) {
return (options?.client ?? this._client).post({
url: "/pty",
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
url: '/app/init',
...options
});
}
/**
* Remove a PTY session
* Write a log entry to the server logs
*/
remove(options) {
return (options.client ?? this._client).delete({
url: "/pty/{id}",
log(options) {
return (options?.client ?? this._client).post({
url: '/log',
...options,
});
}
/**
* Get PTY session info
*/
get(options) {
return (options.client ?? this._client).get({
url: "/pty/{id}",
...options,
});
}
/**
* Update PTY session
*/
update(options) {
return (options.client ?? this._client).put({
url: "/pty/{id}",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
'Content-Type': 'application/json',
...options?.headers
}
});
}
/**
* Connect to a PTY session
* List all modes
*/
connect(options) {
return (options.client ?? this._client).get({
url: "/pty/{id}/connect",
...options,
modes(options) {
return (options?.client ?? this._client).get({
url: '/mode',
...options
});

@@ -113,20 +71,7 @@ }

return (options?.client ?? this._client).get({
url: "/config",
...options,
url: '/config',
...options
});
}
/**
* Update config
*/
update(options) {
return (options?.client ?? this._client).patch({
url: "/config",
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
});
}
/**
* List all providers

@@ -136,60 +81,7 @@ */

return (options?.client ?? this._client).get({
url: "/config/providers",
...options,
url: '/config/providers',
...options
});
}
}
class Tool extends _HeyApiClient {
/**
* List all tool IDs (including built-in and dynamically registered)
*/
ids(options) {
return (options?.client ?? this._client).get({
url: "/experimental/tool/ids",
...options,
});
}
/**
* List tools with JSON schema parameters for a provider/model
*/
list(options) {
return (options.client ?? this._client).get({
url: "/experimental/tool",
...options,
});
}
}
class Instance extends _HeyApiClient {
/**
* Dispose the current instance
*/
dispose(options) {
return (options?.client ?? this._client).post({
url: "/instance/dispose",
...options,
});
}
}
class Path extends _HeyApiClient {
/**
* Get the current path
*/
get(options) {
return (options?.client ?? this._client).get({
url: "/path",
...options,
});
}
}
class Vcs extends _HeyApiClient {
/**
* Get VCS info for the current instance
*/
get(options) {
return (options?.client ?? this._client).get({
url: "/vcs",
...options,
});
}
}
class Session extends _HeyApiClient {

@@ -201,4 +93,4 @@ /**

return (options?.client ?? this._client).get({
url: "/session",
...options,
url: '/session',
...options
});

@@ -211,20 +103,7 @@ }

return (options?.client ?? this._client).post({
url: "/session",
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
url: '/session',
...options
});
}
/**
* Get session status
*/
status(options) {
return (options?.client ?? this._client).get({
url: "/session/status",
...options,
});
}
/**
* Delete a session and all its data

@@ -234,47 +113,7 @@ */

return (options.client ?? this._client).delete({
url: "/session/{id}",
...options,
url: '/session/{id}',
...options
});
}
/**
* Get session
*/
get(options) {
return (options.client ?? this._client).get({
url: "/session/{id}",
...options,
});
}
/**
* Update session properties
*/
update(options) {
return (options.client ?? this._client).patch({
url: "/session/{id}",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
}
/**
* Get a session's children
*/
children(options) {
return (options.client ?? this._client).get({
url: "/session/{id}/children",
...options,
});
}
/**
* Get the todo list for a session
*/
todo(options) {
return (options.client ?? this._client).get({
url: "/session/{id}/todo",
...options,
});
}
/**
* Analyze the app and create an AGENTS.md file

@@ -284,24 +123,11 @@ */

return (options.client ?? this._client).post({
url: "/session/{id}/init",
url: '/session/{id}/init',
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
'Content-Type': 'application/json',
...options.headers
}
});
}
/**
* Fork an existing session at a specific message
*/
fork(options) {
return (options.client ?? this._client).post({
url: "/session/{id}/fork",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
}
/**
* Abort a session

@@ -311,4 +137,4 @@ */

return (options.client ?? this._client).post({
url: "/session/{id}/abort",
...options,
url: '/session/{id}/abort',
...options
});

@@ -321,4 +147,4 @@ }

return (options.client ?? this._client).delete({
url: "/session/{id}/share",
...options,
url: '/session/{id}/share',
...options
});

@@ -331,16 +157,7 @@ }

return (options.client ?? this._client).post({
url: "/session/{id}/share",
...options,
url: '/session/{id}/share',
...options
});
}
/**
* Get the diff for this session
*/
diff(options) {
return (options.client ?? this._client).get({
url: "/session/{id}/diff",
...options,
});
}
/**
* Summarize the session

@@ -350,8 +167,8 @@ */

return (options.client ?? this._client).post({
url: "/session/{id}/summarize",
url: '/session/{id}/summarize',
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
'Content-Type': 'application/json',
...options.headers
}
});

@@ -364,4 +181,4 @@ }

return (options.client ?? this._client).get({
url: "/session/{id}/message",
...options,
url: '/session/{id}/message',
...options
});

@@ -372,61 +189,13 @@ }

*/
prompt(options) {
chat(options) {
return (options.client ?? this._client).post({
url: "/session/{id}/message",
url: '/session/{id}/message',
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
'Content-Type': 'application/json',
...options.headers
}
});
}
/**
* Get a message from a session
*/
message(options) {
return (options.client ?? this._client).get({
url: "/session/{id}/message/{messageID}",
...options,
});
}
/**
* Create and send a new message to a session, start if needed and return immediately
*/
promptAsync(options) {
return (options.client ?? this._client).post({
url: "/session/{id}/prompt_async",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
}
/**
* Send a new command to a session
*/
command(options) {
return (options.client ?? this._client).post({
url: "/session/{id}/command",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
}
/**
* Run a shell command
*/
shell(options) {
return (options.client ?? this._client).post({
url: "/session/{id}/shell",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
}
/**
* Revert a message

@@ -436,8 +205,8 @@ */

return (options.client ?? this._client).post({
url: "/session/{id}/revert",
url: '/session/{id}/revert',
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
'Content-Type': 'application/json',
...options.headers
}
});

@@ -450,67 +219,7 @@ }

return (options.client ?? this._client).post({
url: "/session/{id}/unrevert",
...options,
url: '/session/{id}/unrevert',
...options
});
}
}
class Command extends _HeyApiClient {
/**
* List all commands
*/
list(options) {
return (options?.client ?? this._client).get({
url: "/command",
...options,
});
}
}
class Oauth extends _HeyApiClient {
/**
* Authorize a provider using OAuth
*/
authorize(options) {
return (options.client ?? this._client).post({
url: "/provider/{id}/oauth/authorize",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
}
/**
* Handle OAuth callback for a provider
*/
callback(options) {
return (options.client ?? this._client).post({
url: "/provider/{id}/oauth/callback",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
}
}
class Provider extends _HeyApiClient {
/**
* List all providers
*/
list(options) {
return (options?.client ?? this._client).get({
url: "/provider",
...options,
});
}
/**
* Get provider authentication methods
*/
auth(options) {
return (options?.client ?? this._client).get({
url: "/provider/auth",
...options,
});
}
oauth = new Oauth({ client: this._client });
}
class Find extends _HeyApiClient {

@@ -522,4 +231,4 @@ /**

return (options.client ?? this._client).get({
url: "/find",
...options,
url: '/find',
...options
});

@@ -532,4 +241,4 @@ }

return (options.client ?? this._client).get({
url: "/find/file",
...options,
url: '/find/file',
...options
});

@@ -542,4 +251,4 @@ }

return (options.client ?? this._client).get({
url: "/find/symbol",
...options,
url: '/find/symbol',
...options
});

@@ -550,11 +259,2 @@ }

/**
* List files and directories
*/
list(options) {
return (options.client ?? this._client).get({
url: "/file",
...options,
});
}
/**
* Read a file

@@ -564,4 +264,4 @@ */

return (options.client ?? this._client).get({
url: "/file/content",
...options,
url: '/file',
...options
});

@@ -574,175 +274,7 @@ }

return (options?.client ?? this._client).get({
url: "/file/status",
...options,
url: '/file/status',
...options
});
}
}
class App extends _HeyApiClient {
/**
* Write a log entry to the server logs
*/
log(options) {
return (options?.client ?? this._client).post({
url: "/log",
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
});
}
/**
* List all agents
*/
agents(options) {
return (options?.client ?? this._client).get({
url: "/agent",
...options,
});
}
}
class Auth extends _HeyApiClient {
/**
* Remove OAuth credentials for an MCP server
*/
remove(options) {
return (options.client ?? this._client).delete({
url: "/mcp/{name}/auth",
...options,
});
}
/**
* Start OAuth authentication flow for an MCP server
*/
start(options) {
return (options.client ?? this._client).post({
url: "/mcp/{name}/auth",
...options,
});
}
/**
* Complete OAuth authentication with authorization code
*/
callback(options) {
return (options.client ?? this._client).post({
url: "/mcp/{name}/auth/callback",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
}
/**
* Start OAuth flow and wait for callback (opens browser)
*/
authenticate(options) {
return (options.client ?? this._client).post({
url: "/mcp/{name}/auth/authenticate",
...options,
});
}
/**
* Set authentication credentials
*/
set(options) {
return (options.client ?? this._client).put({
url: "/auth/{id}",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
}
}
class Mcp extends _HeyApiClient {
/**
* Get MCP server status
*/
status(options) {
return (options?.client ?? this._client).get({
url: "/mcp",
...options,
});
}
/**
* Add MCP server dynamically
*/
add(options) {
return (options?.client ?? this._client).post({
url: "/mcp",
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
});
}
/**
* Connect an MCP server
*/
connect(options) {
return (options.client ?? this._client).post({
url: "/mcp/{name}/connect",
...options,
});
}
/**
* Disconnect an MCP server
*/
disconnect(options) {
return (options.client ?? this._client).post({
url: "/mcp/{name}/disconnect",
...options,
});
}
auth = new Auth({ client: this._client });
}
class Lsp extends _HeyApiClient {
/**
* Get LSP server status
*/
status(options) {
return (options?.client ?? this._client).get({
url: "/lsp",
...options,
});
}
}
class Formatter extends _HeyApiClient {
/**
* Get formatter status
*/
status(options) {
return (options?.client ?? this._client).get({
url: "/formatter",
...options,
});
}
}
class Control extends _HeyApiClient {
/**
* Get the next TUI request from the queue
*/
next(options) {
return (options?.client ?? this._client).get({
url: "/tui/control/next",
...options,
});
}
/**
* Submit a response to the TUI request queue
*/
response(options) {
return (options?.client ?? this._client).post({
url: "/tui/control/response",
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
});
}
}
class Tui extends _HeyApiClient {

@@ -754,8 +286,8 @@ /**

return (options?.client ?? this._client).post({
url: "/tui/append-prompt",
url: '/tui/append-prompt',
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
'Content-Type': 'application/json',
...options?.headers
}
});

@@ -768,137 +300,15 @@ }

return (options?.client ?? this._client).post({
url: "/tui/open-help",
...options,
url: '/tui/open-help',
...options
});
}
/**
* Open the session dialog
*/
openSessions(options) {
return (options?.client ?? this._client).post({
url: "/tui/open-sessions",
...options,
});
}
/**
* Open the theme dialog
*/
openThemes(options) {
return (options?.client ?? this._client).post({
url: "/tui/open-themes",
...options,
});
}
/**
* Open the model dialog
*/
openModels(options) {
return (options?.client ?? this._client).post({
url: "/tui/open-models",
...options,
});
}
/**
* Submit the prompt
*/
submitPrompt(options) {
return (options?.client ?? this._client).post({
url: "/tui/submit-prompt",
...options,
});
}
/**
* Clear the prompt
*/
clearPrompt(options) {
return (options?.client ?? this._client).post({
url: "/tui/clear-prompt",
...options,
});
}
/**
* Execute a TUI command (e.g. agent_cycle)
*/
executeCommand(options) {
return (options?.client ?? this._client).post({
url: "/tui/execute-command",
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
});
}
/**
* Show a toast notification in the TUI
*/
showToast(options) {
return (options?.client ?? this._client).post({
url: "/tui/show-toast",
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
});
}
/**
* Publish a TUI event
*/
publish(options) {
return (options?.client ?? this._client).post({
url: "/tui/publish",
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
});
}
control = new Control({ client: this._client });
}
class Event extends _HeyApiClient {
/**
* Get events
*/
subscribe(options) {
return (options?.client ?? this._client).get.sse({
url: "/event",
...options,
});
}
}
export class OpencodeClient extends _HeyApiClient {
/**
* Respond to a permission request
*/
postSessionIdPermissionsPermissionId(options) {
return (options.client ?? this._client).post({
url: "/session/{id}/permissions/{permissionID}",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
}
global = new Global({ client: this._client });
project = new Project({ client: this._client });
pty = new Pty({ client: this._client });
event = new Event({ client: this._client });
app = new App({ client: this._client });
config = new Config({ client: this._client });
tool = new Tool({ client: this._client });
instance = new Instance({ client: this._client });
path = new Path({ client: this._client });
vcs = new Vcs({ client: this._client });
session = new Session({ client: this._client });
command = new Command({ client: this._client });
provider = new Provider({ client: this._client });
find = new Find({ client: this._client });
file = new File({ client: this._client });
app = new App({ client: this._client });
mcp = new Mcp({ client: this._client });
lsp = new Lsp({ client: this._client });
formatter = new Formatter({ client: this._client });
tui = new Tui({ client: this._client });
auth = new Auth({ client: this._client });
event = new Event({ client: this._client });
}
// This file is auto-generated by @hey-api/openapi-ts
export {};

@@ -1,10 +0,3 @@

export * from "./client.js";
export * from "./server.js";
import type { ServerOptions } from "./server.js";
export declare function createOpencode(options?: ServerOptions): Promise<{
client: import("./client.js").OpencodeClient;
server: {
url: string;
close(): void;
};
}>;
import { type Config } from "./gen/client/types";
import { OpencodeClient } from "./gen/sdk.gen";
export declare function createOpencodeClient(config?: Config): OpencodeClient;

@@ -1,16 +0,6 @@

export * from "./client.js";
export * from "./server.js";
import { createOpencodeClient } from "./client.js";
import { createOpencodeServer } from "./server.js";
export async function createOpencode(options) {
const server = await createOpencodeServer({
...options,
});
const client = createOpencodeClient({
baseUrl: server.url,
});
return {
client,
server,
};
import { createClient } from "./gen/client/client";
import { OpencodeClient } from "./gen/sdk.gen";
export function createOpencodeClient(config) {
const client = createClient(config);
return new OpencodeClient({ client });
}
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode-ai/sdk",
"version": "0.0.0-next-15065",
"type": "module",
"license": "MIT",
"scripts": {
"test": "bun test",
"typecheck": "tsgo --noEmit",
"build": "bun ./script/build.ts"
},
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./client": {
"import": "./dist/client.js",
"types": "./dist/client.d.ts"
},
"./server": {
"import": "./dist/server.js",
"types": "./dist/server.d.ts"
},
"./v2": {
"import": "./dist/v2/index.js",
"types": "./dist/v2/index.d.ts"
},
"./v2/client": {
"import": "./dist/v2/client.js",
"types": "./dist/v2/client.d.ts"
},
"./v2/gen/client": {
"import": "./dist/v2/gen/client/index.js",
"types": "./dist/v2/gen/client/index.d.ts"
},
"./v2/server": {
"import": "./dist/v2/server.js",
"types": "./dist/v2/server.d.ts"
},
"./v2/types": {
"import": "./dist/v2/gen/types.gen.js",
"types": "./dist/v2/gen/types.gen.d.ts"
}
".": "./dist/index.js"
},
"version": "0.0.1",
"files": [

@@ -50,12 +13,6 @@ "dist"

"devDependencies": {
"@hey-api/openapi-ts": "0.90.10",
"@tsconfig/node22": "22.0.2",
"@types/cross-spawn": "6.0.6",
"@types/node": "24.12.2",
"@typescript/native-preview": "7.0.0-dev.20251207.1",
"typescript": "5.8.2"
},
"dependencies": {
"cross-spawn": "7.0.6"
"typescript": "5.8.2",
"@hey-api/openapi-ts": "0.80.1",
"@tsconfig/node22": "22.0.2"
}
}
}
export * from "./gen/types.gen.js";
import { type Config } from "./gen/client/types.gen.js";
import { OpencodeClient } from "./gen/sdk.gen.js";
export { type Config as OpencodeClientConfig, OpencodeClient };
export declare function createOpencodeClient(config?: Config & {
directory?: string;
}): OpencodeClient;
export * from "./gen/types.gen.js";
import { createClient } from "./gen/client/client.gen.js";
import { OpencodeClient } from "./gen/sdk.gen.js";
import { wrapClientError } from "./error-interceptor.js";
export { OpencodeClient };
function pick(value, fallback) {
if (!value)
return;
if (!fallback)
return value;
if (value === fallback)
return fallback;
if (value === encodeURIComponent(fallback))
return fallback;
return value;
}
function rewrite(request, directory) {
if (request.method !== "GET" && request.method !== "HEAD")
return request;
const value = pick(request.headers.get("x-opencode-directory"), directory);
if (!value)
return request;
const url = new URL(request.url);
if (!url.searchParams.has("directory")) {
url.searchParams.set("directory", value);
}
const next = new Request(url, request);
next.headers.delete("x-opencode-directory");
return next;
}
export function createOpencodeClient(config) {
if (!config?.fetch) {
const customFetch = (req) => {
// @ts-ignore
req.timeout = false;
return fetch(req);
};
config = {
...config,
fetch: customFetch,
};
}
if (config?.directory) {
config.headers = {
...config.headers,
"x-opencode-directory": encodeURIComponent(config.directory),
};
}
const client = createClient(config);
client.interceptors.request.use((request) => rewrite(request, config?.directory));
client.interceptors.error.use(wrapClientError);
return new OpencodeClient({ client });
}
/**
* Wrap whatever the generated client decoded from a non-2xx error body
* into a real `Error` so downstream formatters (TUI, plugins) get a
* useful `.message` instead of `[object Object]` or blank. The original
* parsed body and status live under `.cause` for callers that need
* structured fields.
*
* Only fires when the caller used `{ throwOnError: true }`. Callers that
* read `result.error` directly (the result-tuple path) get the parsed
* body unchanged so existing field-level reads (`.error.name`,
* `JSON.stringify(error)`, etc.) are byte-for-byte identical to before.
*/
export declare function wrapClientError(error: unknown, response: Response | undefined, request: Request | undefined, opts: {
throwOnError?: boolean;
} | undefined): unknown;
/**
* Wrap whatever the generated client decoded from a non-2xx error body
* into a real `Error` so downstream formatters (TUI, plugins) get a
* useful `.message` instead of `[object Object]` or blank. The original
* parsed body and status live under `.cause` for callers that need
* structured fields.
*
* Only fires when the caller used `{ throwOnError: true }`. Callers that
* read `result.error` directly (the result-tuple path) get the parsed
* body unchanged so existing field-level reads (`.error.name`,
* `JSON.stringify(error)`, etc.) are byte-for-byte identical to before.
*/
export function wrapClientError(error, response, request, opts) {
if (!opts?.throwOnError)
return error;
if (error instanceof Error)
return error;
// NamedError-shaped responses (the common case for opencode 4xx) come
// through as POJOs — extract a useful message first, then wrap.
if (typeof error === "object" && error !== null && Object.keys(error).length > 0) {
const obj = error;
const message = (typeof obj.data?.message === "string" && obj.data.message) ||
(typeof obj.message === "string" && obj.message) ||
(typeof obj.name === "string" && obj.name) ||
describe(request, response);
return new Error(message, { cause: { body: error, status: response?.status } });
}
if (typeof error === "string" && error.length > 0) {
return new Error(error, { cause: { body: error, status: response?.status } });
}
// Empty body / network failure / undefined / null / empty object.
const reason = response ? "(empty response body)" : "network error (no response)";
return new Error(`opencode server ${describe(request, response)}: ${reason}`, {
cause: { body: error, status: response?.status },
});
}
function describe(request, response) {
const method = request?.method ?? "?";
const url = request?.url ?? "?";
const status = response?.status;
const statusText = response?.statusText;
return `${method} ${url}${status ? " → " + status : ""}${statusText ? " " + statusText : ""}`;
}
import type { Client, Config } from "./types.gen.js";
export declare const createClient: (config?: Config) => Client;
// This file is auto-generated by @hey-api/openapi-ts
import { createSseClient } from "../core/serverSentEvents.gen.js";
import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from "./utils.gen.js";
export const createClient = (config = {}) => {
let _config = mergeConfigs(createConfig(), config);
const getConfig = () => ({ ..._config });
const setConfig = (config) => {
_config = mergeConfigs(_config, config);
return getConfig();
};
const interceptors = createInterceptors();
const beforeRequest = async (options) => {
const opts = {
..._config,
...options,
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
headers: mergeHeaders(_config.headers, options.headers),
serializedBody: undefined,
};
if (opts.security) {
await setAuthParams({
...opts,
security: opts.security,
});
}
if (opts.requestValidator) {
await opts.requestValidator(opts);
}
if (opts.body && opts.bodySerializer) {
opts.serializedBody = opts.bodySerializer(opts.body);
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.serializedBody === undefined || opts.serializedBody === "") {
opts.headers.delete("Content-Type");
}
const url = buildUrl(opts);
return { opts, url };
};
const request = async (options) => {
// @ts-expect-error
const { opts, url } = await beforeRequest(options);
const requestInit = {
redirect: "follow",
...opts,
body: opts.serializedBody,
};
let request = new Request(url, requestInit);
for (const fn of interceptors.request._fns) {
if (fn) {
request = await fn(request, opts);
}
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = opts.fetch;
let response = await _fetch(request);
for (const fn of interceptors.response._fns) {
if (fn) {
response = await fn(response, request, opts);
}
}
const result = {
request,
response,
};
if (response.ok) {
if (response.status === 204 || response.headers.get("Content-Length") === "0") {
return opts.responseStyle === "data"
? {}
: {
data: {},
...result,
};
}
const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
let data;
switch (parseAs) {
case "arrayBuffer":
case "blob":
case "formData":
case "json":
case "text":
data = await response[parseAs]();
break;
case "stream":
return opts.responseStyle === "data"
? response.body
: {
data: response.body,
...result,
};
}
if (parseAs === "json") {
if (opts.responseValidator) {
await opts.responseValidator(data);
}
if (opts.responseTransformer) {
data = await opts.responseTransformer(data);
}
}
return opts.responseStyle === "data"
? data
: {
data,
...result,
};
}
const textError = await response.text();
let jsonError;
try {
jsonError = JSON.parse(textError);
}
catch {
// noop
}
const error = jsonError ?? textError;
let finalError = error;
for (const fn of interceptors.error._fns) {
if (fn) {
finalError = (await fn(error, response, request, opts));
}
}
finalError = finalError || {};
if (opts.throwOnError) {
throw finalError;
}
// TODO: we probably want to return error and improve types
return opts.responseStyle === "data"
? undefined
: {
error: finalError,
...result,
};
};
const makeMethod = (method) => {
const fn = (options) => request({ ...options, method });
fn.sse = async (options) => {
const { opts, url } = await beforeRequest(options);
return createSseClient({
...opts,
body: opts.body,
headers: opts.headers,
method,
url,
});
};
return fn;
};
return {
buildUrl,
connect: makeMethod("CONNECT"),
delete: makeMethod("DELETE"),
get: makeMethod("GET"),
getConfig,
head: makeMethod("HEAD"),
interceptors,
options: makeMethod("OPTIONS"),
patch: makeMethod("PATCH"),
post: makeMethod("POST"),
put: makeMethod("PUT"),
request,
setConfig,
trace: makeMethod("TRACE"),
};
};
import type { Auth } from "../core/auth.gen.js";
import type { ServerSentEventsOptions, ServerSentEventsResult } from "../core/serverSentEvents.gen.js";
import type { Client as CoreClient, Config as CoreConfig } from "../core/types.gen.js";
import type { Middleware } from "./utils.gen.js";
export type ResponseStyle = "data" | "fields";
export interface Config<T extends ClientOptions = ClientOptions> extends Omit<RequestInit, "body" | "headers" | "method">, CoreConfig {
/**
* Base URL for all requests made by this client.
*/
baseUrl?: T["baseUrl"];
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: (request: Request) => ReturnType<typeof fetch>;
/**
* Please don't use the Fetch client for Next.js applications. The `next`
* options won't have any effect.
*
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
*/
next?: never;
/**
* Return the response data parsed in a specified format. By default, `auto`
* will infer the appropriate method from the `Content-Type` response header.
* You can override this behavior with any of the {@link Body} methods.
* Select `stream` if you don't want to parse response data at all.
*
* @default 'auto'
*/
parseAs?: "arrayBuffer" | "auto" | "blob" | "formData" | "json" | "stream" | "text";
/**
* Should we return only data or multiple fields (data, error, response, etc.)?
*
* @default 'fields'
*/
responseStyle?: ResponseStyle;
/**
* Throw an error instead of returning it in the response?
*
* @default false
*/
throwOnError?: T["throwOnError"];
}
export interface RequestOptions<TData = unknown, TResponseStyle extends ResponseStyle = "fields", ThrowOnError extends boolean = boolean, Url extends string = string> extends Config<{
responseStyle: TResponseStyle;
throwOnError: ThrowOnError;
}>, Pick<ServerSentEventsOptions<TData>, "onSseError" | "onSseEvent" | "sseDefaultRetryDelay" | "sseMaxRetryAttempts" | "sseMaxRetryDelay"> {
/**
* Any body that you want to add to your request.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
*/
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
/**
* Security mechanism(s) to use for the request.
*/
security?: ReadonlyArray<Auth>;
url: Url;
}
export interface ResolvedRequestOptions<TResponseStyle extends ResponseStyle = "fields", ThrowOnError extends boolean = boolean, Url extends string = string> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
serializedBody?: string;
}
export type RequestResult<TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = "fields"> = ThrowOnError extends true ? Promise<TResponseStyle extends "data" ? TData extends Record<string, unknown> ? TData[keyof TData] : TData : {
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
request: Request;
response: Response;
}> : Promise<TResponseStyle extends "data" ? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined : ({
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
error: undefined;
} | {
data: undefined;
error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
}) & {
request: Request;
response: Response;
}>;
export interface ClientOptions {
baseUrl?: string;
responseStyle?: ResponseStyle;
throwOnError?: boolean;
}
type MethodFnBase = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = "fields">(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type MethodFnServerSentEvents = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = "fields">(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">) => Promise<ServerSentEventsResult<TData, TError>>;
type MethodFn = MethodFnBase & {
sse: MethodFnServerSentEvents;
};
type RequestFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = "fields">(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method"> & Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, "method">) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type BuildUrlFn = <TData extends {
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
url: string;
}>(options: Pick<TData, "url"> & Options<TData>) => string;
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>;
};
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
export interface TDataShape {
body?: unknown;
headers?: unknown;
path?: unknown;
query?: unknown;
url: string;
}
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = "fields"> = OmitKeys<RequestOptions<TResponse, TResponseStyle, ThrowOnError>, "body" | "path" | "query" | "url"> & Omit<TData, "url">;
export type OptionsLegacyParser<TData = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = "fields"> = TData extends {
body?: any;
} ? TData extends {
headers?: any;
} ? OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body" | "headers" | "url"> & TData : OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body" | "url"> & TData & Pick<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "headers"> : TData extends {
headers?: any;
} ? OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "headers" | "url"> & TData & Pick<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body"> : OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "url"> & TData;
export {};
// This file is auto-generated by @hey-api/openapi-ts
export {};
import type { QuerySerializerOptions } from "../core/bodySerializer.gen.js";
import type { Client, ClientOptions, Config, RequestOptions } from "./types.gen.js";
export declare const createQuerySerializer: <T = unknown>({ allowReserved, array, object }?: QuerySerializerOptions) => (queryParams: T) => string;
/**
* Infers parseAs value from provided Content-Type header.
*/
export declare const getParseAs: (contentType: string | null) => Exclude<Config["parseAs"], "auto">;
export declare const setAuthParams: ({ security, ...options }: Pick<Required<RequestOptions>, "security"> & Pick<RequestOptions, "auth" | "query"> & {
headers: Headers;
}) => Promise<void>;
export declare const buildUrl: Client["buildUrl"];
export declare const mergeConfigs: (a: Config, b: Config) => Config;
export declare const mergeHeaders: (...headers: Array<Required<Config>["headers"] | undefined>) => Headers;
type ErrInterceptor<Err, Res, Req, Options> = (error: Err, response: Res, request: Req, options: Options) => Err | Promise<Err>;
type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;
type ResInterceptor<Res, Req, Options> = (response: Res, request: Req, options: Options) => Res | Promise<Res>;
declare class Interceptors<Interceptor> {
_fns: (Interceptor | null)[];
constructor();
clear(): void;
getInterceptorIndex(id: number | Interceptor): number;
exists(id: number | Interceptor): boolean;
eject(id: number | Interceptor): void;
update(id: number | Interceptor, fn: Interceptor): number | false | Interceptor;
use(fn: Interceptor): number;
}
export interface Middleware<Req, Res, Err, Options> {
error: Pick<Interceptors<ErrInterceptor<Err, Res, Req, Options>>, "eject" | "use">;
request: Pick<Interceptors<ReqInterceptor<Req, Options>>, "eject" | "use">;
response: Pick<Interceptors<ResInterceptor<Res, Req, Options>>, "eject" | "use">;
}
export declare const createInterceptors: <Req, Res, Err, Options>() => {
error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
request: Interceptors<ReqInterceptor<Req, Options>>;
response: Interceptors<ResInterceptor<Res, Req, Options>>;
};
export declare const createConfig: <T extends ClientOptions = ClientOptions>(override?: Config<Omit<ClientOptions, keyof T> & T>) => Config<Omit<ClientOptions, keyof T> & T>;
export {};
// This file is auto-generated by @hey-api/openapi-ts
import { getAuthToken } from "../core/auth.gen.js";
import { jsonBodySerializer } from "../core/bodySerializer.gen.js";
import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam } from "../core/pathSerializer.gen.js";
import { getUrl } from "../core/utils.gen.js";
export const createQuerySerializer = ({ allowReserved, array, object } = {}) => {
const querySerializer = (queryParams) => {
const search = [];
if (queryParams && typeof queryParams === "object") {
for (const name in queryParams) {
const value = queryParams[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
const serializedArray = serializeArrayParam({
allowReserved,
explode: true,
name,
style: "form",
value,
...array,
});
if (serializedArray)
search.push(serializedArray);
}
else if (typeof value === "object") {
const serializedObject = serializeObjectParam({
allowReserved,
explode: true,
name,
style: "deepObject",
value: value,
...object,
});
if (serializedObject)
search.push(serializedObject);
}
else {
const serializedPrimitive = serializePrimitiveParam({
allowReserved,
name,
value: value,
});
if (serializedPrimitive)
search.push(serializedPrimitive);
}
}
}
return search.join("&");
};
return querySerializer;
};
/**
* Infers parseAs value from provided Content-Type header.
*/
export const getParseAs = (contentType) => {
if (!contentType) {
// If no Content-Type header is provided, the best we can do is return the raw response body,
// which is effectively the same as the 'stream' option.
return "stream";
}
const cleanContent = contentType.split(";")[0]?.trim();
if (!cleanContent) {
return;
}
if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
return "json";
}
if (cleanContent === "multipart/form-data") {
return "formData";
}
if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
return "blob";
}
if (cleanContent.startsWith("text/")) {
return "text";
}
return;
};
const checkForExistence = (options, name) => {
if (!name) {
return false;
}
if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
return true;
}
return false;
};
export const setAuthParams = async ({ security, ...options }) => {
for (const auth of security) {
if (checkForExistence(options, auth.name)) {
continue;
}
const token = await getAuthToken(auth, options.auth);
if (!token) {
continue;
}
const name = auth.name ?? "Authorization";
switch (auth.in) {
case "query":
if (!options.query) {
options.query = {};
}
options.query[name] = token;
break;
case "cookie":
options.headers.append("Cookie", `${name}=${token}`);
break;
case "header":
default:
options.headers.set(name, token);
break;
}
}
};
export const buildUrl = (options) => getUrl({
baseUrl: options.baseUrl,
path: options.path,
query: options.query,
querySerializer: typeof options.querySerializer === "function"
? options.querySerializer
: createQuerySerializer(options.querySerializer),
url: options.url,
});
export const mergeConfigs = (a, b) => {
const config = { ...a, ...b };
if (config.baseUrl?.endsWith("/")) {
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
}
config.headers = mergeHeaders(a.headers, b.headers);
return config;
};
export const mergeHeaders = (...headers) => {
const mergedHeaders = new Headers();
for (const header of headers) {
if (!header || typeof header !== "object") {
continue;
}
const iterator = header instanceof Headers ? header.entries() : Object.entries(header);
for (const [key, value] of iterator) {
if (value === null) {
mergedHeaders.delete(key);
}
else if (Array.isArray(value)) {
for (const v of value) {
mergedHeaders.append(key, v);
}
}
else if (value !== undefined) {
// assume object headers are meant to be JSON stringified, i.e. their
// content value in OpenAPI specification is 'application/json'
mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
}
}
}
return mergedHeaders;
};
class Interceptors {
_fns;
constructor() {
this._fns = [];
}
clear() {
this._fns = [];
}
getInterceptorIndex(id) {
if (typeof id === "number") {
return this._fns[id] ? id : -1;
}
else {
return this._fns.indexOf(id);
}
}
exists(id) {
const index = this.getInterceptorIndex(id);
return !!this._fns[index];
}
eject(id) {
const index = this.getInterceptorIndex(id);
if (this._fns[index]) {
this._fns[index] = null;
}
}
update(id, fn) {
const index = this.getInterceptorIndex(id);
if (this._fns[index]) {
this._fns[index] = fn;
return id;
}
else {
return false;
}
}
use(fn) {
this._fns = [...this._fns, fn];
return this._fns.length - 1;
}
}
// do not add `Middleware` as return type so we can use _fns internally
export const createInterceptors = () => ({
error: new Interceptors(),
request: new Interceptors(),
response: new Interceptors(),
});
const defaultQuerySerializer = createQuerySerializer({
allowReserved: false,
array: {
explode: true,
style: "form",
},
object: {
explode: true,
style: "deepObject",
},
});
const defaultHeaders = {
"Content-Type": "application/json",
};
export const createConfig = (override = {}) => ({
...jsonBodySerializer,
headers: defaultHeaders,
parseAs: "auto",
querySerializer: defaultQuerySerializer,
...override,
});
export type AuthToken = string | undefined;
export interface Auth {
/**
* Which part of the request do we use to send the auth?
*
* @default 'header'
*/
in?: "header" | "query" | "cookie";
/**
* Header or query parameter name.
*
* @default 'Authorization'
*/
name?: string;
scheme?: "basic" | "bearer";
type: "apiKey" | "http";
}
export declare const getAuthToken: (auth: Auth, callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken) => Promise<string | undefined>;
// This file is auto-generated by @hey-api/openapi-ts
export const getAuthToken = async (auth, callback) => {
const token = typeof callback === "function" ? await callback(auth) : callback;
if (!token) {
return;
}
if (auth.scheme === "bearer") {
return `Bearer ${token}`;
}
if (auth.scheme === "basic") {
return `Basic ${btoa(token)}`;
}
return token;
};
import type { ArrayStyle, ObjectStyle, SerializerOptions } from "./pathSerializer.gen.js";
export type QuerySerializer = (query: Record<string, unknown>) => string;
export type BodySerializer = (body: any) => any;
export interface QuerySerializerOptions {
allowReserved?: boolean;
array?: SerializerOptions<ArrayStyle>;
object?: SerializerOptions<ObjectStyle>;
}
export declare const formDataBodySerializer: {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T) => FormData;
};
export declare const jsonBodySerializer: {
bodySerializer: <T>(body: T) => string;
};
export declare const urlSearchParamsBodySerializer: {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T) => string;
};
// This file is auto-generated by @hey-api/openapi-ts
const serializeFormDataPair = (data, key, value) => {
if (typeof value === "string" || value instanceof Blob) {
data.append(key, value);
}
else if (value instanceof Date) {
data.append(key, value.toISOString());
}
else {
data.append(key, JSON.stringify(value));
}
};
const serializeUrlSearchParamsPair = (data, key, value) => {
if (typeof value === "string") {
data.append(key, value);
}
else {
data.append(key, JSON.stringify(value));
}
};
export const formDataBodySerializer = {
bodySerializer: (body) => {
const data = new FormData();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeFormDataPair(data, key, v));
}
else {
serializeFormDataPair(data, key, value);
}
});
return data;
},
};
export const jsonBodySerializer = {
bodySerializer: (body) => JSON.stringify(body, (_key, value) => (typeof value === "bigint" ? value.toString() : value)),
};
export const urlSearchParamsBodySerializer = {
bodySerializer: (body) => {
const data = new URLSearchParams();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
}
else {
serializeUrlSearchParamsPair(data, key, value);
}
});
return data.toString();
},
};
type Slot = "body" | "headers" | "path" | "query";
export type Field = {
in: Exclude<Slot, "body">;
/**
* Field name. This is the name we want the user to see and use.
*/
key: string;
/**
* Field mapped name. This is the name we want to use in the request.
* If omitted, we use the same value as `key`.
*/
map?: string;
} | {
in: Extract<Slot, "body">;
/**
* Key isn't required for bodies.
*/
key?: string;
map?: string;
};
export interface Fields {
allowExtra?: Partial<Record<Slot, boolean>>;
args?: ReadonlyArray<Field>;
}
export type FieldsConfig = ReadonlyArray<Field | Fields>;
interface Params {
body: unknown;
headers: Record<string, unknown>;
path: Record<string, unknown>;
query: Record<string, unknown>;
}
export declare const buildClientParams: (args: ReadonlyArray<unknown>, fields: FieldsConfig) => Params;
export {};
// This file is auto-generated by @hey-api/openapi-ts
const extraPrefixesMap = {
$body_: "body",
$headers_: "headers",
$path_: "path",
$query_: "query",
};
const extraPrefixes = Object.entries(extraPrefixesMap);
const buildKeyMap = (fields, map) => {
if (!map) {
map = new Map();
}
for (const config of fields) {
if ("in" in config) {
if (config.key) {
map.set(config.key, {
in: config.in,
map: config.map,
});
}
}
else if (config.args) {
buildKeyMap(config.args, map);
}
}
return map;
};
const stripEmptySlots = (params) => {
for (const [slot, value] of Object.entries(params)) {
if (value && typeof value === "object" && !Object.keys(value).length) {
delete params[slot];
}
}
};
export const buildClientParams = (args, fields) => {
const params = {
body: {},
headers: {},
path: {},
query: {},
};
const map = buildKeyMap(fields);
let config;
for (const [index, arg] of args.entries()) {
if (fields[index]) {
config = fields[index];
}
if (!config) {
continue;
}
if ("in" in config) {
if (config.key) {
const field = map.get(config.key);
const name = field.map || config.key;
params[field.in][name] = arg;
}
else {
params.body = arg;
}
}
else {
for (const [key, value] of Object.entries(arg ?? {})) {
const field = map.get(key);
if (field) {
const name = field.map || key;
params[field.in][name] = value;
}
else {
const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));
if (extra) {
const [prefix, slot] = extra;
params[slot][key.slice(prefix.length)] = value;
}
else {
for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) {
if (allowed) {
;
params[slot][key] = value;
break;
}
}
}
}
}
}
}
stripEmptySlots(params);
return params;
};
interface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {
}
interface SerializePrimitiveOptions {
allowReserved?: boolean;
name: string;
}
export interface SerializerOptions<T> {
/**
* @default true
*/
explode: boolean;
style: T;
}
export type ArrayStyle = "form" | "spaceDelimited" | "pipeDelimited";
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
type MatrixStyle = "label" | "matrix" | "simple";
export type ObjectStyle = "form" | "deepObject";
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
value: string;
}
export declare const separatorArrayExplode: (style: ArraySeparatorStyle) => "." | ";" | "," | "&";
export declare const separatorArrayNoExplode: (style: ArraySeparatorStyle) => "," | "|" | "%20";
export declare const separatorObjectExplode: (style: ObjectSeparatorStyle) => "." | ";" | "," | "&";
export declare const serializeArrayParam: ({ allowReserved, explode, name, style, value, }: SerializeOptions<ArraySeparatorStyle> & {
value: unknown[];
}) => string;
export declare const serializePrimitiveParam: ({ allowReserved, name, value }: SerializePrimitiveParam) => string;
export declare const serializeObjectParam: ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions<ObjectSeparatorStyle> & {
value: Record<string, unknown> | Date;
valueOnly?: boolean;
}) => string;
export {};
// This file is auto-generated by @hey-api/openapi-ts
export const separatorArrayExplode = (style) => {
switch (style) {
case "label":
return ".";
case "matrix":
return ";";
case "simple":
return ",";
default:
return "&";
}
};
export const separatorArrayNoExplode = (style) => {
switch (style) {
case "form":
return ",";
case "pipeDelimited":
return "|";
case "spaceDelimited":
return "%20";
default:
return ",";
}
};
export const separatorObjectExplode = (style) => {
switch (style) {
case "label":
return ".";
case "matrix":
return ";";
case "simple":
return ",";
default:
return "&";
}
};
export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }) => {
if (!explode) {
const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
switch (style) {
case "label":
return `.${joinedValues}`;
case "matrix":
return `;${name}=${joinedValues}`;
case "simple":
return joinedValues;
default:
return `${name}=${joinedValues}`;
}
}
const separator = separatorArrayExplode(style);
const joinedValues = value
.map((v) => {
if (style === "label" || style === "simple") {
return allowReserved ? v : encodeURIComponent(v);
}
return serializePrimitiveParam({
allowReserved,
name,
value: v,
});
})
.join(separator);
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
};
export const serializePrimitiveParam = ({ allowReserved, name, value }) => {
if (value === undefined || value === null) {
return "";
}
if (typeof value === "object") {
throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
}
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
};
export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }) => {
if (value instanceof Date) {
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
}
if (style !== "deepObject" && !explode) {
let values = [];
Object.entries(value).forEach(([key, v]) => {
values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
});
const joinedValues = values.join(",");
switch (style) {
case "form":
return `${name}=${joinedValues}`;
case "label":
return `.${joinedValues}`;
case "matrix":
return `;${name}=${joinedValues}`;
default:
return joinedValues;
}
}
const separator = separatorObjectExplode(style);
const joinedValues = Object.entries(value)
.map(([key, v]) => serializePrimitiveParam({
allowReserved,
name: style === "deepObject" ? `${name}[${key}]` : key,
value: v,
}))
.join(separator);
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
};
/**
* JSON-friendly union that mirrors what Pinia Colada can hash.
*/
export type JsonValue = null | string | number | boolean | JsonValue[] | {
[key: string]: JsonValue;
};
/**
* Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
*/
export declare const queryKeyJsonReplacer: (_key: string, value: unknown) => {} | null | undefined;
/**
* Safely stringifies a value and parses it back into a JsonValue.
*/
export declare const stringifyToJsonValue: (input: unknown) => JsonValue | undefined;
/**
* Normalizes any accepted value into a JSON-friendly shape for query keys.
*/
export declare const serializeQueryKeyValue: (value: unknown) => JsonValue | undefined;
// This file is auto-generated by @hey-api/openapi-ts
/**
* Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
*/
export const queryKeyJsonReplacer = (_key, value) => {
if (value === undefined || typeof value === "function" || typeof value === "symbol") {
return undefined;
}
if (typeof value === "bigint") {
return value.toString();
}
if (value instanceof Date) {
return value.toISOString();
}
return value;
};
/**
* Safely stringifies a value and parses it back into a JsonValue.
*/
export const stringifyToJsonValue = (input) => {
try {
const json = JSON.stringify(input, queryKeyJsonReplacer);
if (json === undefined) {
return undefined;
}
return JSON.parse(json);
}
catch {
return undefined;
}
};
/**
* Detects plain objects (including objects with a null prototype).
*/
const isPlainObject = (value) => {
if (value === null || typeof value !== "object") {
return false;
}
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
};
/**
* Turns URLSearchParams into a sorted JSON object for deterministic keys.
*/
const serializeSearchParams = (params) => {
const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b));
const result = {};
for (const [key, value] of entries) {
const existing = result[key];
if (existing === undefined) {
result[key] = value;
continue;
}
if (Array.isArray(existing)) {
;
existing.push(value);
}
else {
result[key] = [existing, value];
}
}
return result;
};
/**
* Normalizes any accepted value into a JSON-friendly shape for query keys.
*/
export const serializeQueryKeyValue = (value) => {
if (value === null) {
return null;
}
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return value;
}
if (value === undefined || typeof value === "function" || typeof value === "symbol") {
return undefined;
}
if (typeof value === "bigint") {
return value.toString();
}
if (value instanceof Date) {
return value.toISOString();
}
if (Array.isArray(value)) {
return stringifyToJsonValue(value);
}
if (typeof URLSearchParams !== "undefined" && value instanceof URLSearchParams) {
return serializeSearchParams(value);
}
if (isPlainObject(value)) {
return stringifyToJsonValue(value);
}
return undefined;
};
import type { Config } from "./types.gen.js";
export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, "method"> & Pick<Config, "method" | "responseTransformer" | "responseValidator"> & {
/**
* Callback invoked when a network or parsing error occurs during streaming.
*
* This option applies only if the endpoint returns a stream of events.
*
* @param error The error that occurred.
*/
onSseError?: (error: unknown) => void;
/**
* Callback invoked when an event is streamed from the server.
*
* This option applies only if the endpoint returns a stream of events.
*
* @param event Event streamed from the server.
* @returns Nothing (void).
*/
onSseEvent?: (event: StreamEvent<TData>) => void;
/**
* Default retry delay in milliseconds.
*
* This option applies only if the endpoint returns a stream of events.
*
* @default 3000
*/
sseDefaultRetryDelay?: number;
/**
* Maximum number of retry attempts before giving up.
*/
sseMaxRetryAttempts?: number;
/**
* Maximum retry delay in milliseconds.
*
* Applies only when exponential backoff is used.
*
* This option applies only if the endpoint returns a stream of events.
*
* @default 30000
*/
sseMaxRetryDelay?: number;
/**
* Optional sleep function for retry backoff.
*
* Defaults to using `setTimeout`.
*/
sseSleepFn?: (ms: number) => Promise<void>;
url: string;
};
export interface StreamEvent<TData = unknown> {
data: TData;
event?: string;
id?: string;
retry?: number;
}
export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
stream: AsyncGenerator<TData extends Record<string, unknown> ? TData[keyof TData] : TData, TReturn, TNext>;
};
export declare const createSseClient: <TData = unknown>({ onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions) => ServerSentEventsResult<TData>;
// This file is auto-generated by @hey-api/openapi-ts
export const createSseClient = ({ onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) => {
let lastEventId;
const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
const createStream = async function* () {
let retryDelay = sseDefaultRetryDelay ?? 3000;
let attempt = 0;
const signal = options.signal ?? new AbortController().signal;
while (true) {
if (signal.aborted)
break;
attempt++;
const headers = options.headers instanceof Headers
? options.headers
: new Headers(options.headers);
if (lastEventId !== undefined) {
headers.set("Last-Event-ID", lastEventId);
}
try {
const response = await fetch(url, { ...options, headers, signal });
if (!response.ok)
throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
if (!response.body)
throw new Error("No body in SSE response");
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
const abortHandler = () => {
try {
void reader.cancel();
}
catch {
// noop
}
};
signal.addEventListener("abort", abortHandler);
try {
while (true) {
const { done, value } = await reader.read();
if (done)
break;
buffer += value;
const chunks = buffer.split("\n\n");
buffer = chunks.pop() ?? "";
for (const chunk of chunks) {
const lines = chunk.split("\n");
const dataLines = [];
let eventName;
for (const line of lines) {
if (line.startsWith("data:")) {
dataLines.push(line.replace(/^data:\s*/, ""));
}
else if (line.startsWith("event:")) {
eventName = line.replace(/^event:\s*/, "");
}
else if (line.startsWith("id:")) {
lastEventId = line.replace(/^id:\s*/, "");
}
else if (line.startsWith("retry:")) {
const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
if (!Number.isNaN(parsed)) {
retryDelay = parsed;
}
}
}
let data;
let parsedJson = false;
if (dataLines.length) {
const rawData = dataLines.join("\n");
try {
data = JSON.parse(rawData);
parsedJson = true;
}
catch {
data = rawData;
}
}
if (parsedJson) {
if (responseValidator) {
await responseValidator(data);
}
if (responseTransformer) {
data = await responseTransformer(data);
}
}
onSseEvent?.({
data,
event: eventName,
id: lastEventId,
retry: retryDelay,
});
if (dataLines.length) {
yield data;
}
}
}
}
finally {
signal.removeEventListener("abort", abortHandler);
reader.releaseLock();
}
break; // exit loop on normal completion
}
catch (error) {
// connection failed or aborted; retry after delay
onSseError?.(error);
if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
break; // stop after firing error
}
// exponential backoff: double retry each attempt, cap at 30s
const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
await sleep(backoff);
}
}
};
const stream = createStream();
return { stream };
};
import type { Auth, AuthToken } from "./auth.gen.js";
import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from "./bodySerializer.gen.js";
export interface Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never> {
/**
* Returns the final request URL.
*/
buildUrl: BuildUrlFn;
connect: MethodFn;
delete: MethodFn;
get: MethodFn;
getConfig: () => Config;
head: MethodFn;
options: MethodFn;
patch: MethodFn;
post: MethodFn;
put: MethodFn;
request: RequestFn;
setConfig: (config: Config) => Config;
trace: MethodFn;
}
export interface Config {
/**
* Auth token or a function returning auth token. The resolved value will be
* added to the request payload as defined by its `security` array.
*/
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
/**
* A function for serializing request body parameter. By default,
* {@link JSON.stringify()} will be used.
*/
bodySerializer?: BodySerializer | null;
/**
* An object containing any HTTP headers that you want to pre-populate your
* `Headers` object with.
*
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
*/
headers?: RequestInit["headers"] | Record<string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown>;
/**
* The request method.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
*/
method?: "CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE";
/**
* A function for serializing request query parameters. By default, arrays
* will be exploded in form style, objects will be exploded in deepObject
* style, and reserved characters are percent-encoded.
*
* This method will have no effect if the native `paramsSerializer()` Axios
* API function is used.
*
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
*/
querySerializer?: QuerySerializer | QuerySerializerOptions;
/**
* A function validating request data. This is useful if you want to ensure
* the request conforms to the desired shape, so it can be safely sent to
* the server.
*/
requestValidator?: (data: unknown) => Promise<unknown>;
/**
* A function transforming response data before it's returned. This is useful
* for post-processing data, e.g. converting ISO strings into Date objects.
*/
responseTransformer?: (data: unknown) => Promise<unknown>;
/**
* A function validating response data. This is useful if you want to ensure
* the response conforms to the desired shape, so it can be safely passed to
* the transformers and returned to the user.
*/
responseValidator?: (data: unknown) => Promise<unknown>;
}
type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false;
export type OmitNever<T extends Record<string, unknown>> = {
[K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true ? never : K]: T[K];
};
export {};
// This file is auto-generated by @hey-api/openapi-ts
export {};
import type { QuerySerializer } from "./bodySerializer.gen.js";
export interface PathSerializer {
path: Record<string, unknown>;
url: string;
}
export declare const PATH_PARAM_RE: RegExp;
export declare const defaultPathSerializer: ({ path, url: _url }: PathSerializer) => string;
export declare const getUrl: ({ baseUrl, path, query, querySerializer, url: _url, }: {
baseUrl?: string;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
querySerializer: QuerySerializer;
url: string;
}) => string;
// This file is auto-generated by @hey-api/openapi-ts
import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from "./pathSerializer.gen.js";
export const PATH_PARAM_RE = /\{[^{}]+\}/g;
export const defaultPathSerializer = ({ path, url: _url }) => {
let url = _url;
const matches = _url.match(PATH_PARAM_RE);
if (matches) {
for (const match of matches) {
let explode = false;
let name = match.substring(1, match.length - 1);
let style = "simple";
if (name.endsWith("*")) {
explode = true;
name = name.substring(0, name.length - 1);
}
if (name.startsWith(".")) {
name = name.substring(1);
style = "label";
}
else if (name.startsWith(";")) {
name = name.substring(1);
style = "matrix";
}
const value = path[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
continue;
}
if (typeof value === "object") {
url = url.replace(match, serializeObjectParam({
explode,
name,
style,
value: value,
valueOnly: true,
}));
continue;
}
if (style === "matrix") {
url = url.replace(match, `;${serializePrimitiveParam({
name,
value: value,
})}`);
continue;
}
const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
url = url.replace(match, replaceValue);
}
}
return url;
};
export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }) => {
const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
let url = (baseUrl ?? "") + pathUrl;
if (path) {
url = defaultPathSerializer({ path, url });
}
let search = query ? querySerializer(query) : "";
if (search.startsWith("?")) {
search = search.substring(1);
}
if (search) {
url += `?${search}`;
}
return url;
};
import { type ChildProcess } from "node:child_process";
export declare function stop(proc: ChildProcess): void;
export declare function bindAbort(proc: ChildProcess, signal?: AbortSignal, onAbort?: () => void): () => void;
import { spawnSync } from "node:child_process";
// Duplicated from `packages/opencode/src/util/process.ts` because the SDK cannot
// import `opencode` without creating a cycle (`opencode` depends on `@opencode-ai/sdk`).
export function stop(proc) {
if (proc.exitCode !== null || proc.signalCode !== null)
return;
if (process.platform === "win32" && proc.pid) {
const out = spawnSync("taskkill", ["/pid", String(proc.pid), "/T", "/F"], { windowsHide: true });
if (!out.error && out.status === 0)
return;
}
proc.kill();
}
export function bindAbort(proc, signal, onAbort) {
if (!signal)
return () => { };
const abort = () => {
clear();
stop(proc);
onAbort?.();
};
const clear = () => {
signal.removeEventListener("abort", abort);
proc.off("exit", clear);
proc.off("error", clear);
};
signal.addEventListener("abort", abort, { once: true });
proc.on("exit", clear);
proc.on("error", clear);
if (signal.aborted)
abort();
return clear;
}
import { type Config } from "./gen/types.gen.js";
export type ServerOptions = {
hostname?: string;
port?: number;
signal?: AbortSignal;
timeout?: number;
config?: Config;
};
export type TuiOptions = {
project?: string;
model?: string;
session?: string;
agent?: string;
signal?: AbortSignal;
config?: Config;
};
export declare function createOpencodeServer(options?: ServerOptions): Promise<{
url: string;
close(): void;
}>;
export declare function createOpencodeTui(options?: TuiOptions): {
close(): void;
};
import launch from "cross-spawn";
import { stop, bindAbort } from "./process.js";
export async function createOpencodeServer(options) {
options = Object.assign({
hostname: "127.0.0.1",
port: 4096,
timeout: 5000,
}, options ?? {});
const args = [`serve`, `--hostname=${options.hostname}`, `--port=${options.port}`];
if (options.config?.logLevel)
args.push(`--log-level=${options.config.logLevel}`);
const proc = launch(`opencode`, args, {
env: {
...process.env,
OPENCODE_CONFIG_CONTENT: JSON.stringify(options.config ?? {}),
},
});
let clear = () => { };
const url = await new Promise((resolve, reject) => {
const id = setTimeout(() => {
clear();
stop(proc);
reject(new Error(`Timeout waiting for server to start after ${options.timeout}ms`));
}, options.timeout);
let output = "";
let resolved = false;
proc.stdout?.on("data", (chunk) => {
if (resolved)
return;
output += chunk.toString();
const lines = output.split("\n");
for (const line of lines) {
if (line.startsWith("opencode server listening")) {
const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
if (!match) {
clear();
stop(proc);
clearTimeout(id);
reject(new Error(`Failed to parse server url from output: ${line}`));
return;
}
clearTimeout(id);
resolved = true;
resolve(match[1]);
return;
}
}
});
proc.stderr?.on("data", (chunk) => {
output += chunk.toString();
});
proc.on("exit", (code) => {
clearTimeout(id);
let msg = `Server exited with code ${code}`;
if (output.trim()) {
msg += `\nServer output: ${output}`;
}
reject(new Error(msg));
});
proc.on("error", (error) => {
clearTimeout(id);
reject(error);
});
clear = bindAbort(proc, options.signal, () => {
clearTimeout(id);
reject(options.signal?.reason);
});
});
return {
url,
close() {
clear();
stop(proc);
},
};
}
export function createOpencodeTui(options) {
const args = [];
if (options?.project) {
args.push(`--project=${options.project}`);
}
if (options?.model) {
args.push(`--model=${options.model}`);
}
if (options?.session) {
args.push(`--session=${options.session}`);
}
if (options?.agent) {
args.push(`--agent=${options.agent}`);
}
const proc = launch(`opencode`, args, {
stdio: "inherit",
env: {
...process.env,
OPENCODE_CONFIG_CONTENT: JSON.stringify(options?.config ?? {}),
},
});
const clear = bindAbort(proc, options?.signal);
return {
close() {
clear();
stop(proc);
},
};
}
export * from "./gen/types.gen.js";
export type { FileSystemEntry as LocationFileSystemEntry } from "./gen/types.gen.js";
import { type Config } from "./gen/client/types.gen.js";
import { OpencodeClient } from "./gen/sdk.gen.js";
export { type Config as OpencodeClientConfig, OpencodeClient };
export declare function createOpencodeClient(config?: Config & {
directory?: string;
experimental_workspaceID?: string;
}): OpencodeClient;
export * from "./gen/types.gen.js";
import { createClient } from "./gen/client/client.gen.js";
import { OpencodeClient } from "./gen/sdk.gen.js";
import { wrapClientError } from "../error-interceptor.js";
export { OpencodeClient };
function pick(value, fallback, encode) {
if (!value)
return;
if (!fallback)
return value;
if (value === fallback)
return fallback;
if (encode && value === encode(fallback))
return fallback;
return value;
}
function rewrite(request, values) {
if (request.method !== "GET" && request.method !== "HEAD")
return request;
const url = new URL(request.url);
let changed = false;
for (const [name, key] of [
["x-opencode-directory", "directory"],
["x-opencode-workspace", "workspace"],
]) {
const value = pick(request.headers.get(name), key === "directory" ? values.directory : values.workspace, key === "directory" ? encodeURIComponent : undefined);
if (!value)
continue;
for (const query of url.pathname.startsWith("/api/") ? [key, `location[${key}]`] : [key]) {
if (!url.searchParams.has(query)) {
url.searchParams.set(query, value);
}
}
changed = true;
}
if (!changed)
return request;
const next = new Request(url, request);
next.headers.delete("x-opencode-directory");
next.headers.delete("x-opencode-workspace");
return next;
}
export function createOpencodeClient(config) {
if (!config?.fetch) {
const customFetch = (req) => {
// @ts-ignore
req.timeout = false;
return fetch(req);
};
config = {
...config,
fetch: customFetch,
};
}
if (config?.directory) {
config.headers = {
...config.headers,
"x-opencode-directory": encodeURIComponent(config.directory),
};
}
if (config?.experimental_workspaceID) {
config.headers = {
...config.headers,
"x-opencode-workspace": config.experimental_workspaceID,
};
}
const client = createClient(config);
client.interceptors.request.use((request) => rewrite(request, {
directory: config?.directory,
workspace: config?.experimental_workspaceID,
}));
client.interceptors.response.use((response) => {
const contentType = response.headers.get("content-type");
if (contentType === "text/html")
throw new Error("Request is not supported by this version of OpenCode Server (Server responded with text/html)");
return response;
});
client.interceptors.error.use(wrapClientError);
return new OpencodeClient({ client });
}
import type { Part, UserMessage } from "./client.js";
export declare const message: {
user(input: Omit<UserMessage, "role" | "time" | "id"> & {
parts: Omit<Part, "id" | "sessionID" | "messageID">[];
}): {
info: UserMessage;
parts: Part[];
};
};
export const message = {
user(input) {
const { parts: _parts, ...rest } = input;
const info = {
...rest,
id: "asdasd",
time: {
created: Date.now(),
},
role: "user",
};
return {
info,
parts: input.parts.map((part) => ({
...part,
id: "asdasd",
messageID: info.id,
sessionID: info.sessionID,
})),
};
},
};
import { type ClientOptions, type Config } from "./client/index.js";
import type { ClientOptions as ClientOptions2 } from "./types.gen.js";
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
export declare const client: import("./client/types.gen.js").Client;
// This file is auto-generated by @hey-api/openapi-ts
import { createClient, createConfig } from "./client/index.js";
export const client = createClient(createConfig({ baseUrl: "http://localhost:4096" }));
import type { Client, Config } from "./types.gen.js";
export declare const createClient: (config?: Config) => Client;
// This file is auto-generated by @hey-api/openapi-ts
import { createSseClient } from "../core/serverSentEvents.gen.js";
import { getValidRequestBody } from "../core/utils.gen.js";
import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from "./utils.gen.js";
export const createClient = (config = {}) => {
let _config = mergeConfigs(createConfig(), config);
const getConfig = () => ({ ..._config });
const setConfig = (config) => {
_config = mergeConfigs(_config, config);
return getConfig();
};
const interceptors = createInterceptors();
const beforeRequest = async (options) => {
const opts = {
..._config,
...options,
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
headers: mergeHeaders(_config.headers, options.headers),
serializedBody: undefined,
};
if (opts.security) {
await setAuthParams({
...opts,
security: opts.security,
});
}
if (opts.requestValidator) {
await opts.requestValidator(opts);
}
if (opts.body !== undefined && opts.bodySerializer) {
opts.serializedBody = opts.bodySerializer(opts.body);
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.body === undefined || opts.serializedBody === "") {
opts.headers.delete("Content-Type");
}
const url = buildUrl(opts);
return { opts, url };
};
const request = async (options) => {
// @ts-expect-error
const { opts, url } = await beforeRequest(options);
const requestInit = {
redirect: "follow",
...opts,
body: getValidRequestBody(opts),
};
let request = new Request(url, requestInit);
for (const fn of interceptors.request.fns) {
if (fn) {
request = await fn(request, opts);
}
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = opts.fetch;
let response;
try {
response = await _fetch(request);
}
catch (error) {
// Handle fetch exceptions (AbortError, network errors, etc.)
let finalError = error;
for (const fn of interceptors.error.fns) {
if (fn) {
finalError = (await fn(error, undefined, request, opts));
}
}
finalError = finalError || {};
if (opts.throwOnError) {
throw finalError;
}
// Return error response
return opts.responseStyle === "data"
? undefined
: {
error: finalError,
request,
response: undefined,
};
}
for (const fn of interceptors.response.fns) {
if (fn) {
response = await fn(response, request, opts);
}
}
const result = {
request,
response,
};
if (response.ok) {
const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
if (response.status === 204 || response.headers.get("Content-Length") === "0") {
let emptyData;
switch (parseAs) {
case "arrayBuffer":
case "blob":
case "text":
emptyData = await response[parseAs]();
break;
case "formData":
emptyData = new FormData();
break;
case "stream":
emptyData = response.body;
break;
case "json":
default:
emptyData = {};
break;
}
return opts.responseStyle === "data"
? emptyData
: {
data: emptyData,
...result,
};
}
let data;
switch (parseAs) {
case "arrayBuffer":
case "blob":
case "formData":
case "text":
data = await response[parseAs]();
break;
case "json": {
// Some servers return 200 with no Content-Length and empty body.
// response.json() would throw; read as text and parse if non-empty.
const text = await response.text();
data = text ? JSON.parse(text) : {};
break;
}
case "stream":
return opts.responseStyle === "data"
? response.body
: {
data: response.body,
...result,
};
}
if (parseAs === "json") {
if (opts.responseValidator) {
await opts.responseValidator(data);
}
if (opts.responseTransformer) {
data = await opts.responseTransformer(data);
}
}
return opts.responseStyle === "data"
? data
: {
data,
...result,
};
}
const textError = await response.text();
let jsonError;
try {
jsonError = JSON.parse(textError);
}
catch {
// noop
}
const error = jsonError ?? textError;
let finalError = error;
for (const fn of interceptors.error.fns) {
if (fn) {
finalError = (await fn(error, response, request, opts));
}
}
finalError = finalError || {};
if (opts.throwOnError) {
throw finalError;
}
// TODO: we probably want to return error and improve types
return opts.responseStyle === "data"
? undefined
: {
error: finalError,
...result,
};
};
const makeMethodFn = (method) => (options) => request({ ...options, method });
const makeSseFn = (method) => async (options) => {
const { opts, url } = await beforeRequest(options);
return createSseClient({
...opts,
body: opts.body,
headers: opts.headers,
method,
onRequest: async (url, init) => {
let request = new Request(url, init);
for (const fn of interceptors.request.fns) {
if (fn) {
request = await fn(request, opts);
}
}
return request;
},
serializedBody: getValidRequestBody(opts),
url,
});
};
return {
buildUrl,
connect: makeMethodFn("CONNECT"),
delete: makeMethodFn("DELETE"),
get: makeMethodFn("GET"),
getConfig,
head: makeMethodFn("HEAD"),
interceptors,
options: makeMethodFn("OPTIONS"),
patch: makeMethodFn("PATCH"),
post: makeMethodFn("POST"),
put: makeMethodFn("PUT"),
request,
setConfig,
sse: {
connect: makeSseFn("CONNECT"),
delete: makeSseFn("DELETE"),
get: makeSseFn("GET"),
head: makeSseFn("HEAD"),
options: makeSseFn("OPTIONS"),
patch: makeSseFn("PATCH"),
post: makeSseFn("POST"),
put: makeSseFn("PUT"),
trace: makeSseFn("TRACE"),
},
trace: makeMethodFn("TRACE"),
};
};
export type { Auth } from "../core/auth.gen.js";
export type { QuerySerializerOptions } from "../core/bodySerializer.gen.js";
export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from "../core/bodySerializer.gen.js";
export { buildClientParams } from "../core/params.gen.js";
export { serializeQueryKeyValue } from "../core/queryKeySerializer.gen.js";
export { createClient } from "./client.gen.js";
export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from "./types.gen.js";
export { createConfig, mergeHeaders } from "./utils.gen.js";
// This file is auto-generated by @hey-api/openapi-ts
export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from "../core/bodySerializer.gen.js";
export { buildClientParams } from "../core/params.gen.js";
export { serializeQueryKeyValue } from "../core/queryKeySerializer.gen.js";
export { createClient } from "./client.gen.js";
export { createConfig, mergeHeaders } from "./utils.gen.js";
import type { Auth } from "../core/auth.gen.js";
import type { ServerSentEventsOptions, ServerSentEventsResult } from "../core/serverSentEvents.gen.js";
import type { Client as CoreClient, Config as CoreConfig } from "../core/types.gen.js";
import type { Middleware } from "./utils.gen.js";
export type ResponseStyle = "data" | "fields";
export interface Config<T extends ClientOptions = ClientOptions> extends Omit<RequestInit, "body" | "headers" | "method">, CoreConfig {
/**
* Base URL for all requests made by this client.
*/
baseUrl?: T["baseUrl"];
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: typeof fetch;
/**
* Please don't use the Fetch client for Next.js applications. The `next`
* options won't have any effect.
*
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
*/
next?: never;
/**
* Return the response data parsed in a specified format. By default, `auto`
* will infer the appropriate method from the `Content-Type` response header.
* You can override this behavior with any of the {@link Body} methods.
* Select `stream` if you don't want to parse response data at all.
*
* @default 'auto'
*/
parseAs?: "arrayBuffer" | "auto" | "blob" | "formData" | "json" | "stream" | "text";
/**
* Should we return only data or multiple fields (data, error, response, etc.)?
*
* @default 'fields'
*/
responseStyle?: ResponseStyle;
/**
* Throw an error instead of returning it in the response?
*
* @default false
*/
throwOnError?: T["throwOnError"];
}
export interface RequestOptions<TData = unknown, TResponseStyle extends ResponseStyle = "fields", ThrowOnError extends boolean = boolean, Url extends string = string> extends Config<{
responseStyle: TResponseStyle;
throwOnError: ThrowOnError;
}>, Pick<ServerSentEventsOptions<TData>, "onSseError" | "onSseEvent" | "sseDefaultRetryDelay" | "sseMaxRetryAttempts" | "sseMaxRetryDelay"> {
/**
* Any body that you want to add to your request.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
*/
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
/**
* Security mechanism(s) to use for the request.
*/
security?: ReadonlyArray<Auth>;
url: Url;
}
export interface ResolvedRequestOptions<TResponseStyle extends ResponseStyle = "fields", ThrowOnError extends boolean = boolean, Url extends string = string> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
serializedBody?: string;
}
export type RequestResult<TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = "fields"> = ThrowOnError extends true ? Promise<TResponseStyle extends "data" ? TData extends Record<string, unknown> ? TData[keyof TData] : TData : {
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
request: Request;
response: Response;
}> : Promise<TResponseStyle extends "data" ? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined : ({
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
error: undefined;
} | {
data: undefined;
error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
}) & {
request: Request;
response: Response;
}>;
export interface ClientOptions {
baseUrl?: string;
responseStyle?: ResponseStyle;
throwOnError?: boolean;
}
type MethodFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = "fields">(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type SseFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = "fields">(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">) => Promise<ServerSentEventsResult<TData>>;
type RequestFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = "fields">(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method"> & Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, "method">) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type BuildUrlFn = <TData extends {
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
url: string;
}>(options: TData & Options<TData>) => string;
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>;
};
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
export interface TDataShape {
body?: unknown;
headers?: unknown;
path?: unknown;
query?: unknown;
url: string;
}
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = "fields"> = OmitKeys<RequestOptions<TResponse, TResponseStyle, ThrowOnError>, "body" | "path" | "query" | "url"> & ([TData] extends [never] ? unknown : Omit<TData, "url">);
export {};
// This file is auto-generated by @hey-api/openapi-ts
export {};
import type { QuerySerializerOptions } from "../core/bodySerializer.gen.js";
import type { Client, ClientOptions, Config, RequestOptions } from "./types.gen.js";
export declare const createQuerySerializer: <T = unknown>({ parameters, ...args }?: QuerySerializerOptions) => (queryParams: T) => string;
/**
* Infers parseAs value from provided Content-Type header.
*/
export declare const getParseAs: (contentType: string | null) => Exclude<Config["parseAs"], "auto">;
export declare const setAuthParams: ({ security, ...options }: Pick<Required<RequestOptions>, "security"> & Pick<RequestOptions, "auth" | "query"> & {
headers: Headers;
}) => Promise<void>;
export declare const buildUrl: Client["buildUrl"];
export declare const mergeConfigs: (a: Config, b: Config) => Config;
export declare const mergeHeaders: (...headers: Array<Required<Config>["headers"] | undefined>) => Headers;
type ErrInterceptor<Err, Res, Req, Options> = (error: Err, response: Res, request: Req, options: Options) => Err | Promise<Err>;
type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;
type ResInterceptor<Res, Req, Options> = (response: Res, request: Req, options: Options) => Res | Promise<Res>;
declare class Interceptors<Interceptor> {
fns: Array<Interceptor | null>;
clear(): void;
eject(id: number | Interceptor): void;
exists(id: number | Interceptor): boolean;
getInterceptorIndex(id: number | Interceptor): number;
update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false;
use(fn: Interceptor): number;
}
export interface Middleware<Req, Res, Err, Options> {
error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
request: Interceptors<ReqInterceptor<Req, Options>>;
response: Interceptors<ResInterceptor<Res, Req, Options>>;
}
export declare const createInterceptors: <Req, Res, Err, Options>() => Middleware<Req, Res, Err, Options>;
export declare const createConfig: <T extends ClientOptions = ClientOptions>(override?: Config<Omit<ClientOptions, keyof T> & T>) => Config<Omit<ClientOptions, keyof T> & T>;
export {};
// This file is auto-generated by @hey-api/openapi-ts
import { getAuthToken } from "../core/auth.gen.js";
import { jsonBodySerializer } from "../core/bodySerializer.gen.js";
import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam } from "../core/pathSerializer.gen.js";
import { getUrl } from "../core/utils.gen.js";
export const createQuerySerializer = ({ parameters = {}, ...args } = {}) => {
const querySerializer = (queryParams) => {
const search = [];
if (queryParams && typeof queryParams === "object") {
for (const name in queryParams) {
const value = queryParams[name];
if (value === undefined) {
continue;
}
if (value === null) {
search.push(`${name}=null`);
continue;
}
const options = parameters[name] || args;
if (Array.isArray(value)) {
const serializedArray = serializeArrayParam({
allowReserved: options.allowReserved,
explode: true,
name,
style: "form",
value,
...options.array,
});
if (serializedArray)
search.push(serializedArray);
}
else if (typeof value === "object") {
const serializedObject = serializeObjectParam({
allowReserved: options.allowReserved,
explode: true,
name,
style: "deepObject",
value: value,
...options.object,
});
if (serializedObject)
search.push(serializedObject);
}
else {
const serializedPrimitive = serializePrimitiveParam({
allowReserved: options.allowReserved,
name,
value: value,
});
if (serializedPrimitive)
search.push(serializedPrimitive);
}
}
}
return search.join("&");
};
return querySerializer;
};
/**
* Infers parseAs value from provided Content-Type header.
*/
export const getParseAs = (contentType) => {
if (!contentType) {
// If no Content-Type header is provided, the best we can do is return the raw response body,
// which is effectively the same as the 'stream' option.
return "stream";
}
const cleanContent = contentType.split(";")[0]?.trim();
if (!cleanContent) {
return;
}
if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
return "json";
}
if (cleanContent === "multipart/form-data") {
return "formData";
}
if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
return "blob";
}
if (cleanContent.startsWith("text/")) {
return "text";
}
return;
};
const checkForExistence = (options, name) => {
if (!name) {
return false;
}
if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
return true;
}
return false;
};
export const setAuthParams = async ({ security, ...options }) => {
for (const auth of security) {
if (checkForExistence(options, auth.name)) {
continue;
}
const token = await getAuthToken(auth, options.auth);
if (!token) {
continue;
}
const name = auth.name ?? "Authorization";
switch (auth.in) {
case "query":
if (!options.query) {
options.query = {};
}
options.query[name] = token;
break;
case "cookie":
options.headers.append("Cookie", `${name}=${token}`);
break;
case "header":
default:
options.headers.set(name, token);
break;
}
}
};
export const buildUrl = (options) => getUrl({
baseUrl: options.baseUrl,
path: options.path,
query: options.query,
querySerializer: typeof options.querySerializer === "function"
? options.querySerializer
: createQuerySerializer(options.querySerializer),
url: options.url,
});
export const mergeConfigs = (a, b) => {
const config = { ...a, ...b };
if (config.baseUrl?.endsWith("/")) {
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
}
config.headers = mergeHeaders(a.headers, b.headers);
return config;
};
const headersEntries = (headers) => {
const entries = [];
headers.forEach((value, key) => {
entries.push([key, value]);
});
return entries;
};
export const mergeHeaders = (...headers) => {
const mergedHeaders = new Headers();
for (const header of headers) {
if (!header) {
continue;
}
const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
for (const [key, value] of iterator) {
if (value === null) {
mergedHeaders.delete(key);
}
else if (Array.isArray(value)) {
for (const v of value) {
mergedHeaders.append(key, v);
}
}
else if (value !== undefined) {
// assume object headers are meant to be JSON stringified, i.e. their
// content value in OpenAPI specification is 'application/json'
mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
}
}
}
return mergedHeaders;
};
class Interceptors {
fns = [];
clear() {
this.fns = [];
}
eject(id) {
const index = this.getInterceptorIndex(id);
if (this.fns[index]) {
this.fns[index] = null;
}
}
exists(id) {
const index = this.getInterceptorIndex(id);
return Boolean(this.fns[index]);
}
getInterceptorIndex(id) {
if (typeof id === "number") {
return this.fns[id] ? id : -1;
}
return this.fns.indexOf(id);
}
update(id, fn) {
const index = this.getInterceptorIndex(id);
if (this.fns[index]) {
this.fns[index] = fn;
return id;
}
return false;
}
use(fn) {
this.fns.push(fn);
return this.fns.length - 1;
}
}
export const createInterceptors = () => ({
error: new Interceptors(),
request: new Interceptors(),
response: new Interceptors(),
});
const defaultQuerySerializer = createQuerySerializer({
allowReserved: false,
array: {
explode: true,
style: "form",
},
object: {
explode: true,
style: "deepObject",
},
});
const defaultHeaders = {
"Content-Type": "application/json",
};
export const createConfig = (override = {}) => ({
...jsonBodySerializer,
headers: defaultHeaders,
parseAs: "auto",
querySerializer: defaultQuerySerializer,
...override,
});
export type AuthToken = string | undefined;
export interface Auth {
/**
* Which part of the request do we use to send the auth?
*
* @default 'header'
*/
in?: "header" | "query" | "cookie";
/**
* Header or query parameter name.
*
* @default 'Authorization'
*/
name?: string;
scheme?: "basic" | "bearer";
type: "apiKey" | "http";
}
export declare const getAuthToken: (auth: Auth, callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken) => Promise<string | undefined>;
// This file is auto-generated by @hey-api/openapi-ts
export const getAuthToken = async (auth, callback) => {
const token = typeof callback === "function" ? await callback(auth) : callback;
if (!token) {
return;
}
if (auth.scheme === "bearer") {
return `Bearer ${token}`;
}
if (auth.scheme === "basic") {
return `Basic ${btoa(token)}`;
}
return token;
};
import type { ArrayStyle, ObjectStyle, SerializerOptions } from "./pathSerializer.gen.js";
export type QuerySerializer = (query: Record<string, unknown>) => string;
export type BodySerializer = (body: any) => any;
type QuerySerializerOptionsObject = {
allowReserved?: boolean;
array?: Partial<SerializerOptions<ArrayStyle>>;
object?: Partial<SerializerOptions<ObjectStyle>>;
};
export type QuerySerializerOptions = QuerySerializerOptionsObject & {
/**
* Per-parameter serialization overrides. When provided, these settings
* override the global array/object settings for specific parameter names.
*/
parameters?: Record<string, QuerySerializerOptionsObject>;
};
export declare const formDataBodySerializer: {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T) => FormData;
};
export declare const jsonBodySerializer: {
bodySerializer: <T>(body: T) => string;
};
export declare const urlSearchParamsBodySerializer: {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T) => string;
};
export {};
// This file is auto-generated by @hey-api/openapi-ts
const serializeFormDataPair = (data, key, value) => {
if (typeof value === "string" || value instanceof Blob) {
data.append(key, value);
}
else if (value instanceof Date) {
data.append(key, value.toISOString());
}
else {
data.append(key, JSON.stringify(value));
}
};
const serializeUrlSearchParamsPair = (data, key, value) => {
if (typeof value === "string") {
data.append(key, value);
}
else {
data.append(key, JSON.stringify(value));
}
};
export const formDataBodySerializer = {
bodySerializer: (body) => {
const data = new FormData();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeFormDataPair(data, key, v));
}
else {
serializeFormDataPair(data, key, value);
}
});
return data;
},
};
export const jsonBodySerializer = {
bodySerializer: (body) => JSON.stringify(body, (_key, value) => (typeof value === "bigint" ? value.toString() : value)),
};
export const urlSearchParamsBodySerializer = {
bodySerializer: (body) => {
const data = new URLSearchParams();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
}
else {
serializeUrlSearchParamsPair(data, key, value);
}
});
return data.toString();
},
};
type Slot = "body" | "headers" | "path" | "query";
export type Field = {
in: Exclude<Slot, "body">;
/**
* Field name. This is the name we want the user to see and use.
*/
key: string;
/**
* Field mapped name. This is the name we want to use in the request.
* If omitted, we use the same value as `key`.
*/
map?: string;
} | {
in: Extract<Slot, "body">;
/**
* Key isn't required for bodies.
*/
key?: string;
map?: string;
} | {
/**
* Field name. This is the name we want the user to see and use.
*/
key: string;
/**
* Field mapped name. This is the name we want to use in the request.
* If `in` is omitted, `map` aliases `key` to the transport layer.
*/
map: Slot;
};
export interface Fields {
allowExtra?: Partial<Record<Slot, boolean>>;
args?: ReadonlyArray<Field>;
}
export type FieldsConfig = ReadonlyArray<Field | Fields>;
interface Params {
body: unknown;
headers: Record<string, unknown>;
path: Record<string, unknown>;
query: Record<string, unknown>;
}
export declare const buildClientParams: (args: ReadonlyArray<unknown>, fields: FieldsConfig) => Params;
export {};
// This file is auto-generated by @hey-api/openapi-ts
const extraPrefixesMap = {
$body_: "body",
$headers_: "headers",
$path_: "path",
$query_: "query",
};
const extraPrefixes = Object.entries(extraPrefixesMap);
const buildKeyMap = (fields, map) => {
if (!map) {
map = new Map();
}
for (const config of fields) {
if ("in" in config) {
if (config.key) {
map.set(config.key, {
in: config.in,
map: config.map,
});
}
}
else if ("key" in config) {
map.set(config.key, {
map: config.map,
});
}
else if (config.args) {
buildKeyMap(config.args, map);
}
}
return map;
};
const stripEmptySlots = (params) => {
for (const [slot, value] of Object.entries(params)) {
if (value && typeof value === "object" && !Object.keys(value).length) {
delete params[slot];
}
}
};
export const buildClientParams = (args, fields) => {
const params = {
body: {},
headers: {},
path: {},
query: {},
};
const map = buildKeyMap(fields);
let config;
for (const [index, arg] of args.entries()) {
if (fields[index]) {
config = fields[index];
}
if (!config) {
continue;
}
if ("in" in config) {
if (config.key) {
const field = map.get(config.key);
const name = field.map || config.key;
if (field.in) {
;
params[field.in][name] = arg;
}
}
else {
params.body = arg;
}
}
else {
for (const [key, value] of Object.entries(arg ?? {})) {
const field = map.get(key);
if (field) {
if (field.in) {
const name = field.map || key;
params[field.in][name] = value;
}
else {
params[field.map] = value;
}
}
else {
const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));
if (extra) {
const [prefix, slot] = extra;
params[slot][key.slice(prefix.length)] = value;
}
else if ("allowExtra" in config && config.allowExtra) {
for (const [slot, allowed] of Object.entries(config.allowExtra)) {
if (allowed) {
;
params[slot][key] = value;
break;
}
}
}
}
}
}
}
stripEmptySlots(params);
return params;
};
interface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {
}
interface SerializePrimitiveOptions {
allowReserved?: boolean;
name: string;
}
export interface SerializerOptions<T> {
/**
* @default true
*/
explode: boolean;
style: T;
}
export type ArrayStyle = "form" | "spaceDelimited" | "pipeDelimited";
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
type MatrixStyle = "label" | "matrix" | "simple";
export type ObjectStyle = "form" | "deepObject";
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
value: string;
}
export declare const separatorArrayExplode: (style: ArraySeparatorStyle) => "." | ";" | "," | "&";
export declare const separatorArrayNoExplode: (style: ArraySeparatorStyle) => "," | "|" | "%20";
export declare const separatorObjectExplode: (style: ObjectSeparatorStyle) => "." | ";" | "," | "&";
export declare const serializeArrayParam: ({ allowReserved, explode, name, style, value, }: SerializeOptions<ArraySeparatorStyle> & {
value: unknown[];
}) => string;
export declare const serializePrimitiveParam: ({ allowReserved, name, value }: SerializePrimitiveParam) => string;
export declare const serializeObjectParam: ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions<ObjectSeparatorStyle> & {
value: Record<string, unknown> | Date;
valueOnly?: boolean;
}) => string;
export {};
// This file is auto-generated by @hey-api/openapi-ts
export const separatorArrayExplode = (style) => {
switch (style) {
case "label":
return ".";
case "matrix":
return ";";
case "simple":
return ",";
default:
return "&";
}
};
export const separatorArrayNoExplode = (style) => {
switch (style) {
case "form":
return ",";
case "pipeDelimited":
return "|";
case "spaceDelimited":
return "%20";
default:
return ",";
}
};
export const separatorObjectExplode = (style) => {
switch (style) {
case "label":
return ".";
case "matrix":
return ";";
case "simple":
return ",";
default:
return "&";
}
};
export const serializeArrayParam = ({ allowReserved, explode, name, style, value, }) => {
if (!explode) {
const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
switch (style) {
case "label":
return `.${joinedValues}`;
case "matrix":
return `;${name}=${joinedValues}`;
case "simple":
return joinedValues;
default:
return `${name}=${joinedValues}`;
}
}
const separator = separatorArrayExplode(style);
const joinedValues = value
.map((v) => {
if (style === "label" || style === "simple") {
return allowReserved ? v : encodeURIComponent(v);
}
return serializePrimitiveParam({
allowReserved,
name,
value: v,
});
})
.join(separator);
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
};
export const serializePrimitiveParam = ({ allowReserved, name, value }) => {
if (value === undefined || value === null) {
return "";
}
if (typeof value === "object") {
throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
}
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
};
export const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly, }) => {
if (value instanceof Date) {
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
}
if (style !== "deepObject" && !explode) {
let values = [];
Object.entries(value).forEach(([key, v]) => {
values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
});
const joinedValues = values.join(",");
switch (style) {
case "form":
return `${name}=${joinedValues}`;
case "label":
return `.${joinedValues}`;
case "matrix":
return `;${name}=${joinedValues}`;
default:
return joinedValues;
}
}
const separator = separatorObjectExplode(style);
const joinedValues = Object.entries(value)
.map(([key, v]) => serializePrimitiveParam({
allowReserved,
name: style === "deepObject" ? `${name}[${key}]` : key,
value: v,
}))
.join(separator);
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
};
/**
* JSON-friendly union that mirrors what Pinia Colada can hash.
*/
export type JsonValue = null | string | number | boolean | JsonValue[] | {
[key: string]: JsonValue;
};
/**
* Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
*/
export declare const queryKeyJsonReplacer: (_key: string, value: unknown) => {} | null | undefined;
/**
* Safely stringifies a value and parses it back into a JsonValue.
*/
export declare const stringifyToJsonValue: (input: unknown) => JsonValue | undefined;
/**
* Normalizes any accepted value into a JSON-friendly shape for query keys.
*/
export declare const serializeQueryKeyValue: (value: unknown) => JsonValue | undefined;
// This file is auto-generated by @hey-api/openapi-ts
/**
* Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
*/
export const queryKeyJsonReplacer = (_key, value) => {
if (value === undefined || typeof value === "function" || typeof value === "symbol") {
return undefined;
}
if (typeof value === "bigint") {
return value.toString();
}
if (value instanceof Date) {
return value.toISOString();
}
return value;
};
/**
* Safely stringifies a value and parses it back into a JsonValue.
*/
export const stringifyToJsonValue = (input) => {
try {
const json = JSON.stringify(input, queryKeyJsonReplacer);
if (json === undefined) {
return undefined;
}
return JSON.parse(json);
}
catch {
return undefined;
}
};
/**
* Detects plain objects (including objects with a null prototype).
*/
const isPlainObject = (value) => {
if (value === null || typeof value !== "object") {
return false;
}
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
};
/**
* Turns URLSearchParams into a sorted JSON object for deterministic keys.
*/
const serializeSearchParams = (params) => {
const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b));
const result = {};
for (const [key, value] of entries) {
const existing = result[key];
if (existing === undefined) {
result[key] = value;
continue;
}
if (Array.isArray(existing)) {
;
existing.push(value);
}
else {
result[key] = [existing, value];
}
}
return result;
};
/**
* Normalizes any accepted value into a JSON-friendly shape for query keys.
*/
export const serializeQueryKeyValue = (value) => {
if (value === null) {
return null;
}
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return value;
}
if (value === undefined || typeof value === "function" || typeof value === "symbol") {
return undefined;
}
if (typeof value === "bigint") {
return value.toString();
}
if (value instanceof Date) {
return value.toISOString();
}
if (Array.isArray(value)) {
return stringifyToJsonValue(value);
}
if (typeof URLSearchParams !== "undefined" && value instanceof URLSearchParams) {
return serializeSearchParams(value);
}
if (isPlainObject(value)) {
return stringifyToJsonValue(value);
}
return undefined;
};
import type { Config } from "./types.gen.js";
export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, "method"> & Pick<Config, "method" | "responseTransformer" | "responseValidator"> & {
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: typeof fetch;
/**
* Implementing clients can call request interceptors inside this hook.
*/
onRequest?: (url: string, init: RequestInit) => Promise<Request>;
/**
* Callback invoked when a network or parsing error occurs during streaming.
*
* This option applies only if the endpoint returns a stream of events.
*
* @param error The error that occurred.
*/
onSseError?: (error: unknown) => void;
/**
* Callback invoked when an event is streamed from the server.
*
* This option applies only if the endpoint returns a stream of events.
*
* @param event Event streamed from the server.
* @returns Nothing (void).
*/
onSseEvent?: (event: StreamEvent<TData>) => void;
serializedBody?: RequestInit["body"];
/**
* Default retry delay in milliseconds.
*
* This option applies only if the endpoint returns a stream of events.
*
* @default 3000
*/
sseDefaultRetryDelay?: number;
/**
* Maximum number of retry attempts before giving up.
*/
sseMaxRetryAttempts?: number;
/**
* Maximum retry delay in milliseconds.
*
* Applies only when exponential backoff is used.
*
* This option applies only if the endpoint returns a stream of events.
*
* @default 30000
*/
sseMaxRetryDelay?: number;
/**
* Optional sleep function for retry backoff.
*
* Defaults to using `setTimeout`.
*/
sseSleepFn?: (ms: number) => Promise<void>;
url: string;
};
export interface StreamEvent<TData = unknown> {
data: TData;
event?: string;
id?: string;
retry?: number;
}
export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
stream: AsyncGenerator<TData extends Record<string, unknown> ? TData[keyof TData] : TData, TReturn, TNext>;
};
export declare const createSseClient: <TData = unknown>({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions) => ServerSentEventsResult<TData>;
// This file is auto-generated by @hey-api/openapi-ts
export const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) => {
let lastEventId;
const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
const createStream = async function* () {
let retryDelay = sseDefaultRetryDelay ?? 3000;
let attempt = 0;
const signal = options.signal ?? new AbortController().signal;
while (true) {
if (signal.aborted)
break;
attempt++;
const headers = options.headers instanceof Headers
? options.headers
: new Headers(options.headers);
if (lastEventId !== undefined) {
headers.set("Last-Event-ID", lastEventId);
}
try {
const requestInit = {
redirect: "follow",
...options,
body: options.serializedBody,
headers,
signal,
};
let request = new Request(url, requestInit);
if (onRequest) {
request = await onRequest(url, requestInit);
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = options.fetch ?? globalThis.fetch;
const response = await _fetch(request);
if (!response.ok)
throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
if (!response.body)
throw new Error("No body in SSE response");
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
const abortHandler = () => {
try {
reader.cancel();
}
catch {
// noop
}
};
signal.addEventListener("abort", abortHandler);
try {
while (true) {
const { done, value } = await reader.read();
if (done)
break;
buffer += value;
// Normalize line endings: CRLF -> LF, then CR -> LF
buffer = buffer.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
const chunks = buffer.split("\n\n");
buffer = chunks.pop() ?? "";
for (const chunk of chunks) {
const lines = chunk.split("\n");
const dataLines = [];
let eventName;
for (const line of lines) {
if (line.startsWith("data:")) {
dataLines.push(line.replace(/^data:\s*/, ""));
}
else if (line.startsWith("event:")) {
eventName = line.replace(/^event:\s*/, "");
}
else if (line.startsWith("id:")) {
lastEventId = line.replace(/^id:\s*/, "");
}
else if (line.startsWith("retry:")) {
const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
if (!Number.isNaN(parsed)) {
retryDelay = parsed;
}
}
}
let data;
let parsedJson = false;
if (dataLines.length) {
const rawData = dataLines.join("\n");
try {
data = JSON.parse(rawData);
parsedJson = true;
}
catch {
data = rawData;
}
}
if (parsedJson) {
if (responseValidator) {
await responseValidator(data);
}
if (responseTransformer) {
data = await responseTransformer(data);
}
}
onSseEvent?.({
data,
event: eventName,
id: lastEventId,
retry: retryDelay,
});
if (dataLines.length) {
yield data;
}
}
}
}
finally {
signal.removeEventListener("abort", abortHandler);
reader.releaseLock();
}
break; // exit loop on normal completion
}
catch (error) {
// connection failed or aborted; retry after delay
onSseError?.(error);
if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
break; // stop after firing error
}
// exponential backoff: double retry each attempt, cap at 30s
const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
await sleep(backoff);
}
}
};
const stream = createStream();
return { stream };
};
import type { Auth, AuthToken } from "./auth.gen.js";
import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from "./bodySerializer.gen.js";
export type HttpMethod = "connect" | "delete" | "get" | "head" | "options" | "patch" | "post" | "put" | "trace";
export type Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never> = {
/**
* Returns the final request URL.
*/
buildUrl: BuildUrlFn;
getConfig: () => Config;
request: RequestFn;
setConfig: (config: Config) => Config;
} & {
[K in HttpMethod]: MethodFn;
} & ([SseFn] extends [never] ? {
sse?: never;
} : {
sse: {
[K in HttpMethod]: SseFn;
};
});
export interface Config {
/**
* Auth token or a function returning auth token. The resolved value will be
* added to the request payload as defined by its `security` array.
*/
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
/**
* A function for serializing request body parameter. By default,
* {@link JSON.stringify()} will be used.
*/
bodySerializer?: BodySerializer | null;
/**
* An object containing any HTTP headers that you want to pre-populate your
* `Headers` object with.
*
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
*/
headers?: RequestInit["headers"] | Record<string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown>;
/**
* The request method.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
*/
method?: Uppercase<HttpMethod>;
/**
* A function for serializing request query parameters. By default, arrays
* will be exploded in form style, objects will be exploded in deepObject
* style, and reserved characters are percent-encoded.
*
* This method will have no effect if the native `paramsSerializer()` Axios
* API function is used.
*
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
*/
querySerializer?: QuerySerializer | QuerySerializerOptions;
/**
* A function validating request data. This is useful if you want to ensure
* the request conforms to the desired shape, so it can be safely sent to
* the server.
*/
requestValidator?: (data: unknown) => Promise<unknown>;
/**
* A function transforming response data before it's returned. This is useful
* for post-processing data, e.g. converting ISO strings into Date objects.
*/
responseTransformer?: (data: unknown) => Promise<unknown>;
/**
* A function validating response data. This is useful if you want to ensure
* the response conforms to the desired shape, so it can be safely passed to
* the transformers and returned to the user.
*/
responseValidator?: (data: unknown) => Promise<unknown>;
}
type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false;
export type OmitNever<T extends Record<string, unknown>> = {
[K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true ? never : K]: T[K];
};
export {};
// This file is auto-generated by @hey-api/openapi-ts
export {};
import type { BodySerializer, QuerySerializer } from "./bodySerializer.gen.js";
export interface PathSerializer {
path: Record<string, unknown>;
url: string;
}
export declare const PATH_PARAM_RE: RegExp;
export declare const defaultPathSerializer: ({ path, url: _url }: PathSerializer) => string;
export declare const getUrl: ({ baseUrl, path, query, querySerializer, url: _url, }: {
baseUrl?: string;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
querySerializer: QuerySerializer;
url: string;
}) => string;
export declare function getValidRequestBody(options: {
body?: unknown;
bodySerializer?: BodySerializer | null;
serializedBody?: unknown;
}): unknown;
// This file is auto-generated by @hey-api/openapi-ts
import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from "./pathSerializer.gen.js";
export const PATH_PARAM_RE = /\{[^{}]+\}/g;
export const defaultPathSerializer = ({ path, url: _url }) => {
let url = _url;
const matches = _url.match(PATH_PARAM_RE);
if (matches) {
for (const match of matches) {
let explode = false;
let name = match.substring(1, match.length - 1);
let style = "simple";
if (name.endsWith("*")) {
explode = true;
name = name.substring(0, name.length - 1);
}
if (name.startsWith(".")) {
name = name.substring(1);
style = "label";
}
else if (name.startsWith(";")) {
name = name.substring(1);
style = "matrix";
}
const value = path[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
continue;
}
if (typeof value === "object") {
url = url.replace(match, serializeObjectParam({
explode,
name,
style,
value: value,
valueOnly: true,
}));
continue;
}
if (style === "matrix") {
url = url.replace(match, `;${serializePrimitiveParam({
name,
value: value,
})}`);
continue;
}
const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
url = url.replace(match, replaceValue);
}
}
return url;
};
export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }) => {
const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
let url = (baseUrl ?? "") + pathUrl;
if (path) {
url = defaultPathSerializer({ path, url });
}
let search = query ? querySerializer(query) : "";
if (search.startsWith("?")) {
search = search.substring(1);
}
if (search) {
url += `?${search}`;
}
return url;
};
export function getValidRequestBody(options) {
const hasBody = options.body !== undefined;
const isSerializedBody = hasBody && options.bodySerializer;
if (isSerializedBody) {
if ("serializedBody" in options) {
const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== "";
return hasSerializedBody ? options.serializedBody : null;
}
// not all clients implement a serializedBody property (i.e. client-axios)
return options.body !== "" ? options.body : null;
}
// plain/text body
if (hasBody) {
return options.body;
}
// no body was provided
return undefined;
}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

// This file is auto-generated by @hey-api/openapi-ts
export {};
export * from "./client.js";
export * from "./server.js";
import type { ServerOptions } from "./server.js";
export * as data from "./data.js";
export declare function createOpencode(options?: ServerOptions): Promise<{
client: import("./client.js").OpencodeClient;
server: {
url: string;
close(): void;
};
}>;
export * from "./client.js";
export * from "./server.js";
import { createOpencodeClient } from "./client.js";
import { createOpencodeServer } from "./server.js";
export * as data from "./data.js";
export async function createOpencode(options) {
const server = await createOpencodeServer({
...options,
});
const client = createOpencodeClient({
baseUrl: server.url,
});
return {
client,
server,
};
}
import { type Config } from "./gen/types.gen.js";
export type ServerOptions = {
hostname?: string;
port?: number;
signal?: AbortSignal;
timeout?: number;
config?: Config;
};
export type TuiOptions = {
project?: string;
model?: string;
session?: string;
agent?: string;
signal?: AbortSignal;
config?: Config;
};
export declare function createOpencodeServer(options?: ServerOptions): Promise<{
url: string;
close(): void;
}>;
export declare function createOpencodeTui(options?: TuiOptions): {
close(): void;
};
import launch from "cross-spawn";
import { stop, bindAbort } from "../process.js";
export async function createOpencodeServer(options) {
options = Object.assign({
hostname: "127.0.0.1",
port: 4096,
timeout: 5000,
}, options ?? {});
const args = [`serve`, `--hostname=${options.hostname}`, `--port=${options.port}`];
if (options.config?.logLevel)
args.push(`--log-level=${options.config.logLevel}`);
const proc = launch(`opencode`, args, {
env: {
...process.env,
OPENCODE_CONFIG_CONTENT: JSON.stringify(options.config ?? {}),
},
});
let clear = () => { };
const url = await new Promise((resolve, reject) => {
const id = setTimeout(() => {
clear();
stop(proc);
reject(new Error(`Timeout waiting for server to start after ${options.timeout}ms`));
}, options.timeout);
let output = "";
let resolved = false;
proc.stdout?.on("data", (chunk) => {
if (resolved)
return;
output += chunk.toString();
const lines = output.split("\n");
for (const line of lines) {
if (line.startsWith("opencode server listening")) {
const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
if (!match) {
clear();
stop(proc);
clearTimeout(id);
reject(new Error(`Failed to parse server url from output: ${line}`));
return;
}
clearTimeout(id);
resolved = true;
resolve(match[1]);
return;
}
}
});
proc.stderr?.on("data", (chunk) => {
output += chunk.toString();
});
proc.on("exit", (code) => {
clearTimeout(id);
let msg = `Server exited with code ${code}`;
if (output.trim()) {
msg += `\nServer output: ${output}`;
}
reject(new Error(msg));
});
proc.on("error", (error) => {
clearTimeout(id);
reject(error);
});
clear = bindAbort(proc, options.signal, () => {
clearTimeout(id);
reject(options.signal?.reason);
});
});
return {
url,
close() {
clear();
stop(proc);
},
};
}
export function createOpencodeTui(options) {
const args = [];
if (options?.project) {
args.push(`--project=${options.project}`);
}
if (options?.model) {
args.push(`--model=${options.model}`);
}
if (options?.session) {
args.push(`--session=${options.session}`);
}
if (options?.agent) {
args.push(`--agent=${options.agent}`);
}
const proc = launch(`opencode`, args, {
stdio: "inherit",
env: {
...process.env,
OPENCODE_CONFIG_CONTENT: JSON.stringify(options?.config ?? {}),
},
});
const clear = bindAbort(proc, options?.signal);
return {
close() {
clear();
stop(proc);
},
};
}

Sorry, the diff of this file is too big to display