@firela/api-types 0.0.0-canary.209966

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.
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@firela/api-types",
3
+ "version": "0.0.0-canary.209966",
4
+ "description": "TypeScript types generated from IGN OpenAPI specification",
5
+ "license": "MIT",
6
+ "author": "FireLa Team",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/fire-zu/ign.git",
10
+ "directory": "libs/api-types"
11
+ },
12
+ "main": "./dist/index.js",
13
+ "module": "./dist/index.mjs",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "import": "./dist/index.mjs",
18
+ "require": "./dist/index.js",
19
+ "types": "./dist/index.d.ts"
20
+ },
21
+ "./client": {
22
+ "types": "./dist/generated/sdk.gen.d.ts",
23
+ "import": "./dist/generated/sdk.gen.mjs",
24
+ "default": "./dist/generated/sdk.gen.js"
25
+ }
26
+ },
27
+ "files": ["dist", "src"],
28
+ "scripts": {
29
+ "sync": "npx ts-node scripts/sync-spec.ts",
30
+ "generate": "npm run sync && openapi-ts",
31
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
32
+ "lint": "spectral lint openapi.yaml",
33
+ "prepublishOnly": "npm run generate && npm run build"
34
+ },
35
+ "dependencies": {},
36
+ "devDependencies": {
37
+ "@hey-api/client-fetch": "^0.4.0",
38
+ "@hey-api/openapi-ts": "^0.45.0",
39
+ "@stoplight/spectral-cli": "^6.11.0",
40
+ "ts-node": "^10.9.0",
41
+ "tsup": "^8.0.0",
42
+ "typescript": "^5.3.0"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ }
47
+ }
@@ -0,0 +1,25 @@
1
+ import type { ApiRequestOptions } from './ApiRequestOptions';
2
+ import type { ApiResult } from './ApiResult';
3
+
4
+ export class ApiError extends Error {
5
+ public readonly url: string;
6
+ public readonly status: number;
7
+ public readonly statusText: string;
8
+ public readonly body: unknown;
9
+ public readonly request: ApiRequestOptions;
10
+
11
+ constructor(
12
+ request: ApiRequestOptions,
13
+ response: ApiResult,
14
+ message: string
15
+ ) {
16
+ super(message);
17
+
18
+ this.name = 'ApiError';
19
+ this.url = response.url;
20
+ this.status = response.status;
21
+ this.statusText = response.statusText;
22
+ this.body = response.body;
23
+ this.request = request;
24
+ }
25
+ }
@@ -0,0 +1,20 @@
1
+ export type ApiRequestOptions = {
2
+ readonly method:
3
+ | 'GET'
4
+ | 'PUT'
5
+ | 'POST'
6
+ | 'DELETE'
7
+ | 'OPTIONS'
8
+ | 'HEAD'
9
+ | 'PATCH';
10
+ readonly url: string;
11
+ readonly path?: Record<string, unknown>;
12
+ readonly cookies?: Record<string, unknown>;
13
+ readonly headers?: Record<string, unknown>;
14
+ readonly query?: Record<string, unknown>;
15
+ readonly formData?: Record<string, unknown>;
16
+ readonly body?: any;
17
+ readonly mediaType?: string;
18
+ readonly responseHeader?: string;
19
+ readonly errors?: Record<number, string>;
20
+ };
@@ -0,0 +1,7 @@
1
+ export type ApiResult<TData = any> = {
2
+ readonly body: TData;
3
+ readonly ok: boolean;
4
+ readonly status: number;
5
+ readonly statusText: string;
6
+ readonly url: string;
7
+ };
@@ -0,0 +1,126 @@
1
+ export class CancelError extends Error {
2
+ constructor(message: string) {
3
+ super(message);
4
+ this.name = 'CancelError';
5
+ }
6
+
7
+ public get isCancelled(): boolean {
8
+ return true;
9
+ }
10
+ }
11
+
12
+ export interface OnCancel {
13
+ readonly isResolved: boolean;
14
+ readonly isRejected: boolean;
15
+ readonly isCancelled: boolean;
16
+
17
+ (cancelHandler: () => void): void;
18
+ }
19
+
20
+ export class CancelablePromise<T> implements Promise<T> {
21
+ private _isResolved: boolean;
22
+ private _isRejected: boolean;
23
+ private _isCancelled: boolean;
24
+ readonly cancelHandlers: (() => void)[];
25
+ readonly promise: Promise<T>;
26
+ private _resolve?: (value: T | PromiseLike<T>) => void;
27
+ private _reject?: (reason?: unknown) => void;
28
+
29
+ constructor(
30
+ executor: (
31
+ resolve: (value: T | PromiseLike<T>) => void,
32
+ reject: (reason?: unknown) => void,
33
+ onCancel: OnCancel
34
+ ) => void
35
+ ) {
36
+ this._isResolved = false;
37
+ this._isRejected = false;
38
+ this._isCancelled = false;
39
+ this.cancelHandlers = [];
40
+ this.promise = new Promise<T>((resolve, reject) => {
41
+ this._resolve = resolve;
42
+ this._reject = reject;
43
+
44
+ const onResolve = (value: T | PromiseLike<T>): void => {
45
+ if (this._isResolved || this._isRejected || this._isCancelled) {
46
+ return;
47
+ }
48
+ this._isResolved = true;
49
+ if (this._resolve) this._resolve(value);
50
+ };
51
+
52
+ const onReject = (reason?: unknown): void => {
53
+ if (this._isResolved || this._isRejected || this._isCancelled) {
54
+ return;
55
+ }
56
+ this._isRejected = true;
57
+ if (this._reject) this._reject(reason);
58
+ };
59
+
60
+ const onCancel = (cancelHandler: () => void): void => {
61
+ if (this._isResolved || this._isRejected || this._isCancelled) {
62
+ return;
63
+ }
64
+ this.cancelHandlers.push(cancelHandler);
65
+ };
66
+
67
+ Object.defineProperty(onCancel, 'isResolved', {
68
+ get: (): boolean => this._isResolved
69
+ });
70
+
71
+ Object.defineProperty(onCancel, 'isRejected', {
72
+ get: (): boolean => this._isRejected
73
+ });
74
+
75
+ Object.defineProperty(onCancel, 'isCancelled', {
76
+ get: (): boolean => this._isCancelled
77
+ });
78
+
79
+ return executor(onResolve, onReject, onCancel as OnCancel);
80
+ });
81
+ }
82
+
83
+ get [Symbol.toStringTag]() {
84
+ return 'Cancellable Promise';
85
+ }
86
+
87
+ public then<TResult1 = T, TResult2 = never>(
88
+ onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
89
+ onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null
90
+ ): Promise<TResult1 | TResult2> {
91
+ return this.promise.then(onFulfilled, onRejected);
92
+ }
93
+
94
+ public catch<TResult = never>(
95
+ onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null
96
+ ): Promise<T | TResult> {
97
+ return this.promise.catch(onRejected);
98
+ }
99
+
100
+ public finally(onFinally?: (() => void) | null): Promise<T> {
101
+ return this.promise.finally(onFinally);
102
+ }
103
+
104
+ public cancel(): void {
105
+ if (this._isResolved || this._isRejected || this._isCancelled) {
106
+ return;
107
+ }
108
+ this._isCancelled = true;
109
+ if (this.cancelHandlers.length) {
110
+ try {
111
+ for (const cancelHandler of this.cancelHandlers) {
112
+ cancelHandler();
113
+ }
114
+ } catch (error) {
115
+ console.warn('Cancellation threw an error', error);
116
+ return;
117
+ }
118
+ }
119
+ this.cancelHandlers.length = 0;
120
+ if (this._reject) this._reject(new CancelError('Request aborted'));
121
+ }
122
+
123
+ public get isCancelled(): boolean {
124
+ return this._isCancelled;
125
+ }
126
+ }
@@ -0,0 +1,56 @@
1
+ import type { ApiRequestOptions } from './ApiRequestOptions';
2
+
3
+ type Headers = Record<string, string>;
4
+ type Middleware<T> = (value: T) => T | Promise<T>;
5
+ type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
6
+
7
+ export class Interceptors<T> {
8
+ _fns: Middleware<T>[];
9
+
10
+ constructor() {
11
+ this._fns = [];
12
+ }
13
+
14
+ eject(fn: Middleware<T>) {
15
+ const index = this._fns.indexOf(fn);
16
+ if (index !== -1) {
17
+ this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)];
18
+ }
19
+ }
20
+
21
+ use(fn: Middleware<T>) {
22
+ this._fns = [...this._fns, fn];
23
+ }
24
+ }
25
+
26
+ export type OpenAPIConfig = {
27
+ BASE: string;
28
+ CREDENTIALS: 'include' | 'omit' | 'same-origin';
29
+ ENCODE_PATH?: ((path: string) => string) | undefined;
30
+ HEADERS?: Headers | Resolver<Headers> | undefined;
31
+ PASSWORD?: string | Resolver<string> | undefined;
32
+ TOKEN?: string | Resolver<string> | undefined;
33
+ USERNAME?: string | Resolver<string> | undefined;
34
+ VERSION: string;
35
+ WITH_CREDENTIALS: boolean;
36
+ interceptors: {
37
+ request: Interceptors<RequestInit>;
38
+ response: Interceptors<Response>;
39
+ };
40
+ };
41
+
42
+ export const OpenAPI: OpenAPIConfig = {
43
+ BASE: '',
44
+ CREDENTIALS: 'include',
45
+ ENCODE_PATH: undefined,
46
+ HEADERS: undefined,
47
+ PASSWORD: undefined,
48
+ TOKEN: undefined,
49
+ USERNAME: undefined,
50
+ VERSION: 'dev',
51
+ WITH_CREDENTIALS: false,
52
+ interceptors: {
53
+ request: new Interceptors(),
54
+ response: new Interceptors()
55
+ }
56
+ };
@@ -0,0 +1,391 @@
1
+ import { ApiError } from './ApiError';
2
+ import type { ApiRequestOptions } from './ApiRequestOptions';
3
+ import type { ApiResult } from './ApiResult';
4
+ import { CancelablePromise } from './CancelablePromise';
5
+ import type { OnCancel } from './CancelablePromise';
6
+ import type { OpenAPIConfig } from './OpenAPI';
7
+
8
+ export const isString = (value: unknown): value is string => {
9
+ return typeof value === 'string';
10
+ };
11
+
12
+ export const isStringWithValue = (value: unknown): value is string => {
13
+ return isString(value) && value !== '';
14
+ };
15
+
16
+ export const isBlob = (value: any): value is Blob => {
17
+ return value instanceof Blob;
18
+ };
19
+
20
+ export const isFormData = (value: unknown): value is FormData => {
21
+ return value instanceof FormData;
22
+ };
23
+
24
+ export const base64 = (str: string): string => {
25
+ try {
26
+ return btoa(str);
27
+ } catch (err) {
28
+ // @ts-ignore
29
+ return Buffer.from(str).toString('base64');
30
+ }
31
+ };
32
+
33
+ export const getQueryString = (params: Record<string, unknown>): string => {
34
+ const qs: string[] = [];
35
+
36
+ const append = (key: string, value: unknown) => {
37
+ qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
38
+ };
39
+
40
+ const encodePair = (key: string, value: unknown) => {
41
+ if (value === undefined || value === null) {
42
+ return;
43
+ }
44
+
45
+ if (value instanceof Date) {
46
+ append(key, value.toISOString());
47
+ } else if (Array.isArray(value)) {
48
+ value.forEach((v) => encodePair(key, v));
49
+ } else if (typeof value === 'object') {
50
+ Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v));
51
+ } else {
52
+ append(key, value);
53
+ }
54
+ };
55
+
56
+ Object.entries(params).forEach(([key, value]) => encodePair(key, value));
57
+
58
+ return qs.length ? `?${qs.join('&')}` : '';
59
+ };
60
+
61
+ const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {
62
+ const encoder = config.ENCODE_PATH || encodeURI;
63
+
64
+ const path = options.url
65
+ .replace('{api-version}', config.VERSION)
66
+ .replace(/{(.*?)}/g, (substring: string, group: string) => {
67
+ if (options.path?.hasOwnProperty(group)) {
68
+ return encoder(String(options.path[group]));
69
+ }
70
+ return substring;
71
+ });
72
+
73
+ const url = config.BASE + path;
74
+ return options.query ? url + getQueryString(options.query) : url;
75
+ };
76
+
77
+ export const getFormData = (
78
+ options: ApiRequestOptions
79
+ ): FormData | undefined => {
80
+ if (options.formData) {
81
+ const formData = new FormData();
82
+
83
+ const process = (key: string, value: unknown) => {
84
+ if (isString(value) || isBlob(value)) {
85
+ formData.append(key, value);
86
+ } else {
87
+ formData.append(key, JSON.stringify(value));
88
+ }
89
+ };
90
+
91
+ Object.entries(options.formData)
92
+ .filter(([, value]) => value !== undefined && value !== null)
93
+ .forEach(([key, value]) => {
94
+ if (Array.isArray(value)) {
95
+ value.forEach((v) => process(key, v));
96
+ } else {
97
+ process(key, value);
98
+ }
99
+ });
100
+
101
+ return formData;
102
+ }
103
+ return undefined;
104
+ };
105
+
106
+ type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
107
+
108
+ export const resolve = async <T>(
109
+ options: ApiRequestOptions,
110
+ resolver?: T | Resolver<T>
111
+ ): Promise<T | undefined> => {
112
+ if (typeof resolver === 'function') {
113
+ return (resolver as Resolver<T>)(options);
114
+ }
115
+ return resolver;
116
+ };
117
+
118
+ export const getHeaders = async (
119
+ config: OpenAPIConfig,
120
+ options: ApiRequestOptions
121
+ ): Promise<Headers> => {
122
+ const [token, username, password, additionalHeaders] = await Promise.all([
123
+ resolve(options, config.TOKEN),
124
+ resolve(options, config.USERNAME),
125
+ resolve(options, config.PASSWORD),
126
+ resolve(options, config.HEADERS)
127
+ ]);
128
+
129
+ const headers = Object.entries({
130
+ Accept: 'application/json',
131
+ ...additionalHeaders,
132
+ ...options.headers
133
+ })
134
+ .filter(([, value]) => value !== undefined && value !== null)
135
+ .reduce(
136
+ (headers, [key, value]) => ({
137
+ ...headers,
138
+ [key]: String(value)
139
+ }),
140
+ {} as Record<string, string>
141
+ );
142
+
143
+ if (isStringWithValue(token)) {
144
+ headers['Authorization'] = `Bearer ${token}`;
145
+ }
146
+
147
+ if (isStringWithValue(username) && isStringWithValue(password)) {
148
+ const credentials = base64(`${username}:${password}`);
149
+ headers['Authorization'] = `Basic ${credentials}`;
150
+ }
151
+
152
+ if (options.body !== undefined) {
153
+ if (options.mediaType) {
154
+ headers['Content-Type'] = options.mediaType;
155
+ } else if (isBlob(options.body)) {
156
+ headers['Content-Type'] = options.body.type || 'application/octet-stream';
157
+ } else if (isString(options.body)) {
158
+ headers['Content-Type'] = 'text/plain';
159
+ } else if (!isFormData(options.body)) {
160
+ headers['Content-Type'] = 'application/json';
161
+ }
162
+ }
163
+
164
+ return new Headers(headers);
165
+ };
166
+
167
+ export const getRequestBody = (options: ApiRequestOptions): unknown => {
168
+ if (options.body !== undefined) {
169
+ if (
170
+ options.mediaType?.includes('application/json') ||
171
+ options.mediaType?.includes('+json')
172
+ ) {
173
+ return JSON.stringify(options.body);
174
+ } else if (
175
+ isString(options.body) ||
176
+ isBlob(options.body) ||
177
+ isFormData(options.body)
178
+ ) {
179
+ return options.body;
180
+ } else {
181
+ return JSON.stringify(options.body);
182
+ }
183
+ }
184
+ return undefined;
185
+ };
186
+
187
+ export const sendRequest = async (
188
+ config: OpenAPIConfig,
189
+ options: ApiRequestOptions,
190
+ url: string,
191
+ body: any,
192
+ formData: FormData | undefined,
193
+ headers: Headers,
194
+ onCancel: OnCancel
195
+ ): Promise<Response> => {
196
+ const controller = new AbortController();
197
+
198
+ let request: RequestInit = {
199
+ headers,
200
+ body: body ?? formData,
201
+ method: options.method,
202
+ signal: controller.signal
203
+ };
204
+
205
+ if (config.WITH_CREDENTIALS) {
206
+ request.credentials = config.CREDENTIALS;
207
+ }
208
+
209
+ for (const fn of config.interceptors.request._fns) {
210
+ request = await fn(request);
211
+ }
212
+
213
+ onCancel(() => controller.abort());
214
+
215
+ return await fetch(url, request);
216
+ };
217
+
218
+ export const getResponseHeader = (
219
+ response: Response,
220
+ responseHeader?: string
221
+ ): string | undefined => {
222
+ if (responseHeader) {
223
+ const content = response.headers.get(responseHeader);
224
+ if (isString(content)) {
225
+ return content;
226
+ }
227
+ }
228
+ return undefined;
229
+ };
230
+
231
+ export const getResponseBody = async (response: Response): Promise<unknown> => {
232
+ if (response.status !== 204) {
233
+ try {
234
+ const contentType = response.headers.get('Content-Type');
235
+ if (contentType) {
236
+ const binaryTypes = [
237
+ 'application/octet-stream',
238
+ 'application/pdf',
239
+ 'application/zip',
240
+ 'audio/',
241
+ 'image/',
242
+ 'video/'
243
+ ];
244
+ if (
245
+ contentType.includes('application/json') ||
246
+ contentType.includes('+json')
247
+ ) {
248
+ return await response.json();
249
+ } else if (binaryTypes.some((type) => contentType.includes(type))) {
250
+ return await response.blob();
251
+ } else if (contentType.includes('multipart/form-data')) {
252
+ return await response.formData();
253
+ } else if (contentType.includes('text/')) {
254
+ return await response.text();
255
+ }
256
+ }
257
+ } catch (error) {
258
+ console.error(error);
259
+ }
260
+ }
261
+ return undefined;
262
+ };
263
+
264
+ export const catchErrorCodes = (
265
+ options: ApiRequestOptions,
266
+ result: ApiResult
267
+ ): void => {
268
+ const errors: Record<number, string> = {
269
+ 400: 'Bad Request',
270
+ 401: 'Unauthorized',
271
+ 402: 'Payment Required',
272
+ 403: 'Forbidden',
273
+ 404: 'Not Found',
274
+ 405: 'Method Not Allowed',
275
+ 406: 'Not Acceptable',
276
+ 407: 'Proxy Authentication Required',
277
+ 408: 'Request Timeout',
278
+ 409: 'Conflict',
279
+ 410: 'Gone',
280
+ 411: 'Length Required',
281
+ 412: 'Precondition Failed',
282
+ 413: 'Payload Too Large',
283
+ 414: 'URI Too Long',
284
+ 415: 'Unsupported Media Type',
285
+ 416: 'Range Not Satisfiable',
286
+ 417: 'Expectation Failed',
287
+ 418: 'Im a teapot',
288
+ 421: 'Misdirected Request',
289
+ 422: 'Unprocessable Content',
290
+ 423: 'Locked',
291
+ 424: 'Failed Dependency',
292
+ 425: 'Too Early',
293
+ 426: 'Upgrade Required',
294
+ 428: 'Precondition Required',
295
+ 429: 'Too Many Requests',
296
+ 431: 'Request Header Fields Too Large',
297
+ 451: 'Unavailable For Legal Reasons',
298
+ 500: 'Internal Server Error',
299
+ 501: 'Not Implemented',
300
+ 502: 'Bad Gateway',
301
+ 503: 'Service Unavailable',
302
+ 504: 'Gateway Timeout',
303
+ 505: 'HTTP Version Not Supported',
304
+ 506: 'Variant Also Negotiates',
305
+ 507: 'Insufficient Storage',
306
+ 508: 'Loop Detected',
307
+ 510: 'Not Extended',
308
+ 511: 'Network Authentication Required',
309
+ ...options.errors
310
+ };
311
+
312
+ const error = errors[result.status];
313
+ if (error) {
314
+ throw new ApiError(options, result, error);
315
+ }
316
+
317
+ if (!result.ok) {
318
+ const errorStatus = result.status ?? 'unknown';
319
+ const errorStatusText = result.statusText ?? 'unknown';
320
+ const errorBody = (() => {
321
+ try {
322
+ return JSON.stringify(result.body, null, 2);
323
+ } catch (e) {
324
+ return undefined;
325
+ }
326
+ })();
327
+
328
+ throw new ApiError(
329
+ options,
330
+ result,
331
+ `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`
332
+ );
333
+ }
334
+ };
335
+
336
+ /**
337
+ * Request method
338
+ * @param config The OpenAPI configuration object
339
+ * @param options The request options from the service
340
+ * @returns CancelablePromise<T>
341
+ * @throws ApiError
342
+ */
343
+ export const request = <T>(
344
+ config: OpenAPIConfig,
345
+ options: ApiRequestOptions
346
+ ): CancelablePromise<T> => {
347
+ return new CancelablePromise(async (resolve, reject, onCancel) => {
348
+ try {
349
+ const url = getUrl(config, options);
350
+ const formData = getFormData(options);
351
+ const body = getRequestBody(options);
352
+ const headers = await getHeaders(config, options);
353
+
354
+ if (!onCancel.isCancelled) {
355
+ let response = await sendRequest(
356
+ config,
357
+ options,
358
+ url,
359
+ body,
360
+ formData,
361
+ headers,
362
+ onCancel
363
+ );
364
+
365
+ for (const fn of config.interceptors.response._fns) {
366
+ response = await fn(response);
367
+ }
368
+
369
+ const responseBody = await getResponseBody(response);
370
+ const responseHeader = getResponseHeader(
371
+ response,
372
+ options.responseHeader
373
+ );
374
+
375
+ const result: ApiResult = {
376
+ url,
377
+ ok: response.ok,
378
+ status: response.status,
379
+ statusText: response.statusText,
380
+ body: responseHeader ?? responseBody
381
+ };
382
+
383
+ catchErrorCodes(options, result);
384
+
385
+ resolve(result.body);
386
+ }
387
+ } catch (error) {
388
+ reject(error);
389
+ }
390
+ });
391
+ };
@@ -0,0 +1,7 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export { ApiError } from './core/ApiError';
3
+ export { CancelablePromise, CancelError } from './core/CancelablePromise';
4
+ export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI';
5
+ export * from './schemas.gen';
6
+ export * from './services.gen';
7
+ export * from './types.gen';