@hey-api/openapi-ts 0.0.0-next-20260205083026

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +381 -0
  3. package/bin/run.cmd +3 -0
  4. package/bin/run.js +18 -0
  5. package/dist/clients/angular/client.ts +237 -0
  6. package/dist/clients/angular/index.ts +23 -0
  7. package/dist/clients/angular/types.ts +231 -0
  8. package/dist/clients/angular/utils.ts +408 -0
  9. package/dist/clients/axios/client.ts +154 -0
  10. package/dist/clients/axios/index.ts +21 -0
  11. package/dist/clients/axios/types.ts +158 -0
  12. package/dist/clients/axios/utils.ts +206 -0
  13. package/dist/clients/core/auth.ts +39 -0
  14. package/dist/clients/core/bodySerializer.ts +82 -0
  15. package/dist/clients/core/params.ts +167 -0
  16. package/dist/clients/core/pathSerializer.ts +169 -0
  17. package/dist/clients/core/queryKeySerializer.ts +115 -0
  18. package/dist/clients/core/serverSentEvents.ts +241 -0
  19. package/dist/clients/core/types.ts +102 -0
  20. package/dist/clients/core/utils.ts +138 -0
  21. package/dist/clients/fetch/client.ts +286 -0
  22. package/dist/clients/fetch/index.ts +23 -0
  23. package/dist/clients/fetch/types.ts +211 -0
  24. package/dist/clients/fetch/utils.ts +314 -0
  25. package/dist/clients/ky/client.ts +318 -0
  26. package/dist/clients/ky/index.ts +24 -0
  27. package/dist/clients/ky/types.ts +243 -0
  28. package/dist/clients/ky/utils.ts +312 -0
  29. package/dist/clients/next/client.ts +253 -0
  30. package/dist/clients/next/index.ts +21 -0
  31. package/dist/clients/next/types.ts +162 -0
  32. package/dist/clients/next/utils.ts +413 -0
  33. package/dist/clients/nuxt/client.ts +213 -0
  34. package/dist/clients/nuxt/index.ts +22 -0
  35. package/dist/clients/nuxt/types.ts +189 -0
  36. package/dist/clients/nuxt/utils.ts +384 -0
  37. package/dist/clients/ofetch/client.ts +259 -0
  38. package/dist/clients/ofetch/index.ts +23 -0
  39. package/dist/clients/ofetch/types.ts +275 -0
  40. package/dist/clients/ofetch/utils.ts +504 -0
  41. package/dist/index.d.mts +8634 -0
  42. package/dist/index.d.mts.map +1 -0
  43. package/dist/index.mjs +4 -0
  44. package/dist/init-DlaW5Djq.mjs +13832 -0
  45. package/dist/init-DlaW5Djq.mjs.map +1 -0
  46. package/dist/internal.d.mts +33 -0
  47. package/dist/internal.d.mts.map +1 -0
  48. package/dist/internal.mjs +4 -0
  49. package/dist/run.d.mts +1 -0
  50. package/dist/run.mjs +60 -0
  51. package/dist/run.mjs.map +1 -0
  52. package/dist/src-BYA2YioO.mjs +225 -0
  53. package/dist/src-BYA2YioO.mjs.map +1 -0
  54. package/dist/types-Ba27ofyy.d.mts +157 -0
  55. package/dist/types-Ba27ofyy.d.mts.map +1 -0
  56. package/package.json +109 -0
@@ -0,0 +1,154 @@
1
+ import type { AxiosError, AxiosInstance, RawAxiosRequestHeaders } from 'axios';
2
+ import axios from 'axios';
3
+
4
+ import { createSseClient } from '../core/serverSentEvents';
5
+ import type { HttpMethod } from '../core/types';
6
+ import { getValidRequestBody } from '../core/utils';
7
+ import type { Client, Config, RequestOptions } from './types';
8
+ import { buildUrl, createConfig, mergeConfigs, mergeHeaders, setAuthParams } from './utils';
9
+
10
+ export const createClient = (config: Config = {}): Client => {
11
+ let _config = mergeConfigs(createConfig(), config);
12
+
13
+ let instance: AxiosInstance;
14
+
15
+ if (_config.axios && !('Axios' in _config.axios)) {
16
+ instance = _config.axios;
17
+ } else {
18
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
19
+ const { auth, ...configWithoutAuth } = _config;
20
+ instance = axios.create(configWithoutAuth);
21
+ }
22
+
23
+ const getConfig = (): Config => ({ ..._config });
24
+
25
+ const setConfig = (config: Config): Config => {
26
+ _config = mergeConfigs(_config, config);
27
+ instance.defaults = {
28
+ ...instance.defaults,
29
+ ..._config,
30
+ // @ts-expect-error
31
+ headers: mergeHeaders(instance.defaults.headers, _config.headers),
32
+ };
33
+ return getConfig();
34
+ };
35
+
36
+ const beforeRequest = async (options: RequestOptions) => {
37
+ const opts = {
38
+ ..._config,
39
+ ...options,
40
+ axios: options.axios ?? _config.axios ?? instance,
41
+ headers: mergeHeaders(_config.headers, options.headers),
42
+ };
43
+
44
+ if (opts.security) {
45
+ await setAuthParams({
46
+ ...opts,
47
+ security: opts.security,
48
+ });
49
+ }
50
+
51
+ if (opts.requestValidator) {
52
+ await opts.requestValidator(opts);
53
+ }
54
+
55
+ if (opts.body !== undefined && opts.bodySerializer) {
56
+ opts.body = opts.bodySerializer(opts.body);
57
+ }
58
+
59
+ const url = buildUrl(opts);
60
+
61
+ return { opts, url };
62
+ };
63
+
64
+ // @ts-expect-error
65
+ const request: Client['request'] = async (options) => {
66
+ // @ts-expect-error
67
+ const { opts, url } = await beforeRequest(options);
68
+ try {
69
+ // assign Axios here for consistency with fetch
70
+ const _axios = opts.axios!;
71
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
72
+ const { auth, ...optsWithoutAuth } = opts;
73
+ const response = await _axios({
74
+ ...optsWithoutAuth,
75
+ baseURL: '', // the baseURL is already included in `url`
76
+ data: getValidRequestBody(opts),
77
+ headers: opts.headers as RawAxiosRequestHeaders,
78
+ // let `paramsSerializer()` handle query params if it exists
79
+ params: opts.paramsSerializer ? opts.query : undefined,
80
+ url,
81
+ });
82
+
83
+ let { data } = response;
84
+
85
+ if (opts.responseType === 'json') {
86
+ if (opts.responseValidator) {
87
+ await opts.responseValidator(data);
88
+ }
89
+
90
+ if (opts.responseTransformer) {
91
+ data = await opts.responseTransformer(data);
92
+ }
93
+ }
94
+
95
+ return {
96
+ ...response,
97
+ data: data ?? {},
98
+ };
99
+ } catch (error) {
100
+ const e = error as AxiosError;
101
+ if (opts.throwOnError) {
102
+ throw e;
103
+ }
104
+ // @ts-expect-error
105
+ e.error = e.response?.data ?? {};
106
+ return e;
107
+ }
108
+ };
109
+
110
+ const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>
111
+ request({ ...options, method });
112
+
113
+ const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
114
+ const { opts, url } = await beforeRequest(options);
115
+ return createSseClient({
116
+ ...opts,
117
+ body: opts.body as BodyInit | null | undefined,
118
+ headers: opts.headers as Record<string, string>,
119
+ method,
120
+ serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,
121
+ // @ts-expect-error
122
+ signal: opts.signal,
123
+ url,
124
+ });
125
+ };
126
+
127
+ return {
128
+ buildUrl,
129
+ connect: makeMethodFn('CONNECT'),
130
+ delete: makeMethodFn('DELETE'),
131
+ get: makeMethodFn('GET'),
132
+ getConfig,
133
+ head: makeMethodFn('HEAD'),
134
+ instance,
135
+ options: makeMethodFn('OPTIONS'),
136
+ patch: makeMethodFn('PATCH'),
137
+ post: makeMethodFn('POST'),
138
+ put: makeMethodFn('PUT'),
139
+ request,
140
+ setConfig,
141
+ sse: {
142
+ connect: makeSseFn('CONNECT'),
143
+ delete: makeSseFn('DELETE'),
144
+ get: makeSseFn('GET'),
145
+ head: makeSseFn('HEAD'),
146
+ options: makeSseFn('OPTIONS'),
147
+ patch: makeSseFn('PATCH'),
148
+ post: makeSseFn('POST'),
149
+ put: makeSseFn('PUT'),
150
+ trace: makeSseFn('TRACE'),
151
+ },
152
+ trace: makeMethodFn('TRACE'),
153
+ } as Client;
154
+ };
@@ -0,0 +1,21 @@
1
+ export type { Auth } from '../core/auth';
2
+ export type { QuerySerializerOptions } from '../core/bodySerializer';
3
+ export {
4
+ formDataBodySerializer,
5
+ jsonBodySerializer,
6
+ urlSearchParamsBodySerializer,
7
+ } from '../core/bodySerializer';
8
+ export { buildClientParams } from '../core/params';
9
+ export { serializeQueryKeyValue } from '../core/queryKeySerializer';
10
+ export { createClient } from './client';
11
+ export type {
12
+ Client,
13
+ ClientOptions,
14
+ Config,
15
+ CreateClientConfig,
16
+ Options,
17
+ RequestOptions,
18
+ RequestResult,
19
+ TDataShape,
20
+ } from './types';
21
+ export { createConfig } from './utils';
@@ -0,0 +1,158 @@
1
+ import type {
2
+ AxiosError,
3
+ AxiosInstance,
4
+ AxiosRequestHeaders,
5
+ AxiosResponse,
6
+ AxiosStatic,
7
+ CreateAxiosDefaults,
8
+ } from 'axios';
9
+
10
+ import type { Auth } from '../core/auth';
11
+ import type {
12
+ ServerSentEventsOptions,
13
+ ServerSentEventsResult,
14
+ } from '../core/serverSentEvents';
15
+ import type { Client as CoreClient, Config as CoreConfig } from '../core/types';
16
+
17
+ export interface Config<T extends ClientOptions = ClientOptions>
18
+ extends Omit<CreateAxiosDefaults, 'auth' | 'baseURL' | 'headers' | 'method'>, CoreConfig {
19
+ /**
20
+ * Axios implementation. You can use this option to provide either an
21
+ * `AxiosStatic` or an `AxiosInstance`.
22
+ *
23
+ * @default axios
24
+ */
25
+ axios?: AxiosStatic | AxiosInstance;
26
+ /**
27
+ * Base URL for all requests made by this client.
28
+ */
29
+ baseURL?: T['baseURL'];
30
+ /**
31
+ * An object containing any HTTP headers that you want to pre-populate your
32
+ * `Headers` object with.
33
+ *
34
+ * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
35
+ */
36
+ headers?:
37
+ | AxiosRequestHeaders
38
+ | Record<
39
+ string,
40
+ string | number | boolean | (string | number | boolean)[] | null | undefined | unknown
41
+ >;
42
+ /**
43
+ * Throw an error instead of returning it in the response?
44
+ *
45
+ * @default false
46
+ */
47
+ throwOnError?: T['throwOnError'];
48
+ }
49
+
50
+ export interface RequestOptions<
51
+ TData = unknown,
52
+ ThrowOnError extends boolean = boolean,
53
+ Url extends string = string,
54
+ >
55
+ extends
56
+ Config<{
57
+ throwOnError: ThrowOnError;
58
+ }>,
59
+ Pick<
60
+ ServerSentEventsOptions<TData>,
61
+ | 'onSseError'
62
+ | 'onSseEvent'
63
+ | 'sseDefaultRetryDelay'
64
+ | 'sseMaxRetryAttempts'
65
+ | 'sseMaxRetryDelay'
66
+ > {
67
+ /**
68
+ * Any body that you want to add to your request.
69
+ *
70
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
71
+ */
72
+ body?: unknown;
73
+ path?: Record<string, unknown>;
74
+ query?: Record<string, unknown>;
75
+ /**
76
+ * Security mechanism(s) to use for the request.
77
+ */
78
+ security?: ReadonlyArray<Auth>;
79
+ url: Url;
80
+ }
81
+
82
+ export interface ClientOptions {
83
+ baseURL?: string;
84
+ throwOnError?: boolean;
85
+ }
86
+
87
+ export type RequestResult<
88
+ TData = unknown,
89
+ TError = unknown,
90
+ ThrowOnError extends boolean = boolean,
91
+ > = ThrowOnError extends true
92
+ ? Promise<AxiosResponse<TData extends Record<string, unknown> ? TData[keyof TData] : TData>>
93
+ : Promise<
94
+ | (AxiosResponse<TData extends Record<string, unknown> ? TData[keyof TData] : TData> & {
95
+ error: undefined;
96
+ })
97
+ | (AxiosError<TError extends Record<string, unknown> ? TError[keyof TError] : TError> & {
98
+ data: undefined;
99
+ error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
100
+ })
101
+ >;
102
+
103
+ type MethodFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false>(
104
+ options: Omit<RequestOptions<TData, ThrowOnError>, 'method'>,
105
+ ) => RequestResult<TData, TError, ThrowOnError>;
106
+
107
+ type SseFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false>(
108
+ options: Omit<RequestOptions<TData, ThrowOnError>, 'method'>,
109
+ ) => Promise<ServerSentEventsResult<TData, TError>>;
110
+
111
+ type RequestFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false>(
112
+ options: Omit<RequestOptions<TData, ThrowOnError>, 'method'> &
113
+ Pick<Required<RequestOptions<TData, ThrowOnError>>, 'method'>,
114
+ ) => RequestResult<TData, TError, ThrowOnError>;
115
+
116
+ type BuildUrlFn = <
117
+ TData extends {
118
+ body?: unknown;
119
+ path?: Record<string, unknown>;
120
+ query?: Record<string, unknown>;
121
+ url: string;
122
+ },
123
+ >(
124
+ options: TData & Options<TData>,
125
+ ) => string;
126
+
127
+ export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
128
+ instance: AxiosInstance;
129
+ };
130
+
131
+ /**
132
+ * The `createClientConfig()` function will be called on client initialization
133
+ * and the returned object will become the client's initial configuration.
134
+ *
135
+ * You may want to initialize your client this way instead of calling
136
+ * `setConfig()`. This is useful for example if you're using Next.js
137
+ * to ensure your client always has the correct values.
138
+ */
139
+ export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
140
+ override?: Config<ClientOptions & T>,
141
+ ) => Config<Required<ClientOptions> & T>;
142
+
143
+ export interface TDataShape {
144
+ body?: unknown;
145
+ headers?: unknown;
146
+ path?: unknown;
147
+ query?: unknown;
148
+ url: string;
149
+ }
150
+
151
+ type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
152
+
153
+ export type Options<
154
+ TData extends TDataShape = TDataShape,
155
+ ThrowOnError extends boolean = boolean,
156
+ TResponse = unknown,
157
+ > = OmitKeys<RequestOptions<TResponse, ThrowOnError>, 'body' | 'path' | 'query' | 'url'> &
158
+ ([TData] extends [never] ? unknown : Omit<TData, 'url'>);
@@ -0,0 +1,206 @@
1
+ import { getAuthToken } from '../core/auth';
2
+ import type { QuerySerializerOptions } from '../core/bodySerializer';
3
+ import {
4
+ serializeArrayParam,
5
+ serializeObjectParam,
6
+ serializePrimitiveParam,
7
+ } from '../core/pathSerializer';
8
+ import { getUrl } from '../core/utils';
9
+ import type { Client, ClientOptions, Config, RequestOptions } from './types';
10
+
11
+ export const createQuerySerializer = <T = unknown>({
12
+ parameters = {},
13
+ ...args
14
+ }: QuerySerializerOptions = {}) => {
15
+ const querySerializer = (queryParams: T) => {
16
+ const search: string[] = [];
17
+ if (queryParams && typeof queryParams === 'object') {
18
+ for (const name in queryParams) {
19
+ const value = queryParams[name];
20
+
21
+ if (value === undefined || value === null) {
22
+ continue;
23
+ }
24
+
25
+ const options = parameters[name] || args;
26
+
27
+ if (Array.isArray(value)) {
28
+ const serializedArray = serializeArrayParam({
29
+ allowReserved: options.allowReserved,
30
+ explode: true,
31
+ name,
32
+ style: 'form',
33
+ value,
34
+ ...options.array,
35
+ });
36
+ if (serializedArray) search.push(serializedArray);
37
+ } else if (typeof value === 'object') {
38
+ const serializedObject = serializeObjectParam({
39
+ allowReserved: options.allowReserved,
40
+ explode: true,
41
+ name,
42
+ style: 'deepObject',
43
+ value: value as Record<string, unknown>,
44
+ ...options.object,
45
+ });
46
+ if (serializedObject) search.push(serializedObject);
47
+ } else {
48
+ const serializedPrimitive = serializePrimitiveParam({
49
+ allowReserved: options.allowReserved,
50
+ name,
51
+ value: value as string,
52
+ });
53
+ if (serializedPrimitive) search.push(serializedPrimitive);
54
+ }
55
+ }
56
+ }
57
+ return search.join('&');
58
+ };
59
+ return querySerializer;
60
+ };
61
+
62
+ const checkForExistence = (
63
+ options: Pick<RequestOptions, 'auth' | 'query'> & {
64
+ headers: Record<any, unknown>;
65
+ },
66
+ name?: string,
67
+ ): boolean => {
68
+ if (!name) {
69
+ return false;
70
+ }
71
+ if (name in options.headers || options.query?.[name]) {
72
+ return true;
73
+ }
74
+ if (
75
+ 'Cookie' in options.headers &&
76
+ options.headers['Cookie'] &&
77
+ typeof options.headers['Cookie'] === 'string'
78
+ ) {
79
+ return options.headers['Cookie'].includes(`${name}=`);
80
+ }
81
+ return false;
82
+ };
83
+
84
+ export const setAuthParams = async ({
85
+ security,
86
+ ...options
87
+ }: Pick<Required<RequestOptions>, 'security'> &
88
+ Pick<RequestOptions, 'auth' | 'query'> & {
89
+ headers: Record<any, unknown>;
90
+ }) => {
91
+ for (const auth of security) {
92
+ if (checkForExistence(options, auth.name)) {
93
+ continue;
94
+ }
95
+ const token = await getAuthToken(auth, options.auth);
96
+
97
+ if (!token) {
98
+ continue;
99
+ }
100
+
101
+ const name = auth.name ?? 'Authorization';
102
+
103
+ switch (auth.in) {
104
+ case 'query':
105
+ if (!options.query) {
106
+ options.query = {};
107
+ }
108
+ options.query[name] = token;
109
+ break;
110
+ case 'cookie': {
111
+ const value = `${name}=${token}`;
112
+ if ('Cookie' in options.headers && options.headers['Cookie']) {
113
+ options.headers['Cookie'] = `${options.headers['Cookie']}; ${value}`;
114
+ } else {
115
+ options.headers['Cookie'] = value;
116
+ }
117
+ break;
118
+ }
119
+ case 'header':
120
+ default:
121
+ options.headers[name] = token;
122
+ break;
123
+ }
124
+ }
125
+ };
126
+
127
+ export const buildUrl: Client['buildUrl'] = (options) => {
128
+ const instanceBaseUrl = options.axios?.defaults?.baseURL;
129
+
130
+ const baseUrl =
131
+ !!options.baseURL && typeof options.baseURL === 'string' ? options.baseURL : instanceBaseUrl;
132
+
133
+ return getUrl({
134
+ baseUrl: baseUrl as string,
135
+ path: options.path,
136
+ // let `paramsSerializer()` handle query params if it exists
137
+ query: !options.paramsSerializer ? options.query : undefined,
138
+ querySerializer:
139
+ typeof options.querySerializer === 'function'
140
+ ? options.querySerializer
141
+ : createQuerySerializer(options.querySerializer),
142
+ url: options.url,
143
+ });
144
+ };
145
+
146
+ export const mergeConfigs = (a: Config, b: Config): Config => {
147
+ const config = { ...a, ...b };
148
+ config.headers = mergeHeaders(a.headers, b.headers);
149
+ return config;
150
+ };
151
+
152
+ /**
153
+ * Special Axios headers keywords allowing to set headers by request method.
154
+ */
155
+ export const axiosHeadersKeywords = [
156
+ 'common',
157
+ 'delete',
158
+ 'get',
159
+ 'head',
160
+ 'patch',
161
+ 'post',
162
+ 'put',
163
+ ] as const;
164
+
165
+ export const mergeHeaders = (
166
+ ...headers: Array<Required<Config>['headers'] | undefined>
167
+ ): Record<any, unknown> => {
168
+ const mergedHeaders: Record<any, unknown> = {};
169
+ for (const header of headers) {
170
+ if (!header || typeof header !== 'object') {
171
+ continue;
172
+ }
173
+
174
+ const iterator = Object.entries(header);
175
+
176
+ for (const [key, value] of iterator) {
177
+ if (
178
+ axiosHeadersKeywords.includes(key as (typeof axiosHeadersKeywords)[number]) &&
179
+ typeof value === 'object'
180
+ ) {
181
+ mergedHeaders[key] = {
182
+ ...(mergedHeaders[key] as Record<any, unknown>),
183
+ ...value,
184
+ };
185
+ } else if (value === null) {
186
+ delete mergedHeaders[key];
187
+ } else if (Array.isArray(value)) {
188
+ for (const v of value) {
189
+ // @ts-expect-error
190
+ mergedHeaders[key] = [...(mergedHeaders[key] ?? []), v as string];
191
+ }
192
+ } else if (value !== undefined) {
193
+ // assume object headers are meant to be JSON stringified, i.e. their
194
+ // content value in OpenAPI specification is 'application/json'
195
+ mergedHeaders[key] = typeof value === 'object' ? JSON.stringify(value) : (value as string);
196
+ }
197
+ }
198
+ }
199
+ return mergedHeaders;
200
+ };
201
+
202
+ export const createConfig = <T extends ClientOptions = ClientOptions>(
203
+ override: Config<Omit<ClientOptions, keyof T> & T> = {},
204
+ ): Config<Omit<ClientOptions, keyof T> & T> => ({
205
+ ...override,
206
+ });
@@ -0,0 +1,39 @@
1
+ export type AuthToken = string | undefined;
2
+
3
+ export interface Auth {
4
+ /**
5
+ * Which part of the request do we use to send the auth?
6
+ *
7
+ * @default 'header'
8
+ */
9
+ in?: 'header' | 'query' | 'cookie';
10
+ /**
11
+ * Header or query parameter name.
12
+ *
13
+ * @default 'Authorization'
14
+ */
15
+ name?: string;
16
+ scheme?: 'basic' | 'bearer';
17
+ type: 'apiKey' | 'http';
18
+ }
19
+
20
+ export const getAuthToken = async (
21
+ auth: Auth,
22
+ callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
23
+ ): Promise<string | undefined> => {
24
+ const token = typeof callback === 'function' ? await callback(auth) : callback;
25
+
26
+ if (!token) {
27
+ return;
28
+ }
29
+
30
+ if (auth.scheme === 'bearer') {
31
+ return `Bearer ${token}`;
32
+ }
33
+
34
+ if (auth.scheme === 'basic') {
35
+ return `Basic ${btoa(token)}`;
36
+ }
37
+
38
+ return token;
39
+ };
@@ -0,0 +1,82 @@
1
+ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer';
2
+
3
+ export type QuerySerializer = (query: Record<string, unknown>) => string;
4
+
5
+ export type BodySerializer = (body: any) => any;
6
+
7
+ type QuerySerializerOptionsObject = {
8
+ allowReserved?: boolean;
9
+ array?: Partial<SerializerOptions<ArrayStyle>>;
10
+ object?: Partial<SerializerOptions<ObjectStyle>>;
11
+ };
12
+
13
+ export type QuerySerializerOptions = QuerySerializerOptionsObject & {
14
+ /**
15
+ * Per-parameter serialization overrides. When provided, these settings
16
+ * override the global array/object settings for specific parameter names.
17
+ */
18
+ parameters?: Record<string, QuerySerializerOptionsObject>;
19
+ };
20
+
21
+ const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {
22
+ if (typeof value === 'string' || value instanceof Blob) {
23
+ data.append(key, value);
24
+ } else if (value instanceof Date) {
25
+ data.append(key, value.toISOString());
26
+ } else {
27
+ data.append(key, JSON.stringify(value));
28
+ }
29
+ };
30
+
31
+ const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => {
32
+ if (typeof value === 'string') {
33
+ data.append(key, value);
34
+ } else {
35
+ data.append(key, JSON.stringify(value));
36
+ }
37
+ };
38
+
39
+ export const formDataBodySerializer = {
40
+ bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
41
+ body: T,
42
+ ): FormData => {
43
+ const data = new FormData();
44
+
45
+ Object.entries(body).forEach(([key, value]) => {
46
+ if (value === undefined || value === null) {
47
+ return;
48
+ }
49
+ if (Array.isArray(value)) {
50
+ value.forEach((v) => serializeFormDataPair(data, key, v));
51
+ } else {
52
+ serializeFormDataPair(data, key, value);
53
+ }
54
+ });
55
+
56
+ return data;
57
+ },
58
+ };
59
+
60
+ export const jsonBodySerializer = {
61
+ bodySerializer: <T>(body: T): string =>
62
+ JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)),
63
+ };
64
+
65
+ export const urlSearchParamsBodySerializer = {
66
+ bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T): string => {
67
+ const data = new URLSearchParams();
68
+
69
+ Object.entries(body).forEach(([key, value]) => {
70
+ if (value === undefined || value === null) {
71
+ return;
72
+ }
73
+ if (Array.isArray(value)) {
74
+ value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
75
+ } else {
76
+ serializeUrlSearchParamsPair(data, key, value);
77
+ }
78
+ });
79
+
80
+ return data.toString();
81
+ },
82
+ };