@swapkit/api-sdk-typescript 1.0.0 → 1.0.3

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.
@@ -0,0 +1,243 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+
3
+ import type { Config } from './types';
4
+
5
+ export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> &
6
+ Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {
7
+ /**
8
+ * Fetch API implementation. You can use this option to provide a custom
9
+ * fetch instance.
10
+ *
11
+ * @default globalThis.fetch
12
+ */
13
+ fetch?: typeof fetch;
14
+ /**
15
+ * Implementing clients can call request interceptors inside this hook.
16
+ */
17
+ onRequest?: (url: string, init: RequestInit) => Promise<Request>;
18
+ /**
19
+ * Callback invoked when a network or parsing error occurs during streaming.
20
+ *
21
+ * This option applies only if the endpoint returns a stream of events.
22
+ *
23
+ * @param error The error that occurred.
24
+ */
25
+ onSseError?: (error: unknown) => void;
26
+ /**
27
+ * Callback invoked when an event is streamed from the server.
28
+ *
29
+ * This option applies only if the endpoint returns a stream of events.
30
+ *
31
+ * @param event Event streamed from the server.
32
+ * @returns Nothing (void).
33
+ */
34
+ onSseEvent?: (event: StreamEvent<TData>) => void;
35
+ serializedBody?: RequestInit['body'];
36
+ /**
37
+ * Default retry delay in milliseconds.
38
+ *
39
+ * This option applies only if the endpoint returns a stream of events.
40
+ *
41
+ * @default 3000
42
+ */
43
+ sseDefaultRetryDelay?: number;
44
+ /**
45
+ * Maximum number of retry attempts before giving up.
46
+ */
47
+ sseMaxRetryAttempts?: number;
48
+ /**
49
+ * Maximum retry delay in milliseconds.
50
+ *
51
+ * Applies only when exponential backoff is used.
52
+ *
53
+ * This option applies only if the endpoint returns a stream of events.
54
+ *
55
+ * @default 30000
56
+ */
57
+ sseMaxRetryDelay?: number;
58
+ /**
59
+ * Optional sleep function for retry backoff.
60
+ *
61
+ * Defaults to using `setTimeout`.
62
+ */
63
+ sseSleepFn?: (ms: number) => Promise<void>;
64
+ url: string;
65
+ };
66
+
67
+ export interface StreamEvent<TData = unknown> {
68
+ data: TData;
69
+ event?: string;
70
+ id?: string;
71
+ retry?: number;
72
+ }
73
+
74
+ export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
75
+ stream: AsyncGenerator<
76
+ TData extends Record<string, unknown> ? TData[keyof TData] : TData,
77
+ TReturn,
78
+ TNext
79
+ >;
80
+ };
81
+
82
+ export const createSseClient = <TData = unknown>({
83
+ onRequest,
84
+ onSseError,
85
+ onSseEvent,
86
+ responseTransformer,
87
+ responseValidator,
88
+ sseDefaultRetryDelay,
89
+ sseMaxRetryAttempts,
90
+ sseMaxRetryDelay,
91
+ sseSleepFn,
92
+ url,
93
+ ...options
94
+ }: ServerSentEventsOptions): ServerSentEventsResult<TData> => {
95
+ let lastEventId: string | undefined;
96
+
97
+ const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
98
+
99
+ const createStream = async function* () {
100
+ let retryDelay: number = sseDefaultRetryDelay ?? 3000;
101
+ let attempt = 0;
102
+ const signal = options.signal ?? new AbortController().signal;
103
+
104
+ while (true) {
105
+ if (signal.aborted) break;
106
+
107
+ attempt++;
108
+
109
+ const headers =
110
+ options.headers instanceof Headers
111
+ ? options.headers
112
+ : new Headers(options.headers as Record<string, string> | undefined);
113
+
114
+ if (lastEventId !== undefined) {
115
+ headers.set('Last-Event-ID', lastEventId);
116
+ }
117
+
118
+ try {
119
+ const requestInit: RequestInit = {
120
+ redirect: 'follow',
121
+ ...options,
122
+ body: options.serializedBody,
123
+ headers,
124
+ signal,
125
+ };
126
+ let request = new Request(url, requestInit);
127
+ if (onRequest) {
128
+ request = await onRequest(url, requestInit);
129
+ }
130
+ // fetch must be assigned here, otherwise it would throw the error:
131
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
132
+ const _fetch = options.fetch ?? globalThis.fetch;
133
+ const response = await _fetch(request);
134
+
135
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
136
+
137
+ if (!response.body) throw new Error('No body in SSE response');
138
+
139
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
140
+
141
+ let buffer = '';
142
+
143
+ const abortHandler = () => {
144
+ try {
145
+ reader.cancel();
146
+ } catch {
147
+ // noop
148
+ }
149
+ };
150
+
151
+ signal.addEventListener('abort', abortHandler);
152
+
153
+ try {
154
+ while (true) {
155
+ const { done, value } = await reader.read();
156
+ if (done) break;
157
+ buffer += value;
158
+ // Normalize line endings: CRLF -> LF, then CR -> LF
159
+ buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
160
+
161
+ const chunks = buffer.split('\n\n');
162
+ buffer = chunks.pop() ?? '';
163
+
164
+ for (const chunk of chunks) {
165
+ const lines = chunk.split('\n');
166
+ const dataLines: Array<string> = [];
167
+ let eventName: string | undefined;
168
+
169
+ for (const line of lines) {
170
+ if (line.startsWith('data:')) {
171
+ dataLines.push(line.replace(/^data:\s*/, ''));
172
+ } else if (line.startsWith('event:')) {
173
+ eventName = line.replace(/^event:\s*/, '');
174
+ } else if (line.startsWith('id:')) {
175
+ lastEventId = line.replace(/^id:\s*/, '');
176
+ } else if (line.startsWith('retry:')) {
177
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10);
178
+ if (!Number.isNaN(parsed)) {
179
+ retryDelay = parsed;
180
+ }
181
+ }
182
+ }
183
+
184
+ let data: unknown;
185
+ let parsedJson = false;
186
+
187
+ if (dataLines.length) {
188
+ const rawData = dataLines.join('\n');
189
+ try {
190
+ data = JSON.parse(rawData);
191
+ parsedJson = true;
192
+ } catch {
193
+ data = rawData;
194
+ }
195
+ }
196
+
197
+ if (parsedJson) {
198
+ if (responseValidator) {
199
+ await responseValidator(data);
200
+ }
201
+
202
+ if (responseTransformer) {
203
+ data = await responseTransformer(data);
204
+ }
205
+ }
206
+
207
+ onSseEvent?.({
208
+ data,
209
+ event: eventName,
210
+ id: lastEventId,
211
+ retry: retryDelay,
212
+ });
213
+
214
+ if (dataLines.length) {
215
+ yield data as any;
216
+ }
217
+ }
218
+ }
219
+ } finally {
220
+ signal.removeEventListener('abort', abortHandler);
221
+ reader.releaseLock();
222
+ }
223
+
224
+ break; // exit loop on normal completion
225
+ } catch (error) {
226
+ // connection failed or aborted; retry after delay
227
+ onSseError?.(error);
228
+
229
+ if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
230
+ break; // stop after firing error
231
+ }
232
+
233
+ // exponential backoff: double retry each attempt, cap at 30s
234
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
235
+ await sleep(backoff);
236
+ }
237
+ }
238
+ };
239
+
240
+ const stream = createStream();
241
+
242
+ return { stream };
243
+ };
@@ -0,0 +1,104 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+
3
+ import type { Auth, AuthToken } from './auth';
4
+ import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer';
5
+
6
+ export type HttpMethod =
7
+ | 'connect'
8
+ | 'delete'
9
+ | 'get'
10
+ | 'head'
11
+ | 'options'
12
+ | 'patch'
13
+ | 'post'
14
+ | 'put'
15
+ | 'trace';
16
+
17
+ export type Client<
18
+ RequestFn = never,
19
+ Config = unknown,
20
+ MethodFn = never,
21
+ BuildUrlFn = never,
22
+ SseFn = never,
23
+ > = {
24
+ /**
25
+ * Returns the final request URL.
26
+ */
27
+ buildUrl: BuildUrlFn;
28
+ getConfig: () => Config;
29
+ request: RequestFn;
30
+ setConfig: (config: Config) => Config;
31
+ } & {
32
+ [K in HttpMethod]: MethodFn;
33
+ } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } });
34
+
35
+ export interface Config {
36
+ /**
37
+ * Auth token or a function returning auth token. The resolved value will be
38
+ * added to the request payload as defined by its `security` array.
39
+ */
40
+ auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
41
+ /**
42
+ * A function for serializing request body parameter. By default,
43
+ * {@link JSON.stringify()} will be used.
44
+ */
45
+ bodySerializer?: BodySerializer | null;
46
+ /**
47
+ * An object containing any HTTP headers that you want to pre-populate your
48
+ * `Headers` object with.
49
+ *
50
+ * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
51
+ */
52
+ headers?:
53
+ | RequestInit['headers']
54
+ | Record<
55
+ string,
56
+ string | number | boolean | (string | number | boolean)[] | null | undefined | unknown
57
+ >;
58
+ /**
59
+ * The request method.
60
+ *
61
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
62
+ */
63
+ method?: Uppercase<HttpMethod>;
64
+ /**
65
+ * A function for serializing request query parameters. By default, arrays
66
+ * will be exploded in form style, objects will be exploded in deepObject
67
+ * style, and reserved characters are percent-encoded.
68
+ *
69
+ * This method will have no effect if the native `paramsSerializer()` Axios
70
+ * API function is used.
71
+ *
72
+ * {@link https://swagger.io/docs/specification/serialization/#query View examples}
73
+ */
74
+ querySerializer?: QuerySerializer | QuerySerializerOptions;
75
+ /**
76
+ * A function validating request data. This is useful if you want to ensure
77
+ * the request conforms to the desired shape, so it can be safely sent to
78
+ * the server.
79
+ */
80
+ requestValidator?: (data: unknown) => Promise<unknown>;
81
+ /**
82
+ * A function transforming response data before it's returned. This is useful
83
+ * for post-processing data, e.g. converting ISO strings into Date objects.
84
+ */
85
+ responseTransformer?: (data: unknown) => Promise<unknown>;
86
+ /**
87
+ * A function validating response data. This is useful if you want to ensure
88
+ * the response conforms to the desired shape, so it can be safely passed to
89
+ * the transformers and returned to the user.
90
+ */
91
+ responseValidator?: (data: unknown) => Promise<unknown>;
92
+ }
93
+
94
+ type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
95
+ ? true
96
+ : [T] extends [never | undefined]
97
+ ? [undefined] extends [T]
98
+ ? false
99
+ : true
100
+ : false;
101
+
102
+ export type OmitNever<T extends Record<string, unknown>> = {
103
+ [K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true ? never : K]: T[K];
104
+ };
@@ -0,0 +1,140 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+
3
+ import type { BodySerializer, QuerySerializer } from './bodySerializer';
4
+ import {
5
+ type ArraySeparatorStyle,
6
+ serializeArrayParam,
7
+ serializeObjectParam,
8
+ serializePrimitiveParam,
9
+ } from './pathSerializer';
10
+
11
+ export interface PathSerializer {
12
+ path: Record<string, unknown>;
13
+ url: string;
14
+ }
15
+
16
+ export const PATH_PARAM_RE = /\{[^{}]+\}/g;
17
+
18
+ export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
19
+ let url = _url;
20
+ const matches = _url.match(PATH_PARAM_RE);
21
+ if (matches) {
22
+ for (const match of matches) {
23
+ let explode = false;
24
+ let name = match.substring(1, match.length - 1);
25
+ let style: ArraySeparatorStyle = 'simple';
26
+
27
+ if (name.endsWith('*')) {
28
+ explode = true;
29
+ name = name.substring(0, name.length - 1);
30
+ }
31
+
32
+ if (name.startsWith('.')) {
33
+ name = name.substring(1);
34
+ style = 'label';
35
+ } else if (name.startsWith(';')) {
36
+ name = name.substring(1);
37
+ style = 'matrix';
38
+ }
39
+
40
+ const value = path[name];
41
+
42
+ if (value === undefined || value === null) {
43
+ continue;
44
+ }
45
+
46
+ if (Array.isArray(value)) {
47
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
48
+ continue;
49
+ }
50
+
51
+ if (typeof value === 'object') {
52
+ url = url.replace(
53
+ match,
54
+ serializeObjectParam({
55
+ explode,
56
+ name,
57
+ style,
58
+ value: value as Record<string, unknown>,
59
+ valueOnly: true,
60
+ }),
61
+ );
62
+ continue;
63
+ }
64
+
65
+ if (style === 'matrix') {
66
+ url = url.replace(
67
+ match,
68
+ `;${serializePrimitiveParam({
69
+ name,
70
+ value: value as string,
71
+ })}`,
72
+ );
73
+ continue;
74
+ }
75
+
76
+ const replaceValue = encodeURIComponent(
77
+ style === 'label' ? `.${value as string}` : (value as string),
78
+ );
79
+ url = url.replace(match, replaceValue);
80
+ }
81
+ }
82
+ return url;
83
+ };
84
+
85
+ export const getUrl = ({
86
+ baseUrl,
87
+ path,
88
+ query,
89
+ querySerializer,
90
+ url: _url,
91
+ }: {
92
+ baseUrl?: string;
93
+ path?: Record<string, unknown>;
94
+ query?: Record<string, unknown>;
95
+ querySerializer: QuerySerializer;
96
+ url: string;
97
+ }) => {
98
+ const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
99
+ let url = (baseUrl ?? '') + pathUrl;
100
+ if (path) {
101
+ url = defaultPathSerializer({ path, url });
102
+ }
103
+ let search = query ? querySerializer(query) : '';
104
+ if (search.startsWith('?')) {
105
+ search = search.substring(1);
106
+ }
107
+ if (search) {
108
+ url += `?${search}`;
109
+ }
110
+ return url;
111
+ };
112
+
113
+ export function getValidRequestBody(options: {
114
+ body?: unknown;
115
+ bodySerializer?: BodySerializer | null;
116
+ serializedBody?: unknown;
117
+ }) {
118
+ const hasBody = options.body !== undefined;
119
+ const isSerializedBody = hasBody && options.bodySerializer;
120
+
121
+ if (isSerializedBody) {
122
+ if ('serializedBody' in options) {
123
+ const hasSerializedBody =
124
+ options.serializedBody !== undefined && options.serializedBody !== '';
125
+
126
+ return hasSerializedBody ? options.serializedBody : null;
127
+ }
128
+
129
+ // not all clients implement a serializedBody property (i.e. client-axios)
130
+ return options.body !== '' ? options.body : null;
131
+ }
132
+
133
+ // plain/text body
134
+ if (hasBody) {
135
+ return options.body;
136
+ }
137
+
138
+ // no body was provided
139
+ return undefined;
140
+ }