diff --git a/.changeset/changelog.js b/.changeset/changelog.js index d9d837f0f..dc3c1a837 100644 --- a/.changeset/changelog.js +++ b/.changeset/changelog.js @@ -86,10 +86,7 @@ export default { const users = usersFromSummary.length ? usersFromSummary - .map( - (userFromSummary) => - `[@${userFromSummary}](https://github.com/${userFromSummary})`, - ) + .map((userFromSummary) => `[@${userFromSummary}](https://github.com/${userFromSummary})`) .join(', ') : links.user; diff --git a/__tests__/changelog.test.ts b/__tests__/changelog.test.ts index dee49ca24..4aa0477c4 100644 --- a/__tests__/changelog.test.ts +++ b/__tests__/changelog.test.ts @@ -1,10 +1,6 @@ import type * as getGitHubInfo from '@changesets/get-github-info'; import parse from '@changesets/parse'; -import type { - ModCompWithPackage, - NewChangesetWithCommit, - VersionType, -} from '@changesets/types'; +import type { ModCompWithPackage, NewChangesetWithCommit, VersionType } from '@changesets/types'; import { describe, expect, it, vi } from 'vitest'; import changelog from '../.changeset/changelog.js'; @@ -100,9 +96,7 @@ describe('changelog', () => { repo: 'org/repo', }); - expect(line).toEqual( - '### Updated Dependencies:\n - @hey-api/openapi-ts@0.0.2', - ); + expect(line).toEqual('### Updated Dependencies:\n - @hey-api/openapi-ts@0.0.2'); }); it('formats regular release lines', async () => { @@ -124,10 +118,7 @@ describe('changelog', () => { it('with multiple authors', async () => { expect( await changelog.getReleaseLine( - ...getChangeset( - ['author: @one', 'author: @two'].join('\n'), - data.commit, - ), + ...getChangeset(['author: @one', 'author: @two'].join('\n'), data.commit), ), ).toEqual( `\n- something ([#1613](https://github.com/hey-api/openapi-ts/pull/1613)) ([\`a085003\`](https://github.com/hey-api/openapi-ts/commit/a085003)) by [@one](https://github.com/one), [@two](https://github.com/two)`, @@ -171,9 +162,7 @@ describe('changelog', () => { expect(line).not.toContain('````'); // Should contain a markdown code block expect(line).toContain('```js\nexport default {'); - expect(line).toContain( - ' input: "hey-api/backend", // sign up at app.heyapi.dev', - ); + expect(line).toContain(' input: "hey-api/backend", // sign up at app.heyapi.dev'); expect(line).toContain(' output: {'); expect(line).toContain(' format: null,'); expect(line).toContain(' lint: null,'); @@ -212,44 +201,35 @@ describe('changelog', () => { expect(line).toContain('Some text.'); }); - describe.each(['author', 'user'])( - 'override author with %s keyword', - (keyword) => { - it.each(['with @', 'without @'])('%s', async (kind) => { - expect( - await changelog.getReleaseLine( - ...getChangeset( - `${keyword}: ${kind === 'with @' ? '@' : ''}other`, - data.commit, - ), - ), - ).toEqual( - `\n- something ([#1613](https://github.com/hey-api/openapi-ts/pull/1613)) ([\`a085003\`](https://github.com/hey-api/openapi-ts/commit/a085003)) by [@other](https://github.com/other)`, - ); - }); - }, - ); + describe.each(['author', 'user'])('override author with %s keyword', (keyword) => { + it.each(['with @', 'without @'])('%s', async (kind) => { + expect( + await changelog.getReleaseLine( + ...getChangeset(`${keyword}: ${kind === 'with @' ? '@' : ''}other`, data.commit), + ), + ).toEqual( + `\n- something ([#1613](https://github.com/hey-api/openapi-ts/pull/1613)) ([\`a085003\`](https://github.com/hey-api/openapi-ts/commit/a085003)) by [@other](https://github.com/other)`, + ); + }); + }); describe.each([data.commit, 'wrongcommit', undefined])( 'with commit from changeset of %s', (commitFromChangeset) => { - describe.each(['pr', 'pull request', 'pull'])( - 'override pr with %s keyword', - (keyword) => { - it.each(['with #', 'without #'])('%s', async (kind) => { - expect( - await changelog.getReleaseLine( - ...getChangeset( - `${keyword}: ${kind === 'with #' ? '#' : ''}${data.pull}`, - commitFromChangeset, - ), + describe.each(['pr', 'pull request', 'pull'])('override pr with %s keyword', (keyword) => { + it.each(['with #', 'without #'])('%s', async (kind) => { + expect( + await changelog.getReleaseLine( + ...getChangeset( + `${keyword}: ${kind === 'with #' ? '#' : ''}${data.pull}`, + commitFromChangeset, ), - ).toEqual( - `\n- something ([#1613](https://github.com/hey-api/openapi-ts/pull/1613)) ([\`a085003\`](https://github.com/hey-api/openapi-ts/commit/a085003)) by [@someone](https://github.com/someone)`, - ); - }); - }, - ); + ), + ).toEqual( + `\n- something ([#1613](https://github.com/hey-api/openapi-ts/pull/1613)) ([\`a085003\`](https://github.com/hey-api/openapi-ts/commit/a085003)) by [@someone](https://github.com/someone)`, + ); + }); + }); it('override commit with commit keyword', async () => { expect( diff --git a/dev/graph-hotspots.js b/dev/graph-hotspots.js index 58d4049a6..2668f67ca 100644 --- a/dev/graph-hotspots.js +++ b/dev/graph-hotspots.js @@ -6,9 +6,7 @@ const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Load your exported graph -const nodes = JSON.parse( - fs.readFileSync(path.resolve(__dirname, 'graph.json'), 'utf-8'), -); +const nodes = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'graph.json'), 'utf-8')); // Annotate nodes with children count const annotatedNodes = nodes.map((n) => ({ diff --git a/dev/inputs.ts b/dev/inputs.ts index 24f746a87..0a5a1db5b 100644 --- a/dev/inputs.ts +++ b/dev/inputs.ts @@ -16,14 +16,10 @@ export const inputs = { export type InputKey = keyof typeof inputs; -export function getInput( - key: InputKey = (process.env.INPUT as InputKey) || 'opencode', -) { +export function getInput(key: InputKey = (process.env.INPUT as InputKey) || 'opencode') { const input = inputs[key]; if (!input) { - throw new Error( - `Unknown input: ${key}. Available: ${Object.keys(inputs).join(', ')}`, - ); + throw new Error(`Unknown input: ${key}. Available: ${Object.keys(inputs).join(', ')}`); } return input; } diff --git a/dev/json-to-dot.js b/dev/json-to-dot.js index a530b9fb9..05b28dcac 100644 --- a/dev/json-to-dot.js +++ b/dev/json-to-dot.js @@ -5,9 +5,7 @@ import { fileURLToPath } from 'node:url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); -const nodes = JSON.parse( - fs.readFileSync(path.resolve(__dirname, 'graph.json'), 'utf-8'), -); +const nodes = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'graph.json'), 'utf-8')); // --- Filter nodes for readability --- const threshold = 10; // high-fanout threshold @@ -33,8 +31,7 @@ let dot = 'digraph OpenAPIGraph {\nrankdir=LR;\nnode [style=filled];\n'; // Add nodes with color based on fanout for (const n of filteredNodes) { const childCount = n.childrenPointers?.length ?? 0; - const color = - childCount > 50 ? 'red' : childCount > 20 ? 'orange' : 'lightgray'; + const color = childCount > 50 ? 'red' : childCount > 20 ? 'orange' : 'lightgray'; dot += `"${n.pointer}" [label="${n.pointer}\\n${childCount} children", fillcolor=${color}];\n`; } diff --git a/dev/package.json b/dev/package.json index bc238c5c9..cf5dc4278 100644 --- a/dev/package.json +++ b/dev/package.json @@ -3,9 +3,6 @@ "version": "0.0.0", "private": true, "type": "module", - "engines": { - "node": ">=20.19.0" - }, "scripts": { "dev": "ts-node ./playground.ts" }, @@ -29,5 +26,8 @@ "valibot": "1.2.0", "vue": "3.5.25", "zod": "4.1.12" + }, + "engines": { + "node": ">=20.19.0" } } diff --git a/dev/python/plugins.ts b/dev/python/plugins.ts index f8abab906..7e931cb9c 100644 --- a/dev/python/plugins.ts +++ b/dev/python/plugins.ts @@ -3,9 +3,7 @@ import type { UserConfig } from '@hey-api/openapi-python'; type PluginConfig = NonNullable[number]>; export function sdk( - options?: Partial< - Omit, 'name'> - >, + options?: Partial, 'name'>>, ) { return { name: '@hey-api/python-sdk' as const, diff --git a/dev/python/presets.ts b/dev/python/presets.ts index c53cb9edf..72790b14b 100644 --- a/dev/python/presets.ts +++ b/dev/python/presets.ts @@ -9,14 +9,10 @@ export const presets = { export type PresetKey = keyof typeof presets; -export function getPreset( - key: PresetKey = (process.env.PRESET as PresetKey) || 'sdk', -) { +export function getPreset(key: PresetKey = (process.env.PRESET as PresetKey) || 'sdk') { const preset = presets[key]; if (!preset) { - throw new Error( - `Unknown preset: ${key}. Available: ${Object.keys(presets).join(', ')}`, - ); + throw new Error(`Unknown preset: ${key}. Available: ${Object.keys(presets).join(', ')}`); } return preset(); } diff --git a/dev/typescript/plugins.ts b/dev/typescript/plugins.ts index 2848c837e..6f7df3b12 100644 --- a/dev/typescript/plugins.ts +++ b/dev/typescript/plugins.ts @@ -3,9 +3,7 @@ import type { UserConfig } from '@hey-api/openapi-ts'; type PluginConfig = NonNullable[number]>; export function typescript( - options?: Partial< - Omit, 'name'> - >, + options?: Partial, 'name'>>, ) { return { name: '@hey-api/typescript' as const, @@ -14,9 +12,7 @@ export function typescript( } export function sdk( - options?: Partial< - Omit, 'name'> - >, + options?: Partial, 'name'>>, ) { return { name: '@hey-api/sdk' as const, @@ -24,9 +20,7 @@ export function sdk( }; } -export function zod( - options?: Partial, 'name'>>, -) { +export function zod(options?: Partial, 'name'>>) { return { name: 'zod' as const, ...options, @@ -43,9 +37,7 @@ export function valibot( } export function tanstackReactQuery( - options?: Partial< - Omit, 'name'> - >, + options?: Partial, 'name'>>, ) { return { name: '@tanstack/react-query' as const, @@ -54,9 +46,7 @@ export function tanstackReactQuery( } export function transformers( - options?: Partial< - Omit, 'name'> - >, + options?: Partial, 'name'>>, ) { return { name: '@hey-api/transformers' as const, diff --git a/dev/typescript/presets.ts b/dev/typescript/presets.ts index 8099689e0..d13a208be 100644 --- a/dev/typescript/presets.ts +++ b/dev/typescript/presets.ts @@ -1,10 +1,4 @@ -import { - sdk, - tanstackReactQuery, - transformers, - typescript, - zod, -} from './plugins'; +import { sdk, tanstackReactQuery, transformers, typescript, zod } from './plugins'; export const presets = { full: () => [ @@ -40,14 +34,10 @@ export const presets = { export type PresetKey = keyof typeof presets; -export function getPreset( - key: PresetKey = (process.env.PRESET as PresetKey) || 'sdk', -) { +export function getPreset(key: PresetKey = (process.env.PRESET as PresetKey) || 'sdk') { const preset = presets[key]; if (!preset) { - throw new Error( - `Unknown preset: ${key}. Available: ${Object.keys(presets).join(', ')}`, - ); + throw new Error(`Unknown preset: ${key}. Available: ${Object.keys(presets).join(', ')}`); } return preset(); } diff --git a/docs/.vitepress/config/scripts/optimize-images.ts b/docs/.vitepress/config/scripts/optimize-images.ts index b9c38c54a..86b78c2f6 100644 --- a/docs/.vitepress/config/scripts/optimize-images.ts +++ b/docs/.vitepress/config/scripts/optimize-images.ts @@ -4,13 +4,7 @@ import path from 'node:path'; import type { FormatEnum } from 'sharp'; import sharp from 'sharp'; -const allowedImageExtensions = [ - '.png', - '.jpg', - '.jpeg', - '.webp', - '.svg', -] as const; +const allowedImageExtensions = ['.png', '.jpg', '.jpeg', '.webp', '.svg'] as const; const images: ReadonlyArray<{ formats?: ReadonlyArray; sizes: ReadonlyArray<{ @@ -129,20 +123,14 @@ export async function processImages() { const ext = path.extname(image.source).toLowerCase(); const name = path.basename(image.source, ext); - if ( - !allowedImageExtensions.includes( - ext as (typeof allowedImageExtensions)[number], - ) - ) { + if (!allowedImageExtensions.includes(ext as (typeof allowedImageExtensions)[number])) { continue; } for (const imageSize of image.sizes) { const size = typeof imageSize === 'object' ? imageSize.width : imageSize; const formats = - typeof imageSize === 'object' - ? imageSize.formats || image.formats - : image.formats; + typeof imageSize === 'object' ? imageSize.formats || image.formats : image.formats; for (const format of formats) { const outputFileName = `${name}-${size}w.${format}`; const outputPath = path.join(outputDir, outputFileName); diff --git a/docs/.vitepress/theme/components/Layout.vue b/docs/.vitepress/theme/components/Layout.vue index da4b7667f..942341beb 100644 --- a/docs/.vitepress/theme/components/Layout.vue +++ b/docs/.vitepress/theme/components/Layout.vue @@ -9,12 +9,7 @@ const { Layout } = DefaultTheme; @if (error()) { @@ -17,20 +15,14 @@
@if (pet()?.photoUrls?.[0]) { - + } @else {
{{ pet()?.name?.slice(0, 1) || 'N' }}
}
Name: {{ pet()?.name || 'N/A' }}
-
- Category: {{ pet()?.category?.name || 'N/A' }} -
+
Category: {{ pet()?.category?.name || 'N/A' }}
diff --git a/examples/openapi-ts-angular/src/client/client.gen.ts b/examples/openapi-ts-angular/src/client/client.gen.ts index 069f4daba..84318ba67 100644 --- a/examples/openapi-ts-angular/src/client/client.gen.ts +++ b/examples/openapi-ts-angular/src/client/client.gen.ts @@ -1,11 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { - type ClientOptions, - type Config, - createClient, - createConfig, -} from './client'; +import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** @@ -21,7 +16,5 @@ export type CreateClientConfig = ( ) => Config & T>; export const client = createClient( - createConfig({ - baseUrl: 'https://petstore3.swagger.io/api/v3', - }), + createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); diff --git a/examples/openapi-ts-angular/src/client/client/client.gen.ts b/examples/openapi-ts-angular/src/client/client/client.gen.ts index 9d2351eb7..b38335c7e 100644 --- a/examples/openapi-ts-angular/src/client/client/client.gen.ts +++ b/examples/openapi-ts-angular/src/client/client/client.gen.ts @@ -1,12 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts import type { HttpResponse } from '@angular/common/http'; -import { - HttpClient, - HttpErrorResponse, - HttpEventType, - HttpRequest, -} from '@angular/common/http'; +import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http'; import { assertInInjectionContext, inject, @@ -75,9 +70,7 @@ export const createClient = (config: Config = {}): Client => { if (!opts.httpClient) { if (opts.injector) { - opts.httpClient = runInInjectionContext(opts.injector, () => - inject(HttpClient), - ); + opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient)); } else { assertInInjectionContext(requestOptions); opts.httpClient = inject(HttpClient); @@ -95,15 +88,10 @@ export const createClient = (config: Config = {}): Client => { const url = buildUrl(opts as any); - const req = new HttpRequest( - opts.method ?? 'GET', - url, - getValidRequestBody(opts), - { - redirect: 'follow', - ...opts, - }, - ); + const req = new HttpRequest(opts.method ?? 'GET', url, getValidRequestBody(opts), { + redirect: 'follow', + ...opts, + }); return { opts, req, url }; }; @@ -168,9 +156,7 @@ export const createClient = (config: Config = {}): Client => { bodyResponse = await opts.responseTransformer(bodyResponse); } - return opts.responseStyle === 'data' - ? bodyResponse - : { data: bodyResponse, ...result }; + return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result }; } catch (error) { if (error instanceof HttpErrorResponse) { result.response = error; @@ -180,12 +166,7 @@ export const createClient = (config: Config = {}): Client => { for (const fn of interceptors.error.fns) { if (fn) { - finalError = (await fn( - finalError, - result.response as any, - req, - opts as any, - )) as string; + finalError = (await fn(finalError, result.response as any, req, opts as any)) as string; } } @@ -202,25 +183,20 @@ export const createClient = (config: Config = {}): Client => { } }; - const makeMethodFn = - (method: Uppercase) => (options: RequestOptions) => - request({ ...options, method }); - - const makeSseFn = - (method: Uppercase) => async (options: RequestOptions) => { - const { opts, url } = await beforeRequest(options); - return createSseClient({ - ...opts, - body: opts.body as BodyInit | null | undefined, - headers: opts.headers as unknown as Record, - method, - serializedBody: getValidRequestBody(opts) as - | BodyInit - | null - | undefined, - url, - }); - }; + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + method, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; return { buildUrl, @@ -241,9 +217,7 @@ export const createClient = (config: Config = {}): Client => { } if (options.requestValidator) { - throw new Error( - 'Request validation is not supported in requestOptions', - ); + throw new Error('Request validation is not supported in requestOptions'); } return requestOptions(options).req; diff --git a/examples/openapi-ts-angular/src/client/client/types.gen.ts b/examples/openapi-ts-angular/src/client/client/types.gen.ts index c7b4e2e12..18bc780ef 100644 --- a/examples/openapi-ts-angular/src/client/client/types.gen.ts +++ b/examples/openapi-ts-angular/src/client/client/types.gen.ts @@ -10,21 +10,14 @@ import type { import type { Injector } from '@angular/core'; import type { Auth } from '../core/auth.gen'; -import type { - ServerSentEventsOptions, - ServerSentEventsResult, -} from '../core/serverSentEvents.gen'; -import type { - Client as CoreClient, - Config as CoreConfig, -} from '../core/types.gen'; +import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config - extends Omit, - Omit { + extends Omit, Omit { /** * Base URL for all requests made by this client. */ @@ -39,13 +32,7 @@ export interface Config | HttpHeaders | Record< string, - | string - | number - | boolean - | (string | number | boolean)[] - | null - | undefined - | unknown + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The HTTP client to use for making requests. @@ -71,7 +58,9 @@ export interface RequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, -> extends Config<{ +> + extends + Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, @@ -122,21 +111,15 @@ export type RequestResult< ? TData[keyof TData] : TData : { - data: TData extends Record - ? TData[keyof TData] - : TData; + data: TData extends Record ? TData[keyof TData] : TData; request: HttpRequest; response: HttpResponse; } : TResponseStyle extends 'data' - ? - | (TData extends Record ? TData[keyof TData] : TData) - | undefined + ? (TData extends Record ? TData[keyof TData] : TData) | undefined : | { - data: TData extends Record - ? TData[keyof TData] - : TData; + data: TData extends Record ? TData[keyof TData] : TData; error: undefined; request: HttpRequest; response: HttpResponse; @@ -182,10 +165,7 @@ type RequestFn = < TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & - Pick< - Required>, - 'method' - >, + Pick>, 'method'>, ) => RequestResult; type RequestOptionsFn = < @@ -206,13 +186,7 @@ type BuildUrlFn = < options: TData & Options, ) => string; -export type Client = CoreClient< - RequestFn, - Config, - MethodFn, - BuildUrlFn, - SseFn -> & { +export type Client = CoreClient & { interceptors: Middleware< HttpRequest, HttpResponse, diff --git a/examples/openapi-ts-angular/src/client/client/utils.gen.ts b/examples/openapi-ts-angular/src/client/client/utils.gen.ts index 0ccb649e0..a3d1a513e 100644 --- a/examples/openapi-ts-angular/src/client/client/utils.gen.ts +++ b/examples/openapi-ts-angular/src/client/client/utils.gen.ts @@ -3,21 +3,13 @@ import { HttpHeaders } from '@angular/common/http'; import { getAuthToken } from '../core/auth.gen'; -import type { - QuerySerializer, - QuerySerializerOptions, -} from '../core/bodySerializer.gen'; +import type { QuerySerializer, QuerySerializerOptions } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; -import type { - Client, - ClientOptions, - Config, - RequestOptions, -} from './types.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; @@ -59,10 +51,7 @@ const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { } if (Array.isArray(value)) { - url = url.replace( - match, - serializeArrayParam({ explode, name, style, value }), - ); + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } @@ -169,10 +158,7 @@ export const getParseAs = ( return; } - if ( - cleanContent.startsWith('application/json') || - cleanContent.endsWith('+json') - ) { + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } @@ -181,9 +167,7 @@ export const getParseAs = ( } if ( - ['application/', 'audio/', 'image/', 'video/'].some((type) => - cleanContent.startsWith(type), - ) + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } @@ -315,9 +299,7 @@ export const mergeHeaders = ( // content value in OpenAPI specification is 'application/json' mergedHeaders = mergedHeaders.set( key, - typeof value === 'object' - ? JSON.stringify(value) - : (value as string), + typeof value === 'object' ? JSON.stringify(value) : (value as string), ); } } @@ -334,10 +316,7 @@ type ErrInterceptor = ( options: Options, ) => Err | Promise; -type ReqInterceptor = ( - request: Req, - options: Options, -) => Req | Promise; +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, @@ -371,10 +350,7 @@ class Interceptors { return this.fns.indexOf(id); } - update( - id: number | Interceptor, - fn: Interceptor, - ): number | Interceptor | false { + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; diff --git a/examples/openapi-ts-angular/src/client/core/auth.gen.ts b/examples/openapi-ts-angular/src/client/core/auth.gen.ts index f8a73266f..3ebf99478 100644 --- a/examples/openapi-ts-angular/src/client/core/auth.gen.ts +++ b/examples/openapi-ts-angular/src/client/core/auth.gen.ts @@ -23,8 +23,7 @@ export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { - const token = - typeof callback === 'function' ? await callback(auth) : callback; + const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; diff --git a/examples/openapi-ts-angular/src/client/core/bodySerializer.gen.ts b/examples/openapi-ts-angular/src/client/core/bodySerializer.gen.ts index 552b50f7c..8ad92c9ff 100644 --- a/examples/openapi-ts-angular/src/client/core/bodySerializer.gen.ts +++ b/examples/openapi-ts-angular/src/client/core/bodySerializer.gen.ts @@ -1,10 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import type { - ArrayStyle, - ObjectStyle, - SerializerOptions, -} from './pathSerializer.gen'; +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; @@ -24,11 +20,7 @@ export type QuerySerializerOptions = QuerySerializerOptionsObject & { parameters?: Record; }; -const serializeFormDataPair = ( - data: FormData, - key: string, - value: unknown, -): void => { +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { @@ -38,11 +30,7 @@ const serializeFormDataPair = ( } }; -const serializeUrlSearchParamsPair = ( - data: URLSearchParams, - key: string, - value: unknown, -): void => { +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { @@ -73,15 +61,11 @@ export const formDataBodySerializer = { export const jsonBodySerializer = { bodySerializer: (body: T): string => - JSON.stringify(body, (_key, value) => - typeof value === 'bigint' ? value.toString() : value, - ), + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { - bodySerializer: | Array>>( - body: T, - ): string => { + bodySerializer: | Array>>(body: T): string => { const data = new URLSearchParams(); Object.entries(body).forEach(([key, value]) => { diff --git a/examples/openapi-ts-angular/src/client/core/params.gen.ts b/examples/openapi-ts-angular/src/client/core/params.gen.ts index 602715c46..6099cab1b 100644 --- a/examples/openapi-ts-angular/src/client/core/params.gen.ts +++ b/examples/openapi-ts-angular/src/client/core/params.gen.ts @@ -102,10 +102,7 @@ const stripEmptySlots = (params: Params) => { } }; -export const buildClientParams = ( - args: ReadonlyArray, - fields: FieldsConfig, -) => { +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, @@ -148,15 +145,11 @@ export const buildClientParams = ( params[field.map] = value; } } else { - const extra = extraPrefixes.find(([prefix]) => - key.startsWith(prefix), - ); + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; - (params[slot] as Record)[ - key.slice(prefix.length) - ] = value; + (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { diff --git a/examples/openapi-ts-angular/src/client/core/pathSerializer.gen.ts b/examples/openapi-ts-angular/src/client/core/pathSerializer.gen.ts index 8d9993104..994b2848c 100644 --- a/examples/openapi-ts-angular/src/client/core/pathSerializer.gen.ts +++ b/examples/openapi-ts-angular/src/client/core/pathSerializer.gen.ts @@ -1,8 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -interface SerializeOptions - extends SerializePrimitiveOptions, - SerializerOptions {} +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; @@ -105,9 +103,7 @@ export const serializeArrayParam = ({ }); }) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ @@ -146,11 +142,7 @@ export const serializeObjectParam = ({ if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { - values = [ - ...values, - key, - allowReserved ? (v as string) : encodeURIComponent(v as string), - ]; + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { @@ -175,7 +167,5 @@ export const serializeObjectParam = ({ }), ) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; diff --git a/examples/openapi-ts-angular/src/client/core/queryKeySerializer.gen.ts b/examples/openapi-ts-angular/src/client/core/queryKeySerializer.gen.ts index d3bb68396..5000df606 100644 --- a/examples/openapi-ts-angular/src/client/core/queryKeySerializer.gen.ts +++ b/examples/openapi-ts-angular/src/client/core/queryKeySerializer.gen.ts @@ -15,11 +15,7 @@ export type JsonValue = * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { @@ -61,9 +57,7 @@ const isPlainObject = (value: unknown): value is Record => { * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { - const entries = Array.from(params.entries()).sort(([a], [b]) => - a.localeCompare(b), - ); + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { @@ -86,26 +80,16 @@ const serializeSearchParams = (params: URLSearchParams): JsonValue => { /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ -export const serializeQueryKeyValue = ( - value: unknown, -): JsonValue | undefined => { +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } - if ( - typeof value === 'string' || - typeof value === 'number' || - typeof value === 'boolean' - ) { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } @@ -121,10 +105,7 @@ export const serializeQueryKeyValue = ( return stringifyToJsonValue(value); } - if ( - typeof URLSearchParams !== 'undefined' && - value instanceof URLSearchParams - ) { + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } diff --git a/examples/openapi-ts-angular/src/client/core/serverSentEvents.gen.ts b/examples/openapi-ts-angular/src/client/core/serverSentEvents.gen.ts index 343d25af8..6aa6cf02a 100644 --- a/examples/openapi-ts-angular/src/client/core/serverSentEvents.gen.ts +++ b/examples/openapi-ts-angular/src/client/core/serverSentEvents.gen.ts @@ -2,10 +2,7 @@ import type { Config } from './types.gen'; -export type ServerSentEventsOptions = Omit< - RequestInit, - 'method' -> & +export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom @@ -74,11 +71,7 @@ export interface StreamEvent { retry?: number; } -export type ServerSentEventsResult< - TData = unknown, - TReturn = void, - TNext = unknown, -> = { +export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, @@ -101,9 +94,7 @@ export const createSseClient = ({ }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; - const sleep = - sseSleepFn ?? - ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; @@ -141,16 +132,11 @@ export const createSseClient = ({ 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.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(); + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; @@ -188,10 +174,7 @@ export const createSseClient = ({ } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { - const parsed = Number.parseInt( - line.replace(/^retry:\s*/, ''), - 10, - ); + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } @@ -243,18 +226,12 @@ export const createSseClient = ({ // connection failed or aborted; retry after delay onSseError?.(error); - if ( - sseMaxRetryAttempts !== undefined && - attempt >= sseMaxRetryAttempts - ) { + 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, - ); + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } diff --git a/examples/openapi-ts-angular/src/client/core/types.gen.ts b/examples/openapi-ts-angular/src/client/core/types.gen.ts index 643c070c9..97463257e 100644 --- a/examples/openapi-ts-angular/src/client/core/types.gen.ts +++ b/examples/openapi-ts-angular/src/client/core/types.gen.ts @@ -1,11 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; -import type { - BodySerializer, - QuerySerializer, - QuerySerializerOptions, -} from './bodySerializer.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' @@ -34,9 +30,7 @@ export type Client< setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; -} & ([SseFn] extends [never] - ? { sse?: never } - : { sse: { [K in HttpMethod]: SseFn } }); +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** @@ -59,13 +53,7 @@ export interface Config { | RequestInit['headers'] | Record< string, - | string - | number - | boolean - | (string | number | boolean)[] - | null - | undefined - | unknown + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. @@ -112,7 +100,5 @@ type IsExactlyNeverOrNeverUndefined = [T] extends [never] : false; export type OmitNever> = { - [K in keyof T as IsExactlyNeverOrNeverUndefined extends true - ? never - : K]: T[K]; + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; diff --git a/examples/openapi-ts-angular/src/client/core/utils.gen.ts b/examples/openapi-ts-angular/src/client/core/utils.gen.ts index 0b5389d08..e7ddbe354 100644 --- a/examples/openapi-ts-angular/src/client/core/utils.gen.ts +++ b/examples/openapi-ts-angular/src/client/core/utils.gen.ts @@ -44,10 +44,7 @@ export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { } if (Array.isArray(value)) { - url = url.replace( - match, - serializeArrayParam({ explode, name, style, value }), - ); + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } diff --git a/examples/openapi-ts-angular/src/client/sdk.gen.ts b/examples/openapi-ts-angular/src/client/sdk.gen.ts index d7d470137..168df5ff0 100644 --- a/examples/openapi-ts-angular/src/client/sdk.gen.ts +++ b/examples/openapi-ts-angular/src/client/sdk.gen.ts @@ -88,14 +88,8 @@ export class PetService { * * Add a new pet to the store. */ - public addPet( - options: Options, - ) { - return (options.client ?? client).post< - AddPetResponses, - AddPetErrors, - ThrowOnError - >({ + public addPet(options: Options) { + return (options.client ?? client).post({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, @@ -114,11 +108,7 @@ export class PetService { public updatePet( options: Options, ) { - return (options.client ?? client).put< - UpdatePetResponses, - UpdatePetErrors, - ThrowOnError - >({ + return (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, @@ -175,11 +165,7 @@ export class PetService { public deletePet( options: Options, ) { - return (options.client ?? client).delete< - DeletePetResponses, - DeletePetErrors, - ThrowOnError - >({ + return (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, @@ -194,11 +180,7 @@ export class PetService { public getPetById( options: Options, ) { - return (options.client ?? client).get< - GetPetByIdResponses, - GetPetByIdErrors, - ThrowOnError - >({ + return (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, @@ -235,11 +217,7 @@ export class PetService { public uploadFile( options: Options, ) { - return (options.client ?? client).post< - UploadFileResponses, - UploadFileErrors, - ThrowOnError - >({ + return (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', @@ -262,15 +240,13 @@ export class StoreService { public getInventory( options?: Options, ) { - return (options?.client ?? client).get< - GetInventoryResponses, - GetInventoryErrors, - ThrowOnError - >({ - security: [{ name: 'api_key', type: 'apiKey' }], - url: '/store/inventory', - ...options, - }); + return (options?.client ?? client).get( + { + security: [{ name: 'api_key', type: 'apiKey' }], + url: '/store/inventory', + ...options, + }, + ); } /** @@ -281,11 +257,7 @@ export class StoreService { public placeOrder( options?: Options, ) { - return (options?.client ?? client).post< - PlaceOrderResponses, - PlaceOrderErrors, - ThrowOnError - >({ + return (options?.client ?? client).post({ url: '/store/order', ...options, headers: { @@ -303,11 +275,9 @@ export class StoreService { public deleteOrder( options: Options, ) { - return (options.client ?? client).delete< - DeleteOrderResponses, - DeleteOrderErrors, - ThrowOnError - >({ url: '/store/order/{orderId}', ...options }); + return (options.client ?? client).delete( + { url: '/store/order/{orderId}', ...options }, + ); } /** @@ -318,11 +288,10 @@ export class StoreService { public getOrderById( options: Options, ) { - return (options.client ?? client).get< - GetOrderByIdResponses, - GetOrderByIdErrors, - ThrowOnError - >({ url: '/store/order/{orderId}', ...options }); + return (options.client ?? client).get({ + url: '/store/order/{orderId}', + ...options, + }); } } @@ -336,11 +305,7 @@ export class UserService { public createUser( options?: Options, ) { - return (options?.client ?? client).post< - CreateUserResponses, - CreateUserErrors, - ThrowOnError - >({ + return (options?.client ?? client).post({ url: '/user', ...options, headers: { @@ -380,11 +345,10 @@ export class UserService { public loginUser( options?: Options, ) { - return (options?.client ?? client).get< - LoginUserResponses, - LoginUserErrors, - ThrowOnError - >({ url: '/user/login', ...options }); + return (options?.client ?? client).get({ + url: '/user/login', + ...options, + }); } /** @@ -395,11 +359,10 @@ export class UserService { public logoutUser( options?: Options, ) { - return (options?.client ?? client).get< - LogoutUserResponses, - LogoutUserErrors, - ThrowOnError - >({ url: '/user/logout', ...options }); + return (options?.client ?? client).get({ + url: '/user/logout', + ...options, + }); } /** @@ -410,11 +373,10 @@ export class UserService { public deleteUser( options: Options, ) { - return (options.client ?? client).delete< - DeleteUserResponses, - DeleteUserErrors, - ThrowOnError - >({ url: '/user/{username}', ...options }); + return (options.client ?? client).delete({ + url: '/user/{username}', + ...options, + }); } /** @@ -440,11 +402,7 @@ export class UserService { public updateUser( options: Options, ) { - return (options.client ?? client).put< - UpdateUserResponses, - UpdateUserErrors, - ThrowOnError - >({ + return (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { diff --git a/examples/openapi-ts-angular/src/client/types.gen.ts b/examples/openapi-ts-angular/src/client/types.gen.ts index a2e6be0fa..a8ea86379 100644 --- a/examples/openapi-ts-angular/src/client/types.gen.ts +++ b/examples/openapi-ts-angular/src/client/types.gen.ts @@ -167,8 +167,7 @@ export type FindPetsByStatusResponses = { 200: Array; }; -export type FindPetsByStatusResponse = - FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; +export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; @@ -200,8 +199,7 @@ export type FindPetsByTagsResponses = { 200: Array; }; -export type FindPetsByTagsResponse = - FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; +export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; @@ -378,8 +376,7 @@ export type GetInventoryResponses = { }; }; -export type GetInventoryResponse = - GetInventoryResponses[keyof GetInventoryResponses]; +export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; @@ -480,8 +477,7 @@ export type GetOrderByIdResponses = { 200: Order; }; -export type GetOrderByIdResponse = - GetOrderByIdResponses[keyof GetOrderByIdResponses]; +export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** @@ -658,8 +654,7 @@ export type GetUserByNameResponses = { 200: User; }; -export type GetUserByNameResponse = - GetUserByNameResponses[keyof GetUserByNameResponses]; +export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** diff --git a/examples/openapi-ts-angular/src/main.ts b/examples/openapi-ts-angular/src/main.ts index 5953a0277..14afb2d0e 100644 --- a/examples/openapi-ts-angular/src/main.ts +++ b/examples/openapi-ts-angular/src/main.ts @@ -3,6 +3,4 @@ import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { appConfig } from './app/app.config'; -bootstrapApplication(AppComponent, appConfig).catch((err) => - console.error(err), -); +bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err)); diff --git a/examples/openapi-ts-angular/src/server.ts b/examples/openapi-ts-angular/src/server.ts index b653cac91..c5d5d7648 100644 --- a/examples/openapi-ts-angular/src/server.ts +++ b/examples/openapi-ts-angular/src/server.ts @@ -44,9 +44,7 @@ app.use( app.use('/**', (req, res, next) => { angularApp .handle(req) - .then((response) => - response ? writeResponseToNodeResponse(response, res) : next(), - ) + .then((response) => (response ? writeResponseToNodeResponse(response, res) : next())) .catch(next); }); diff --git a/examples/openapi-ts-axios/src/App.tsx b/examples/openapi-ts-axios/src/App.tsx index cd85e2889..549558fdf 100644 --- a/examples/openapi-ts-axios/src/App.tsx +++ b/examples/openapi-ts-axios/src/App.tsx @@ -38,11 +38,7 @@ localClient.instance.interceptors.request.use((config) => { // Middleware is great for adding authorization tokens to requests made to // protected paths. Headers are set randomly here to allow surfacing the // default headers, too. - if ( - config.url?.startsWith('/pet/') && - config.method === 'get' && - Math.random() < 0.5 - ) { + if (config.url?.startsWith('/pet/') && config.method === 'get' && Math.random() < 0.5) { config.headers.set('Authorization', 'Bearer '); } return config; @@ -131,9 +127,7 @@ function App() { }; return ( - +
@@ -201,20 +195,12 @@ function App() { Category - + Please enter a category - + diff --git a/examples/openapi-ts-axios/src/client/client.gen.ts b/examples/openapi-ts-axios/src/client/client.gen.ts index c8bfd460b..b01c360ba 100644 --- a/examples/openapi-ts-axios/src/client/client.gen.ts +++ b/examples/openapi-ts-axios/src/client/client.gen.ts @@ -1,11 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { - type ClientOptions, - type Config, - createClient, - createConfig, -} from './client'; +import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** @@ -21,7 +16,5 @@ export type CreateClientConfig = ( ) => Config & T>; export const client = createClient( - createConfig({ - baseURL: 'https://petstore3.swagger.io/api/v3', - }), + createConfig({ baseURL: 'https://petstore3.swagger.io/api/v3' }), ); diff --git a/examples/openapi-ts-axios/src/client/client/client.gen.ts b/examples/openapi-ts-axios/src/client/client/client.gen.ts index a4f9b45e7..9b3b2fa6a 100644 --- a/examples/openapi-ts-axios/src/client/client/client.gen.ts +++ b/examples/openapi-ts-axios/src/client/client/client.gen.ts @@ -7,13 +7,7 @@ import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; import type { Client, Config, RequestOptions } from './types.gen'; -import { - buildUrl, - createConfig, - mergeConfigs, - mergeHeaders, - setAuthParams, -} from './utils.gen'; +import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils.gen'; export const createClient = (config: Config = {}): Client => { let _config = mergeConfigs(createConfig(), config); @@ -115,27 +109,22 @@ export const createClient = (config: Config = {}): Client => { } }; - const makeMethodFn = - (method: Uppercase) => (options: RequestOptions) => - request({ ...options, method }); + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); - const makeSseFn = - (method: Uppercase) => async (options: RequestOptions) => { - const { opts, url } = await beforeRequest(options); - return createSseClient({ - ...opts, - body: opts.body as BodyInit | null | undefined, - headers: opts.headers as Record, - method, - serializedBody: getValidRequestBody(opts) as - | BodyInit - | null - | undefined, - // @ts-expect-error - signal: opts.signal, - url, - }); - }; + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as Record, + method, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + // @ts-expect-error + signal: opts.signal, + url, + }); + }; return { buildUrl, diff --git a/examples/openapi-ts-axios/src/client/client/types.gen.ts b/examples/openapi-ts-axios/src/client/client/types.gen.ts index 59be50cc3..de5050a23 100644 --- a/examples/openapi-ts-axios/src/client/client/types.gen.ts +++ b/examples/openapi-ts-axios/src/client/client/types.gen.ts @@ -10,18 +10,11 @@ import type { } from 'axios'; import type { Auth } from '../core/auth.gen'; -import type { - ServerSentEventsOptions, - ServerSentEventsResult, -} from '../core/serverSentEvents.gen'; -import type { - Client as CoreClient, - Config as CoreConfig, -} from '../core/types.gen'; +import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; export interface Config - extends Omit, - CoreConfig { + extends Omit, CoreConfig { /** * Axios implementation. You can use this option to provide either an * `AxiosStatic` or an `AxiosInstance`. @@ -43,13 +36,7 @@ export interface Config | AxiosRequestHeaders | Record< string, - | string - | number - | boolean - | (string | number | boolean)[] - | null - | undefined - | unknown + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * Throw an error instead of returning it in the response? @@ -63,7 +50,9 @@ export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, -> extends Config<{ +> + extends + Config<{ throwOnError: ThrowOnError; }>, Pick< @@ -99,46 +88,26 @@ export type RequestResult< TError = unknown, ThrowOnError extends boolean = boolean, > = ThrowOnError extends true - ? Promise< - AxiosResponse< - TData extends Record ? TData[keyof TData] : TData - > - > + ? Promise ? TData[keyof TData] : TData>> : Promise< - | (AxiosResponse< - TData extends Record ? TData[keyof TData] : TData - > & { error: undefined }) - | (AxiosError< - TError extends Record ? TError[keyof TError] : TError - > & { + | (AxiosResponse ? TData[keyof TData] : TData> & { + error: undefined; + }) + | (AxiosError ? TError[keyof TError] : TError> & { data: undefined; - error: TError extends Record - ? TError[keyof TError] - : TError; + error: TError extends Record ? TError[keyof TError] : TError; }) >; -type MethodFn = < - TData = unknown, - TError = unknown, - ThrowOnError extends boolean = false, ->( +type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; -type SseFn = < - TData = unknown, - TError = unknown, - ThrowOnError extends boolean = false, ->( +type SseFn = ( options: Omit, 'method'>, ) => Promise>; -type RequestFn = < - TData = unknown, - TError = unknown, - ThrowOnError extends boolean = false, ->( +type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; @@ -154,13 +123,7 @@ type BuildUrlFn = < options: TData & Options, ) => string; -export type Client = CoreClient< - RequestFn, - Config, - MethodFn, - BuildUrlFn, - SseFn -> & { +export type Client = CoreClient & { instance: AxiosInstance; }; @@ -190,8 +153,5 @@ export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, -> = OmitKeys< - RequestOptions, - 'body' | 'path' | 'query' | 'url' -> & +> = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); diff --git a/examples/openapi-ts-axios/src/client/client/utils.gen.ts b/examples/openapi-ts-axios/src/client/client/utils.gen.ts index 436bf6559..1b4600f76 100644 --- a/examples/openapi-ts-axios/src/client/client/utils.gen.ts +++ b/examples/openapi-ts-axios/src/client/client/utils.gen.ts @@ -8,12 +8,7 @@ import { serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; -import type { - Client, - ClientOptions, - Config, - RequestOptions, -} from './types.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, @@ -135,9 +130,7 @@ export const buildUrl: Client['buildUrl'] = (options) => { const instanceBaseUrl = options.axios?.defaults?.baseURL; const baseUrl = - !!options.baseURL && typeof options.baseURL === 'string' - ? options.baseURL - : instanceBaseUrl; + !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl; return getUrl({ baseUrl: baseUrl as string, @@ -184,9 +177,7 @@ export const mergeHeaders = ( for (const [key, value] of iterator) { if ( - axiosHeadersKeywords.includes( - key as (typeof axiosHeadersKeywords)[number], - ) && + axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) && typeof value === 'object' ) { mergedHeaders[key] = { @@ -203,8 +194,7 @@ export const mergeHeaders = ( } 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[key] = - typeof value === 'object' ? JSON.stringify(value) : (value as string); + mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string); } } } diff --git a/examples/openapi-ts-axios/src/client/core/auth.gen.ts b/examples/openapi-ts-axios/src/client/core/auth.gen.ts index f8a73266f..3ebf99478 100644 --- a/examples/openapi-ts-axios/src/client/core/auth.gen.ts +++ b/examples/openapi-ts-axios/src/client/core/auth.gen.ts @@ -23,8 +23,7 @@ export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { - const token = - typeof callback === 'function' ? await callback(auth) : callback; + const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; diff --git a/examples/openapi-ts-axios/src/client/core/bodySerializer.gen.ts b/examples/openapi-ts-axios/src/client/core/bodySerializer.gen.ts index 552b50f7c..8ad92c9ff 100644 --- a/examples/openapi-ts-axios/src/client/core/bodySerializer.gen.ts +++ b/examples/openapi-ts-axios/src/client/core/bodySerializer.gen.ts @@ -1,10 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import type { - ArrayStyle, - ObjectStyle, - SerializerOptions, -} from './pathSerializer.gen'; +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; @@ -24,11 +20,7 @@ export type QuerySerializerOptions = QuerySerializerOptionsObject & { parameters?: Record; }; -const serializeFormDataPair = ( - data: FormData, - key: string, - value: unknown, -): void => { +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { @@ -38,11 +30,7 @@ const serializeFormDataPair = ( } }; -const serializeUrlSearchParamsPair = ( - data: URLSearchParams, - key: string, - value: unknown, -): void => { +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { @@ -73,15 +61,11 @@ export const formDataBodySerializer = { export const jsonBodySerializer = { bodySerializer: (body: T): string => - JSON.stringify(body, (_key, value) => - typeof value === 'bigint' ? value.toString() : value, - ), + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { - bodySerializer: | Array>>( - body: T, - ): string => { + bodySerializer: | Array>>(body: T): string => { const data = new URLSearchParams(); Object.entries(body).forEach(([key, value]) => { diff --git a/examples/openapi-ts-axios/src/client/core/params.gen.ts b/examples/openapi-ts-axios/src/client/core/params.gen.ts index 602715c46..6099cab1b 100644 --- a/examples/openapi-ts-axios/src/client/core/params.gen.ts +++ b/examples/openapi-ts-axios/src/client/core/params.gen.ts @@ -102,10 +102,7 @@ const stripEmptySlots = (params: Params) => { } }; -export const buildClientParams = ( - args: ReadonlyArray, - fields: FieldsConfig, -) => { +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, @@ -148,15 +145,11 @@ export const buildClientParams = ( params[field.map] = value; } } else { - const extra = extraPrefixes.find(([prefix]) => - key.startsWith(prefix), - ); + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; - (params[slot] as Record)[ - key.slice(prefix.length) - ] = value; + (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { diff --git a/examples/openapi-ts-axios/src/client/core/pathSerializer.gen.ts b/examples/openapi-ts-axios/src/client/core/pathSerializer.gen.ts index 8d9993104..994b2848c 100644 --- a/examples/openapi-ts-axios/src/client/core/pathSerializer.gen.ts +++ b/examples/openapi-ts-axios/src/client/core/pathSerializer.gen.ts @@ -1,8 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -interface SerializeOptions - extends SerializePrimitiveOptions, - SerializerOptions {} +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; @@ -105,9 +103,7 @@ export const serializeArrayParam = ({ }); }) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ @@ -146,11 +142,7 @@ export const serializeObjectParam = ({ if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { - values = [ - ...values, - key, - allowReserved ? (v as string) : encodeURIComponent(v as string), - ]; + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { @@ -175,7 +167,5 @@ export const serializeObjectParam = ({ }), ) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; diff --git a/examples/openapi-ts-axios/src/client/core/queryKeySerializer.gen.ts b/examples/openapi-ts-axios/src/client/core/queryKeySerializer.gen.ts index d3bb68396..5000df606 100644 --- a/examples/openapi-ts-axios/src/client/core/queryKeySerializer.gen.ts +++ b/examples/openapi-ts-axios/src/client/core/queryKeySerializer.gen.ts @@ -15,11 +15,7 @@ export type JsonValue = * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { @@ -61,9 +57,7 @@ const isPlainObject = (value: unknown): value is Record => { * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { - const entries = Array.from(params.entries()).sort(([a], [b]) => - a.localeCompare(b), - ); + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { @@ -86,26 +80,16 @@ const serializeSearchParams = (params: URLSearchParams): JsonValue => { /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ -export const serializeQueryKeyValue = ( - value: unknown, -): JsonValue | undefined => { +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } - if ( - typeof value === 'string' || - typeof value === 'number' || - typeof value === 'boolean' - ) { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } @@ -121,10 +105,7 @@ export const serializeQueryKeyValue = ( return stringifyToJsonValue(value); } - if ( - typeof URLSearchParams !== 'undefined' && - value instanceof URLSearchParams - ) { + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } diff --git a/examples/openapi-ts-axios/src/client/core/serverSentEvents.gen.ts b/examples/openapi-ts-axios/src/client/core/serverSentEvents.gen.ts index 343d25af8..6aa6cf02a 100644 --- a/examples/openapi-ts-axios/src/client/core/serverSentEvents.gen.ts +++ b/examples/openapi-ts-axios/src/client/core/serverSentEvents.gen.ts @@ -2,10 +2,7 @@ import type { Config } from './types.gen'; -export type ServerSentEventsOptions = Omit< - RequestInit, - 'method' -> & +export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom @@ -74,11 +71,7 @@ export interface StreamEvent { retry?: number; } -export type ServerSentEventsResult< - TData = unknown, - TReturn = void, - TNext = unknown, -> = { +export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, @@ -101,9 +94,7 @@ export const createSseClient = ({ }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; - const sleep = - sseSleepFn ?? - ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; @@ -141,16 +132,11 @@ export const createSseClient = ({ 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.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(); + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; @@ -188,10 +174,7 @@ export const createSseClient = ({ } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { - const parsed = Number.parseInt( - line.replace(/^retry:\s*/, ''), - 10, - ); + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } @@ -243,18 +226,12 @@ export const createSseClient = ({ // connection failed or aborted; retry after delay onSseError?.(error); - if ( - sseMaxRetryAttempts !== undefined && - attempt >= sseMaxRetryAttempts - ) { + 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, - ); + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } diff --git a/examples/openapi-ts-axios/src/client/core/types.gen.ts b/examples/openapi-ts-axios/src/client/core/types.gen.ts index 643c070c9..97463257e 100644 --- a/examples/openapi-ts-axios/src/client/core/types.gen.ts +++ b/examples/openapi-ts-axios/src/client/core/types.gen.ts @@ -1,11 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; -import type { - BodySerializer, - QuerySerializer, - QuerySerializerOptions, -} from './bodySerializer.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' @@ -34,9 +30,7 @@ export type Client< setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; -} & ([SseFn] extends [never] - ? { sse?: never } - : { sse: { [K in HttpMethod]: SseFn } }); +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** @@ -59,13 +53,7 @@ export interface Config { | RequestInit['headers'] | Record< string, - | string - | number - | boolean - | (string | number | boolean)[] - | null - | undefined - | unknown + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. @@ -112,7 +100,5 @@ type IsExactlyNeverOrNeverUndefined = [T] extends [never] : false; export type OmitNever> = { - [K in keyof T as IsExactlyNeverOrNeverUndefined extends true - ? never - : K]: T[K]; + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; diff --git a/examples/openapi-ts-axios/src/client/core/utils.gen.ts b/examples/openapi-ts-axios/src/client/core/utils.gen.ts index 0b5389d08..e7ddbe354 100644 --- a/examples/openapi-ts-axios/src/client/core/utils.gen.ts +++ b/examples/openapi-ts-axios/src/client/core/utils.gen.ts @@ -44,10 +44,7 @@ export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { } if (Array.isArray(value)) { - url = url.replace( - match, - serializeArrayParam({ explode, name, style, value }), - ); + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } diff --git a/examples/openapi-ts-axios/src/client/sdk.gen.ts b/examples/openapi-ts-axios/src/client/sdk.gen.ts index 860344081..fb8035a57 100644 --- a/examples/openapi-ts-axios/src/client/sdk.gen.ts +++ b/examples/openapi-ts-axios/src/client/sdk.gen.ts @@ -106,11 +106,7 @@ export const addPet = ( export const updatePet = ( options: Options, ) => - (options.client ?? client).put< - UpdatePetResponses, - UpdatePetErrors, - ThrowOnError - >({ + (options.client ?? client).put({ responseType: 'json', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', @@ -129,11 +125,7 @@ export const updatePet = ( export const findPetsByStatus = ( options: Options, ) => - (options.client ?? client).get< - FindPetsByStatusResponses, - FindPetsByStatusErrors, - ThrowOnError - >({ + (options.client ?? client).get({ responseType: 'json', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', @@ -148,11 +140,7 @@ export const findPetsByStatus = ( export const findPetsByTags = ( options: Options, ) => - (options.client ?? client).get< - FindPetsByTagsResponses, - FindPetsByTagsErrors, - ThrowOnError - >({ + (options.client ?? client).get({ responseType: 'json', security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', @@ -167,11 +155,7 @@ export const findPetsByTags = ( export const deletePet = ( options: Options, ) => - (options.client ?? client).delete< - DeletePetResponses, - DeletePetErrors, - ThrowOnError - >({ + (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, @@ -185,11 +169,7 @@ export const deletePet = ( export const getPetById = ( options: Options, ) => - (options.client ?? client).get< - GetPetByIdResponses, - GetPetByIdErrors, - ThrowOnError - >({ + (options.client ?? client).get({ responseType: 'json', security: [ { name: 'api_key', type: 'apiKey' }, @@ -226,11 +206,7 @@ export const updatePetWithForm = ( export const uploadFile = ( options: Options, ) => - (options.client ?? client).post< - UploadFileResponses, - UploadFileErrors, - ThrowOnError - >({ + (options.client ?? client).post({ bodySerializer: null, responseType: 'json', security: [{ scheme: 'bearer', type: 'http' }], @@ -250,11 +226,7 @@ export const uploadFile = ( export const getInventory = ( options?: Options, ) => - (options?.client ?? client).get< - GetInventoryResponses, - GetInventoryErrors, - ThrowOnError - >({ + (options?.client ?? client).get({ responseType: 'json', security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', @@ -269,11 +241,7 @@ export const getInventory = ( export const placeOrder = ( options?: Options, ) => - (options?.client ?? client).post< - PlaceOrderResponses, - PlaceOrderErrors, - ThrowOnError - >({ + (options?.client ?? client).post({ responseType: 'json', url: '/store/order', ...options, @@ -291,11 +259,10 @@ export const placeOrder = ( export const deleteOrder = ( options: Options, ) => - (options.client ?? client).delete< - DeleteOrderResponses, - DeleteOrderErrors, - ThrowOnError - >({ url: '/store/order/{orderId}', ...options }); + (options.client ?? client).delete({ + url: '/store/order/{orderId}', + ...options, + }); /** * Find purchase order by ID. @@ -305,11 +272,7 @@ export const deleteOrder = ( export const getOrderById = ( options: Options, ) => - (options.client ?? client).get< - GetOrderByIdResponses, - GetOrderByIdErrors, - ThrowOnError - >({ + (options.client ?? client).get({ responseType: 'json', url: '/store/order/{orderId}', ...options, @@ -323,11 +286,7 @@ export const getOrderById = ( export const createUser = ( options?: Options, ) => - (options?.client ?? client).post< - CreateUserResponses, - CreateUserErrors, - ThrowOnError - >({ + (options?.client ?? client).post({ responseType: 'json', url: '/user', ...options, @@ -367,11 +326,7 @@ export const createUsersWithListInput = ( export const loginUser = ( options?: Options, ) => - (options?.client ?? client).get< - LoginUserResponses, - LoginUserErrors, - ThrowOnError - >({ + (options?.client ?? client).get({ responseType: 'json', url: '/user/login', ...options, @@ -385,11 +340,10 @@ export const loginUser = ( export const logoutUser = ( options?: Options, ) => - (options?.client ?? client).get< - LogoutUserResponses, - LogoutUserErrors, - ThrowOnError - >({ url: '/user/logout', ...options }); + (options?.client ?? client).get({ + url: '/user/logout', + ...options, + }); /** * Delete user resource. @@ -399,11 +353,10 @@ export const logoutUser = ( export const deleteUser = ( options: Options, ) => - (options.client ?? client).delete< - DeleteUserResponses, - DeleteUserErrors, - ThrowOnError - >({ url: '/user/{username}', ...options }); + (options.client ?? client).delete({ + url: '/user/{username}', + ...options, + }); /** * Get user by user name. @@ -413,11 +366,7 @@ export const deleteUser = ( export const getUserByName = ( options: Options, ) => - (options.client ?? client).get< - GetUserByNameResponses, - GetUserByNameErrors, - ThrowOnError - >({ + (options.client ?? client).get({ responseType: 'json', url: '/user/{username}', ...options, @@ -431,11 +380,7 @@ export const getUserByName = ( export const updateUser = ( options: Options, ) => - (options.client ?? client).put< - UpdateUserResponses, - UpdateUserErrors, - ThrowOnError - >({ + (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { diff --git a/examples/openapi-ts-axios/src/client/types.gen.ts b/examples/openapi-ts-axios/src/client/types.gen.ts index 48da19d87..48a6cd4a7 100644 --- a/examples/openapi-ts-axios/src/client/types.gen.ts +++ b/examples/openapi-ts-axios/src/client/types.gen.ts @@ -167,8 +167,7 @@ export type FindPetsByStatusResponses = { 200: Array; }; -export type FindPetsByStatusResponse = - FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; +export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; @@ -200,8 +199,7 @@ export type FindPetsByTagsResponses = { 200: Array; }; -export type FindPetsByTagsResponse = - FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; +export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; @@ -378,8 +376,7 @@ export type GetInventoryResponses = { }; }; -export type GetInventoryResponse = - GetInventoryResponses[keyof GetInventoryResponses]; +export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; @@ -480,8 +477,7 @@ export type GetOrderByIdResponses = { 200: Order; }; -export type GetOrderByIdResponse = - GetOrderByIdResponses[keyof GetOrderByIdResponses]; +export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** @@ -658,8 +654,7 @@ export type GetUserByNameResponses = { 200: User; }; -export type GetUserByNameResponse = - GetUserByNameResponses[keyof GetUserByNameResponses]; +export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** diff --git a/examples/openapi-ts-fastify/src/client/client.gen.ts b/examples/openapi-ts-fastify/src/client/client.gen.ts index 98b5a32f7..4aab8bcaa 100644 --- a/examples/openapi-ts-fastify/src/client/client.gen.ts +++ b/examples/openapi-ts-fastify/src/client/client.gen.ts @@ -1,11 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { - type ClientOptions, - type Config, - createClient, - createConfig, -} from './client'; +import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** diff --git a/examples/openapi-ts-fastify/src/client/client/client.gen.ts b/examples/openapi-ts-fastify/src/client/client/client.gen.ts index d4cbcce50..d2e55a144 100644 --- a/examples/openapi-ts-fastify/src/client/client/client.gen.ts +++ b/examples/openapi-ts-fastify/src/client/client/client.gen.ts @@ -3,12 +3,7 @@ import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; -import type { - Client, - Config, - RequestOptions, - ResolvedRequestOptions, -} from './types.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, @@ -34,12 +29,7 @@ export const createClient = (config: Config = {}): Client => { return getConfig(); }; - const interceptors = createInterceptors< - Request, - Response, - unknown, - ResolvedRequestOptions - >(); + const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { @@ -105,12 +95,7 @@ export const createClient = (config: Config = {}): Client => { for (const fn of interceptors.error.fns) { if (fn) { - finalError = (await fn( - error, - undefined as any, - request, - opts, - )) as unknown; + finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } @@ -147,10 +132,7 @@ export const createClient = (config: Config = {}): Client => { ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; - if ( - response.status === 204 || - response.headers.get('Content-Length') === '0' - ) { + if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': @@ -252,34 +234,29 @@ export const createClient = (config: Config = {}): Client => { }; }; - const makeMethodFn = - (method: Uppercase) => (options: RequestOptions) => - request({ ...options, method }); + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); - const makeSseFn = - (method: Uppercase) => async (options: RequestOptions) => { - const { opts, url } = await beforeRequest(options); - return createSseClient({ - ...opts, - body: opts.body as BodyInit | null | undefined, - headers: opts.headers as unknown as Record, - 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); - } + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + 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) as - | BodyInit - | null - | undefined, - url, - }); - }; + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; return { buildUrl, diff --git a/examples/openapi-ts-fastify/src/client/client/types.gen.ts b/examples/openapi-ts-fastify/src/client/client/types.gen.ts index b4a499cc0..61a8dffa3 100644 --- a/examples/openapi-ts-fastify/src/client/client/types.gen.ts +++ b/examples/openapi-ts-fastify/src/client/client/types.gen.ts @@ -1,21 +1,14 @@ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; -import type { - ServerSentEventsOptions, - ServerSentEventsResult, -} from '../core/serverSentEvents.gen'; -import type { - Client as CoreClient, - Config as CoreConfig, -} from '../core/types.gen'; +import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config - extends Omit, - CoreConfig { + extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ @@ -42,14 +35,7 @@ export interface Config * * @default 'auto' */ - parseAs?: - | 'arrayBuffer' - | 'auto' - | 'blob' - | 'formData' - | 'json' - | 'stream' - | 'text'; + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * @@ -69,7 +55,9 @@ export interface RequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, -> extends Config<{ +> + extends + Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, @@ -116,32 +104,22 @@ export type RequestResult< ? TData[keyof TData] : TData : { - data: TData extends Record - ? TData[keyof TData] - : TData; + data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' - ? - | (TData extends Record - ? TData[keyof TData] - : TData) - | undefined + ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { - data: TData extends Record - ? TData[keyof TData] - : TData; + data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; - error: TError extends Record - ? TError[keyof TError] - : TError; + error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; @@ -180,10 +158,7 @@ type RequestFn = < TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & - Pick< - Required>, - 'method' - >, + Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < @@ -197,13 +172,7 @@ type BuildUrlFn = < options: TData & Options, ) => string; -export type Client = CoreClient< - RequestFn, - Config, - MethodFn, - BuildUrlFn, - SseFn -> & { +export type Client = CoreClient & { interceptors: Middleware; }; diff --git a/examples/openapi-ts-fastify/src/client/client/utils.gen.ts b/examples/openapi-ts-fastify/src/client/client/utils.gen.ts index 89416454b..b4bd2435c 100644 --- a/examples/openapi-ts-fastify/src/client/client/utils.gen.ts +++ b/examples/openapi-ts-fastify/src/client/client/utils.gen.ts @@ -9,12 +9,7 @@ import { serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; -import type { - Client, - ClientOptions, - Config, - RequestOptions, -} from './types.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, @@ -70,9 +65,7 @@ export const createQuerySerializer = ({ /** * Infers parseAs value from provided Content-Type header. */ -export const getParseAs = ( - contentType: string | null, -): Exclude => { +export const getParseAs = (contentType: string | null): Exclude => { 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. @@ -85,10 +78,7 @@ export const getParseAs = ( return; } - if ( - cleanContent.startsWith('application/json') || - cleanContent.endsWith('+json') - ) { + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } @@ -97,9 +87,7 @@ export const getParseAs = ( } if ( - ['application/', 'audio/', 'image/', 'video/'].some((type) => - cleanContent.startsWith(type), - ) + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } @@ -206,10 +194,7 @@ export const mergeHeaders = ( continue; } - const iterator = - header instanceof Headers - ? headersEntries(header) - : Object.entries(header); + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { @@ -238,10 +223,7 @@ type ErrInterceptor = ( options: Options, ) => Err | Promise; -type ReqInterceptor = ( - request: Req, - options: Options, -) => Req | Promise; +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, @@ -275,10 +257,7 @@ class Interceptors { return this.fns.indexOf(id); } - update( - id: number | Interceptor, - fn: Interceptor, - ): number | Interceptor | false { + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; diff --git a/examples/openapi-ts-fastify/src/client/core/auth.gen.ts b/examples/openapi-ts-fastify/src/client/core/auth.gen.ts index f8a73266f..3ebf99478 100644 --- a/examples/openapi-ts-fastify/src/client/core/auth.gen.ts +++ b/examples/openapi-ts-fastify/src/client/core/auth.gen.ts @@ -23,8 +23,7 @@ export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { - const token = - typeof callback === 'function' ? await callback(auth) : callback; + const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; diff --git a/examples/openapi-ts-fastify/src/client/core/bodySerializer.gen.ts b/examples/openapi-ts-fastify/src/client/core/bodySerializer.gen.ts index 552b50f7c..8ad92c9ff 100644 --- a/examples/openapi-ts-fastify/src/client/core/bodySerializer.gen.ts +++ b/examples/openapi-ts-fastify/src/client/core/bodySerializer.gen.ts @@ -1,10 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import type { - ArrayStyle, - ObjectStyle, - SerializerOptions, -} from './pathSerializer.gen'; +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; @@ -24,11 +20,7 @@ export type QuerySerializerOptions = QuerySerializerOptionsObject & { parameters?: Record; }; -const serializeFormDataPair = ( - data: FormData, - key: string, - value: unknown, -): void => { +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { @@ -38,11 +30,7 @@ const serializeFormDataPair = ( } }; -const serializeUrlSearchParamsPair = ( - data: URLSearchParams, - key: string, - value: unknown, -): void => { +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { @@ -73,15 +61,11 @@ export const formDataBodySerializer = { export const jsonBodySerializer = { bodySerializer: (body: T): string => - JSON.stringify(body, (_key, value) => - typeof value === 'bigint' ? value.toString() : value, - ), + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { - bodySerializer: | Array>>( - body: T, - ): string => { + bodySerializer: | Array>>(body: T): string => { const data = new URLSearchParams(); Object.entries(body).forEach(([key, value]) => { diff --git a/examples/openapi-ts-fastify/src/client/core/params.gen.ts b/examples/openapi-ts-fastify/src/client/core/params.gen.ts index 602715c46..6099cab1b 100644 --- a/examples/openapi-ts-fastify/src/client/core/params.gen.ts +++ b/examples/openapi-ts-fastify/src/client/core/params.gen.ts @@ -102,10 +102,7 @@ const stripEmptySlots = (params: Params) => { } }; -export const buildClientParams = ( - args: ReadonlyArray, - fields: FieldsConfig, -) => { +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, @@ -148,15 +145,11 @@ export const buildClientParams = ( params[field.map] = value; } } else { - const extra = extraPrefixes.find(([prefix]) => - key.startsWith(prefix), - ); + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; - (params[slot] as Record)[ - key.slice(prefix.length) - ] = value; + (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { diff --git a/examples/openapi-ts-fastify/src/client/core/pathSerializer.gen.ts b/examples/openapi-ts-fastify/src/client/core/pathSerializer.gen.ts index 8d9993104..994b2848c 100644 --- a/examples/openapi-ts-fastify/src/client/core/pathSerializer.gen.ts +++ b/examples/openapi-ts-fastify/src/client/core/pathSerializer.gen.ts @@ -1,8 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -interface SerializeOptions - extends SerializePrimitiveOptions, - SerializerOptions {} +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; @@ -105,9 +103,7 @@ export const serializeArrayParam = ({ }); }) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ @@ -146,11 +142,7 @@ export const serializeObjectParam = ({ if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { - values = [ - ...values, - key, - allowReserved ? (v as string) : encodeURIComponent(v as string), - ]; + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { @@ -175,7 +167,5 @@ export const serializeObjectParam = ({ }), ) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; diff --git a/examples/openapi-ts-fastify/src/client/core/queryKeySerializer.gen.ts b/examples/openapi-ts-fastify/src/client/core/queryKeySerializer.gen.ts index d3bb68396..5000df606 100644 --- a/examples/openapi-ts-fastify/src/client/core/queryKeySerializer.gen.ts +++ b/examples/openapi-ts-fastify/src/client/core/queryKeySerializer.gen.ts @@ -15,11 +15,7 @@ export type JsonValue = * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { @@ -61,9 +57,7 @@ const isPlainObject = (value: unknown): value is Record => { * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { - const entries = Array.from(params.entries()).sort(([a], [b]) => - a.localeCompare(b), - ); + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { @@ -86,26 +80,16 @@ const serializeSearchParams = (params: URLSearchParams): JsonValue => { /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ -export const serializeQueryKeyValue = ( - value: unknown, -): JsonValue | undefined => { +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } - if ( - typeof value === 'string' || - typeof value === 'number' || - typeof value === 'boolean' - ) { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } @@ -121,10 +105,7 @@ export const serializeQueryKeyValue = ( return stringifyToJsonValue(value); } - if ( - typeof URLSearchParams !== 'undefined' && - value instanceof URLSearchParams - ) { + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } diff --git a/examples/openapi-ts-fastify/src/client/core/serverSentEvents.gen.ts b/examples/openapi-ts-fastify/src/client/core/serverSentEvents.gen.ts index 343d25af8..6aa6cf02a 100644 --- a/examples/openapi-ts-fastify/src/client/core/serverSentEvents.gen.ts +++ b/examples/openapi-ts-fastify/src/client/core/serverSentEvents.gen.ts @@ -2,10 +2,7 @@ import type { Config } from './types.gen'; -export type ServerSentEventsOptions = Omit< - RequestInit, - 'method' -> & +export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom @@ -74,11 +71,7 @@ export interface StreamEvent { retry?: number; } -export type ServerSentEventsResult< - TData = unknown, - TReturn = void, - TNext = unknown, -> = { +export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, @@ -101,9 +94,7 @@ export const createSseClient = ({ }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; - const sleep = - sseSleepFn ?? - ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; @@ -141,16 +132,11 @@ export const createSseClient = ({ 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.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(); + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; @@ -188,10 +174,7 @@ export const createSseClient = ({ } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { - const parsed = Number.parseInt( - line.replace(/^retry:\s*/, ''), - 10, - ); + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } @@ -243,18 +226,12 @@ export const createSseClient = ({ // connection failed or aborted; retry after delay onSseError?.(error); - if ( - sseMaxRetryAttempts !== undefined && - attempt >= sseMaxRetryAttempts - ) { + 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, - ); + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } diff --git a/examples/openapi-ts-fastify/src/client/core/types.gen.ts b/examples/openapi-ts-fastify/src/client/core/types.gen.ts index 643c070c9..97463257e 100644 --- a/examples/openapi-ts-fastify/src/client/core/types.gen.ts +++ b/examples/openapi-ts-fastify/src/client/core/types.gen.ts @@ -1,11 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; -import type { - BodySerializer, - QuerySerializer, - QuerySerializerOptions, -} from './bodySerializer.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' @@ -34,9 +30,7 @@ export type Client< setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; -} & ([SseFn] extends [never] - ? { sse?: never } - : { sse: { [K in HttpMethod]: SseFn } }); +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** @@ -59,13 +53,7 @@ export interface Config { | RequestInit['headers'] | Record< string, - | string - | number - | boolean - | (string | number | boolean)[] - | null - | undefined - | unknown + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. @@ -112,7 +100,5 @@ type IsExactlyNeverOrNeverUndefined = [T] extends [never] : false; export type OmitNever> = { - [K in keyof T as IsExactlyNeverOrNeverUndefined extends true - ? never - : K]: T[K]; + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; diff --git a/examples/openapi-ts-fastify/src/client/core/utils.gen.ts b/examples/openapi-ts-fastify/src/client/core/utils.gen.ts index 0b5389d08..e7ddbe354 100644 --- a/examples/openapi-ts-fastify/src/client/core/utils.gen.ts +++ b/examples/openapi-ts-fastify/src/client/core/utils.gen.ts @@ -44,10 +44,7 @@ export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { } if (Array.isArray(value)) { - url = url.replace( - match, - serializeArrayParam({ explode, name, style, value }), - ); + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } diff --git a/examples/openapi-ts-fastify/src/client/sdk.gen.ts b/examples/openapi-ts-fastify/src/client/sdk.gen.ts index 7ae103592..3078709f9 100644 --- a/examples/openapi-ts-fastify/src/client/sdk.gen.ts +++ b/examples/openapi-ts-fastify/src/client/sdk.gen.ts @@ -37,11 +37,10 @@ export type Options< export const listPets = ( options?: Options, ) => - (options?.client ?? client).get< - ListPetsResponses, - ListPetsErrors, - ThrowOnError - >({ url: '/pets', ...options }); + (options?.client ?? client).get({ + url: '/pets', + ...options, + }); /** * Create a pet @@ -49,11 +48,10 @@ export const listPets = ( export const createPets = ( options?: Options, ) => - (options?.client ?? client).post< - CreatePetsResponses, - CreatePetsErrors, - ThrowOnError - >({ url: '/pets', ...options }); + (options?.client ?? client).post({ + url: '/pets', + ...options, + }); /** * Info for a specific pet @@ -61,8 +59,7 @@ export const createPets = ( export const showPetById = ( options: Options, ) => - (options.client ?? client).get< - ShowPetByIdResponses, - ShowPetByIdErrors, - ThrowOnError - >({ url: '/pets/{petId}', ...options }); + (options.client ?? client).get({ + url: '/pets/{petId}', + ...options, + }); diff --git a/examples/openapi-ts-fastify/src/client/types.gen.ts b/examples/openapi-ts-fastify/src/client/types.gen.ts index bd956ecb7..7dca9c242 100644 --- a/examples/openapi-ts-fastify/src/client/types.gen.ts +++ b/examples/openapi-ts-fastify/src/client/types.gen.ts @@ -98,5 +98,4 @@ export type ShowPetByIdResponses = { 200: Pet; }; -export type ShowPetByIdResponse = - ShowPetByIdResponses[keyof ShowPetByIdResponses]; +export type ShowPetByIdResponse = ShowPetByIdResponses[keyof ShowPetByIdResponses]; diff --git a/examples/openapi-ts-fastify/src/server.ts b/examples/openapi-ts-fastify/src/server.ts index 23cd911d8..c2d0e0f79 100644 --- a/examples/openapi-ts-fastify/src/server.ts +++ b/examples/openapi-ts-fastify/src/server.ts @@ -10,9 +10,7 @@ export const buildServer = async () => { const fastify = Fastify(); const specificationPath = join(__dirname, '..', 'openapi.json'); - const specificationJson = JSON.parse( - readFileSync(specificationPath, 'utf-8'), - ); + const specificationJson = JSON.parse(readFileSync(specificationPath, 'utf-8')); fastify.register(glue, { prefix: 'v3', diff --git a/examples/openapi-ts-fastify/vite.config.ts b/examples/openapi-ts-fastify/vite.config.ts index c632ac7b4..9baa55f15 100644 --- a/examples/openapi-ts-fastify/vite.config.ts +++ b/examples/openapi-ts-fastify/vite.config.ts @@ -3,14 +3,11 @@ import { fileURLToPath } from 'node:url'; import { createVitestConfig } from '@config/vite-base'; // https://vitejs.dev/config/ -export default createVitestConfig( - fileURLToPath(new URL('./', import.meta.url)), - { - test: { - environment: 'node', - globals: true, - include: ['test/**/*.test.ts'], - watch: false, - }, +export default createVitestConfig(fileURLToPath(new URL('./', import.meta.url)), { + test: { + environment: 'node', + globals: true, + include: ['test/**/*.test.ts'], + watch: false, }, -); +}); diff --git a/examples/openapi-ts-fetch/src/App.tsx b/examples/openapi-ts-fetch/src/App.tsx index f02bd7b7f..0e73c0b40 100644 --- a/examples/openapi-ts-fetch/src/App.tsx +++ b/examples/openapi-ts-fetch/src/App.tsx @@ -38,11 +38,7 @@ localClient.interceptors.request.use((request, options) => { // Middleware is great for adding authorization tokens to requests made to // protected paths. Headers are set randomly here to allow surfacing the // default headers, too. - if ( - options.url === '/pet/{petId}' && - options.method === 'GET' && - Math.random() < 0.5 - ) { + if (options.url === '/pet/{petId}' && options.method === 'GET' && Math.random() < 0.5) { request.headers.set('Authorization', 'Bearer '); } return request; @@ -136,9 +132,7 @@ function App() { }; return ( - +
@@ -206,20 +200,12 @@ function App() { Category - + Please enter a category - + diff --git a/examples/openapi-ts-fetch/src/client/client.gen.ts b/examples/openapi-ts-fetch/src/client/client.gen.ts index 069f4daba..84318ba67 100644 --- a/examples/openapi-ts-fetch/src/client/client.gen.ts +++ b/examples/openapi-ts-fetch/src/client/client.gen.ts @@ -1,11 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { - type ClientOptions, - type Config, - createClient, - createConfig, -} from './client'; +import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** @@ -21,7 +16,5 @@ export type CreateClientConfig = ( ) => Config & T>; export const client = createClient( - createConfig({ - baseUrl: 'https://petstore3.swagger.io/api/v3', - }), + createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); diff --git a/examples/openapi-ts-fetch/src/client/client/client.gen.ts b/examples/openapi-ts-fetch/src/client/client/client.gen.ts index d4cbcce50..d2e55a144 100644 --- a/examples/openapi-ts-fetch/src/client/client/client.gen.ts +++ b/examples/openapi-ts-fetch/src/client/client/client.gen.ts @@ -3,12 +3,7 @@ import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; -import type { - Client, - Config, - RequestOptions, - ResolvedRequestOptions, -} from './types.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, @@ -34,12 +29,7 @@ export const createClient = (config: Config = {}): Client => { return getConfig(); }; - const interceptors = createInterceptors< - Request, - Response, - unknown, - ResolvedRequestOptions - >(); + const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { @@ -105,12 +95,7 @@ export const createClient = (config: Config = {}): Client => { for (const fn of interceptors.error.fns) { if (fn) { - finalError = (await fn( - error, - undefined as any, - request, - opts, - )) as unknown; + finalError = (await fn(error, undefined as any, request, opts)) as unknown; } } @@ -147,10 +132,7 @@ export const createClient = (config: Config = {}): Client => { ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; - if ( - response.status === 204 || - response.headers.get('Content-Length') === '0' - ) { + if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': @@ -252,34 +234,29 @@ export const createClient = (config: Config = {}): Client => { }; }; - const makeMethodFn = - (method: Uppercase) => (options: RequestOptions) => - request({ ...options, method }); + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); - const makeSseFn = - (method: Uppercase) => async (options: RequestOptions) => { - const { opts, url } = await beforeRequest(options); - return createSseClient({ - ...opts, - body: opts.body as BodyInit | null | undefined, - headers: opts.headers as unknown as Record, - 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); - } + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + 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) as - | BodyInit - | null - | undefined, - url, - }); - }; + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; return { buildUrl, diff --git a/examples/openapi-ts-fetch/src/client/client/types.gen.ts b/examples/openapi-ts-fetch/src/client/client/types.gen.ts index b4a499cc0..61a8dffa3 100644 --- a/examples/openapi-ts-fetch/src/client/client/types.gen.ts +++ b/examples/openapi-ts-fetch/src/client/client/types.gen.ts @@ -1,21 +1,14 @@ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; -import type { - ServerSentEventsOptions, - ServerSentEventsResult, -} from '../core/serverSentEvents.gen'; -import type { - Client as CoreClient, - Config as CoreConfig, -} from '../core/types.gen'; +import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; export interface Config - extends Omit, - CoreConfig { + extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ @@ -42,14 +35,7 @@ export interface Config * * @default 'auto' */ - parseAs?: - | 'arrayBuffer' - | 'auto' - | 'blob' - | 'formData' - | 'json' - | 'stream' - | 'text'; + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * @@ -69,7 +55,9 @@ export interface RequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, -> extends Config<{ +> + extends + Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, @@ -116,32 +104,22 @@ export type RequestResult< ? TData[keyof TData] : TData : { - data: TData extends Record - ? TData[keyof TData] - : TData; + data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' - ? - | (TData extends Record - ? TData[keyof TData] - : TData) - | undefined + ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { - data: TData extends Record - ? TData[keyof TData] - : TData; + data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; - error: TError extends Record - ? TError[keyof TError] - : TError; + error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; @@ -180,10 +158,7 @@ type RequestFn = < TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & - Pick< - Required>, - 'method' - >, + Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < @@ -197,13 +172,7 @@ type BuildUrlFn = < options: TData & Options, ) => string; -export type Client = CoreClient< - RequestFn, - Config, - MethodFn, - BuildUrlFn, - SseFn -> & { +export type Client = CoreClient & { interceptors: Middleware; }; diff --git a/examples/openapi-ts-fetch/src/client/client/utils.gen.ts b/examples/openapi-ts-fetch/src/client/client/utils.gen.ts index 89416454b..b4bd2435c 100644 --- a/examples/openapi-ts-fetch/src/client/client/utils.gen.ts +++ b/examples/openapi-ts-fetch/src/client/client/utils.gen.ts @@ -9,12 +9,7 @@ import { serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; -import type { - Client, - ClientOptions, - Config, - RequestOptions, -} from './types.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, @@ -70,9 +65,7 @@ export const createQuerySerializer = ({ /** * Infers parseAs value from provided Content-Type header. */ -export const getParseAs = ( - contentType: string | null, -): Exclude => { +export const getParseAs = (contentType: string | null): Exclude => { 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. @@ -85,10 +78,7 @@ export const getParseAs = ( return; } - if ( - cleanContent.startsWith('application/json') || - cleanContent.endsWith('+json') - ) { + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } @@ -97,9 +87,7 @@ export const getParseAs = ( } if ( - ['application/', 'audio/', 'image/', 'video/'].some((type) => - cleanContent.startsWith(type), - ) + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } @@ -206,10 +194,7 @@ export const mergeHeaders = ( continue; } - const iterator = - header instanceof Headers - ? headersEntries(header) - : Object.entries(header); + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { @@ -238,10 +223,7 @@ type ErrInterceptor = ( options: Options, ) => Err | Promise; -type ReqInterceptor = ( - request: Req, - options: Options, -) => Req | Promise; +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, @@ -275,10 +257,7 @@ class Interceptors { return this.fns.indexOf(id); } - update( - id: number | Interceptor, - fn: Interceptor, - ): number | Interceptor | false { + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; diff --git a/examples/openapi-ts-fetch/src/client/core/auth.gen.ts b/examples/openapi-ts-fetch/src/client/core/auth.gen.ts index f8a73266f..3ebf99478 100644 --- a/examples/openapi-ts-fetch/src/client/core/auth.gen.ts +++ b/examples/openapi-ts-fetch/src/client/core/auth.gen.ts @@ -23,8 +23,7 @@ export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { - const token = - typeof callback === 'function' ? await callback(auth) : callback; + const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; diff --git a/examples/openapi-ts-fetch/src/client/core/bodySerializer.gen.ts b/examples/openapi-ts-fetch/src/client/core/bodySerializer.gen.ts index 552b50f7c..8ad92c9ff 100644 --- a/examples/openapi-ts-fetch/src/client/core/bodySerializer.gen.ts +++ b/examples/openapi-ts-fetch/src/client/core/bodySerializer.gen.ts @@ -1,10 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import type { - ArrayStyle, - ObjectStyle, - SerializerOptions, -} from './pathSerializer.gen'; +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; @@ -24,11 +20,7 @@ export type QuerySerializerOptions = QuerySerializerOptionsObject & { parameters?: Record; }; -const serializeFormDataPair = ( - data: FormData, - key: string, - value: unknown, -): void => { +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { @@ -38,11 +30,7 @@ const serializeFormDataPair = ( } }; -const serializeUrlSearchParamsPair = ( - data: URLSearchParams, - key: string, - value: unknown, -): void => { +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { @@ -73,15 +61,11 @@ export const formDataBodySerializer = { export const jsonBodySerializer = { bodySerializer: (body: T): string => - JSON.stringify(body, (_key, value) => - typeof value === 'bigint' ? value.toString() : value, - ), + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { - bodySerializer: | Array>>( - body: T, - ): string => { + bodySerializer: | Array>>(body: T): string => { const data = new URLSearchParams(); Object.entries(body).forEach(([key, value]) => { diff --git a/examples/openapi-ts-fetch/src/client/core/params.gen.ts b/examples/openapi-ts-fetch/src/client/core/params.gen.ts index 602715c46..6099cab1b 100644 --- a/examples/openapi-ts-fetch/src/client/core/params.gen.ts +++ b/examples/openapi-ts-fetch/src/client/core/params.gen.ts @@ -102,10 +102,7 @@ const stripEmptySlots = (params: Params) => { } }; -export const buildClientParams = ( - args: ReadonlyArray, - fields: FieldsConfig, -) => { +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, @@ -148,15 +145,11 @@ export const buildClientParams = ( params[field.map] = value; } } else { - const extra = extraPrefixes.find(([prefix]) => - key.startsWith(prefix), - ); + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; - (params[slot] as Record)[ - key.slice(prefix.length) - ] = value; + (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { diff --git a/examples/openapi-ts-fetch/src/client/core/pathSerializer.gen.ts b/examples/openapi-ts-fetch/src/client/core/pathSerializer.gen.ts index 8d9993104..994b2848c 100644 --- a/examples/openapi-ts-fetch/src/client/core/pathSerializer.gen.ts +++ b/examples/openapi-ts-fetch/src/client/core/pathSerializer.gen.ts @@ -1,8 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -interface SerializeOptions - extends SerializePrimitiveOptions, - SerializerOptions {} +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; @@ -105,9 +103,7 @@ export const serializeArrayParam = ({ }); }) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ @@ -146,11 +142,7 @@ export const serializeObjectParam = ({ if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { - values = [ - ...values, - key, - allowReserved ? (v as string) : encodeURIComponent(v as string), - ]; + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { @@ -175,7 +167,5 @@ export const serializeObjectParam = ({ }), ) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; diff --git a/examples/openapi-ts-fetch/src/client/core/queryKeySerializer.gen.ts b/examples/openapi-ts-fetch/src/client/core/queryKeySerializer.gen.ts index d3bb68396..5000df606 100644 --- a/examples/openapi-ts-fetch/src/client/core/queryKeySerializer.gen.ts +++ b/examples/openapi-ts-fetch/src/client/core/queryKeySerializer.gen.ts @@ -15,11 +15,7 @@ export type JsonValue = * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { @@ -61,9 +57,7 @@ const isPlainObject = (value: unknown): value is Record => { * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { - const entries = Array.from(params.entries()).sort(([a], [b]) => - a.localeCompare(b), - ); + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { @@ -86,26 +80,16 @@ const serializeSearchParams = (params: URLSearchParams): JsonValue => { /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ -export const serializeQueryKeyValue = ( - value: unknown, -): JsonValue | undefined => { +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } - if ( - typeof value === 'string' || - typeof value === 'number' || - typeof value === 'boolean' - ) { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } @@ -121,10 +105,7 @@ export const serializeQueryKeyValue = ( return stringifyToJsonValue(value); } - if ( - typeof URLSearchParams !== 'undefined' && - value instanceof URLSearchParams - ) { + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } diff --git a/examples/openapi-ts-fetch/src/client/core/serverSentEvents.gen.ts b/examples/openapi-ts-fetch/src/client/core/serverSentEvents.gen.ts index 343d25af8..6aa6cf02a 100644 --- a/examples/openapi-ts-fetch/src/client/core/serverSentEvents.gen.ts +++ b/examples/openapi-ts-fetch/src/client/core/serverSentEvents.gen.ts @@ -2,10 +2,7 @@ import type { Config } from './types.gen'; -export type ServerSentEventsOptions = Omit< - RequestInit, - 'method' -> & +export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom @@ -74,11 +71,7 @@ export interface StreamEvent { retry?: number; } -export type ServerSentEventsResult< - TData = unknown, - TReturn = void, - TNext = unknown, -> = { +export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, @@ -101,9 +94,7 @@ export const createSseClient = ({ }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; - const sleep = - sseSleepFn ?? - ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; @@ -141,16 +132,11 @@ export const createSseClient = ({ 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.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(); + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; @@ -188,10 +174,7 @@ export const createSseClient = ({ } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { - const parsed = Number.parseInt( - line.replace(/^retry:\s*/, ''), - 10, - ); + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } @@ -243,18 +226,12 @@ export const createSseClient = ({ // connection failed or aborted; retry after delay onSseError?.(error); - if ( - sseMaxRetryAttempts !== undefined && - attempt >= sseMaxRetryAttempts - ) { + 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, - ); + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } diff --git a/examples/openapi-ts-fetch/src/client/core/types.gen.ts b/examples/openapi-ts-fetch/src/client/core/types.gen.ts index 643c070c9..97463257e 100644 --- a/examples/openapi-ts-fetch/src/client/core/types.gen.ts +++ b/examples/openapi-ts-fetch/src/client/core/types.gen.ts @@ -1,11 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; -import type { - BodySerializer, - QuerySerializer, - QuerySerializerOptions, -} from './bodySerializer.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' @@ -34,9 +30,7 @@ export type Client< setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; -} & ([SseFn] extends [never] - ? { sse?: never } - : { sse: { [K in HttpMethod]: SseFn } }); +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** @@ -59,13 +53,7 @@ export interface Config { | RequestInit['headers'] | Record< string, - | string - | number - | boolean - | (string | number | boolean)[] - | null - | undefined - | unknown + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. @@ -112,7 +100,5 @@ type IsExactlyNeverOrNeverUndefined = [T] extends [never] : false; export type OmitNever> = { - [K in keyof T as IsExactlyNeverOrNeverUndefined extends true - ? never - : K]: T[K]; + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; diff --git a/examples/openapi-ts-fetch/src/client/core/utils.gen.ts b/examples/openapi-ts-fetch/src/client/core/utils.gen.ts index 0b5389d08..e7ddbe354 100644 --- a/examples/openapi-ts-fetch/src/client/core/utils.gen.ts +++ b/examples/openapi-ts-fetch/src/client/core/utils.gen.ts @@ -44,10 +44,7 @@ export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { } if (Array.isArray(value)) { - url = url.replace( - match, - serializeArrayParam({ explode, name, style, value }), - ); + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } diff --git a/examples/openapi-ts-fetch/src/client/sdk.gen.ts b/examples/openapi-ts-fetch/src/client/sdk.gen.ts index 6d9563cb0..1da3ca639 100644 --- a/examples/openapi-ts-fetch/src/client/sdk.gen.ts +++ b/examples/openapi-ts-fetch/src/client/sdk.gen.ts @@ -105,11 +105,7 @@ export const addPet = ( export const updatePet = ( options: Options, ) => - (options.client ?? client).put< - UpdatePetResponses, - UpdatePetErrors, - ThrowOnError - >({ + (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, @@ -127,11 +123,7 @@ export const updatePet = ( export const findPetsByStatus = ( options: Options, ) => - (options.client ?? client).get< - FindPetsByStatusResponses, - FindPetsByStatusErrors, - ThrowOnError - >({ + (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, @@ -145,11 +137,7 @@ export const findPetsByStatus = ( export const findPetsByTags = ( options: Options, ) => - (options.client ?? client).get< - FindPetsByTagsResponses, - FindPetsByTagsErrors, - ThrowOnError - >({ + (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, @@ -163,11 +151,7 @@ export const findPetsByTags = ( export const deletePet = ( options: Options, ) => - (options.client ?? client).delete< - DeletePetResponses, - DeletePetErrors, - ThrowOnError - >({ + (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, @@ -181,11 +165,7 @@ export const deletePet = ( export const getPetById = ( options: Options, ) => - (options.client ?? client).get< - GetPetByIdResponses, - GetPetByIdErrors, - ThrowOnError - >({ + (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, @@ -220,11 +200,7 @@ export const updatePetWithForm = ( export const uploadFile = ( options: Options, ) => - (options.client ?? client).post< - UploadFileResponses, - UploadFileErrors, - ThrowOnError - >({ + (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', @@ -243,11 +219,7 @@ export const uploadFile = ( export const getInventory = ( options?: Options, ) => - (options?.client ?? client).get< - GetInventoryResponses, - GetInventoryErrors, - ThrowOnError - >({ + (options?.client ?? client).get({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, @@ -261,11 +233,7 @@ export const getInventory = ( export const placeOrder = ( options?: Options, ) => - (options?.client ?? client).post< - PlaceOrderResponses, - PlaceOrderErrors, - ThrowOnError - >({ + (options?.client ?? client).post({ url: '/store/order', ...options, headers: { @@ -282,11 +250,10 @@ export const placeOrder = ( export const deleteOrder = ( options: Options, ) => - (options.client ?? client).delete< - DeleteOrderResponses, - DeleteOrderErrors, - ThrowOnError - >({ url: '/store/order/{orderId}', ...options }); + (options.client ?? client).delete({ + url: '/store/order/{orderId}', + ...options, + }); /** * Find purchase order by ID. @@ -296,11 +263,10 @@ export const deleteOrder = ( export const getOrderById = ( options: Options, ) => - (options.client ?? client).get< - GetOrderByIdResponses, - GetOrderByIdErrors, - ThrowOnError - >({ url: '/store/order/{orderId}', ...options }); + (options.client ?? client).get({ + url: '/store/order/{orderId}', + ...options, + }); /** * Create user. @@ -310,11 +276,7 @@ export const getOrderById = ( export const createUser = ( options?: Options, ) => - (options?.client ?? client).post< - CreateUserResponses, - CreateUserErrors, - ThrowOnError - >({ + (options?.client ?? client).post({ url: '/user', ...options, headers: { @@ -352,11 +314,10 @@ export const createUsersWithListInput = ( export const loginUser = ( options?: Options, ) => - (options?.client ?? client).get< - LoginUserResponses, - LoginUserErrors, - ThrowOnError - >({ url: '/user/login', ...options }); + (options?.client ?? client).get({ + url: '/user/login', + ...options, + }); /** * Logs out current logged in user session. @@ -366,11 +327,10 @@ export const loginUser = ( export const logoutUser = ( options?: Options, ) => - (options?.client ?? client).get< - LogoutUserResponses, - LogoutUserErrors, - ThrowOnError - >({ url: '/user/logout', ...options }); + (options?.client ?? client).get({ + url: '/user/logout', + ...options, + }); /** * Delete user resource. @@ -380,11 +340,10 @@ export const logoutUser = ( export const deleteUser = ( options: Options, ) => - (options.client ?? client).delete< - DeleteUserResponses, - DeleteUserErrors, - ThrowOnError - >({ url: '/user/{username}', ...options }); + (options.client ?? client).delete({ + url: '/user/{username}', + ...options, + }); /** * Get user by user name. @@ -394,11 +353,10 @@ export const deleteUser = ( export const getUserByName = ( options: Options, ) => - (options.client ?? client).get< - GetUserByNameResponses, - GetUserByNameErrors, - ThrowOnError - >({ url: '/user/{username}', ...options }); + (options.client ?? client).get({ + url: '/user/{username}', + ...options, + }); /** * Update user resource. @@ -408,11 +366,7 @@ export const getUserByName = ( export const updateUser = ( options: Options, ) => - (options.client ?? client).put< - UpdateUserResponses, - UpdateUserErrors, - ThrowOnError - >({ + (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { diff --git a/examples/openapi-ts-fetch/src/client/types.gen.ts b/examples/openapi-ts-fetch/src/client/types.gen.ts index a2e6be0fa..a8ea86379 100644 --- a/examples/openapi-ts-fetch/src/client/types.gen.ts +++ b/examples/openapi-ts-fetch/src/client/types.gen.ts @@ -167,8 +167,7 @@ export type FindPetsByStatusResponses = { 200: Array; }; -export type FindPetsByStatusResponse = - FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; +export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; @@ -200,8 +199,7 @@ export type FindPetsByTagsResponses = { 200: Array; }; -export type FindPetsByTagsResponse = - FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; +export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; @@ -378,8 +376,7 @@ export type GetInventoryResponses = { }; }; -export type GetInventoryResponse = - GetInventoryResponses[keyof GetInventoryResponses]; +export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; @@ -480,8 +477,7 @@ export type GetOrderByIdResponses = { 200: Order; }; -export type GetOrderByIdResponse = - GetOrderByIdResponses[keyof GetOrderByIdResponses]; +export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** @@ -658,8 +654,7 @@ export type GetUserByNameResponses = { 200: User; }; -export type GetUserByNameResponse = - GetUserByNameResponses[keyof GetUserByNameResponses]; +export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** diff --git a/examples/openapi-ts-ky/src/App.tsx b/examples/openapi-ts-ky/src/App.tsx index f02bd7b7f..0e73c0b40 100644 --- a/examples/openapi-ts-ky/src/App.tsx +++ b/examples/openapi-ts-ky/src/App.tsx @@ -38,11 +38,7 @@ localClient.interceptors.request.use((request, options) => { // Middleware is great for adding authorization tokens to requests made to // protected paths. Headers are set randomly here to allow surfacing the // default headers, too. - if ( - options.url === '/pet/{petId}' && - options.method === 'GET' && - Math.random() < 0.5 - ) { + if (options.url === '/pet/{petId}' && options.method === 'GET' && Math.random() < 0.5) { request.headers.set('Authorization', 'Bearer '); } return request; @@ -136,9 +132,7 @@ function App() { }; return ( - +
@@ -206,20 +200,12 @@ function App() { Category - + Please enter a category - + diff --git a/examples/openapi-ts-ky/src/client/client.gen.ts b/examples/openapi-ts-ky/src/client/client.gen.ts index 069f4daba..84318ba67 100644 --- a/examples/openapi-ts-ky/src/client/client.gen.ts +++ b/examples/openapi-ts-ky/src/client/client.gen.ts @@ -1,11 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import { - type ClientOptions, - type Config, - createClient, - createConfig, -} from './client'; +import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** @@ -21,7 +16,5 @@ export type CreateClientConfig = ( ) => Config & T>; export const client = createClient( - createConfig({ - baseUrl: 'https://petstore3.swagger.io/api/v3', - }), + createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ); diff --git a/examples/openapi-ts-ky/src/client/client/client.gen.ts b/examples/openapi-ts-ky/src/client/client/client.gen.ts index 005420333..4abcf759a 100644 --- a/examples/openapi-ts-ky/src/client/client/client.gen.ts +++ b/examples/openapi-ts-ky/src/client/client/client.gen.ts @@ -34,12 +34,7 @@ export const createClient = (config: Config = {}): Client => { return getConfig(); }; - const interceptors = createInterceptors< - Request, - Response, - unknown, - ResolvedRequestOptions - >(); + const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { @@ -78,12 +73,7 @@ export const createClient = (config: Config = {}): Client => { response: Response, request: Request, opts: ResolvedRequestOptions, - interceptorsMiddleware: Middleware< - Request, - Response, - unknown, - ResolvedRequestOptions - >, + interceptorsMiddleware: Middleware, ) => { const result = { request, @@ -153,14 +143,7 @@ export const createClient = (config: Config = {}): Client => { kyOptions.retry = { limit: retryOpts.limit ?? 2, methods: retryOpts.methods as Array< - | 'get' - | 'post' - | 'put' - | 'patch' - | 'head' - | 'delete' - | 'options' - | 'trace' + 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace' >, statusCodes: retryOpts.statusCodes, }; @@ -216,10 +199,7 @@ export const createClient = (config: Config = {}): Client => { ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; - if ( - response.status === 204 || - response.headers.get('Content-Length') === '0' - ) { + if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': @@ -291,35 +271,30 @@ export const createClient = (config: Config = {}): Client => { return parseErrorResponse(response, request, opts, interceptors); }; - const makeMethodFn = - (method: Uppercase) => (options: RequestOptions) => - request({ ...options, method }); + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); - const makeSseFn = - (method: Uppercase) => async (options: RequestOptions) => { - const { opts, url } = await beforeRequest(options); - return createSseClient({ - ...opts, - body: opts.body as BodyInit | null | undefined, - fetch: globalThis.fetch, - headers: opts.headers as unknown as Record, - 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); - } + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + fetch: globalThis.fetch, + headers: opts.headers as unknown as Record, + 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) as - | BodyInit - | null - | undefined, - url, - }); - }; + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; return { buildUrl, diff --git a/examples/openapi-ts-ky/src/client/client/types.gen.ts b/examples/openapi-ts-ky/src/client/client/types.gen.ts index 3b765cc22..5b83a0ab0 100644 --- a/examples/openapi-ts-ky/src/client/client/types.gen.ts +++ b/examples/openapi-ts-ky/src/client/client/types.gen.ts @@ -4,14 +4,8 @@ import type { Options as KyOptions } from 'ky'; import type ky from 'ky'; import type { Auth } from '../core/auth.gen'; -import type { - ServerSentEventsOptions, - ServerSentEventsResult, -} from '../core/serverSentEvents.gen'; -import type { - Client as CoreClient, - Config as CoreConfig, -} from '../core/types.gen'; +import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export type ResponseStyle = 'data' | 'fields'; @@ -28,9 +22,7 @@ export interface RetryOptions { * * @default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ - methods?: Array< - 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace' - >; + methods?: Array<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'>; /** * HTTP status codes to retry * @@ -40,10 +32,8 @@ export interface RetryOptions { } export interface Config - extends Omit< - KyOptions, - 'body' | 'headers' | 'method' | 'prefixUrl' | 'retry' | 'throwHttpErrors' - >, + extends + Omit, CoreConfig { /** * Base URL for all requests made by this client. @@ -67,14 +57,7 @@ export interface Config * * @default 'auto' */ - parseAs?: - | 'arrayBuffer' - | 'auto' - | 'blob' - | 'formData' - | 'json' - | 'stream' - | 'text'; + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Should we return only data or multiple fields (data, error, response, etc.)? * @@ -104,7 +87,9 @@ export interface RequestOptions< TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string, -> extends Config<{ +> + extends + Config<{ responseStyle: TResponseStyle; throwOnError: ThrowOnError; }>, @@ -151,32 +136,22 @@ export type RequestResult< ? TData[keyof TData] : TData : { - data: TData extends Record - ? TData[keyof TData] - : TData; + data: TData extends Record ? TData[keyof TData] : TData; request: Request; response: Response; } > : Promise< TResponseStyle extends 'data' - ? - | (TData extends Record - ? TData[keyof TData] - : TData) - | undefined + ? (TData extends Record ? TData[keyof TData] : TData) | undefined : ( | { - data: TData extends Record - ? TData[keyof TData] - : TData; + data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; - error: TError extends Record - ? TError[keyof TError] - : TError; + error: TError extends Record ? TError[keyof TError] : TError; } ) & { request: Request; @@ -215,10 +190,7 @@ type RequestFn = < TResponseStyle extends ResponseStyle = 'fields', >( options: Omit, 'method'> & - Pick< - Required>, - 'method' - >, + Pick>, 'method'>, ) => RequestResult; type BuildUrlFn = < @@ -232,13 +204,7 @@ type BuildUrlFn = < options: TData & Options, ) => string; -export type Client = CoreClient< - RequestFn, - Config, - MethodFn, - BuildUrlFn, - SseFn -> & { +export type Client = CoreClient & { interceptors: Middleware; }; diff --git a/examples/openapi-ts-ky/src/client/client/utils.gen.ts b/examples/openapi-ts-ky/src/client/client/utils.gen.ts index 3582a06db..4b3317888 100644 --- a/examples/openapi-ts-ky/src/client/client/utils.gen.ts +++ b/examples/openapi-ts-ky/src/client/client/utils.gen.ts @@ -9,12 +9,7 @@ import { serializePrimitiveParam, } from '../core/pathSerializer.gen'; import { getUrl } from '../core/utils.gen'; -import type { - Client, - ClientOptions, - Config, - RequestOptions, -} from './types.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; export const createQuerySerializer = ({ parameters = {}, @@ -70,9 +65,7 @@ export const createQuerySerializer = ({ /** * Infers parseAs value from provided Content-Type header. */ -export const getParseAs = ( - contentType: string | null, -): Exclude => { +export const getParseAs = (contentType: string | null): Exclude => { if (!contentType) { return 'stream'; } @@ -83,10 +76,7 @@ export const getParseAs = ( return; } - if ( - cleanContent.startsWith('application/json') || - cleanContent.endsWith('+json') - ) { + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } @@ -95,9 +85,7 @@ export const getParseAs = ( } if ( - ['application/', 'audio/', 'image/', 'video/'].some((type) => - cleanContent.startsWith(type), - ) + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } @@ -204,10 +192,7 @@ export const mergeHeaders = ( continue; } - const iterator = - header instanceof Headers - ? headersEntries(header) - : Object.entries(header); + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { @@ -234,10 +219,7 @@ type ErrInterceptor = ( options: Options, ) => Err | Promise; -type ReqInterceptor = ( - request: Req, - options: Options, -) => Req | Promise; +type ReqInterceptor = (request: Req, options: Options) => Req | Promise; type ResInterceptor = ( response: Res, @@ -271,10 +253,7 @@ class Interceptors { return this.fns.indexOf(id); } - update( - id: number | Interceptor, - fn: Interceptor, - ): number | Interceptor | false { + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; diff --git a/examples/openapi-ts-ky/src/client/core/auth.gen.ts b/examples/openapi-ts-ky/src/client/core/auth.gen.ts index f8a73266f..3ebf99478 100644 --- a/examples/openapi-ts-ky/src/client/core/auth.gen.ts +++ b/examples/openapi-ts-ky/src/client/core/auth.gen.ts @@ -23,8 +23,7 @@ export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { - const token = - typeof callback === 'function' ? await callback(auth) : callback; + const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; diff --git a/examples/openapi-ts-ky/src/client/core/bodySerializer.gen.ts b/examples/openapi-ts-ky/src/client/core/bodySerializer.gen.ts index 552b50f7c..8ad92c9ff 100644 --- a/examples/openapi-ts-ky/src/client/core/bodySerializer.gen.ts +++ b/examples/openapi-ts-ky/src/client/core/bodySerializer.gen.ts @@ -1,10 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import type { - ArrayStyle, - ObjectStyle, - SerializerOptions, -} from './pathSerializer.gen'; +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; @@ -24,11 +20,7 @@ export type QuerySerializerOptions = QuerySerializerOptionsObject & { parameters?: Record; }; -const serializeFormDataPair = ( - data: FormData, - key: string, - value: unknown, -): void => { +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { @@ -38,11 +30,7 @@ const serializeFormDataPair = ( } }; -const serializeUrlSearchParamsPair = ( - data: URLSearchParams, - key: string, - value: unknown, -): void => { +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { @@ -73,15 +61,11 @@ export const formDataBodySerializer = { export const jsonBodySerializer = { bodySerializer: (body: T): string => - JSON.stringify(body, (_key, value) => - typeof value === 'bigint' ? value.toString() : value, - ), + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { - bodySerializer: | Array>>( - body: T, - ): string => { + bodySerializer: | Array>>(body: T): string => { const data = new URLSearchParams(); Object.entries(body).forEach(([key, value]) => { diff --git a/examples/openapi-ts-ky/src/client/core/params.gen.ts b/examples/openapi-ts-ky/src/client/core/params.gen.ts index 602715c46..6099cab1b 100644 --- a/examples/openapi-ts-ky/src/client/core/params.gen.ts +++ b/examples/openapi-ts-ky/src/client/core/params.gen.ts @@ -102,10 +102,7 @@ const stripEmptySlots = (params: Params) => { } }; -export const buildClientParams = ( - args: ReadonlyArray, - fields: FieldsConfig, -) => { +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, @@ -148,15 +145,11 @@ export const buildClientParams = ( params[field.map] = value; } } else { - const extra = extraPrefixes.find(([prefix]) => - key.startsWith(prefix), - ); + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; - (params[slot] as Record)[ - key.slice(prefix.length) - ] = value; + (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { diff --git a/examples/openapi-ts-ky/src/client/core/pathSerializer.gen.ts b/examples/openapi-ts-ky/src/client/core/pathSerializer.gen.ts index 8d9993104..994b2848c 100644 --- a/examples/openapi-ts-ky/src/client/core/pathSerializer.gen.ts +++ b/examples/openapi-ts-ky/src/client/core/pathSerializer.gen.ts @@ -1,8 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -interface SerializeOptions - extends SerializePrimitiveOptions, - SerializerOptions {} +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; @@ -105,9 +103,7 @@ export const serializeArrayParam = ({ }); }) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ @@ -146,11 +142,7 @@ export const serializeObjectParam = ({ if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { - values = [ - ...values, - key, - allowReserved ? (v as string) : encodeURIComponent(v as string), - ]; + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { @@ -175,7 +167,5 @@ export const serializeObjectParam = ({ }), ) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; diff --git a/examples/openapi-ts-ky/src/client/core/queryKeySerializer.gen.ts b/examples/openapi-ts-ky/src/client/core/queryKeySerializer.gen.ts index d3bb68396..5000df606 100644 --- a/examples/openapi-ts-ky/src/client/core/queryKeySerializer.gen.ts +++ b/examples/openapi-ts-ky/src/client/core/queryKeySerializer.gen.ts @@ -15,11 +15,7 @@ export type JsonValue = * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { @@ -61,9 +57,7 @@ const isPlainObject = (value: unknown): value is Record => { * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { - const entries = Array.from(params.entries()).sort(([a], [b]) => - a.localeCompare(b), - ); + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { @@ -86,26 +80,16 @@ const serializeSearchParams = (params: URLSearchParams): JsonValue => { /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ -export const serializeQueryKeyValue = ( - value: unknown, -): JsonValue | undefined => { +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } - if ( - typeof value === 'string' || - typeof value === 'number' || - typeof value === 'boolean' - ) { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } @@ -121,10 +105,7 @@ export const serializeQueryKeyValue = ( return stringifyToJsonValue(value); } - if ( - typeof URLSearchParams !== 'undefined' && - value instanceof URLSearchParams - ) { + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } diff --git a/examples/openapi-ts-ky/src/client/core/serverSentEvents.gen.ts b/examples/openapi-ts-ky/src/client/core/serverSentEvents.gen.ts index 343d25af8..6aa6cf02a 100644 --- a/examples/openapi-ts-ky/src/client/core/serverSentEvents.gen.ts +++ b/examples/openapi-ts-ky/src/client/core/serverSentEvents.gen.ts @@ -2,10 +2,7 @@ import type { Config } from './types.gen'; -export type ServerSentEventsOptions = Omit< - RequestInit, - 'method' -> & +export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom @@ -74,11 +71,7 @@ export interface StreamEvent { retry?: number; } -export type ServerSentEventsResult< - TData = unknown, - TReturn = void, - TNext = unknown, -> = { +export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, @@ -101,9 +94,7 @@ export const createSseClient = ({ }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; - const sleep = - sseSleepFn ?? - ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; @@ -141,16 +132,11 @@ export const createSseClient = ({ 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.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(); + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; @@ -188,10 +174,7 @@ export const createSseClient = ({ } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { - const parsed = Number.parseInt( - line.replace(/^retry:\s*/, ''), - 10, - ); + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } @@ -243,18 +226,12 @@ export const createSseClient = ({ // connection failed or aborted; retry after delay onSseError?.(error); - if ( - sseMaxRetryAttempts !== undefined && - attempt >= sseMaxRetryAttempts - ) { + 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, - ); + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } diff --git a/examples/openapi-ts-ky/src/client/core/types.gen.ts b/examples/openapi-ts-ky/src/client/core/types.gen.ts index 643c070c9..97463257e 100644 --- a/examples/openapi-ts-ky/src/client/core/types.gen.ts +++ b/examples/openapi-ts-ky/src/client/core/types.gen.ts @@ -1,11 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; -import type { - BodySerializer, - QuerySerializer, - QuerySerializerOptions, -} from './bodySerializer.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' @@ -34,9 +30,7 @@ export type Client< setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; -} & ([SseFn] extends [never] - ? { sse?: never } - : { sse: { [K in HttpMethod]: SseFn } }); +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** @@ -59,13 +53,7 @@ export interface Config { | RequestInit['headers'] | Record< string, - | string - | number - | boolean - | (string | number | boolean)[] - | null - | undefined - | unknown + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. @@ -112,7 +100,5 @@ type IsExactlyNeverOrNeverUndefined = [T] extends [never] : false; export type OmitNever> = { - [K in keyof T as IsExactlyNeverOrNeverUndefined extends true - ? never - : K]: T[K]; + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; diff --git a/examples/openapi-ts-ky/src/client/core/utils.gen.ts b/examples/openapi-ts-ky/src/client/core/utils.gen.ts index 0b5389d08..e7ddbe354 100644 --- a/examples/openapi-ts-ky/src/client/core/utils.gen.ts +++ b/examples/openapi-ts-ky/src/client/core/utils.gen.ts @@ -44,10 +44,7 @@ export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { } if (Array.isArray(value)) { - url = url.replace( - match, - serializeArrayParam({ explode, name, style, value }), - ); + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } diff --git a/examples/openapi-ts-ky/src/client/sdk.gen.ts b/examples/openapi-ts-ky/src/client/sdk.gen.ts index 6d9563cb0..1da3ca639 100644 --- a/examples/openapi-ts-ky/src/client/sdk.gen.ts +++ b/examples/openapi-ts-ky/src/client/sdk.gen.ts @@ -105,11 +105,7 @@ export const addPet = ( export const updatePet = ( options: Options, ) => - (options.client ?? client).put< - UpdatePetResponses, - UpdatePetErrors, - ThrowOnError - >({ + (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, @@ -127,11 +123,7 @@ export const updatePet = ( export const findPetsByStatus = ( options: Options, ) => - (options.client ?? client).get< - FindPetsByStatusResponses, - FindPetsByStatusErrors, - ThrowOnError - >({ + (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, @@ -145,11 +137,7 @@ export const findPetsByStatus = ( export const findPetsByTags = ( options: Options, ) => - (options.client ?? client).get< - FindPetsByTagsResponses, - FindPetsByTagsErrors, - ThrowOnError - >({ + (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, @@ -163,11 +151,7 @@ export const findPetsByTags = ( export const deletePet = ( options: Options, ) => - (options.client ?? client).delete< - DeletePetResponses, - DeletePetErrors, - ThrowOnError - >({ + (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, @@ -181,11 +165,7 @@ export const deletePet = ( export const getPetById = ( options: Options, ) => - (options.client ?? client).get< - GetPetByIdResponses, - GetPetByIdErrors, - ThrowOnError - >({ + (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, @@ -220,11 +200,7 @@ export const updatePetWithForm = ( export const uploadFile = ( options: Options, ) => - (options.client ?? client).post< - UploadFileResponses, - UploadFileErrors, - ThrowOnError - >({ + (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', @@ -243,11 +219,7 @@ export const uploadFile = ( export const getInventory = ( options?: Options, ) => - (options?.client ?? client).get< - GetInventoryResponses, - GetInventoryErrors, - ThrowOnError - >({ + (options?.client ?? client).get({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, @@ -261,11 +233,7 @@ export const getInventory = ( export const placeOrder = ( options?: Options, ) => - (options?.client ?? client).post< - PlaceOrderResponses, - PlaceOrderErrors, - ThrowOnError - >({ + (options?.client ?? client).post({ url: '/store/order', ...options, headers: { @@ -282,11 +250,10 @@ export const placeOrder = ( export const deleteOrder = ( options: Options, ) => - (options.client ?? client).delete< - DeleteOrderResponses, - DeleteOrderErrors, - ThrowOnError - >({ url: '/store/order/{orderId}', ...options }); + (options.client ?? client).delete({ + url: '/store/order/{orderId}', + ...options, + }); /** * Find purchase order by ID. @@ -296,11 +263,10 @@ export const deleteOrder = ( export const getOrderById = ( options: Options, ) => - (options.client ?? client).get< - GetOrderByIdResponses, - GetOrderByIdErrors, - ThrowOnError - >({ url: '/store/order/{orderId}', ...options }); + (options.client ?? client).get({ + url: '/store/order/{orderId}', + ...options, + }); /** * Create user. @@ -310,11 +276,7 @@ export const getOrderById = ( export const createUser = ( options?: Options, ) => - (options?.client ?? client).post< - CreateUserResponses, - CreateUserErrors, - ThrowOnError - >({ + (options?.client ?? client).post({ url: '/user', ...options, headers: { @@ -352,11 +314,10 @@ export const createUsersWithListInput = ( export const loginUser = ( options?: Options, ) => - (options?.client ?? client).get< - LoginUserResponses, - LoginUserErrors, - ThrowOnError - >({ url: '/user/login', ...options }); + (options?.client ?? client).get({ + url: '/user/login', + ...options, + }); /** * Logs out current logged in user session. @@ -366,11 +327,10 @@ export const loginUser = ( export const logoutUser = ( options?: Options, ) => - (options?.client ?? client).get< - LogoutUserResponses, - LogoutUserErrors, - ThrowOnError - >({ url: '/user/logout', ...options }); + (options?.client ?? client).get({ + url: '/user/logout', + ...options, + }); /** * Delete user resource. @@ -380,11 +340,10 @@ export const logoutUser = ( export const deleteUser = ( options: Options, ) => - (options.client ?? client).delete< - DeleteUserResponses, - DeleteUserErrors, - ThrowOnError - >({ url: '/user/{username}', ...options }); + (options.client ?? client).delete({ + url: '/user/{username}', + ...options, + }); /** * Get user by user name. @@ -394,11 +353,10 @@ export const deleteUser = ( export const getUserByName = ( options: Options, ) => - (options.client ?? client).get< - GetUserByNameResponses, - GetUserByNameErrors, - ThrowOnError - >({ url: '/user/{username}', ...options }); + (options.client ?? client).get({ + url: '/user/{username}', + ...options, + }); /** * Update user resource. @@ -408,11 +366,7 @@ export const getUserByName = ( export const updateUser = ( options: Options, ) => - (options.client ?? client).put< - UpdateUserResponses, - UpdateUserErrors, - ThrowOnError - >({ + (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { diff --git a/examples/openapi-ts-ky/src/client/types.gen.ts b/examples/openapi-ts-ky/src/client/types.gen.ts index a2e6be0fa..a8ea86379 100644 --- a/examples/openapi-ts-ky/src/client/types.gen.ts +++ b/examples/openapi-ts-ky/src/client/types.gen.ts @@ -167,8 +167,7 @@ export type FindPetsByStatusResponses = { 200: Array; }; -export type FindPetsByStatusResponse = - FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; +export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; @@ -200,8 +199,7 @@ export type FindPetsByTagsResponses = { 200: Array; }; -export type FindPetsByTagsResponse = - FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; +export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; @@ -378,8 +376,7 @@ export type GetInventoryResponses = { }; }; -export type GetInventoryResponse = - GetInventoryResponses[keyof GetInventoryResponses]; +export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; @@ -480,8 +477,7 @@ export type GetOrderByIdResponses = { 200: Order; }; -export type GetOrderByIdResponse = - GetOrderByIdResponses[keyof GetOrderByIdResponses]; +export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** @@ -658,8 +654,7 @@ export type GetUserByNameResponses = { 200: User; }; -export type GetUserByNameResponse = - GetUserByNameResponses[keyof GetUserByNameResponses]; +export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** diff --git a/examples/openapi-ts-next/app/layout.tsx b/examples/openapi-ts-next/app/layout.tsx index 774a3fd13..25e073166 100644 --- a/examples/openapi-ts-next/app/layout.tsx +++ b/examples/openapi-ts-next/app/layout.tsx @@ -36,11 +36,7 @@ export default function RootLayout({ }>) { return ( - - {children} - + {children} ); } diff --git a/examples/openapi-ts-next/app/page.tsx b/examples/openapi-ts-next/app/page.tsx index 6077403e5..c2701fcd2 100644 --- a/examples/openapi-ts-next/app/page.tsx +++ b/examples/openapi-ts-next/app/page.tsx @@ -85,13 +85,7 @@ export default function Home() { target="_blank" rel="noopener noreferrer" > - File icon + File icon Learn - Window icon + Window icon Examples - Globe icon + Globe icon Go to nextjs.org → diff --git a/examples/openapi-ts-next/app/pet/[id]/page.tsx b/examples/openapi-ts-next/app/pet/[id]/page.tsx index 3ca05ca6f..4059d32a0 100644 --- a/examples/openapi-ts-next/app/pet/[id]/page.tsx +++ b/examples/openapi-ts-next/app/pet/[id]/page.tsx @@ -23,11 +23,7 @@ async function getPet(id: string) { return pet; } -export async function generateMetadata({ - params, -}: { - params: Promise<{ id: string }>; -}) { +export async function generateMetadata({ params }: { params: Promise<{ id: string }> }) { const { id } = await params; const pet = await getPet(id); return { @@ -35,11 +31,7 @@ export async function generateMetadata({ }; } -export default async function Blog({ - params, -}: { - params: Promise<{ id: string }>; -}) { +export default async function Blog({ params }: { params: Promise<{ id: string }> }) { const { id } = await params; const pet = await getPet(id); @@ -79,13 +71,7 @@ export default async function Blog({ target="_blank" rel="noopener noreferrer" > - File icon + File icon Learn - Window icon + Window icon Examples - Globe icon + Globe icon Go to nextjs.org → diff --git a/examples/openapi-ts-next/package.json b/examples/openapi-ts-next/package.json index a98e302c5..74c9baac7 100644 --- a/examples/openapi-ts-next/package.json +++ b/examples/openapi-ts-next/package.json @@ -1,7 +1,7 @@ { "name": "@example/openapi-ts-next", - "private": true, "version": "0.1.13", + "private": true, "scripts": { "build": "next build", "dev": "next dev", diff --git a/examples/openapi-ts-next/src/client/client.gen.ts b/examples/openapi-ts-next/src/client/client.gen.ts index 321368cc7..9085c3bc7 100644 --- a/examples/openapi-ts-next/src/client/client.gen.ts +++ b/examples/openapi-ts-next/src/client/client.gen.ts @@ -1,12 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts import { createClientConfig } from '../hey-api'; -import { - type ClientOptions, - type Config, - createClient, - createConfig, -} from './client'; +import { type ClientOptions, type Config, createClient, createConfig } from './client'; import type { ClientOptions as ClientOptions2 } from './types.gen'; /** @@ -23,8 +18,6 @@ export type CreateClientConfig = ( export const client = createClient( createClientConfig( - createConfig({ - baseUrl: 'https://petstore3.swagger.io/api/v3', - }), + createConfig({ baseUrl: 'https://petstore3.swagger.io/api/v3' }), ), ); diff --git a/examples/openapi-ts-next/src/client/client/client.gen.ts b/examples/openapi-ts-next/src/client/client/client.gen.ts index 7ad3017a8..45519b96b 100644 --- a/examples/openapi-ts-next/src/client/client/client.gen.ts +++ b/examples/openapi-ts-next/src/client/client/client.gen.ts @@ -3,12 +3,7 @@ import { createSseClient } from '../core/serverSentEvents.gen'; import type { HttpMethod } from '../core/types.gen'; import { getValidRequestBody } from '../core/utils.gen'; -import type { - Client, - Config, - RequestOptions, - ResolvedRequestOptions, -} from './types.gen'; +import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen'; import { buildUrl, createConfig, @@ -34,11 +29,7 @@ export const createClient = (config: Config = {}): Client => { return getConfig(); }; - const interceptors = createInterceptors< - Response, - unknown, - ResolvedRequestOptions - >(); + const interceptors = createInterceptors(); const beforeRequest = async (options: RequestOptions) => { const opts = { @@ -111,10 +102,7 @@ export const createClient = (config: Config = {}): Client => { ? getParseAs(response.headers.get('Content-Type')) : opts.parseAs) ?? 'json'; - if ( - response.status === 204 || - response.headers.get('Content-Length') === '0' - ) { + if (response.status === 204 || response.headers.get('Content-Length') === '0') { let emptyData: any; switch (parseAs) { case 'arrayBuffer': @@ -207,40 +195,35 @@ export const createClient = (config: Config = {}): Client => { }; }; - const makeMethodFn = - (method: Uppercase) => (options: RequestOptions) => - request({ ...options, method }); + const makeMethodFn = (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); - const makeSseFn = - (method: Uppercase) => async (options: RequestOptions) => { - const { opts, url } = await beforeRequest(options); - return createSseClient({ - ...opts, - body: opts.body as BodyInit | null | undefined, - headers: opts.headers as unknown as Record, - method, - onRequest: async (url, init) => { - let request = new Request(url, init); - const requestInit = { - ...init, - method: init.method as Config['method'], - url, - }; - for (const fn of interceptors.request.fns) { - if (fn) { - await fn(requestInit); - request = new Request(requestInit.url, requestInit); - } + const makeSseFn = (method: Uppercase) => async (options: RequestOptions) => { + const { opts, url } = await beforeRequest(options); + return createSseClient({ + ...opts, + body: opts.body as BodyInit | null | undefined, + headers: opts.headers as unknown as Record, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + const requestInit = { + ...init, + method: init.method as Config['method'], + url, + }; + for (const fn of interceptors.request.fns) { + if (fn) { + await fn(requestInit); + request = new Request(requestInit.url, requestInit); } - return request; - }, - serializedBody: getValidRequestBody(opts) as - | BodyInit - | null - | undefined, - url, - }); - }; + } + return request; + }, + serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined, + url, + }); + }; return { buildUrl, diff --git a/examples/openapi-ts-next/src/client/client/types.gen.ts b/examples/openapi-ts-next/src/client/client/types.gen.ts index 9309ceeb7..6dcf29dca 100644 --- a/examples/openapi-ts-next/src/client/client/types.gen.ts +++ b/examples/openapi-ts-next/src/client/client/types.gen.ts @@ -1,19 +1,12 @@ // This file is auto-generated by @hey-api/openapi-ts import type { Auth } from '../core/auth.gen'; -import type { - ServerSentEventsOptions, - ServerSentEventsResult, -} from '../core/serverSentEvents.gen'; -import type { - Client as CoreClient, - Config as CoreConfig, -} from '../core/types.gen'; +import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen'; +import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen'; import type { Middleware } from './utils.gen'; export interface Config - extends Omit, - CoreConfig { + extends Omit, CoreConfig { /** * Base URL for all requests made by this client. */ @@ -33,14 +26,7 @@ export interface Config * * @default 'auto' */ - parseAs?: - | 'arrayBuffer' - | 'auto' - | 'blob' - | 'formData' - | 'json' - | 'stream' - | 'text'; + parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text'; /** * Throw an error instead of returning it in the response? * @@ -53,7 +39,9 @@ export interface RequestOptions< TData = unknown, ThrowOnError extends boolean = boolean, Url extends string = string, -> extends Config<{ +> + extends + Config<{ throwOnError: ThrowOnError; }>, Pick< @@ -98,16 +86,12 @@ export type RequestResult< : Promise< ( | { - data: TData extends Record - ? TData[keyof TData] - : TData; + data: TData extends Record ? TData[keyof TData] : TData; error: undefined; } | { data: undefined; - error: TError extends Record - ? TError[keyof TError] - : TError; + error: TError extends Record ? TError[keyof TError] : TError; } ) & { response: Response; @@ -119,27 +103,15 @@ export interface ClientOptions { throwOnError?: boolean; } -type MethodFn = < - TData = unknown, - TError = unknown, - ThrowOnError extends boolean = false, ->( +type MethodFn = ( options: Omit, 'method'>, ) => RequestResult; -type SseFn = < - TData = unknown, - TError = unknown, - ThrowOnError extends boolean = false, ->( +type SseFn = ( options: Omit, 'method'>, ) => Promise>; -type RequestFn = < - TData = unknown, - TError = unknown, - ThrowOnError extends boolean = false, ->( +type RequestFn = ( options: Omit, 'method'> & Pick>, 'method'>, ) => RequestResult; @@ -155,13 +127,7 @@ type BuildUrlFn = < options: TData & Options, ) => string; -export type Client = CoreClient< - RequestFn, - Config, - MethodFn, - BuildUrlFn, - SseFn -> & { +export type Client = CoreClient & { interceptors: Middleware; }; @@ -191,8 +157,5 @@ export type Options< TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, -> = OmitKeys< - RequestOptions, - 'body' | 'path' | 'query' | 'url' -> & +> = OmitKeys, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit); diff --git a/examples/openapi-ts-next/src/client/client/utils.gen.ts b/examples/openapi-ts-next/src/client/client/utils.gen.ts index 2f0c2b2d6..299a3d6f1 100644 --- a/examples/openapi-ts-next/src/client/client/utils.gen.ts +++ b/examples/openapi-ts-next/src/client/client/utils.gen.ts @@ -1,22 +1,14 @@ // This file is auto-generated by @hey-api/openapi-ts import { getAuthToken } from '../core/auth.gen'; -import type { - QuerySerializer, - QuerySerializerOptions, -} from '../core/bodySerializer.gen'; +import type { QuerySerializer, QuerySerializerOptions } from '../core/bodySerializer.gen'; import { jsonBodySerializer } from '../core/bodySerializer.gen'; import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from '../core/pathSerializer.gen'; -import type { - Client, - ClientOptions, - Config, - RequestOptions, -} from './types.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; interface PathSerializer { path: Record; @@ -58,10 +50,7 @@ const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { } if (Array.isArray(value)) { - url = url.replace( - match, - serializeArrayParam({ explode, name, style, value }), - ); + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } @@ -153,9 +142,7 @@ export const createQuerySerializer = ({ /** * Infers parseAs value from provided Content-Type header. */ -export const getParseAs = ( - contentType: string | null, -): Exclude => { +export const getParseAs = (contentType: string | null): Exclude => { 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. @@ -168,10 +155,7 @@ export const getParseAs = ( return; } - if ( - cleanContent.startsWith('application/json') || - cleanContent.endsWith('+json') - ) { + if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) { return 'json'; } @@ -180,9 +164,7 @@ export const getParseAs = ( } if ( - ['application/', 'audio/', 'image/', 'video/'].some((type) => - cleanContent.startsWith(type), - ) + ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type)) ) { return 'blob'; } @@ -318,10 +300,7 @@ export const mergeHeaders = ( continue; } - const iterator = - header instanceof Headers - ? headersEntries(header) - : Object.entries(header); + const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { @@ -351,10 +330,7 @@ type ErrInterceptor = ( type ReqInterceptor = (options: Options) => void | Promise; -type ResInterceptor = ( - response: Res, - options: Options, -) => Res | Promise; +type ResInterceptor = (response: Res, options: Options) => Res | Promise; class Interceptors { fns: Array = []; @@ -382,10 +358,7 @@ class Interceptors { return this.fns.indexOf(id); } - update( - id: number | Interceptor, - fn: Interceptor, - ): number | Interceptor | false { + update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false { const index = this.getInterceptorIndex(id); if (this.fns[index]) { this.fns[index] = fn; @@ -406,11 +379,7 @@ export interface Middleware { response: Interceptors>; } -export const createInterceptors = (): Middleware< - Res, - Err, - Options -> => ({ +export const createInterceptors = (): Middleware => ({ error: new Interceptors>(), request: new Interceptors>(), response: new Interceptors>(), diff --git a/examples/openapi-ts-next/src/client/core/auth.gen.ts b/examples/openapi-ts-next/src/client/core/auth.gen.ts index f8a73266f..3ebf99478 100644 --- a/examples/openapi-ts-next/src/client/core/auth.gen.ts +++ b/examples/openapi-ts-next/src/client/core/auth.gen.ts @@ -23,8 +23,7 @@ export const getAuthToken = async ( auth: Auth, callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, ): Promise => { - const token = - typeof callback === 'function' ? await callback(auth) : callback; + const token = typeof callback === 'function' ? await callback(auth) : callback; if (!token) { return; diff --git a/examples/openapi-ts-next/src/client/core/bodySerializer.gen.ts b/examples/openapi-ts-next/src/client/core/bodySerializer.gen.ts index 552b50f7c..8ad92c9ff 100644 --- a/examples/openapi-ts-next/src/client/core/bodySerializer.gen.ts +++ b/examples/openapi-ts-next/src/client/core/bodySerializer.gen.ts @@ -1,10 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -import type { - ArrayStyle, - ObjectStyle, - SerializerOptions, -} from './pathSerializer.gen'; +import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen'; export type QuerySerializer = (query: Record) => string; @@ -24,11 +20,7 @@ export type QuerySerializerOptions = QuerySerializerOptionsObject & { parameters?: Record; }; -const serializeFormDataPair = ( - data: FormData, - key: string, - value: unknown, -): void => { +const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => { if (typeof value === 'string' || value instanceof Blob) { data.append(key, value); } else if (value instanceof Date) { @@ -38,11 +30,7 @@ const serializeFormDataPair = ( } }; -const serializeUrlSearchParamsPair = ( - data: URLSearchParams, - key: string, - value: unknown, -): void => { +const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => { if (typeof value === 'string') { data.append(key, value); } else { @@ -73,15 +61,11 @@ export const formDataBodySerializer = { export const jsonBodySerializer = { bodySerializer: (body: T): string => - JSON.stringify(body, (_key, value) => - typeof value === 'bigint' ? value.toString() : value, - ), + JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)), }; export const urlSearchParamsBodySerializer = { - bodySerializer: | Array>>( - body: T, - ): string => { + bodySerializer: | Array>>(body: T): string => { const data = new URLSearchParams(); Object.entries(body).forEach(([key, value]) => { diff --git a/examples/openapi-ts-next/src/client/core/params.gen.ts b/examples/openapi-ts-next/src/client/core/params.gen.ts index 602715c46..6099cab1b 100644 --- a/examples/openapi-ts-next/src/client/core/params.gen.ts +++ b/examples/openapi-ts-next/src/client/core/params.gen.ts @@ -102,10 +102,7 @@ const stripEmptySlots = (params: Params) => { } }; -export const buildClientParams = ( - args: ReadonlyArray, - fields: FieldsConfig, -) => { +export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => { const params: Params = { body: {}, headers: {}, @@ -148,15 +145,11 @@ export const buildClientParams = ( params[field.map] = value; } } else { - const extra = extraPrefixes.find(([prefix]) => - key.startsWith(prefix), - ); + const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; - (params[slot] as Record)[ - key.slice(prefix.length) - ] = value; + (params[slot] as Record)[key.slice(prefix.length)] = value; } else if ('allowExtra' in config && config.allowExtra) { for (const [slot, allowed] of Object.entries(config.allowExtra)) { if (allowed) { diff --git a/examples/openapi-ts-next/src/client/core/pathSerializer.gen.ts b/examples/openapi-ts-next/src/client/core/pathSerializer.gen.ts index 8d9993104..994b2848c 100644 --- a/examples/openapi-ts-next/src/client/core/pathSerializer.gen.ts +++ b/examples/openapi-ts-next/src/client/core/pathSerializer.gen.ts @@ -1,8 +1,6 @@ // This file is auto-generated by @hey-api/openapi-ts -interface SerializeOptions - extends SerializePrimitiveOptions, - SerializerOptions {} +interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {} interface SerializePrimitiveOptions { allowReserved?: boolean; @@ -105,9 +103,7 @@ export const serializeArrayParam = ({ }); }) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; export const serializePrimitiveParam = ({ @@ -146,11 +142,7 @@ export const serializeObjectParam = ({ if (style !== 'deepObject' && !explode) { let values: string[] = []; Object.entries(value).forEach(([key, v]) => { - values = [ - ...values, - key, - allowReserved ? (v as string) : encodeURIComponent(v as string), - ]; + values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]; }); const joinedValues = values.join(','); switch (style) { @@ -175,7 +167,5 @@ export const serializeObjectParam = ({ }), ) .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; + return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues; }; diff --git a/examples/openapi-ts-next/src/client/core/queryKeySerializer.gen.ts b/examples/openapi-ts-next/src/client/core/queryKeySerializer.gen.ts index d3bb68396..5000df606 100644 --- a/examples/openapi-ts-next/src/client/core/queryKeySerializer.gen.ts +++ b/examples/openapi-ts-next/src/client/core/queryKeySerializer.gen.ts @@ -15,11 +15,7 @@ export type JsonValue = * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. */ export const queryKeyJsonReplacer = (_key: string, value: unknown) => { - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } if (typeof value === 'bigint') { @@ -61,9 +57,7 @@ const isPlainObject = (value: unknown): value is Record => { * Turns URLSearchParams into a sorted JSON object for deterministic keys. */ const serializeSearchParams = (params: URLSearchParams): JsonValue => { - const entries = Array.from(params.entries()).sort(([a], [b]) => - a.localeCompare(b), - ); + const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b)); const result: Record = {}; for (const [key, value] of entries) { @@ -86,26 +80,16 @@ const serializeSearchParams = (params: URLSearchParams): JsonValue => { /** * Normalizes any accepted value into a JSON-friendly shape for query keys. */ -export const serializeQueryKeyValue = ( - value: unknown, -): JsonValue | undefined => { +export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => { if (value === null) { return null; } - if ( - typeof value === 'string' || - typeof value === 'number' || - typeof value === 'boolean' - ) { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { + if (value === undefined || typeof value === 'function' || typeof value === 'symbol') { return undefined; } @@ -121,10 +105,7 @@ export const serializeQueryKeyValue = ( return stringifyToJsonValue(value); } - if ( - typeof URLSearchParams !== 'undefined' && - value instanceof URLSearchParams - ) { + if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) { return serializeSearchParams(value); } diff --git a/examples/openapi-ts-next/src/client/core/serverSentEvents.gen.ts b/examples/openapi-ts-next/src/client/core/serverSentEvents.gen.ts index 343d25af8..6aa6cf02a 100644 --- a/examples/openapi-ts-next/src/client/core/serverSentEvents.gen.ts +++ b/examples/openapi-ts-next/src/client/core/serverSentEvents.gen.ts @@ -2,10 +2,7 @@ import type { Config } from './types.gen'; -export type ServerSentEventsOptions = Omit< - RequestInit, - 'method' -> & +export type ServerSentEventsOptions = Omit & Pick & { /** * Fetch API implementation. You can use this option to provide a custom @@ -74,11 +71,7 @@ export interface StreamEvent { retry?: number; } -export type ServerSentEventsResult< - TData = unknown, - TReturn = void, - TNext = unknown, -> = { +export type ServerSentEventsResult = { stream: AsyncGenerator< TData extends Record ? TData[keyof TData] : TData, TReturn, @@ -101,9 +94,7 @@ export const createSseClient = ({ }: ServerSentEventsOptions): ServerSentEventsResult => { let lastEventId: string | undefined; - const sleep = - sseSleepFn ?? - ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); const createStream = async function* () { let retryDelay: number = sseDefaultRetryDelay ?? 3000; @@ -141,16 +132,11 @@ export const createSseClient = ({ 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.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(); + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let buffer = ''; @@ -188,10 +174,7 @@ export const createSseClient = ({ } else if (line.startsWith('id:')) { lastEventId = line.replace(/^id:\s*/, ''); } else if (line.startsWith('retry:')) { - const parsed = Number.parseInt( - line.replace(/^retry:\s*/, ''), - 10, - ); + const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10); if (!Number.isNaN(parsed)) { retryDelay = parsed; } @@ -243,18 +226,12 @@ export const createSseClient = ({ // connection failed or aborted; retry after delay onSseError?.(error); - if ( - sseMaxRetryAttempts !== undefined && - attempt >= sseMaxRetryAttempts - ) { + 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, - ); + const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000); await sleep(backoff); } } diff --git a/examples/openapi-ts-next/src/client/core/types.gen.ts b/examples/openapi-ts-next/src/client/core/types.gen.ts index 643c070c9..97463257e 100644 --- a/examples/openapi-ts-next/src/client/core/types.gen.ts +++ b/examples/openapi-ts-next/src/client/core/types.gen.ts @@ -1,11 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts import type { Auth, AuthToken } from './auth.gen'; -import type { - BodySerializer, - QuerySerializer, - QuerySerializerOptions, -} from './bodySerializer.gen'; +import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen'; export type HttpMethod = | 'connect' @@ -34,9 +30,7 @@ export type Client< setConfig: (config: Config) => Config; } & { [K in HttpMethod]: MethodFn; -} & ([SseFn] extends [never] - ? { sse?: never } - : { sse: { [K in HttpMethod]: SseFn } }); +} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } }); export interface Config { /** @@ -59,13 +53,7 @@ export interface Config { | RequestInit['headers'] | Record< string, - | string - | number - | boolean - | (string | number | boolean)[] - | null - | undefined - | unknown + string | number | boolean | (string | number | boolean)[] | null | undefined | unknown >; /** * The request method. @@ -112,7 +100,5 @@ type IsExactlyNeverOrNeverUndefined = [T] extends [never] : false; export type OmitNever> = { - [K in keyof T as IsExactlyNeverOrNeverUndefined extends true - ? never - : K]: T[K]; + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true ? never : K]: T[K]; }; diff --git a/examples/openapi-ts-next/src/client/core/utils.gen.ts b/examples/openapi-ts-next/src/client/core/utils.gen.ts index 0b5389d08..e7ddbe354 100644 --- a/examples/openapi-ts-next/src/client/core/utils.gen.ts +++ b/examples/openapi-ts-next/src/client/core/utils.gen.ts @@ -44,10 +44,7 @@ export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { } if (Array.isArray(value)) { - url = url.replace( - match, - serializeArrayParam({ explode, name, style, value }), - ); + url = url.replace(match, serializeArrayParam({ explode, name, style, value })); continue; } diff --git a/examples/openapi-ts-next/src/client/sdk.gen.ts b/examples/openapi-ts-next/src/client/sdk.gen.ts index 6d9563cb0..1da3ca639 100644 --- a/examples/openapi-ts-next/src/client/sdk.gen.ts +++ b/examples/openapi-ts-next/src/client/sdk.gen.ts @@ -105,11 +105,7 @@ export const addPet = ( export const updatePet = ( options: Options, ) => - (options.client ?? client).put< - UpdatePetResponses, - UpdatePetErrors, - ThrowOnError - >({ + (options.client ?? client).put({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet', ...options, @@ -127,11 +123,7 @@ export const updatePet = ( export const findPetsByStatus = ( options: Options, ) => - (options.client ?? client).get< - FindPetsByStatusResponses, - FindPetsByStatusErrors, - ThrowOnError - >({ + (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByStatus', ...options, @@ -145,11 +137,7 @@ export const findPetsByStatus = ( export const findPetsByTags = ( options: Options, ) => - (options.client ?? client).get< - FindPetsByTagsResponses, - FindPetsByTagsErrors, - ThrowOnError - >({ + (options.client ?? client).get({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/findByTags', ...options, @@ -163,11 +151,7 @@ export const findPetsByTags = ( export const deletePet = ( options: Options, ) => - (options.client ?? client).delete< - DeletePetResponses, - DeletePetErrors, - ThrowOnError - >({ + (options.client ?? client).delete({ security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}', ...options, @@ -181,11 +165,7 @@ export const deletePet = ( export const getPetById = ( options: Options, ) => - (options.client ?? client).get< - GetPetByIdResponses, - GetPetByIdErrors, - ThrowOnError - >({ + (options.client ?? client).get({ security: [ { name: 'api_key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }, @@ -220,11 +200,7 @@ export const updatePetWithForm = ( export const uploadFile = ( options: Options, ) => - (options.client ?? client).post< - UploadFileResponses, - UploadFileErrors, - ThrowOnError - >({ + (options.client ?? client).post({ bodySerializer: null, security: [{ scheme: 'bearer', type: 'http' }], url: '/pet/{petId}/uploadImage', @@ -243,11 +219,7 @@ export const uploadFile = ( export const getInventory = ( options?: Options, ) => - (options?.client ?? client).get< - GetInventoryResponses, - GetInventoryErrors, - ThrowOnError - >({ + (options?.client ?? client).get({ security: [{ name: 'api_key', type: 'apiKey' }], url: '/store/inventory', ...options, @@ -261,11 +233,7 @@ export const getInventory = ( export const placeOrder = ( options?: Options, ) => - (options?.client ?? client).post< - PlaceOrderResponses, - PlaceOrderErrors, - ThrowOnError - >({ + (options?.client ?? client).post({ url: '/store/order', ...options, headers: { @@ -282,11 +250,10 @@ export const placeOrder = ( export const deleteOrder = ( options: Options, ) => - (options.client ?? client).delete< - DeleteOrderResponses, - DeleteOrderErrors, - ThrowOnError - >({ url: '/store/order/{orderId}', ...options }); + (options.client ?? client).delete({ + url: '/store/order/{orderId}', + ...options, + }); /** * Find purchase order by ID. @@ -296,11 +263,10 @@ export const deleteOrder = ( export const getOrderById = ( options: Options, ) => - (options.client ?? client).get< - GetOrderByIdResponses, - GetOrderByIdErrors, - ThrowOnError - >({ url: '/store/order/{orderId}', ...options }); + (options.client ?? client).get({ + url: '/store/order/{orderId}', + ...options, + }); /** * Create user. @@ -310,11 +276,7 @@ export const getOrderById = ( export const createUser = ( options?: Options, ) => - (options?.client ?? client).post< - CreateUserResponses, - CreateUserErrors, - ThrowOnError - >({ + (options?.client ?? client).post({ url: '/user', ...options, headers: { @@ -352,11 +314,10 @@ export const createUsersWithListInput = ( export const loginUser = ( options?: Options, ) => - (options?.client ?? client).get< - LoginUserResponses, - LoginUserErrors, - ThrowOnError - >({ url: '/user/login', ...options }); + (options?.client ?? client).get({ + url: '/user/login', + ...options, + }); /** * Logs out current logged in user session. @@ -366,11 +327,10 @@ export const loginUser = ( export const logoutUser = ( options?: Options, ) => - (options?.client ?? client).get< - LogoutUserResponses, - LogoutUserErrors, - ThrowOnError - >({ url: '/user/logout', ...options }); + (options?.client ?? client).get({ + url: '/user/logout', + ...options, + }); /** * Delete user resource. @@ -380,11 +340,10 @@ export const logoutUser = ( export const deleteUser = ( options: Options, ) => - (options.client ?? client).delete< - DeleteUserResponses, - DeleteUserErrors, - ThrowOnError - >({ url: '/user/{username}', ...options }); + (options.client ?? client).delete({ + url: '/user/{username}', + ...options, + }); /** * Get user by user name. @@ -394,11 +353,10 @@ export const deleteUser = ( export const getUserByName = ( options: Options, ) => - (options.client ?? client).get< - GetUserByNameResponses, - GetUserByNameErrors, - ThrowOnError - >({ url: '/user/{username}', ...options }); + (options.client ?? client).get({ + url: '/user/{username}', + ...options, + }); /** * Update user resource. @@ -408,11 +366,7 @@ export const getUserByName = ( export const updateUser = ( options: Options, ) => - (options.client ?? client).put< - UpdateUserResponses, - UpdateUserErrors, - ThrowOnError - >({ + (options.client ?? client).put({ url: '/user/{username}', ...options, headers: { diff --git a/examples/openapi-ts-next/src/client/types.gen.ts b/examples/openapi-ts-next/src/client/types.gen.ts index a2e6be0fa..a8ea86379 100644 --- a/examples/openapi-ts-next/src/client/types.gen.ts +++ b/examples/openapi-ts-next/src/client/types.gen.ts @@ -167,8 +167,7 @@ export type FindPetsByStatusResponses = { 200: Array; }; -export type FindPetsByStatusResponse = - FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; +export type FindPetsByStatusResponse = FindPetsByStatusResponses[keyof FindPetsByStatusResponses]; export type FindPetsByTagsData = { body?: never; @@ -200,8 +199,7 @@ export type FindPetsByTagsResponses = { 200: Array; }; -export type FindPetsByTagsResponse = - FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; +export type FindPetsByTagsResponse = FindPetsByTagsResponses[keyof FindPetsByTagsResponses]; export type DeletePetData = { body?: never; @@ -378,8 +376,7 @@ export type GetInventoryResponses = { }; }; -export type GetInventoryResponse = - GetInventoryResponses[keyof GetInventoryResponses]; +export type GetInventoryResponse = GetInventoryResponses[keyof GetInventoryResponses]; export type PlaceOrderData = { body?: Order; @@ -480,8 +477,7 @@ export type GetOrderByIdResponses = { 200: Order; }; -export type GetOrderByIdResponse = - GetOrderByIdResponses[keyof GetOrderByIdResponses]; +export type GetOrderByIdResponse = GetOrderByIdResponses[keyof GetOrderByIdResponses]; export type CreateUserData = { /** @@ -658,8 +654,7 @@ export type GetUserByNameResponses = { 200: User; }; -export type GetUserByNameResponse = - GetUserByNameResponses[keyof GetUserByNameResponses]; +export type GetUserByNameResponse = GetUserByNameResponses[keyof GetUserByNameResponses]; export type UpdateUserData = { /** diff --git a/examples/openapi-ts-nuxt/components/home.vue b/examples/openapi-ts-nuxt/components/home.vue index 337e29bab..290045936 100644 --- a/examples/openapi-ts-nuxt/components/home.vue +++ b/examples/openapi-ts-nuxt/components/home.vue @@ -1,8 +1,7 @@