@hey-api/openapi-ts 0.72.2 → 0.73.0

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 (40) hide show
  1. package/README.md +5 -12
  2. package/dist/chunk-QUDCWAFW.js +39 -0
  3. package/dist/chunk-QUDCWAFW.js.map +1 -0
  4. package/dist/clients/axios/client.ts +111 -0
  5. package/dist/clients/axios/index.ts +21 -0
  6. package/dist/clients/axios/types.ts +178 -0
  7. package/dist/clients/axios/utils.ts +286 -0
  8. package/dist/clients/core/auth.ts +40 -0
  9. package/dist/clients/core/bodySerializer.ts +84 -0
  10. package/dist/clients/core/params.ts +141 -0
  11. package/dist/clients/core/pathSerializer.ts +179 -0
  12. package/dist/clients/core/types.ts +98 -0
  13. package/dist/clients/fetch/client.ts +181 -0
  14. package/dist/clients/fetch/index.ts +22 -0
  15. package/dist/clients/fetch/types.ts +215 -0
  16. package/dist/clients/fetch/utils.ts +415 -0
  17. package/dist/clients/next/client.ts +163 -0
  18. package/dist/clients/next/index.ts +21 -0
  19. package/dist/clients/next/types.ts +166 -0
  20. package/dist/clients/next/utils.ts +404 -0
  21. package/dist/clients/nuxt/client.ts +145 -0
  22. package/dist/clients/nuxt/index.ts +22 -0
  23. package/dist/clients/nuxt/types.ts +192 -0
  24. package/dist/clients/nuxt/utils.ts +358 -0
  25. package/dist/index.cjs +63 -63
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.cts +6 -4
  28. package/dist/index.d.ts +6 -4
  29. package/dist/index.js +9 -9
  30. package/dist/index.js.map +1 -1
  31. package/dist/internal.cjs +10 -10
  32. package/dist/internal.cjs.map +1 -1
  33. package/dist/internal.d.cts +2 -2
  34. package/dist/internal.d.ts +2 -2
  35. package/dist/internal.js +1 -1
  36. package/dist/{types.d-DtkupL5A.d.cts → types.d-CAqtwzfv.d.cts} +16 -25
  37. package/dist/{types.d-DtkupL5A.d.ts → types.d-CAqtwzfv.d.ts} +16 -25
  38. package/package.json +4 -3
  39. package/dist/chunk-LC3ZVK3Y.js +0 -39
  40. package/dist/chunk-LC3ZVK3Y.js.map +0 -1
@@ -0,0 +1,404 @@
1
+ import { getAuthToken } from '../core/auth';
2
+ import type {
3
+ QuerySerializer,
4
+ QuerySerializerOptions,
5
+ } from '../core/bodySerializer';
6
+ import { jsonBodySerializer } from '../core/bodySerializer';
7
+ import {
8
+ serializeArrayParam,
9
+ serializeObjectParam,
10
+ serializePrimitiveParam,
11
+ } from '../core/pathSerializer';
12
+ import type { Client, ClientOptions, Config, RequestOptions } from './types';
13
+
14
+ interface PathSerializer {
15
+ path: Record<string, unknown>;
16
+ url: string;
17
+ }
18
+
19
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
20
+
21
+ type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
22
+ type MatrixStyle = 'label' | 'matrix' | 'simple';
23
+ type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
24
+
25
+ const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
26
+ let url = _url;
27
+ const matches = _url.match(PATH_PARAM_RE);
28
+ if (matches) {
29
+ for (const match of matches) {
30
+ let explode = false;
31
+ let name = match.substring(1, match.length - 1);
32
+ let style: ArraySeparatorStyle = 'simple';
33
+
34
+ if (name.endsWith('*')) {
35
+ explode = true;
36
+ name = name.substring(0, name.length - 1);
37
+ }
38
+
39
+ if (name.startsWith('.')) {
40
+ name = name.substring(1);
41
+ style = 'label';
42
+ } else if (name.startsWith(';')) {
43
+ name = name.substring(1);
44
+ style = 'matrix';
45
+ }
46
+
47
+ const value = path[name];
48
+
49
+ if (value === undefined || value === null) {
50
+ continue;
51
+ }
52
+
53
+ if (Array.isArray(value)) {
54
+ url = url.replace(
55
+ match,
56
+ serializeArrayParam({ explode, name, style, value }),
57
+ );
58
+ continue;
59
+ }
60
+
61
+ if (typeof value === 'object') {
62
+ url = url.replace(
63
+ match,
64
+ serializeObjectParam({
65
+ explode,
66
+ name,
67
+ style,
68
+ value: value as Record<string, unknown>,
69
+ valueOnly: true,
70
+ }),
71
+ );
72
+ continue;
73
+ }
74
+
75
+ if (style === 'matrix') {
76
+ url = url.replace(
77
+ match,
78
+ `;${serializePrimitiveParam({
79
+ name,
80
+ value: value as string,
81
+ })}`,
82
+ );
83
+ continue;
84
+ }
85
+
86
+ const replaceValue = encodeURIComponent(
87
+ style === 'label' ? `.${value as string}` : (value as string),
88
+ );
89
+ url = url.replace(match, replaceValue);
90
+ }
91
+ }
92
+ return url;
93
+ };
94
+
95
+ export const createQuerySerializer = <T = unknown>({
96
+ allowReserved,
97
+ array,
98
+ object,
99
+ }: QuerySerializerOptions = {}) => {
100
+ const querySerializer = (queryParams: T) => {
101
+ const search: string[] = [];
102
+ if (queryParams && typeof queryParams === 'object') {
103
+ for (const name in queryParams) {
104
+ const value = queryParams[name];
105
+
106
+ if (value === undefined || value === null) {
107
+ continue;
108
+ }
109
+
110
+ if (Array.isArray(value)) {
111
+ const serializedArray = serializeArrayParam({
112
+ allowReserved,
113
+ explode: true,
114
+ name,
115
+ style: 'form',
116
+ value,
117
+ ...array,
118
+ });
119
+ if (serializedArray) search.push(serializedArray);
120
+ } else if (typeof value === 'object') {
121
+ const serializedObject = serializeObjectParam({
122
+ allowReserved,
123
+ explode: true,
124
+ name,
125
+ style: 'deepObject',
126
+ value: value as Record<string, unknown>,
127
+ ...object,
128
+ });
129
+ if (serializedObject) search.push(serializedObject);
130
+ } else {
131
+ const serializedPrimitive = serializePrimitiveParam({
132
+ allowReserved,
133
+ name,
134
+ value: value as string,
135
+ });
136
+ if (serializedPrimitive) search.push(serializedPrimitive);
137
+ }
138
+ }
139
+ }
140
+ return search.join('&');
141
+ };
142
+ return querySerializer;
143
+ };
144
+
145
+ /**
146
+ * Infers parseAs value from provided Content-Type header.
147
+ */
148
+ export const getParseAs = (
149
+ contentType: string | null,
150
+ ): Exclude<Config['parseAs'], 'auto'> => {
151
+ if (!contentType) {
152
+ // If no Content-Type header is provided, the best we can do is return the raw response body,
153
+ // which is effectively the same as the 'stream' option.
154
+ return 'stream';
155
+ }
156
+
157
+ const cleanContent = contentType.split(';')[0]?.trim();
158
+
159
+ if (!cleanContent) {
160
+ return;
161
+ }
162
+
163
+ if (
164
+ cleanContent.startsWith('application/json') ||
165
+ cleanContent.endsWith('+json')
166
+ ) {
167
+ return 'json';
168
+ }
169
+
170
+ if (cleanContent === 'multipart/form-data') {
171
+ return 'formData';
172
+ }
173
+
174
+ if (
175
+ ['application/', 'audio/', 'image/', 'video/'].some((type) =>
176
+ cleanContent.startsWith(type),
177
+ )
178
+ ) {
179
+ return 'blob';
180
+ }
181
+
182
+ if (cleanContent.startsWith('text/')) {
183
+ return 'text';
184
+ }
185
+ };
186
+
187
+ export const setAuthParams = async ({
188
+ security,
189
+ ...options
190
+ }: Pick<Required<RequestOptions>, 'security'> &
191
+ Pick<RequestOptions, 'auth' | 'query'> & {
192
+ headers: Headers;
193
+ }) => {
194
+ for (const auth of security) {
195
+ const token = await getAuthToken(auth, options.auth);
196
+
197
+ if (!token) {
198
+ continue;
199
+ }
200
+
201
+ const name = auth.name ?? 'Authorization';
202
+
203
+ switch (auth.in) {
204
+ case 'query':
205
+ if (!options.query) {
206
+ options.query = {};
207
+ }
208
+ options.query[name] = token;
209
+ break;
210
+ case 'cookie':
211
+ options.headers.append('Cookie', `${name}=${token}`);
212
+ break;
213
+ case 'header':
214
+ default:
215
+ options.headers.set(name, token);
216
+ break;
217
+ }
218
+
219
+ return;
220
+ }
221
+ };
222
+
223
+ export const buildUrl: Client['buildUrl'] = (options) => {
224
+ const url = getUrl({
225
+ baseUrl: options.baseUrl as string,
226
+ path: options.path,
227
+ query: options.query,
228
+ querySerializer:
229
+ typeof options.querySerializer === 'function'
230
+ ? options.querySerializer
231
+ : createQuerySerializer(options.querySerializer),
232
+ url: options.url,
233
+ });
234
+ return url;
235
+ };
236
+
237
+ export const getUrl = ({
238
+ baseUrl,
239
+ path,
240
+ query,
241
+ querySerializer,
242
+ url: _url,
243
+ }: {
244
+ baseUrl?: string;
245
+ path?: Record<string, unknown>;
246
+ query?: Record<string, unknown>;
247
+ querySerializer: QuerySerializer;
248
+ url: string;
249
+ }) => {
250
+ const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
251
+ let url = (baseUrl ?? '') + pathUrl;
252
+ if (path) {
253
+ url = defaultPathSerializer({ path, url });
254
+ }
255
+ let search = query ? querySerializer(query) : '';
256
+ if (search.startsWith('?')) {
257
+ search = search.substring(1);
258
+ }
259
+ if (search) {
260
+ url += `?${search}`;
261
+ }
262
+ return url;
263
+ };
264
+
265
+ export const mergeConfigs = (a: Config, b: Config): Config => {
266
+ const config = { ...a, ...b };
267
+ if (config.baseUrl?.endsWith('/')) {
268
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
269
+ }
270
+ config.headers = mergeHeaders(a.headers, b.headers);
271
+ return config;
272
+ };
273
+
274
+ export const mergeHeaders = (
275
+ ...headers: Array<Required<Config>['headers'] | undefined>
276
+ ): Headers => {
277
+ const mergedHeaders = new Headers();
278
+ for (const header of headers) {
279
+ if (!header || typeof header !== 'object') {
280
+ continue;
281
+ }
282
+
283
+ const iterator =
284
+ header instanceof Headers ? header.entries() : Object.entries(header);
285
+
286
+ for (const [key, value] of iterator) {
287
+ if (value === null) {
288
+ mergedHeaders.delete(key);
289
+ } else if (Array.isArray(value)) {
290
+ for (const v of value) {
291
+ mergedHeaders.append(key, v as string);
292
+ }
293
+ } else if (value !== undefined) {
294
+ // assume object headers are meant to be JSON stringified, i.e. their
295
+ // content value in OpenAPI specification is 'application/json'
296
+ mergedHeaders.set(
297
+ key,
298
+ typeof value === 'object' ? JSON.stringify(value) : (value as string),
299
+ );
300
+ }
301
+ }
302
+ }
303
+ return mergedHeaders;
304
+ };
305
+
306
+ type ErrInterceptor<Err, Res, Options> = (
307
+ error: Err,
308
+ response: Res,
309
+ options: Options,
310
+ ) => Err | Promise<Err>;
311
+
312
+ type ReqInterceptor<Options> = (options: Options) => void | Promise<void>;
313
+
314
+ type ResInterceptor<Res, Options> = (
315
+ response: Res,
316
+ options: Options,
317
+ ) => Res | Promise<Res>;
318
+
319
+ class Interceptors<Interceptor> {
320
+ _fns: (Interceptor | null)[];
321
+
322
+ constructor() {
323
+ this._fns = [];
324
+ }
325
+
326
+ clear() {
327
+ this._fns = [];
328
+ }
329
+
330
+ getInterceptorIndex(id: number | Interceptor): number {
331
+ if (typeof id === 'number') {
332
+ return this._fns[id] ? id : -1;
333
+ } else {
334
+ return this._fns.indexOf(id);
335
+ }
336
+ }
337
+ exists(id: number | Interceptor) {
338
+ const index = this.getInterceptorIndex(id);
339
+ return !!this._fns[index];
340
+ }
341
+
342
+ eject(id: number | Interceptor) {
343
+ const index = this.getInterceptorIndex(id);
344
+ if (this._fns[index]) {
345
+ this._fns[index] = null;
346
+ }
347
+ }
348
+
349
+ update(id: number | Interceptor, fn: Interceptor) {
350
+ const index = this.getInterceptorIndex(id);
351
+ if (this._fns[index]) {
352
+ this._fns[index] = fn;
353
+ return id;
354
+ } else {
355
+ return false;
356
+ }
357
+ }
358
+
359
+ use(fn: Interceptor) {
360
+ this._fns = [...this._fns, fn];
361
+ return this._fns.length - 1;
362
+ }
363
+ }
364
+
365
+ // `createInterceptors()` response, meant for external use as it does not
366
+ // expose internals
367
+ export interface Middleware<Res, Err, Options> {
368
+ error: Pick<Interceptors<ErrInterceptor<Err, Res, Options>>, 'eject' | 'use'>;
369
+ request: Pick<Interceptors<ReqInterceptor<Options>>, 'eject' | 'use'>;
370
+ response: Pick<Interceptors<ResInterceptor<Res, Options>>, 'eject' | 'use'>;
371
+ }
372
+
373
+ // do not add `Middleware` as return type so we can use _fns internally
374
+ export const createInterceptors = <Res, Err, Options>() => ({
375
+ error: new Interceptors<ErrInterceptor<Err, Res, Options>>(),
376
+ request: new Interceptors<ReqInterceptor<Options>>(),
377
+ response: new Interceptors<ResInterceptor<Res, Options>>(),
378
+ });
379
+
380
+ const defaultQuerySerializer = createQuerySerializer({
381
+ allowReserved: false,
382
+ array: {
383
+ explode: true,
384
+ style: 'form',
385
+ },
386
+ object: {
387
+ explode: true,
388
+ style: 'deepObject',
389
+ },
390
+ });
391
+
392
+ const defaultHeaders = {
393
+ 'Content-Type': 'application/json',
394
+ };
395
+
396
+ export const createConfig = <T extends ClientOptions = ClientOptions>(
397
+ override: Config<Omit<ClientOptions, keyof T> & T> = {},
398
+ ): Config<Omit<ClientOptions, keyof T> & T> => ({
399
+ ...jsonBodySerializer,
400
+ headers: defaultHeaders,
401
+ parseAs: 'auto',
402
+ querySerializer: defaultQuerySerializer,
403
+ ...override,
404
+ });
@@ -0,0 +1,145 @@
1
+ import {
2
+ useAsyncData,
3
+ useFetch,
4
+ useLazyAsyncData,
5
+ useLazyFetch,
6
+ } from 'nuxt/app';
7
+ import { reactive, ref, watch } from 'vue';
8
+
9
+ import type { Client, Config } from './types';
10
+ import {
11
+ buildUrl,
12
+ createConfig,
13
+ executeFetchFn,
14
+ mergeConfigs,
15
+ mergeHeaders,
16
+ mergeInterceptors,
17
+ serializeBody,
18
+ setAuthParams,
19
+ } from './utils';
20
+
21
+ export const createClient = (config: Config = {}): Client => {
22
+ let _config = mergeConfigs(createConfig(), config);
23
+
24
+ const getConfig = (): Config => ({ ..._config });
25
+
26
+ const setConfig = (config: Config): Config => {
27
+ _config = mergeConfigs(_config, config);
28
+ return getConfig();
29
+ };
30
+
31
+ const request: Client['request'] = ({
32
+ asyncDataOptions,
33
+ composable,
34
+ ...options
35
+ }) => {
36
+ const key = options.key;
37
+ const opts = {
38
+ ..._config,
39
+ ...options,
40
+ $fetch: options.$fetch ?? _config.$fetch ?? $fetch,
41
+ headers: mergeHeaders(_config.headers, options.headers),
42
+ onRequest: mergeInterceptors(_config.onRequest, options.onRequest),
43
+ onResponse: mergeInterceptors(_config.onResponse, options.onResponse),
44
+ };
45
+
46
+ const { responseTransformer, responseValidator, security } = opts;
47
+ if (security) {
48
+ // auth must happen in interceptors otherwise we'd need to require
49
+ // asyncContext enabled
50
+ // https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext
51
+ opts.onRequest = [
52
+ async ({ options }) => {
53
+ await setAuthParams({
54
+ auth: opts.auth,
55
+ headers: options.headers,
56
+ query: options.query,
57
+ security,
58
+ });
59
+ },
60
+ ...opts.onRequest,
61
+ ];
62
+ }
63
+
64
+ if (responseTransformer || responseValidator) {
65
+ opts.onResponse = [
66
+ ...opts.onResponse,
67
+ async ({ options, response }) => {
68
+ if (options.responseType && options.responseType !== 'json') {
69
+ return;
70
+ }
71
+
72
+ if (!response.ok) {
73
+ return;
74
+ }
75
+
76
+ if (responseValidator) {
77
+ await responseValidator(response._data);
78
+ }
79
+
80
+ if (responseTransformer) {
81
+ response._data = await responseTransformer(response._data);
82
+ }
83
+ },
84
+ ];
85
+ }
86
+
87
+ // remove Content-Type header if body is empty to avoid sending invalid requests
88
+ if (opts.body === undefined || opts.body === '') {
89
+ opts.headers.delete('Content-Type');
90
+ }
91
+
92
+ const fetchFn = opts.$fetch;
93
+
94
+ if (composable === '$fetch') {
95
+ return executeFetchFn(opts, fetchFn);
96
+ }
97
+
98
+ if (composable === 'useFetch' || composable === 'useLazyFetch') {
99
+ const bodyParams = reactive({
100
+ body: opts.body,
101
+ bodySerializer: opts.bodySerializer,
102
+ });
103
+ const body = ref(serializeBody(opts));
104
+ opts.body = body;
105
+ watch(bodyParams, (changed) => {
106
+ body.value = serializeBody(changed);
107
+ });
108
+ return composable === 'useLazyFetch'
109
+ ? useLazyFetch(() => buildUrl(opts), opts)
110
+ : useFetch(() => buildUrl(opts), opts);
111
+ }
112
+
113
+ const handler: any = () => executeFetchFn(opts, fetchFn);
114
+
115
+ if (composable === 'useAsyncData') {
116
+ return key
117
+ ? useAsyncData(key, handler, asyncDataOptions)
118
+ : useAsyncData(handler, asyncDataOptions);
119
+ }
120
+
121
+ if (composable === 'useLazyAsyncData') {
122
+ return key
123
+ ? useLazyAsyncData(key, handler, asyncDataOptions)
124
+ : useLazyAsyncData(handler, asyncDataOptions);
125
+ }
126
+
127
+ return undefined as any;
128
+ };
129
+
130
+ return {
131
+ buildUrl,
132
+ connect: (options) => request({ ...options, method: 'CONNECT' }),
133
+ delete: (options) => request({ ...options, method: 'DELETE' }),
134
+ get: (options) => request({ ...options, method: 'GET' }),
135
+ getConfig,
136
+ head: (options) => request({ ...options, method: 'HEAD' }),
137
+ options: (options) => request({ ...options, method: 'OPTIONS' }),
138
+ patch: (options) => request({ ...options, method: 'PATCH' }),
139
+ post: (options) => request({ ...options, method: 'POST' }),
140
+ put: (options) => request({ ...options, method: 'PUT' }),
141
+ request,
142
+ setConfig,
143
+ trace: (options) => request({ ...options, method: 'TRACE' }),
144
+ };
145
+ };
@@ -0,0 +1,22 @@
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 { createClient } from './client';
10
+ export type {
11
+ Client,
12
+ ClientOptions,
13
+ Composable,
14
+ Config,
15
+ CreateClientConfig,
16
+ Options,
17
+ OptionsLegacyParser,
18
+ RequestOptions,
19
+ RequestResult,
20
+ TDataShape,
21
+ } from './types';
22
+ export { createConfig } from './utils';