diff --git a/examples/openapi-ts-pinia-colada/src/client/@pinia/colada.gen.ts b/examples/openapi-ts-pinia-colada/src/client/@pinia/colada.gen.ts
index 75aae1970c..f9291cf857 100644
--- a/examples/openapi-ts-pinia-colada/src/client/@pinia/colada.gen.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/@pinia/colada.gen.ts
@@ -1,9 +1,13 @@
// This file is auto-generated by @hey-api/openapi-ts
-import { type _JSONValue, defineQueryOptions, type UseMutationOptions } from '@pinia/colada'
+import {
+ type _JSONValue,
+ defineQueryOptions,
+ type UseMutationOptions,
+} from '@pinia/colada';
-import { serializeQueryKeyValue } from '../client'
-import { client } from '../client.gen'
+import { serializeQueryKeyValue } from '../client';
+import { client } from '../client.gen';
import {
addPet,
createUser,
@@ -24,8 +28,8 @@ import {
updatePet,
updatePetWithForm,
updateUser,
- uploadFile
-} from '../sdk.gen'
+ uploadFile,
+} from '../sdk.gen';
import type {
AddPetData,
AddPetResponse,
@@ -52,8 +56,8 @@ import type {
UpdatePetWithFormResponse,
UpdateUserData,
UploadFileData,
- UploadFileResponse
-} from '../types.gen'
+ UploadFileResponse,
+} from '../types.gen';
/**
* Add a new pet to the store.
@@ -61,17 +65,17 @@ import type {
* Add a new pet to the store.
*/
export const addPetMutation = (
- options?: Partial
>
+ options?: Partial>,
): UseMutationOptions, Error> => ({
mutation: async (vars) => {
const { data } = await addPet({
...options,
...vars,
- throwOnError: true
- })
- return data
- }
-})
+ throwOnError: true,
+ });
+ return data;
+ },
+});
/**
* Update an existing pet.
@@ -79,57 +83,58 @@ export const addPetMutation = (
* Update an existing pet by Id.
*/
export const updatePetMutation = (
- options?: Partial>
+ options?: Partial>,
): UseMutationOptions, Error> => ({
mutation: async (vars) => {
const { data } = await updatePet({
...options,
...vars,
- throwOnError: true
- })
- return data
- }
-})
+ throwOnError: true,
+ });
+ return data;
+ },
+});
export type QueryKey = [
Pick & {
- _id: string
- baseUrl?: _JSONValue
- body?: _JSONValue
- query?: _JSONValue
- tags?: _JSONValue
- }
-]
+ _id: string;
+ baseUrl?: _JSONValue;
+ body?: _JSONValue;
+ query?: _JSONValue;
+ tags?: _JSONValue;
+ },
+];
const createQueryKey = (
id: string,
options?: TOptions,
- tags?: ReadonlyArray
+ tags?: ReadonlyArray,
): [QueryKey[0]] => {
const params: QueryKey[0] = {
_id: id,
- baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl
- } as QueryKey[0]
+ baseUrl:
+ options?.baseUrl || (options?.client ?? client).getConfig().baseUrl,
+ } as QueryKey[0];
if (tags) {
- params.tags = tags as unknown as _JSONValue
+ params.tags = tags as unknown as _JSONValue;
}
if (options?.body !== undefined) {
- const normalizedBody = serializeQueryKeyValue(options.body)
+ const normalizedBody = serializeQueryKeyValue(options.body);
if (normalizedBody !== undefined) {
- params.body = normalizedBody
+ params.body = normalizedBody;
}
}
if (options?.path) {
- params.path = options.path
+ params.path = options.path;
}
if (options?.query !== undefined) {
- const normalizedQuery = serializeQueryKeyValue(options.query)
+ const normalizedQuery = serializeQueryKeyValue(options.query);
if (normalizedQuery !== undefined) {
- params.query = normalizedQuery
+ params.query = normalizedQuery;
}
}
- return [params]
-}
+ return [params];
+};
/**
* Finds Pets by status.
@@ -143,29 +148,31 @@ export const findPetsByStatusQuery = defineQueryOptions(
const { data } = await findPetsByStatus({
...options,
...context,
- throwOnError: true
- })
- return data
- }
- })
-)
+ throwOnError: true,
+ });
+ return data;
+ },
+ }),
+);
/**
* Finds Pets by tags.
*
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*/
-export const findPetsByTagsQuery = defineQueryOptions((options: Options) => ({
- key: createQueryKey('findPetsByTags', options),
- query: async (context) => {
- const { data } = await findPetsByTags({
- ...options,
- ...context,
- throwOnError: true
- })
- return data
- }
-}))
+export const findPetsByTagsQuery = defineQueryOptions(
+ (options: Options) => ({
+ key: createQueryKey('findPetsByTags', options),
+ query: async (context) => {
+ const { data } = await findPetsByTags({
+ ...options,
+ ...context,
+ throwOnError: true,
+ });
+ return data;
+ },
+ }),
+);
/**
* Deletes a pet.
@@ -173,34 +180,36 @@ export const findPetsByTagsQuery = defineQueryOptions((options: Options>
+ options?: Partial>,
): UseMutationOptions, Error> => ({
mutation: async (vars) => {
const { data } = await deletePet({
...options,
...vars,
- throwOnError: true
- })
- return data
- }
-})
+ throwOnError: true,
+ });
+ return data;
+ },
+});
/**
* Find pet by ID.
*
* Returns a single pet.
*/
-export const getPetByIdQuery = defineQueryOptions((options: Options) => ({
- key: createQueryKey('getPetById', options),
- query: async (context) => {
- const { data } = await getPetById({
- ...options,
- ...context,
- throwOnError: true
- })
- return data
- }
-}))
+export const getPetByIdQuery = defineQueryOptions(
+ (options: Options) => ({
+ key: createQueryKey('getPetById', options),
+ query: async (context) => {
+ const { data } = await getPetById({
+ ...options,
+ ...context,
+ throwOnError: true,
+ });
+ return data;
+ },
+ }),
+);
/**
* Updates a pet in the store with form data.
@@ -208,17 +217,21 @@ export const getPetByIdQuery = defineQueryOptions((options: Options>
-): UseMutationOptions, Error> => ({
+ options?: Partial>,
+): UseMutationOptions<
+ UpdatePetWithFormResponse,
+ Options,
+ Error
+> => ({
mutation: async (vars) => {
const { data } = await updatePetWithForm({
...options,
...vars,
- throwOnError: true
- })
- return data
- }
-})
+ throwOnError: true,
+ });
+ return data;
+ },
+});
/**
* Uploads an image.
@@ -226,34 +239,36 @@ export const updatePetWithFormMutation = (
* Upload image of the pet.
*/
export const uploadFileMutation = (
- options?: Partial>
+ options?: Partial>,
): UseMutationOptions, Error> => ({
mutation: async (vars) => {
const { data } = await uploadFile({
...options,
...vars,
- throwOnError: true
- })
- return data
- }
-})
+ throwOnError: true,
+ });
+ return data;
+ },
+});
/**
* Returns pet inventories by status.
*
* Returns a map of status codes to quantities.
*/
-export const getInventoryQuery = defineQueryOptions((options?: Options) => ({
- key: createQueryKey('getInventory', options),
- query: async (context) => {
- const { data } = await getInventory({
- ...options,
- ...context,
- throwOnError: true
- })
- return data
- }
-}))
+export const getInventoryQuery = defineQueryOptions(
+ (options?: Options) => ({
+ key: createQueryKey('getInventory', options),
+ query: async (context) => {
+ const { data } = await getInventory({
+ ...options,
+ ...context,
+ throwOnError: true,
+ });
+ return data;
+ },
+ }),
+);
/**
* Place an order for a pet.
@@ -261,17 +276,17 @@ export const getInventoryQuery = defineQueryOptions((options?: Options>
+ options?: Partial>,
): UseMutationOptions, Error> => ({
mutation: async (vars) => {
const { data } = await placeOrder({
...options,
...vars,
- throwOnError: true
- })
- return data
- }
-})
+ throwOnError: true,
+ });
+ return data;
+ },
+});
/**
* Delete purchase order by identifier.
@@ -279,34 +294,36 @@ export const placeOrderMutation = (
* For valid response try integer IDs with value < 1000. Anything above 1000 or non-integers will generate API errors.
*/
export const deleteOrderMutation = (
- options?: Partial>
+ options?: Partial>,
): UseMutationOptions, Error> => ({
mutation: async (vars) => {
const { data } = await deleteOrder({
...options,
...vars,
- throwOnError: true
- })
- return data
- }
-})
+ throwOnError: true,
+ });
+ return data;
+ },
+});
/**
* Find purchase order by ID.
*
* For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions.
*/
-export const getOrderByIdQuery = defineQueryOptions((options: Options) => ({
- key: createQueryKey('getOrderById', options),
- query: async (context) => {
- const { data } = await getOrderById({
- ...options,
- ...context,
- throwOnError: true
- })
- return data
- }
-}))
+export const getOrderByIdQuery = defineQueryOptions(
+ (options: Options) => ({
+ key: createQueryKey('getOrderById', options),
+ query: async (context) => {
+ const { data } = await getOrderById({
+ ...options,
+ ...context,
+ throwOnError: true,
+ });
+ return data;
+ },
+ }),
+);
/**
* Create user.
@@ -314,17 +331,17 @@ export const getOrderByIdQuery = defineQueryOptions((options: Options>
+ options?: Partial>,
): UseMutationOptions, Error> => ({
mutation: async (vars) => {
const { data } = await createUser({
...options,
...vars,
- throwOnError: true
- })
- return data
- }
-})
+ throwOnError: true,
+ });
+ return data;
+ },
+});
/**
* Creates list of users with given input array.
@@ -332,7 +349,7 @@ export const createUserMutation = (
* Creates list of users with given input array.
*/
export const createUsersWithListInputMutation = (
- options?: Partial>
+ options?: Partial>,
): UseMutationOptions<
CreateUsersWithListInputResponse,
Options,
@@ -342,45 +359,49 @@ export const createUsersWithListInputMutation = (
const { data } = await createUsersWithListInput({
...options,
...vars,
- throwOnError: true
- })
- return data
- }
-})
+ throwOnError: true,
+ });
+ return data;
+ },
+});
/**
* Logs user into the system.
*
* Log into the system.
*/
-export const loginUserQuery = defineQueryOptions((options?: Options) => ({
- key: createQueryKey('loginUser', options),
- query: async (context) => {
- const { data } = await loginUser({
- ...options,
- ...context,
- throwOnError: true
- })
- return data
- }
-}))
+export const loginUserQuery = defineQueryOptions(
+ (options?: Options) => ({
+ key: createQueryKey('loginUser', options),
+ query: async (context) => {
+ const { data } = await loginUser({
+ ...options,
+ ...context,
+ throwOnError: true,
+ });
+ return data;
+ },
+ }),
+);
/**
* Logs out current logged in user session.
*
* Log user out of the system.
*/
-export const logoutUserQuery = defineQueryOptions((options?: Options) => ({
- key: createQueryKey('logoutUser', options),
- query: async (context) => {
- const { data } = await logoutUser({
- ...options,
- ...context,
- throwOnError: true
- })
- return data
- }
-}))
+export const logoutUserQuery = defineQueryOptions(
+ (options?: Options) => ({
+ key: createQueryKey('logoutUser', options),
+ query: async (context) => {
+ const { data } = await logoutUser({
+ ...options,
+ ...context,
+ throwOnError: true,
+ });
+ return data;
+ },
+ }),
+);
/**
* Delete user resource.
@@ -388,34 +409,36 @@ export const logoutUserQuery = defineQueryOptions((options?: Options>
+ options?: Partial>,
): UseMutationOptions, Error> => ({
mutation: async (vars) => {
const { data } = await deleteUser({
...options,
...vars,
- throwOnError: true
- })
- return data
- }
-})
+ throwOnError: true,
+ });
+ return data;
+ },
+});
/**
* Get user by user name.
*
* Get user detail based on username.
*/
-export const getUserByNameQuery = defineQueryOptions((options: Options) => ({
- key: createQueryKey('getUserByName', options),
- query: async (context) => {
- const { data } = await getUserByName({
- ...options,
- ...context,
- throwOnError: true
- })
- return data
- }
-}))
+export const getUserByNameQuery = defineQueryOptions(
+ (options: Options) => ({
+ key: createQueryKey('getUserByName', options),
+ query: async (context) => {
+ const { data } = await getUserByName({
+ ...options,
+ ...context,
+ throwOnError: true,
+ });
+ return data;
+ },
+ }),
+);
/**
* Update user resource.
@@ -423,14 +446,14 @@ export const getUserByNameQuery = defineQueryOptions((options: Options>
+ options?: Partial>,
): UseMutationOptions, Error> => ({
mutation: async (vars) => {
const { data } = await updateUser({
...options,
...vars,
- throwOnError: true
- })
- return data
- }
-})
+ throwOnError: true,
+ });
+ return data;
+ },
+});
diff --git a/examples/openapi-ts-pinia-colada/src/client/client.gen.ts b/examples/openapi-ts-pinia-colada/src/client/client.gen.ts
index 1d374e90be..069f4dabab 100644
--- a/examples/openapi-ts-pinia-colada/src/client/client.gen.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/client.gen.ts
@@ -1,7 +1,12 @@
// This file is auto-generated by @hey-api/openapi-ts
-import { type ClientOptions, type Config, createClient, createConfig } from './client'
-import type { ClientOptions as ClientOptions2 } from './types.gen'
+import {
+ type ClientOptions,
+ type Config,
+ createClient,
+ createConfig,
+} from './client';
+import type { ClientOptions as ClientOptions2 } from './types.gen';
/**
* The `createClientConfig()` function will be called on client initialization
@@ -12,9 +17,11 @@ import type { ClientOptions as ClientOptions2 } from './types.gen'
* to ensure your client always has the correct values.
*/
export type CreateClientConfig = (
- override?: Config
-) => Config & T>
+ override?: Config,
+) => 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-pinia-colada/src/client/client/client.gen.ts b/examples/openapi-ts-pinia-colada/src/client/client/client.gen.ts
index 00dbae3997..c2a5190c22 100644
--- a/examples/openapi-ts-pinia-colada/src/client/client/client.gen.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/client/client.gen.ts
@@ -1,9 +1,14 @@
// This file is auto-generated by @hey-api/openapi-ts
-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 { 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 {
buildUrl,
createConfig,
@@ -11,25 +16,30 @@ import {
getParseAs,
mergeConfigs,
mergeHeaders,
- setAuthParams
-} from './utils.gen'
+ setAuthParams,
+} from './utils.gen';
type ReqInit = Omit & {
- body?: any
- headers: ReturnType
-}
+ body?: any;
+ headers: ReturnType;
+};
export const createClient = (config: Config = {}): Client => {
- let _config = mergeConfigs(createConfig(), config)
+ let _config = mergeConfigs(createConfig(), config);
- const getConfig = (): Config => ({ ..._config })
+ const getConfig = (): Config => ({ ..._config });
const setConfig = (config: Config): Config => {
- _config = mergeConfigs(_config, config)
- return getConfig()
- }
+ _config = mergeConfigs(_config, config);
+ return getConfig();
+ };
- const interceptors = createInterceptors()
+ const interceptors = createInterceptors<
+ Request,
+ Response,
+ unknown,
+ ResolvedRequestOptions
+ >();
const beforeRequest = async (options: RequestOptions) => {
const opts = {
@@ -37,72 +47,77 @@ export const createClient = (config: Config = {}): Client => {
...options,
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
headers: mergeHeaders(_config.headers, options.headers),
- serializedBody: undefined
- }
+ serializedBody: undefined,
+ };
if (opts.security) {
await setAuthParams({
...opts,
- security: opts.security
- })
+ security: opts.security,
+ });
}
if (opts.requestValidator) {
- await opts.requestValidator(opts)
+ await opts.requestValidator(opts);
}
if (opts.body !== undefined && opts.bodySerializer) {
- opts.serializedBody = opts.bodySerializer(opts.body)
+ opts.serializedBody = opts.bodySerializer(opts.body);
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.body === undefined || opts.serializedBody === '') {
- opts.headers.delete('Content-Type')
+ opts.headers.delete('Content-Type');
}
- const url = buildUrl(opts)
+ const url = buildUrl(opts);
- return { opts, url }
- }
+ return { opts, url };
+ };
const request: Client['request'] = async (options) => {
// @ts-expect-error
- const { opts, url } = await beforeRequest(options)
+ const { opts, url } = await beforeRequest(options);
const requestInit: ReqInit = {
redirect: 'follow',
...opts,
- body: getValidRequestBody(opts)
- }
+ body: getValidRequestBody(opts),
+ };
- let request = new Request(url, requestInit)
+ let request = new Request(url, requestInit);
for (const fn of interceptors.request.fns) {
if (fn) {
- request = await fn(request, opts)
+ request = await fn(request, opts);
}
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
- const _fetch = opts.fetch!
- let response: Response
+ const _fetch = opts.fetch!;
+ let response: Response;
try {
- response = await _fetch(request)
+ response = await _fetch(request);
} catch (error) {
// Handle fetch exceptions (AbortError, network errors, etc.)
- let finalError = error
+ let finalError = error;
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;
}
}
- finalError = finalError || ({} as unknown)
+ finalError = finalError || ({} as unknown);
if (opts.throwOnError) {
- throw finalError
+ throw finalError;
}
// Return error response
@@ -111,79 +126,82 @@ export const createClient = (config: Config = {}): Client => {
: {
error: finalError,
request,
- response: undefined as any
- }
+ response: undefined as any,
+ };
}
for (const fn of interceptors.response.fns) {
if (fn) {
- response = await fn(response, request, opts)
+ response = await fn(response, request, opts);
}
}
const result = {
request,
- response
- }
+ response,
+ };
if (response.ok) {
const parseAs =
(opts.parseAs === 'auto'
? getParseAs(response.headers.get('Content-Type'))
- : opts.parseAs) ?? 'json'
+ : opts.parseAs) ?? 'json';
- if (response.status === 204 || response.headers.get('Content-Length') === '0') {
- let emptyData: any
+ if (
+ response.status === 204 ||
+ response.headers.get('Content-Length') === '0'
+ ) {
+ let emptyData: any;
switch (parseAs) {
case 'arrayBuffer':
case 'blob':
case 'text':
- emptyData = await response[parseAs]()
- break
+ emptyData = await response[parseAs]();
+ break;
case 'formData':
- emptyData = new FormData()
- break
+ emptyData = new FormData();
+ break;
case 'stream':
- emptyData = response.body
- break
+ emptyData = response.body;
+ break;
case 'json':
default:
- emptyData = {}
- break
+ emptyData = {};
+ break;
}
return opts.responseStyle === 'data'
? emptyData
: {
data: emptyData,
- ...result
- }
+ ...result,
+ };
}
- let data: any
+ let data: any;
switch (parseAs) {
case 'arrayBuffer':
case 'blob':
case 'formData':
case 'json':
case 'text':
- data = await response[parseAs]()
- break
+ data = await response[parseAs]();
+ break;
case 'stream':
return opts.responseStyle === 'data'
? response.body
: {
data: response.body,
- ...result
- }
+ ...result,
+ };
}
if (parseAs === 'json') {
if (opts.responseValidator) {
- await opts.responseValidator(data)
+ await opts.responseValidator(data);
}
if (opts.responseTransformer) {
- data = await opts.responseTransformer(data)
+ data = await opts.responseTransformer(data);
}
}
@@ -191,32 +209,32 @@ export const createClient = (config: Config = {}): Client => {
? data
: {
data,
- ...result
- }
+ ...result,
+ };
}
- const textError = await response.text()
- let jsonError: unknown
+ const textError = await response.text();
+ let jsonError: unknown;
try {
- jsonError = JSON.parse(textError)
+ jsonError = JSON.parse(textError);
} catch {
// noop
}
- const error = jsonError ?? textError
- let finalError = error
+ const error = jsonError ?? textError;
+ let finalError = error;
for (const fn of interceptors.error.fns) {
if (fn) {
- finalError = (await fn(error, response, request, opts)) as string
+ finalError = (await fn(error, response, request, opts)) as string;
}
}
- finalError = finalError || ({} as string)
+ finalError = finalError || ({} as string);
if (opts.throwOnError) {
- throw finalError
+ throw finalError;
}
// TODO: we probably want to return error and improve types
@@ -224,32 +242,34 @@ export const createClient = (config: Config = {}): Client => {
? undefined
: {
error: finalError,
- ...result
- }
- }
-
- 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)
+ ...result,
+ };
+ };
+
+ 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);
+ }
}
- }
- return request
- },
- url
- })
- }
+ return request;
+ },
+ url,
+ });
+ };
return {
buildUrl,
@@ -274,8 +294,8 @@ export const createClient = (config: Config = {}): Client => {
patch: makeSseFn('PATCH'),
post: makeSseFn('POST'),
put: makeSseFn('PUT'),
- trace: makeSseFn('TRACE')
+ trace: makeSseFn('TRACE'),
},
- trace: makeMethodFn('TRACE')
- } as Client
-}
+ trace: makeMethodFn('TRACE'),
+ } as Client;
+};
diff --git a/examples/openapi-ts-pinia-colada/src/client/client/index.ts b/examples/openapi-ts-pinia-colada/src/client/client/index.ts
index 13cdecb802..b295edeca0 100644
--- a/examples/openapi-ts-pinia-colada/src/client/client/index.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/client/index.ts
@@ -1,15 +1,15 @@
// This file is auto-generated by @hey-api/openapi-ts
-export type { Auth } from '../core/auth.gen'
-export type { QuerySerializerOptions } from '../core/bodySerializer.gen'
+export type { Auth } from '../core/auth.gen';
+export type { QuerySerializerOptions } from '../core/bodySerializer.gen';
export {
formDataBodySerializer,
jsonBodySerializer,
- urlSearchParamsBodySerializer
-} from '../core/bodySerializer.gen'
-export { buildClientParams } from '../core/params.gen'
-export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'
-export { createClient } from './client.gen'
+ urlSearchParamsBodySerializer,
+} from '../core/bodySerializer.gen';
+export { buildClientParams } from '../core/params.gen';
+export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen';
+export { createClient } from './client.gen';
export type {
Client,
ClientOptions,
@@ -20,6 +20,6 @@ export type {
RequestResult,
ResolvedRequestOptions,
ResponseStyle,
- TDataShape
-} from './types.gen'
-export { createConfig, mergeHeaders } from './utils.gen'
+ TDataShape,
+} from './types.gen';
+export { createConfig, mergeHeaders } from './utils.gen';
diff --git a/examples/openapi-ts-pinia-colada/src/client/client/types.gen.ts b/examples/openapi-ts-pinia-colada/src/client/client/types.gen.ts
index 7ebb04c8c4..d2a28bc810 100644
--- a/examples/openapi-ts-pinia-colada/src/client/client/types.gen.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/client/types.gen.ts
@@ -1,33 +1,38 @@
// 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 { Middleware } from './utils.gen'
-
-export type ResponseStyle = 'data' | 'fields'
+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 { 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.
*/
- baseUrl?: T['baseUrl']
+ baseUrl?: T['baseUrl'];
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
- fetch?: typeof fetch
+ fetch?: typeof fetch;
/**
* Please don't use the Fetch client for Next.js applications. The `next`
* options won't have any effect.
*
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
*/
- next?: never
+ next?: never;
/**
* Return the response data parsed in a specified format. By default, `auto`
* will infer the appropriate method from the `Content-Type` response header.
@@ -36,29 +41,38 @@ 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.)?
*
* @default 'fields'
*/
- responseStyle?: ResponseStyle
+ responseStyle?: ResponseStyle;
/**
* Throw an error instead of returning it in the response?
*
* @default false
*/
- throwOnError?: T['throwOnError']
+ throwOnError?: T['throwOnError'];
}
export interface RequestOptions<
TData = unknown,
TResponseStyle extends ResponseStyle = 'fields',
ThrowOnError extends boolean = boolean,
- Url extends string = string
-> extends Config<{
- responseStyle: TResponseStyle
- throwOnError: ThrowOnError
+ Url extends string = string,
+>
+ extends
+ Config<{
+ responseStyle: TResponseStyle;
+ throwOnError: ThrowOnError;
}>,
Pick<
ServerSentEventsOptions,
@@ -73,29 +87,29 @@ export interface RequestOptions<
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
*/
- body?: unknown
- path?: Record
- query?: Record
+ body?: unknown;
+ path?: Record;
+ query?: Record;
/**
* Security mechanism(s) to use for the request.
*/
- security?: ReadonlyArray
- url: Url
+ security?: ReadonlyArray;
+ url: Url;
}
export interface ResolvedRequestOptions<
TResponseStyle extends ResponseStyle = 'fields',
ThrowOnError extends boolean = boolean,
- Url extends string = string
+ Url extends string = string,
> extends RequestOptions {
- serializedBody?: string
+ serializedBody?: string;
}
export type RequestResult<
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = boolean,
- TResponseStyle extends ResponseStyle = 'fields'
+ TResponseStyle extends ResponseStyle = 'fields',
> = ThrowOnError extends true
? Promise<
TResponseStyle extends 'data'
@@ -103,77 +117,96 @@ export type RequestResult<
? TData[keyof TData]
: TData
: {
- data: TData extends Record ? TData[keyof TData] : TData
- request: Request
- response: Response
+ 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
- error: undefined
+ data: TData extends Record
+ ? TData[keyof TData]
+ : TData;
+ error: undefined;
}
| {
- data: undefined
- error: TError extends Record ? TError[keyof TError] : TError
+ data: undefined;
+ error: TError extends Record
+ ? TError[keyof TError]
+ : TError;
}
) & {
- request: Request
- response: Response
+ request: Request;
+ response: Response;
}
- >
+ >;
export interface ClientOptions {
- baseUrl?: string
- responseStyle?: ResponseStyle
- throwOnError?: boolean
+ baseUrl?: string;
+ responseStyle?: ResponseStyle;
+ throwOnError?: boolean;
}
type MethodFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
- TResponseStyle extends ResponseStyle = 'fields'
+ TResponseStyle extends ResponseStyle = 'fields',
>(
- options: Omit, 'method'>
-) => RequestResult
+ options: Omit, 'method'>,
+) => RequestResult;
type SseFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
- TResponseStyle extends ResponseStyle = 'fields'
+ TResponseStyle extends ResponseStyle = 'fields',
>(
- options: Omit, 'method'>
-) => Promise>
+ options: Omit, 'method'>,
+) => Promise>;
type RequestFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
- TResponseStyle extends ResponseStyle = 'fields'
+ TResponseStyle extends ResponseStyle = 'fields',
>(
options: Omit, 'method'> &
- Pick>, 'method'>
-) => RequestResult
+ Pick<
+ Required>,
+ 'method'
+ >,
+) => RequestResult;
type BuildUrlFn = <
TData extends {
- body?: unknown
- path?: Record
- query?: Record
- url: string
- }
+ body?: unknown;
+ path?: Record;
+ query?: Record;
+ url: string;
+ },
>(
- options: TData & Options
-) => string
-
-export type Client = CoreClient & {
- interceptors: Middleware
-}
+ options: TData & Options,
+) => string;
+
+export type Client = CoreClient<
+ RequestFn,
+ Config,
+ MethodFn,
+ BuildUrlFn,
+ SseFn
+> & {
+ interceptors: Middleware;
+};
/**
* The `createClientConfig()` function will be called on client initialization
@@ -184,26 +217,26 @@ export type Client = CoreClient
* to ensure your client always has the correct values.
*/
export type CreateClientConfig = (
- override?: Config
-) => Config & T>
+ override?: Config,
+) => Config & T>;
export interface TDataShape {
- body?: unknown
- headers?: unknown
- path?: unknown
- query?: unknown
- url: string
+ body?: unknown;
+ headers?: unknown;
+ path?: unknown;
+ query?: unknown;
+ url: string;
}
-type OmitKeys = Pick>
+type OmitKeys = Pick>;
export type Options<
TData extends TDataShape = TDataShape,
ThrowOnError extends boolean = boolean,
TResponse = unknown,
- TResponseStyle extends ResponseStyle = 'fields'
+ TResponseStyle extends ResponseStyle = 'fields',
> = OmitKeys<
RequestOptions,
'body' | 'path' | 'query' | 'url'
> &
- ([TData] extends [never] ? unknown : Omit)
+ ([TData] extends [never] ? unknown : Omit);
diff --git a/examples/openapi-ts-pinia-colada/src/client/client/utils.gen.ts b/examples/openapi-ts-pinia-colada/src/client/client/utils.gen.ts
index ca2b3164a1..89416454b6 100644
--- a/examples/openapi-ts-pinia-colada/src/client/client/utils.gen.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/client/utils.gen.ts
@@ -1,31 +1,36 @@
// This file is auto-generated by @hey-api/openapi-ts
-import { getAuthToken } from '../core/auth.gen'
-import type { QuerySerializerOptions } from '../core/bodySerializer.gen'
-import { jsonBodySerializer } from '../core/bodySerializer.gen'
+import { getAuthToken } from '../core/auth.gen';
+import type { QuerySerializerOptions } from '../core/bodySerializer.gen';
+import { jsonBodySerializer } from '../core/bodySerializer.gen';
import {
serializeArrayParam,
serializeObjectParam,
- serializePrimitiveParam
-} from '../core/pathSerializer.gen'
-import { getUrl } from '../core/utils.gen'
-import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'
+ serializePrimitiveParam,
+} from '../core/pathSerializer.gen';
+import { getUrl } from '../core/utils.gen';
+import type {
+ Client,
+ ClientOptions,
+ Config,
+ RequestOptions,
+} from './types.gen';
export const createQuerySerializer = ({
parameters = {},
...args
}: QuerySerializerOptions = {}) => {
const querySerializer = (queryParams: T) => {
- const search: string[] = []
+ const search: string[] = [];
if (queryParams && typeof queryParams === 'object') {
for (const name in queryParams) {
- const value = queryParams[name]
+ const value = queryParams[name];
if (value === undefined || value === null) {
- continue
+ continue;
}
- const options = parameters[name] || args
+ const options = parameters[name] || args;
if (Array.isArray(value)) {
const serializedArray = serializeArrayParam({
@@ -34,9 +39,9 @@ export const createQuerySerializer = ({
name,
style: 'form',
value,
- ...options.array
- })
- if (serializedArray) search.push(serializedArray)
+ ...options.array,
+ });
+ if (serializedArray) search.push(serializedArray);
} else if (typeof value === 'object') {
const serializedObject = serializeObjectParam({
allowReserved: options.allowReserved,
@@ -44,117 +49,124 @@ export const createQuerySerializer = ({
name,
style: 'deepObject',
value: value as Record,
- ...options.object
- })
- if (serializedObject) search.push(serializedObject)
+ ...options.object,
+ });
+ if (serializedObject) search.push(serializedObject);
} else {
const serializedPrimitive = serializePrimitiveParam({
allowReserved: options.allowReserved,
name,
- value: value as string
- })
- if (serializedPrimitive) search.push(serializedPrimitive)
+ value: value as string,
+ });
+ if (serializedPrimitive) search.push(serializedPrimitive);
}
}
}
- return search.join('&')
- }
- return querySerializer
-}
+ return search.join('&');
+ };
+ return querySerializer;
+};
/**
* 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.
- return 'stream'
+ return 'stream';
}
- const cleanContent = contentType.split(';')[0]?.trim()
+ const cleanContent = contentType.split(';')[0]?.trim();
if (!cleanContent) {
- return
+ return;
}
- if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {
- return 'json'
+ if (
+ cleanContent.startsWith('application/json') ||
+ cleanContent.endsWith('+json')
+ ) {
+ return 'json';
}
if (cleanContent === 'multipart/form-data') {
- return 'formData'
+ return 'formData';
}
if (
- ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))
+ ['application/', 'audio/', 'image/', 'video/'].some((type) =>
+ cleanContent.startsWith(type),
+ )
) {
- return 'blob'
+ return 'blob';
}
if (cleanContent.startsWith('text/')) {
- return 'text'
+ return 'text';
}
- return
-}
+ return;
+};
const checkForExistence = (
options: Pick & {
- headers: Headers
+ headers: Headers;
},
- name?: string
+ name?: string,
): boolean => {
if (!name) {
- return false
+ return false;
}
if (
options.headers.has(name) ||
options.query?.[name] ||
options.headers.get('Cookie')?.includes(`${name}=`)
) {
- return true
+ return true;
}
- return false
-}
+ return false;
+};
export const setAuthParams = async ({
security,
...options
}: Pick, 'security'> &
Pick & {
- headers: Headers
+ headers: Headers;
}) => {
for (const auth of security) {
if (checkForExistence(options, auth.name)) {
- continue
+ continue;
}
- const token = await getAuthToken(auth, options.auth)
+ const token = await getAuthToken(auth, options.auth);
if (!token) {
- continue
+ continue;
}
- const name = auth.name ?? 'Authorization'
+ const name = auth.name ?? 'Authorization';
switch (auth.in) {
case 'query':
if (!options.query) {
- options.query = {}
+ options.query = {};
}
- options.query[name] = token
- break
+ options.query[name] = token;
+ break;
case 'cookie':
- options.headers.append('Cookie', `${name}=${token}`)
- break
+ options.headers.append('Cookie', `${name}=${token}`);
+ break;
case 'header':
default:
- options.headers.set(name, token)
- break
+ options.headers.set(name, token);
+ break;
}
}
-}
+};
export const buildUrl: Client['buildUrl'] = (options) =>
getUrl({
@@ -165,117 +177,126 @@ export const buildUrl: Client['buildUrl'] = (options) =>
typeof options.querySerializer === 'function'
? options.querySerializer
: createQuerySerializer(options.querySerializer),
- url: options.url
- })
+ url: options.url,
+ });
export const mergeConfigs = (a: Config, b: Config): Config => {
- const config = { ...a, ...b }
+ const config = { ...a, ...b };
if (config.baseUrl?.endsWith('/')) {
- config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1)
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
}
- config.headers = mergeHeaders(a.headers, b.headers)
- return config
-}
+ config.headers = mergeHeaders(a.headers, b.headers);
+ return config;
+};
const headersEntries = (headers: Headers): Array<[string, string]> => {
- const entries: Array<[string, string]> = []
+ const entries: Array<[string, string]> = [];
headers.forEach((value, key) => {
- entries.push([key, value])
- })
- return entries
-}
+ entries.push([key, value]);
+ });
+ return entries;
+};
export const mergeHeaders = (
...headers: Array['headers'] | undefined>
): Headers => {
- const mergedHeaders = new Headers()
+ const mergedHeaders = new Headers();
for (const header of headers) {
if (!header) {
- continue
+ 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) {
- mergedHeaders.delete(key)
+ mergedHeaders.delete(key);
} else if (Array.isArray(value)) {
for (const v of value) {
- mergedHeaders.append(key, v as string)
+ mergedHeaders.append(key, v as string);
}
} else if (value !== undefined) {
// assume object headers are meant to be JSON stringified, i.e. their
// content value in OpenAPI specification is 'application/json'
mergedHeaders.set(
key,
- typeof value === 'object' ? JSON.stringify(value) : (value as string)
- )
+ typeof value === 'object' ? JSON.stringify(value) : (value as string),
+ );
}
}
}
- return mergedHeaders
-}
+ return mergedHeaders;
+};
type ErrInterceptor = (
error: Err,
response: Res,
request: Req,
- options: Options
-) => Err | Promise
+ options: Options,
+) => Err | Promise;
-type ReqInterceptor = (request: Req, options: Options) => Req | Promise
+type ReqInterceptor = (
+ request: Req,
+ options: Options,
+) => Req | Promise;
type ResInterceptor = (
response: Res,
request: Req,
- options: Options
-) => Res | Promise
+ options: Options,
+) => Res | Promise;
class Interceptors {
- fns: Array = []
+ fns: Array = [];
clear(): void {
- this.fns = []
+ this.fns = [];
}
eject(id: number | Interceptor): void {
- const index = this.getInterceptorIndex(id)
+ const index = this.getInterceptorIndex(id);
if (this.fns[index]) {
- this.fns[index] = null
+ this.fns[index] = null;
}
}
exists(id: number | Interceptor): boolean {
- const index = this.getInterceptorIndex(id)
- return Boolean(this.fns[index])
+ const index = this.getInterceptorIndex(id);
+ return Boolean(this.fns[index]);
}
getInterceptorIndex(id: number | Interceptor): number {
if (typeof id === 'number') {
- return this.fns[id] ? id : -1
+ return this.fns[id] ? id : -1;
}
- return this.fns.indexOf(id)
+ return this.fns.indexOf(id);
}
- update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {
- const index = this.getInterceptorIndex(id)
+ update(
+ id: number | Interceptor,
+ fn: Interceptor,
+ ): number | Interceptor | false {
+ const index = this.getInterceptorIndex(id);
if (this.fns[index]) {
- this.fns[index] = fn
- return id
+ this.fns[index] = fn;
+ return id;
}
- return false
+ return false;
}
use(fn: Interceptor): number {
- this.fns.push(fn)
- return this.fns.length - 1
+ this.fns.push(fn);
+ return this.fns.length - 1;
}
}
export interface Middleware {
- error: Interceptors>
- request: Interceptors>
- response: Interceptors>
+ error: Interceptors>;
+ request: Interceptors>;
+ response: Interceptors>;
}
export const createInterceptors = (): Middleware<
@@ -286,31 +307,31 @@ export const createInterceptors = (): Middleware<
> => ({
error: new Interceptors>(),
request: new Interceptors>(),
- response: new Interceptors>()
-})
+ response: new Interceptors>(),
+});
const defaultQuerySerializer = createQuerySerializer({
allowReserved: false,
array: {
explode: true,
- style: 'form'
+ style: 'form',
},
object: {
explode: true,
- style: 'deepObject'
- }
-})
+ style: 'deepObject',
+ },
+});
const defaultHeaders = {
- 'Content-Type': 'application/json'
-}
+ 'Content-Type': 'application/json',
+};
export const createConfig = (
- override: Config & T> = {}
+ override: Config & T> = {},
): Config & T> => ({
...jsonBodySerializer,
headers: defaultHeaders,
parseAs: 'auto',
querySerializer: defaultQuerySerializer,
- ...override
-})
+ ...override,
+});
diff --git a/examples/openapi-ts-pinia-colada/src/client/core/auth.gen.ts b/examples/openapi-ts-pinia-colada/src/client/core/auth.gen.ts
index dc8ff61977..f8a73266f9 100644
--- a/examples/openapi-ts-pinia-colada/src/client/core/auth.gen.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/core/auth.gen.ts
@@ -1,6 +1,6 @@
// This file is auto-generated by @hey-api/openapi-ts
-export type AuthToken = string | undefined
+export type AuthToken = string | undefined;
export interface Auth {
/**
@@ -8,34 +8,35 @@ export interface Auth {
*
* @default 'header'
*/
- in?: 'header' | 'query' | 'cookie'
+ in?: 'header' | 'query' | 'cookie';
/**
* Header or query parameter name.
*
* @default 'Authorization'
*/
- name?: string
- scheme?: 'basic' | 'bearer'
- type: 'apiKey' | 'http'
+ name?: string;
+ scheme?: 'basic' | 'bearer';
+ type: 'apiKey' | 'http';
}
export const getAuthToken = async (
auth: Auth,
- callback: ((auth: Auth) => Promise | AuthToken) | AuthToken
+ 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
+ return;
}
if (auth.scheme === 'bearer') {
- return `Bearer ${token}`
+ return `Bearer ${token}`;
}
if (auth.scheme === 'basic') {
- return `Basic ${btoa(token)}`
+ return `Basic ${btoa(token)}`;
}
- return token
-}
+ return token;
+};
diff --git a/examples/openapi-ts-pinia-colada/src/client/core/bodySerializer.gen.ts b/examples/openapi-ts-pinia-colada/src/client/core/bodySerializer.gen.ts
index 09ffeb02af..552b50f7c8 100644
--- a/examples/openapi-ts-pinia-colada/src/client/core/bodySerializer.gen.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/core/bodySerializer.gen.ts
@@ -1,84 +1,100 @@
// 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
+export type QuerySerializer = (query: Record) => string;
-export type BodySerializer = (body: any) => any
+export type BodySerializer = (body: any) => any;
type QuerySerializerOptionsObject = {
- allowReserved?: boolean
- array?: Partial>
- object?: Partial>
-}
+ allowReserved?: boolean;
+ array?: Partial>;
+ object?: Partial>;
+};
export type QuerySerializerOptions = QuerySerializerOptionsObject & {
/**
* Per-parameter serialization overrides. When provided, these settings
* override the global array/object settings for specific parameter names.
*/
- parameters?: Record
-}
+ 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)
+ data.append(key, value);
} else if (value instanceof Date) {
- data.append(key, value.toISOString())
+ data.append(key, value.toISOString());
} else {
- data.append(key, JSON.stringify(value))
+ data.append(key, JSON.stringify(value));
}
-}
+};
-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)
+ data.append(key, value);
} else {
- data.append(key, JSON.stringify(value))
+ data.append(key, JSON.stringify(value));
}
-}
+};
export const formDataBodySerializer = {
bodySerializer: | Array>>(
- body: T
+ body: T,
): FormData => {
- const data = new FormData()
+ const data = new FormData();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
- return
+ return;
}
if (Array.isArray(value)) {
- value.forEach((v) => serializeFormDataPair(data, key, v))
+ value.forEach((v) => serializeFormDataPair(data, key, v));
} else {
- serializeFormDataPair(data, key, value)
+ serializeFormDataPair(data, key, value);
}
- })
+ });
- return data
- }
-}
+ return data;
+ },
+};
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 => {
- const data = new URLSearchParams()
+ bodySerializer: | Array>>(
+ body: T,
+ ): string => {
+ const data = new URLSearchParams();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
- return
+ return;
}
if (Array.isArray(value)) {
- value.forEach((v) => serializeUrlSearchParamsPair(data, key, v))
+ value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
} else {
- serializeUrlSearchParamsPair(data, key, value)
+ serializeUrlSearchParamsPair(data, key, value);
}
- })
+ });
- return data.toString()
- }
-}
+ return data.toString();
+ },
+};
diff --git a/examples/openapi-ts-pinia-colada/src/client/core/params.gen.ts b/examples/openapi-ts-pinia-colada/src/client/core/params.gen.ts
index 356b25dfc8..602715c46c 100644
--- a/examples/openapi-ts-pinia-colada/src/client/core/params.gen.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/core/params.gen.ts
@@ -1,70 +1,70 @@
// This file is auto-generated by @hey-api/openapi-ts
-type Slot = 'body' | 'headers' | 'path' | 'query'
+type Slot = 'body' | 'headers' | 'path' | 'query';
export type Field =
| {
- in: Exclude
+ in: Exclude;
/**
* Field name. This is the name we want the user to see and use.
*/
- key: string
+ key: string;
/**
* Field mapped name. This is the name we want to use in the request.
* If omitted, we use the same value as `key`.
*/
- map?: string
+ map?: string;
}
| {
- in: Extract
+ in: Extract;
/**
* Key isn't required for bodies.
*/
- key?: string
- map?: string
+ key?: string;
+ map?: string;
}
| {
/**
* Field name. This is the name we want the user to see and use.
*/
- key: string
+ key: string;
/**
* Field mapped name. This is the name we want to use in the request.
* If `in` is omitted, `map` aliases `key` to the transport layer.
*/
- map: Slot
- }
+ map: Slot;
+ };
export interface Fields {
- allowExtra?: Partial>
- args?: ReadonlyArray
+ allowExtra?: Partial>;
+ args?: ReadonlyArray;
}
-export type FieldsConfig = ReadonlyArray
+export type FieldsConfig = ReadonlyArray;
const extraPrefixesMap: Record = {
$body_: 'body',
$headers_: 'headers',
$path_: 'path',
- $query_: 'query'
-}
-const extraPrefixes = Object.entries(extraPrefixesMap)
+ $query_: 'query',
+};
+const extraPrefixes = Object.entries(extraPrefixesMap);
type KeyMap = Map<
string,
| {
- in: Slot
- map?: string
+ in: Slot;
+ map?: string;
}
| {
- in?: never
- map: Slot
+ in?: never;
+ map: Slot;
}
->
+>;
const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
if (!map) {
- map = new Map()
+ map = new Map();
}
for (const config of fields) {
@@ -72,89 +72,96 @@ const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
if (config.key) {
map.set(config.key, {
in: config.in,
- map: config.map
- })
+ map: config.map,
+ });
}
} else if ('key' in config) {
map.set(config.key, {
- map: config.map
- })
+ map: config.map,
+ });
} else if (config.args) {
- buildKeyMap(config.args, map)
+ buildKeyMap(config.args, map);
}
}
- return map
-}
+ return map;
+};
interface Params {
- body: unknown
- headers: Record
- path: Record
- query: Record
+ body: unknown;
+ headers: Record;
+ path: Record;
+ query: Record;
}
const stripEmptySlots = (params: Params) => {
for (const [slot, value] of Object.entries(params)) {
if (value && typeof value === 'object' && !Object.keys(value).length) {
- delete params[slot as Slot]
+ delete params[slot as Slot];
}
}
-}
+};
-export const buildClientParams = (args: ReadonlyArray, fields: FieldsConfig) => {
+export const buildClientParams = (
+ args: ReadonlyArray,
+ fields: FieldsConfig,
+) => {
const params: Params = {
body: {},
headers: {},
path: {},
- query: {}
- }
+ query: {},
+ };
- const map = buildKeyMap(fields)
+ const map = buildKeyMap(fields);
- let config: FieldsConfig[number] | undefined
+ let config: FieldsConfig[number] | undefined;
for (const [index, arg] of args.entries()) {
if (fields[index]) {
- config = fields[index]
+ config = fields[index];
}
if (!config) {
- continue
+ continue;
}
if ('in' in config) {
if (config.key) {
- const field = map.get(config.key)!
- const name = field.map || config.key
+ const field = map.get(config.key)!;
+ const name = field.map || config.key;
if (field.in) {
- ;(params[field.in] as Record)[name] = arg
+ (params[field.in] as Record)[name] = arg;
}
} else {
- params.body = arg
+ params.body = arg;
}
} else {
for (const [key, value] of Object.entries(arg ?? {})) {
- const field = map.get(key)
+ const field = map.get(key);
if (field) {
if (field.in) {
- const name = field.map || key
- ;(params[field.in] as Record)[name] = value
+ const name = field.map || key;
+ (params[field.in] as Record)[name] = value;
} else {
- params[field.map] = value
+ 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
+ const [prefix, slot] = extra;
+ (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) {
- ;(params[slot as Slot] as Record)[key] = value
- break
+ (params[slot as Slot] as Record)[key] = value;
+ break;
}
}
}
@@ -163,7 +170,7 @@ export const buildClientParams = (args: ReadonlyArray, fields: FieldsCo
}
}
- stripEmptySlots(params)
+ stripEmptySlots(params);
- return params
-}
+ return params;
+};
diff --git a/examples/openapi-ts-pinia-colada/src/client/core/pathSerializer.gen.ts b/examples/openapi-ts-pinia-colada/src/client/core/pathSerializer.gen.ts
index acc13672ee..4241e0a078 100644
--- a/examples/openapi-ts-pinia-colada/src/client/core/pathSerializer.gen.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/core/pathSerializer.gen.ts
@@ -1,128 +1,131 @@
// This file is auto-generated by @hey-api/openapi-ts
-interface SerializeOptions extends SerializePrimitiveOptions, SerializerOptions {}
+interface SerializeOptions
+ extends SerializePrimitiveOptions, SerializerOptions {}
interface SerializePrimitiveOptions {
- allowReserved?: boolean
- name: string
+ allowReserved?: boolean;
+ name: string;
}
export interface SerializerOptions {
/**
* @default true
*/
- explode: boolean
- style: T
+ explode: boolean;
+ style: T;
}
-export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'
-export type ArraySeparatorStyle = ArrayStyle | MatrixStyle
-type MatrixStyle = 'label' | 'matrix' | 'simple'
-export type ObjectStyle = 'form' | 'deepObject'
-type ObjectSeparatorStyle = ObjectStyle | MatrixStyle
+export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
+export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
+type MatrixStyle = 'label' | 'matrix' | 'simple';
+export type ObjectStyle = 'form' | 'deepObject';
+type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
- value: string
+ value: string;
}
export const separatorArrayExplode = (style: ArraySeparatorStyle) => {
switch (style) {
case 'label':
- return '.'
+ return '.';
case 'matrix':
- return ';'
+ return ';';
case 'simple':
- return ','
+ return ',';
default:
- return '&'
+ return '&';
}
-}
+};
export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {
switch (style) {
case 'form':
- return ','
+ return ',';
case 'pipeDelimited':
- return '|'
+ return '|';
case 'spaceDelimited':
- return '%20'
+ return '%20';
default:
- return ','
+ return ',';
}
-}
+};
export const separatorObjectExplode = (style: ObjectSeparatorStyle) => {
switch (style) {
case 'label':
- return '.'
+ return '.';
case 'matrix':
- return ';'
+ return ';';
case 'simple':
- return ','
+ return ',';
default:
- return '&'
+ return '&';
}
-}
+};
export const serializeArrayParam = ({
allowReserved,
explode,
name,
style,
- value
+ value,
}: SerializeOptions & {
- value: unknown[]
+ value: unknown[];
}) => {
if (!explode) {
const joinedValues = (
allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
- ).join(separatorArrayNoExplode(style))
+ ).join(separatorArrayNoExplode(style));
switch (style) {
case 'label':
- return `.${joinedValues}`
+ return `.${joinedValues}`;
case 'matrix':
- return `;${name}=${joinedValues}`
+ return `;${name}=${joinedValues}`;
case 'simple':
- return joinedValues
+ return joinedValues;
default:
- return `${name}=${joinedValues}`
+ return `${name}=${joinedValues}`;
}
}
- const separator = separatorArrayExplode(style)
+ const separator = separatorArrayExplode(style);
const joinedValues = value
.map((v) => {
if (style === 'label' || style === 'simple') {
- return allowReserved ? v : encodeURIComponent(v as string)
+ return allowReserved ? v : encodeURIComponent(v as string);
}
return serializePrimitiveParam({
allowReserved,
name,
- value: v as string
- })
+ value: v as string,
+ });
})
- .join(separator)
- return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues
-}
+ .join(separator);
+ return style === 'label' || style === 'matrix'
+ ? separator + joinedValues
+ : joinedValues;
+};
export const serializePrimitiveParam = ({
allowReserved,
name,
- value
+ value,
}: SerializePrimitiveParam) => {
if (value === undefined || value === null) {
- return ''
+ return '';
}
if (typeof value === 'object') {
throw new Error(
- 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.'
- )
+ 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',
+ );
}
- return `${name}=${allowReserved ? value : encodeURIComponent(value)}`
-}
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
+};
export const serializeObjectParam = ({
allowReserved,
@@ -130,42 +133,48 @@ export const serializeObjectParam = ({
name,
style,
value,
- valueOnly
+ valueOnly,
}: SerializeOptions & {
- value: Record | Date
- valueOnly?: boolean
+ value: Record | Date;
+ valueOnly?: boolean;
}) => {
if (value instanceof Date) {
- return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
}
if (style !== 'deepObject' && !explode) {
- let values: string[] = []
+ let values: string[] = [];
Object.entries(value).forEach(([key, v]) => {
- values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]
- })
- const joinedValues = values.join(',')
+ values = [
+ ...values,
+ key,
+ allowReserved ? (v as string) : encodeURIComponent(v as string),
+ ];
+ });
+ const joinedValues = values.join(',');
switch (style) {
case 'form':
- return `${name}=${joinedValues}`
+ return `${name}=${joinedValues}`;
case 'label':
- return `.${joinedValues}`
+ return `.${joinedValues}`;
case 'matrix':
- return `;${name}=${joinedValues}`
+ return `;${name}=${joinedValues}`;
default:
- return joinedValues
+ return joinedValues;
}
}
- const separator = separatorObjectExplode(style)
+ const separator = separatorObjectExplode(style);
const joinedValues = Object.entries(value)
.map(([key, v]) =>
serializePrimitiveParam({
allowReserved,
name: style === 'deepObject' ? `${name}[${key}]` : key,
- value: v as string
- })
+ value: v as string,
+ }),
)
- .join(separator)
- return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues
-}
+ .join(separator);
+ return style === 'label' || style === 'matrix'
+ ? separator + joinedValues
+ : joinedValues;
+};
diff --git a/examples/openapi-ts-pinia-colada/src/client/core/queryKeySerializer.gen.ts b/examples/openapi-ts-pinia-colada/src/client/core/queryKeySerializer.gen.ts
index 7e9d0d1ec8..d3bb68396e 100644
--- a/examples/openapi-ts-pinia-colada/src/client/core/queryKeySerializer.gen.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/core/queryKeySerializer.gen.ts
@@ -9,109 +9,128 @@ export type JsonValue =
| number
| boolean
| JsonValue[]
- | { [key: string]: JsonValue }
+ | { [key: string]: 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') {
- return undefined
+ if (
+ value === undefined ||
+ typeof value === 'function' ||
+ typeof value === 'symbol'
+ ) {
+ return undefined;
}
if (typeof value === 'bigint') {
- return value.toString()
+ return value.toString();
}
if (value instanceof Date) {
- return value.toISOString()
+ return value.toISOString();
}
- return value
-}
+ return value;
+};
/**
* Safely stringifies a value and parses it back into a JsonValue.
*/
export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => {
try {
- const json = JSON.stringify(input, queryKeyJsonReplacer)
+ const json = JSON.stringify(input, queryKeyJsonReplacer);
if (json === undefined) {
- return undefined
+ return undefined;
}
- return JSON.parse(json) as JsonValue
+ return JSON.parse(json) as JsonValue;
} catch {
- return undefined
+ return undefined;
}
-}
+};
/**
* Detects plain objects (including objects with a null prototype).
*/
const isPlainObject = (value: unknown): value is Record => {
if (value === null || typeof value !== 'object') {
- return false
+ return false;
}
- const prototype = Object.getPrototypeOf(value as object)
- return prototype === Object.prototype || prototype === null
-}
+ const prototype = Object.getPrototypeOf(value as object);
+ return prototype === Object.prototype || prototype === null;
+};
/**
* 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 result: Record = {}
+ const entries = Array.from(params.entries()).sort(([a], [b]) =>
+ a.localeCompare(b),
+ );
+ const result: Record = {};
for (const [key, value] of entries) {
- const existing = result[key]
+ const existing = result[key];
if (existing === undefined) {
- result[key] = value
- continue
+ result[key] = value;
+ continue;
}
if (Array.isArray(existing)) {
- ;(existing as string[]).push(value)
+ (existing as string[]).push(value);
} else {
- result[key] = [existing, value]
+ result[key] = [existing, value];
}
}
- return result
-}
+ return result;
+};
/**
* 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
+ return null;
}
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
- return value
+ if (
+ typeof value === 'string' ||
+ typeof value === 'number' ||
+ typeof value === 'boolean'
+ ) {
+ return value;
}
- if (value === undefined || typeof value === 'function' || typeof value === 'symbol') {
- return undefined
+ if (
+ value === undefined ||
+ typeof value === 'function' ||
+ typeof value === 'symbol'
+ ) {
+ return undefined;
}
if (typeof value === 'bigint') {
- return value.toString()
+ return value.toString();
}
if (value instanceof Date) {
- return value.toISOString()
+ return value.toISOString();
}
if (Array.isArray(value)) {
- return stringifyToJsonValue(value)
+ return stringifyToJsonValue(value);
}
- if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
- return serializeSearchParams(value)
+ if (
+ typeof URLSearchParams !== 'undefined' &&
+ value instanceof URLSearchParams
+ ) {
+ return serializeSearchParams(value);
}
if (isPlainObject(value)) {
- return stringifyToJsonValue(value)
+ return stringifyToJsonValue(value);
}
- return undefined
-}
+ return undefined;
+};
diff --git a/examples/openapi-ts-pinia-colada/src/client/core/serverSentEvents.gen.ts b/examples/openapi-ts-pinia-colada/src/client/core/serverSentEvents.gen.ts
index fa6a2fb66b..343d25af80 100644
--- a/examples/openapi-ts-pinia-colada/src/client/core/serverSentEvents.gen.ts
+++ b/examples/openapi-ts-pinia-colada/src/client/core/serverSentEvents.gen.ts
@@ -1,8 +1,11 @@
// This file is auto-generated by @hey-api/openapi-ts
-import type { Config } from './types.gen'
+import type { Config } from './types.gen';
-export type ServerSentEventsOptions = Omit &
+export type ServerSentEventsOptions = Omit<
+ RequestInit,
+ 'method'
+> &
Pick & {
/**
* Fetch API implementation. You can use this option to provide a custom
@@ -10,11 +13,11 @@ export type ServerSentEventsOptions = Omit Promise
+ onRequest?: (url: string, init: RequestInit) => Promise;
/**
* Callback invoked when a network or parsing error occurs during streaming.
*
@@ -22,7 +25,7 @@ export type ServerSentEventsOptions = Omit void
+ onSseError?: (error: unknown) => void;
/**
* Callback invoked when an event is streamed from the server.
*
@@ -31,8 +34,8 @@ export type ServerSentEventsOptions = Omit) => void
- serializedBody?: RequestInit['body']
+ onSseEvent?: (event: StreamEvent) => void;
+ serializedBody?: RequestInit['body'];
/**
* Default retry delay in milliseconds.
*
@@ -40,11 +43,11 @@ export type ServerSentEventsOptions = Omit = Omit Promise
- url: string
- }
+ sseSleepFn?: (ms: number) => Promise;
+ url: string;
+ };
export interface StreamEvent {
- data: TData
- event?: string
- id?: string
- retry?: number
+ data: TData;
+ event?: string;
+ id?: string;
+ retry?: number;
}
-export type ServerSentEventsResult = {
+export type ServerSentEventsResult<
+ TData = unknown,
+ TReturn = void,
+ TNext = unknown,
+> = {
stream: AsyncGenerator<
TData extends Record ? TData[keyof TData] : TData,
TReturn,
TNext
- >
-}
+ >;
+};
export const createSseClient = ({
onRequest,
@@ -92,27 +99,29 @@ export const createSseClient = ({
url,
...options
}: ServerSentEventsOptions): ServerSentEventsResult => {
- let lastEventId: string | undefined
+ 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
- let attempt = 0
- const signal = options.signal ?? new AbortController().signal
+ let retryDelay: number = sseDefaultRetryDelay ?? 3000;
+ let attempt = 0;
+ const signal = options.signal ?? new AbortController().signal;
while (true) {
- if (signal.aborted) break
+ if (signal.aborted) break;
- attempt++
+ attempt++;
const headers =
options.headers instanceof Headers
? options.headers
- : new Headers(options.headers as Record