@unshared/client 0.3.2 → 0.4.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.
- package/dist/chunks/{mHfUAX_g.d.ts → 5p4H9ZaI.d.ts} +11 -5
- package/dist/chunks/{0ZzUT3m_.js → B6pUErTM.js} +2 -2
- package/dist/chunks/B6pUErTM.js.map +1 -0
- package/dist/chunks/{CYmaYL5B.cjs → BDxlAULu.cjs} +2 -2
- package/dist/chunks/BDxlAULu.cjs.map +1 -0
- package/dist/chunks/{Biic1J5b.js → B_Gz6Yz8.js} +23 -1
- package/dist/chunks/B_Gz6Yz8.js.map +1 -0
- package/dist/chunks/{BMbsYNBd.cjs → BdFNzMcu.cjs} +2 -2
- package/dist/chunks/{BMbsYNBd.cjs.map → BdFNzMcu.cjs.map} +1 -1
- package/dist/chunks/{6IxvRpmY.js → Bys4-xE2.js} +2 -2
- package/dist/chunks/{6IxvRpmY.js.map → Bys4-xE2.js.map} +1 -1
- package/dist/chunks/CS5r-m4U.js +191 -0
- package/dist/chunks/CS5r-m4U.js.map +1 -0
- package/dist/chunks/CVzmr2NA.cjs +189 -0
- package/dist/chunks/CVzmr2NA.cjs.map +1 -0
- package/dist/chunks/D1QsGr3A.js +15 -0
- package/dist/chunks/D1QsGr3A.js.map +1 -0
- package/dist/chunks/{CtW2aMuA.cjs → DEyigyGy.cjs} +23 -1
- package/dist/chunks/DEyigyGy.cjs.map +1 -0
- package/dist/chunks/DXrQkl1A.cjs +14 -0
- package/dist/chunks/DXrQkl1A.cjs.map +1 -0
- package/dist/chunks/{CO11DuYE.d.ts → Nc32BOzg.d.ts} +23 -3
- package/dist/createClient.cjs +4 -58
- package/dist/createClient.cjs.map +1 -1
- package/dist/createClient.d.ts +13 -7
- package/dist/createClient.js +4 -59
- package/dist/createClient.js.map +1 -1
- package/dist/createService.cjs +3 -3
- package/dist/createService.cjs.map +1 -1
- package/dist/createService.d.ts +2 -2
- package/dist/createService.js +4 -4
- package/dist/createService.js.map +1 -1
- package/dist/index.cjs +5 -5
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -5
- package/dist/openapi.cjs +13 -3
- package/dist/openapi.cjs.map +1 -1
- package/dist/openapi.d.ts +45 -4
- package/dist/openapi.js +11 -1
- package/dist/openapi.js.map +1 -1
- package/dist/utils.cjs +15 -3
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.ts +114 -8
- package/dist/utils.js +21 -8
- package/dist/utils.js.map +1 -1
- package/dist/websocket.cjs +2 -2
- package/dist/websocket.js +2 -2
- package/package.json +4 -4
- package/dist/chunks/0ZzUT3m_.js.map +0 -1
- package/dist/chunks/BUeqbyph.js +0 -114
- package/dist/chunks/BUeqbyph.js.map +0 -1
- package/dist/chunks/Biic1J5b.js.map +0 -1
- package/dist/chunks/CYmaYL5B.cjs.map +0 -1
- package/dist/chunks/Cayg8606.cjs +0 -112
- package/dist/chunks/Cayg8606.cjs.map +0 -1
- package/dist/chunks/CtW2aMuA.cjs.map +0 -1
- package/dist/chunks/DJJsADWD.js +0 -9
- package/dist/chunks/DJJsADWD.js.map +0 -1
- package/dist/chunks/Du_W5H6e.cjs +0 -8
- package/dist/chunks/Du_W5H6e.cjs.map +0 -1
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"createClient.cjs","sources":["../createClient.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions'\nimport type { Result } from '@unshared/functions/attempt'\nimport type { ServiceOptions } from './createService'\nimport type { OpenAPILike, OpenAPIOptionsMap } from './openapi'\nimport type { RequestOptions } from './utils'\nimport type { ConnectOptions, WebSocketChannel } from './websocket'\nimport { attempt } from '@unshared/functions/attempt'\nimport { fetch } from './utils/fetch'\nimport { request } from './utils/request'\nimport { connect } from './websocket/connect'\n\ntype Data<T extends RequestOptions> = T extends RequestOptions<any, any, any, any, any, any, infer R, any> ? R : unknown\ntype Routes = Record<string, RequestOptions>\ntype Channels = Record<string, ConnectOptions>\n\nexport class Client<T extends Routes = Routes, U extends Channels = Channels> {\n\n /**\n * Create a new client for the application.\n *\n * @param options The options to pass to the client.\n * @example new Client({ baseUrl: 'https://api.example.com' })\n */\n constructor(public options: RequestOptions = {}) {}\n\n /**\n * Fetch a route from the API and return the `Response` object. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n */\n public fetch<K extends keyof T & string,
|
1
|
+
{"version":3,"file":"createClient.cjs","sources":["../createClient.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions'\nimport type { Result } from '@unshared/functions/attempt'\nimport type { ServiceOptions } from './createService'\nimport type { OpenAPILike, OpenAPIOptionsMap } from './openapi'\nimport type { FetchOptions, RequestOptions } from './utils'\nimport type { ConnectOptions, WebSocketChannel } from './websocket'\nimport { attempt } from '@unshared/functions/attempt'\nimport { fetch } from './utils/fetch'\nimport { request } from './utils/request'\nimport { connect } from './websocket/connect'\n\ntype Data<T extends RequestOptions> = T extends RequestOptions<any, any, any, any, any, any, infer R, any> ? R : unknown\ntype Routes = Record<string, RequestOptions>\ntype Channels = Record<string, ConnectOptions>\n\nexport class Client<T extends Routes = Routes, U extends Channels = Channels> {\n\n /**\n * Create a new client for the application.\n *\n * @param options The options to pass to the client.\n * @example new Client({ baseUrl: 'https://api.example.com' })\n */\n constructor(public options: RequestOptions = {}) {}\n\n /**\n * Fetch a route from the API and return the `Response` object. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n */\n public fetch<K extends keyof T & string>(route: K, options?: T[K]): Promise<Response & { json: () => Promise<Data<T[K]>> }>\n public fetch(route: string, options?: FetchOptions): Promise<Response>\n public fetch(route: string, options?: FetchOptions): Promise<Response> {\n return fetch(route, { ...this.options, ...options })\n }\n\n /**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\n public request<K extends keyof T & string>(route: K, options?: T[K]): Promise<Data<T[K]>>\n public request(route: string, options?: RequestOptions): Promise<unknown>\n public request(route: string, options?: RequestOptions): Promise<unknown> {\n return request(route, { ...this.options, ...options })\n }\n\n /**\n * Attempt to fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns A result object with either the data or an error.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const { data, error } = requestAttempt('GET /api/product/:id', { data: { id: '1' } })\n * if (error) console.error(error)\n * else console.log(data)\n */\n public requestAttempt<K extends keyof T & string>(route: K, options?: T[K]): Promise<Result<Data<T[K]>>>\n public requestAttempt(route: string, options?: RequestOptions): Promise<Result<unknown>>\n public requestAttempt(route: string, options?: RequestOptions): Promise<Result<unknown>> {\n return attempt(() => this.request(route, options))\n }\n\n /**\n * Create a new WebSocket connection to the server with the given path. The connection will\n * automatically reconnect if the connection is closed unexpectedly.\n *\n * @param channel The path to connect to.\n * @param options The options to pass to the connection.\n * @returns The WebSocket connection.\n */\n public connect<P extends keyof U & string>(channel: P, options?: U[P]): Awaitable<WebSocketChannel<U[P]>, WebSocketChannel<U[P]>>\n public connect(channel: string, options?: ConnectOptions): Awaitable<WebSocketChannel, WebSocketChannel>\n public connect(channel: string, options?: ConnectOptions): Awaitable<WebSocketChannel, WebSocketChannel> {\n return connect(channel, { baseUrl: this.options.baseUrl, ...options })\n }\n}\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends OpenAPILike>(options?: ServiceOptions<T>): Client<OpenAPIOptionsMap<T>>\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends Routes = Routes, V extends Channels = Channels>(options?: RequestOptions): Client<T, V>\nexport function createClient(options?: RequestOptions): Client {\n return new Client(options)\n}\n"],"names":["fetch","request","attempt","connect"],"mappings":";;;;;;AAeO,MAAM,OAAiE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ5E,YAAmB,UAA0B,IAAI;AAA9B,SAAA,UAAA;AAAA,EAAA;AAAA,EAaZ,MAAM,OAAe,SAA2C;AAC9D,WAAAA,QAAAA,MAAM,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA,EAuB9C,QAAQ,OAAe,SAA4C;AACjE,WAAAC,QAAAA,QAAQ,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA,EAyBhD,eAAe,OAAe,SAAoD;AACvF,WAAOC,QAAAA,QAAQ,MAAM,KAAK,QAAQ,OAAO,OAAO,CAAC;AAAA,EAAA;AAAA,EAa5C,QAAQ,SAAiB,SAAyE;AAChG,WAAAC,QAAA,QAAQ,SAAS,EAAE,SAAS,KAAK,QAAQ,SAAS,GAAG,SAAS;AAAA,EAAA;AAEzE;AAqCO,SAAS,aAAa,SAAkC;AACtD,SAAA,IAAI,OAAO,OAAO;AAC3B;;;"}
|
package/dist/createClient.d.ts
CHANGED
@@ -1,13 +1,13 @@
|
|
1
1
|
import { Awaitable } from '@unshared/functions';
|
2
2
|
import { Result } from '@unshared/functions/attempt';
|
3
3
|
import { ServiceOptions } from './createService.js';
|
4
|
-
import {
|
5
|
-
import {
|
4
|
+
import { R as RequestOptions, F as FetchOptions } from './chunks/Nc32BOzg.js';
|
5
|
+
import { O as OpenAPILike, a as OpenAPIOptionsMap } from './chunks/5p4H9ZaI.js';
|
6
6
|
import { WebSocketChannel, ConnectOptions } from './websocket.js';
|
7
7
|
import '@unshared/types';
|
8
|
-
import 'openapi-types';
|
9
8
|
import './HttpHeaders.js';
|
10
9
|
import './HttpMethods.js';
|
10
|
+
import 'openapi-types';
|
11
11
|
|
12
12
|
type Data<T extends RequestOptions> = T extends RequestOptions<any, any, any, any, any, any, infer R, any> ? R : unknown;
|
13
13
|
type Routes = Record<string, RequestOptions>;
|
@@ -30,7 +30,10 @@ declare class Client<T extends Routes = Routes, U extends Channels = Channels> {
|
|
30
30
|
* @param options The options to pass to the request.
|
31
31
|
* @returns The response from the server.
|
32
32
|
*/
|
33
|
-
fetch<K extends keyof T & string
|
33
|
+
fetch<K extends keyof T & string>(route: K, options?: T[K]): Promise<Response & {
|
34
|
+
json: () => Promise<Data<T[K]>>;
|
35
|
+
}>;
|
36
|
+
fetch(route: string, options?: FetchOptions): Promise<Response>;
|
34
37
|
/**
|
35
38
|
* Fetch a route from the API and return the data. If the client was instantiated with an
|
36
39
|
* application, the route name will be inferred from the application routes. Otherwise, you
|
@@ -49,7 +52,8 @@ declare class Client<T extends Routes = Routes, U extends Channels = Channels> {
|
|
49
52
|
* // Fetch the data from the API.
|
50
53
|
* const data = request('GET /api/product/:id', { data: { id: '1' } })
|
51
54
|
*/
|
52
|
-
request<K extends keyof T & string
|
55
|
+
request<K extends keyof T & string>(route: K, options?: T[K]): Promise<Data<T[K]>>;
|
56
|
+
request(route: string, options?: RequestOptions): Promise<unknown>;
|
53
57
|
/**
|
54
58
|
* Attempt to fetch a route from the API and return the data. If the client was instantiated with an
|
55
59
|
* application, the route name will be inferred from the application routes. Otherwise, you
|
@@ -70,7 +74,8 @@ declare class Client<T extends Routes = Routes, U extends Channels = Channels> {
|
|
70
74
|
* if (error) console.error(error)
|
71
75
|
* else console.log(data)
|
72
76
|
*/
|
73
|
-
requestAttempt<K extends keyof T & string
|
77
|
+
requestAttempt<K extends keyof T & string>(route: K, options?: T[K]): Promise<Result<Data<T[K]>>>;
|
78
|
+
requestAttempt(route: string, options?: RequestOptions): Promise<Result<unknown>>;
|
74
79
|
/**
|
75
80
|
* Create a new WebSocket connection to the server with the given path. The connection will
|
76
81
|
* automatically reconnect if the connection is closed unexpectedly.
|
@@ -79,7 +84,8 @@ declare class Client<T extends Routes = Routes, U extends Channels = Channels> {
|
|
79
84
|
* @param options The options to pass to the connection.
|
80
85
|
* @returns The WebSocket connection.
|
81
86
|
*/
|
82
|
-
connect<P extends keyof U & string
|
87
|
+
connect<P extends keyof U & string>(channel: P, options?: U[P]): Awaitable<WebSocketChannel<U[P]>, WebSocketChannel<U[P]>>;
|
88
|
+
connect(channel: string, options?: ConnectOptions): Awaitable<WebSocketChannel, WebSocketChannel>;
|
83
89
|
}
|
84
90
|
/**
|
85
91
|
* Create a new type-safe client for the application. The client can be used to fetch data from
|
package/dist/createClient.js
CHANGED
@@ -1,8 +1,8 @@
|
|
1
1
|
import { attempt } from "@unshared/functions/attempt";
|
2
|
-
import { f as fetch } from "./chunks/
|
3
|
-
import {
|
4
|
-
import
|
5
|
-
import "./chunks/
|
2
|
+
import { f as fetch, r as request } from "./chunks/D1QsGr3A.js";
|
3
|
+
import { c as connect } from "./chunks/Bys4-xE2.js";
|
4
|
+
import "./chunks/CS5r-m4U.js";
|
5
|
+
import "./chunks/B6pUErTM.js";
|
6
6
|
import "@unshared/functions/awaitable";
|
7
7
|
import "@unshared/functions";
|
8
8
|
class Client {
|
@@ -15,70 +15,15 @@ class Client {
|
|
15
15
|
constructor(options = {}) {
|
16
16
|
this.options = options;
|
17
17
|
}
|
18
|
-
/**
|
19
|
-
* Fetch a route from the API and return the `Response` object. If the client was instantiated with an
|
20
|
-
* application, the route name will be inferred from the application routes. Otherwise, you
|
21
|
-
* can pass the route name as a string.
|
22
|
-
*
|
23
|
-
* @param route The name of the route to fetch.
|
24
|
-
* @param options The options to pass to the request.
|
25
|
-
* @returns The response from the server.
|
26
|
-
*/
|
27
18
|
fetch(route, options) {
|
28
19
|
return fetch(route, { ...this.options, ...options });
|
29
20
|
}
|
30
|
-
/**
|
31
|
-
* Fetch a route from the API and return the data. If the client was instantiated with an
|
32
|
-
* application, the route name will be inferred from the application routes. Otherwise, you
|
33
|
-
* can pass the route name as a string.
|
34
|
-
*
|
35
|
-
* @param route The name of the route to fetch.
|
36
|
-
* @param options The options to pass to the request.
|
37
|
-
* @returns The data from the API.
|
38
|
-
* @example
|
39
|
-
* // Declare the application type.
|
40
|
-
* type App = Application<[ModuleProduct]>
|
41
|
-
*
|
42
|
-
* // Create a type-safe client for the application.
|
43
|
-
* const request = createClient<App>()
|
44
|
-
*
|
45
|
-
* // Fetch the data from the API.
|
46
|
-
* const data = request('GET /api/product/:id', { data: { id: '1' } })
|
47
|
-
*/
|
48
21
|
request(route, options) {
|
49
22
|
return request(route, { ...this.options, ...options });
|
50
23
|
}
|
51
|
-
/**
|
52
|
-
* Attempt to fetch a route from the API and return the data. If the client was instantiated with an
|
53
|
-
* application, the route name will be inferred from the application routes. Otherwise, you
|
54
|
-
* can pass the route name as a string.
|
55
|
-
*
|
56
|
-
* @param route The name of the route to fetch.
|
57
|
-
* @param options The options to pass to the request.
|
58
|
-
* @returns A result object with either the data or an error.
|
59
|
-
* @example
|
60
|
-
* // Declare the application type.
|
61
|
-
* type App = Application<[ModuleProduct]>
|
62
|
-
*
|
63
|
-
* // Create a type-safe client for the application.
|
64
|
-
* const request = createClient<App>()
|
65
|
-
*
|
66
|
-
* // Fetch the data from the API.
|
67
|
-
* const { data, error } = requestAttempt('GET /api/product/:id', { data: { id: '1' } })
|
68
|
-
* if (error) console.error(error)
|
69
|
-
* else console.log(data)
|
70
|
-
*/
|
71
24
|
requestAttempt(route, options) {
|
72
25
|
return attempt(() => this.request(route, options));
|
73
26
|
}
|
74
|
-
/**
|
75
|
-
* Create a new WebSocket connection to the server with the given path. The connection will
|
76
|
-
* automatically reconnect if the connection is closed unexpectedly.
|
77
|
-
*
|
78
|
-
* @param channel The path to connect to.
|
79
|
-
* @param options The options to pass to the connection.
|
80
|
-
* @returns The WebSocket connection.
|
81
|
-
*/
|
82
27
|
connect(channel, options) {
|
83
28
|
return connect(channel, { baseUrl: this.options.baseUrl, ...options });
|
84
29
|
}
|
package/dist/createClient.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"createClient.js","sources":["../createClient.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions'\nimport type { Result } from '@unshared/functions/attempt'\nimport type { ServiceOptions } from './createService'\nimport type { OpenAPILike, OpenAPIOptionsMap } from './openapi'\nimport type { RequestOptions } from './utils'\nimport type { ConnectOptions, WebSocketChannel } from './websocket'\nimport { attempt } from '@unshared/functions/attempt'\nimport { fetch } from './utils/fetch'\nimport { request } from './utils/request'\nimport { connect } from './websocket/connect'\n\ntype Data<T extends RequestOptions> = T extends RequestOptions<any, any, any, any, any, any, infer R, any> ? R : unknown\ntype Routes = Record<string, RequestOptions>\ntype Channels = Record<string, ConnectOptions>\n\nexport class Client<T extends Routes = Routes, U extends Channels = Channels> {\n\n /**\n * Create a new client for the application.\n *\n * @param options The options to pass to the client.\n * @example new Client({ baseUrl: 'https://api.example.com' })\n */\n constructor(public options: RequestOptions = {}) {}\n\n /**\n * Fetch a route from the API and return the `Response` object. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n */\n public fetch<K extends keyof T & string,
|
1
|
+
{"version":3,"file":"createClient.js","sources":["../createClient.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions'\nimport type { Result } from '@unshared/functions/attempt'\nimport type { ServiceOptions } from './createService'\nimport type { OpenAPILike, OpenAPIOptionsMap } from './openapi'\nimport type { FetchOptions, RequestOptions } from './utils'\nimport type { ConnectOptions, WebSocketChannel } from './websocket'\nimport { attempt } from '@unshared/functions/attempt'\nimport { fetch } from './utils/fetch'\nimport { request } from './utils/request'\nimport { connect } from './websocket/connect'\n\ntype Data<T extends RequestOptions> = T extends RequestOptions<any, any, any, any, any, any, infer R, any> ? R : unknown\ntype Routes = Record<string, RequestOptions>\ntype Channels = Record<string, ConnectOptions>\n\nexport class Client<T extends Routes = Routes, U extends Channels = Channels> {\n\n /**\n * Create a new client for the application.\n *\n * @param options The options to pass to the client.\n * @example new Client({ baseUrl: 'https://api.example.com' })\n */\n constructor(public options: RequestOptions = {}) {}\n\n /**\n * Fetch a route from the API and return the `Response` object. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n */\n public fetch<K extends keyof T & string>(route: K, options?: T[K]): Promise<Response & { json: () => Promise<Data<T[K]>> }>\n public fetch(route: string, options?: FetchOptions): Promise<Response>\n public fetch(route: string, options?: FetchOptions): Promise<Response> {\n return fetch(route, { ...this.options, ...options })\n }\n\n /**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\n public request<K extends keyof T & string>(route: K, options?: T[K]): Promise<Data<T[K]>>\n public request(route: string, options?: RequestOptions): Promise<unknown>\n public request(route: string, options?: RequestOptions): Promise<unknown> {\n return request(route, { ...this.options, ...options })\n }\n\n /**\n * Attempt to fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns A result object with either the data or an error.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const { data, error } = requestAttempt('GET /api/product/:id', { data: { id: '1' } })\n * if (error) console.error(error)\n * else console.log(data)\n */\n public requestAttempt<K extends keyof T & string>(route: K, options?: T[K]): Promise<Result<Data<T[K]>>>\n public requestAttempt(route: string, options?: RequestOptions): Promise<Result<unknown>>\n public requestAttempt(route: string, options?: RequestOptions): Promise<Result<unknown>> {\n return attempt(() => this.request(route, options))\n }\n\n /**\n * Create a new WebSocket connection to the server with the given path. The connection will\n * automatically reconnect if the connection is closed unexpectedly.\n *\n * @param channel The path to connect to.\n * @param options The options to pass to the connection.\n * @returns The WebSocket connection.\n */\n public connect<P extends keyof U & string>(channel: P, options?: U[P]): Awaitable<WebSocketChannel<U[P]>, WebSocketChannel<U[P]>>\n public connect(channel: string, options?: ConnectOptions): Awaitable<WebSocketChannel, WebSocketChannel>\n public connect(channel: string, options?: ConnectOptions): Awaitable<WebSocketChannel, WebSocketChannel> {\n return connect(channel, { baseUrl: this.options.baseUrl, ...options })\n }\n}\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends OpenAPILike>(options?: ServiceOptions<T>): Client<OpenAPIOptionsMap<T>>\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends Routes = Routes, V extends Channels = Channels>(options?: RequestOptions): Client<T, V>\nexport function createClient(options?: RequestOptions): Client {\n return new Client(options)\n}\n"],"names":[],"mappings":";;;;;;;AAeO,MAAM,OAAiE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ5E,YAAmB,UAA0B,IAAI;AAA9B,SAAA,UAAA;AAAA,EAAA;AAAA,EAaZ,MAAM,OAAe,SAA2C;AAC9D,WAAA,MAAM,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA,EAuB9C,QAAQ,OAAe,SAA4C;AACjE,WAAA,QAAQ,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA,EAyBhD,eAAe,OAAe,SAAoD;AACvF,WAAO,QAAQ,MAAM,KAAK,QAAQ,OAAO,OAAO,CAAC;AAAA,EAAA;AAAA,EAa5C,QAAQ,SAAiB,SAAyE;AAChG,WAAA,QAAQ,SAAS,EAAE,SAAS,KAAK,QAAQ,SAAS,GAAG,SAAS;AAAA,EAAA;AAEzE;AAqCO,SAAS,aAAa,SAAkC;AACtD,SAAA,IAAI,OAAO,OAAO;AAC3B;"}
|
package/dist/createService.cjs
CHANGED
@@ -1,12 +1,12 @@
|
|
1
1
|
"use strict";
|
2
|
-
var
|
3
|
-
require("./chunks/
|
2
|
+
var resolveOperationTokenOptions = require("./chunks/DEyigyGy.cjs"), handleResponse = require("./chunks/CVzmr2NA.cjs");
|
3
|
+
require("./chunks/BDxlAULu.cjs");
|
4
4
|
require("@unshared/functions/awaitable");
|
5
5
|
function createService(document, initialOptions) {
|
6
6
|
return new Proxy({}, {
|
7
7
|
get(_, id) {
|
8
8
|
return async (data, options) => {
|
9
|
-
const baseUrl =
|
9
|
+
const baseUrl = resolveOperationTokenOptions.getServerUrl(document), operation = resolveOperationTokenOptions.resolveOperation(document, id), tokenOptions = resolveOperationTokenOptions.resolveOperationTokenOptions(document, operation), { method, path, responses = {} } = operation, { url, init } = handleResponse.parseRequest(path, { method, baseUrl, data, ...tokenOptions, ...initialOptions, ...options }), response = await globalThis.fetch(url, init);
|
10
10
|
if (response.ok) return handleResponse.handleResponse(response, { ...initialOptions, ...options });
|
11
11
|
const status = response.status.toString();
|
12
12
|
throw status in responses && typeof responses[status] == "object" && responses[status] !== null && "description" in responses[status] && typeof responses[status].description == "string" ? new Error(responses[status].description) : new Error(response.statusText);
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"createService.cjs","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport {
|
1
|
+
{"version":3,"file":"createService.cjs","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport { resolveOperationTokenOptions } from './openapi/resolveOperationTokenOptions'\nimport { handleResponse } from './utils/handleResponse'\nimport { parseRequest } from './utils/parseRequest'\n\n/** A service instance for the given OpenAPI specification. */\nexport type Service<T> = {\n [K in OperationId<T>]:\n OperationById<T, K> extends infer U extends OperationById<T, K>\n ? (data: OperationOptions<T, U>['data'], options?: OperationOptions<T, U>) => Promise<OperationResult<T, U>>\n : never\n}\n\n/** The options to pass to the service client. */\nexport interface ServiceOptions<T = any> extends RequestOptions {\n baseUrl?: MaybeLiteral<ServerUrl<T>>\n headers?: T extends { openapi: string } ? OpenAPIV3.ServerHeaders<T> : never\n}\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n *\n * // Import the Giphy OpenAPI specification.\n * import Giphy from './giphy.openapi.json'\n *\n * // Create a new service instance for the Giphy API.\n * const service = createService(Giphy, { headers: { 'Bearer' } })\n *\n * // Request the \"searchGifs\" operation from the Giphy API.\n * await service.getGifs({ limit: 10, offset: 0, q: 'cats' }) // => { data: [...] }\n */\nexport function createService<T extends object>(document: Readonly<T>, initialOptions?: ServiceOptions<T>): Service<T> {\n return new Proxy({}, {\n get(_, id: OperationId<T>) {\n return async(data: object, options: RequestOptions) => {\n\n // --- Find the operation in the OpenAPI specification.\n const baseUrl = getServerUrl(document)\n const operation = resolveOperation(document, id) as Operation\n const tokenOptions = resolveOperationTokenOptions(document, operation)\n\n // --- Fetch the relevant resource from the server.\n const { method, path, responses = {} } = operation\n const { url, init } = parseRequest(path, { method, baseUrl, data, ...tokenOptions, ...initialOptions, ...options })\n const response = await globalThis.fetch(url, init)\n if (response.ok) return handleResponse(response, { ...initialOptions, ...options })\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n },\n }) as Service<T>\n}\n"],"names":["getServerUrl","resolveOperation","resolveOperationTokenOptions","parseRequest","handleResponse"],"mappings":";;;;AAwCgB,SAAA,cAAgC,UAAuB,gBAAgD;AAC9G,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,IAAoB;AAClB,aAAA,OAAM,MAAc,YAA4B;AAG/C,cAAA,UAAUA,0CAAa,QAAQ,GAC/B,YAAYC,8CAAiB,UAAU,EAAE,GACzC,eAAeC,6BAAAA,6BAA6B,UAAU,SAAS,GAG/D,EAAE,QAAQ,MAAM,YAAY,OAAO,WACnC,EAAE,KAAK,KAAA,IAASC,eAAAA,aAAa,MAAM,EAAE,QAAQ,SAAS,MAAM,GAAG,cAAc,GAAG,gBAAgB,GAAG,QAAS,CAAA,GAC5G,WAAW,MAAM,WAAW,MAAM,KAAK,IAAI;AAC7C,YAAA,SAAS,GAAI,QAAOC,eAAe,eAAA,UAAU,EAAE,GAAG,gBAAgB,GAAG,SAAS;AAG5E,cAAA,SAAS,SAAS,OAAO,SAAS;AACxC,cAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,MACrC;AAAA,IAAA;AAAA,EACF,CACD;AACH;;"}
|
package/dist/createService.d.ts
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
import { MaybeLiteral } from '@unshared/types';
|
2
|
-
import { b as OperationId, c as OperationById, d as OperationOptions, e as OperationResult, S as ServerUrl, f as OpenAPIV3 } from './chunks/
|
3
|
-
import { R as RequestOptions } from './chunks/
|
2
|
+
import { b as OperationId, c as OperationById, d as OperationOptions, e as OperationResult, S as ServerUrl, f as OpenAPIV3 } from './chunks/5p4H9ZaI.js';
|
3
|
+
import { R as RequestOptions } from './chunks/Nc32BOzg.js';
|
4
4
|
import 'openapi-types';
|
5
5
|
import './HttpHeaders.js';
|
6
6
|
import './HttpMethods.js';
|
package/dist/createService.js
CHANGED
@@ -1,12 +1,12 @@
|
|
1
|
-
import { g as getServerUrl, r as resolveOperation } from "./chunks/
|
2
|
-
import {
|
3
|
-
import "./chunks/
|
1
|
+
import { g as getServerUrl, r as resolveOperation, a as resolveOperationTokenOptions } from "./chunks/B_Gz6Yz8.js";
|
2
|
+
import { p as parseRequest, h as handleResponse } from "./chunks/CS5r-m4U.js";
|
3
|
+
import "./chunks/B6pUErTM.js";
|
4
4
|
import "@unshared/functions/awaitable";
|
5
5
|
function createService(document, initialOptions) {
|
6
6
|
return new Proxy({}, {
|
7
7
|
get(_, id) {
|
8
8
|
return async (data, options) => {
|
9
|
-
const baseUrl = getServerUrl(document), operation = resolveOperation(document, id), { method, path, responses = {} } = operation,
|
9
|
+
const baseUrl = getServerUrl(document), operation = resolveOperation(document, id), tokenOptions = resolveOperationTokenOptions(document, operation), { method, path, responses = {} } = operation, { url, init } = parseRequest(path, { method, baseUrl, data, ...tokenOptions, ...initialOptions, ...options }), response = await globalThis.fetch(url, init);
|
10
10
|
if (response.ok) return handleResponse(response, { ...initialOptions, ...options });
|
11
11
|
const status = response.status.toString();
|
12
12
|
throw status in responses && typeof responses[status] == "object" && responses[status] !== null && "description" in responses[status] && typeof responses[status].description == "string" ? new Error(responses[status].description) : new Error(response.statusText);
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"createService.js","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport {
|
1
|
+
{"version":3,"file":"createService.js","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport { resolveOperationTokenOptions } from './openapi/resolveOperationTokenOptions'\nimport { handleResponse } from './utils/handleResponse'\nimport { parseRequest } from './utils/parseRequest'\n\n/** A service instance for the given OpenAPI specification. */\nexport type Service<T> = {\n [K in OperationId<T>]:\n OperationById<T, K> extends infer U extends OperationById<T, K>\n ? (data: OperationOptions<T, U>['data'], options?: OperationOptions<T, U>) => Promise<OperationResult<T, U>>\n : never\n}\n\n/** The options to pass to the service client. */\nexport interface ServiceOptions<T = any> extends RequestOptions {\n baseUrl?: MaybeLiteral<ServerUrl<T>>\n headers?: T extends { openapi: string } ? OpenAPIV3.ServerHeaders<T> : never\n}\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n *\n * // Import the Giphy OpenAPI specification.\n * import Giphy from './giphy.openapi.json'\n *\n * // Create a new service instance for the Giphy API.\n * const service = createService(Giphy, { headers: { 'Bearer' } })\n *\n * // Request the \"searchGifs\" operation from the Giphy API.\n * await service.getGifs({ limit: 10, offset: 0, q: 'cats' }) // => { data: [...] }\n */\nexport function createService<T extends object>(document: Readonly<T>, initialOptions?: ServiceOptions<T>): Service<T> {\n return new Proxy({}, {\n get(_, id: OperationId<T>) {\n return async(data: object, options: RequestOptions) => {\n\n // --- Find the operation in the OpenAPI specification.\n const baseUrl = getServerUrl(document)\n const operation = resolveOperation(document, id) as Operation\n const tokenOptions = resolveOperationTokenOptions(document, operation)\n\n // --- Fetch the relevant resource from the server.\n const { method, path, responses = {} } = operation\n const { url, init } = parseRequest(path, { method, baseUrl, data, ...tokenOptions, ...initialOptions, ...options })\n const response = await globalThis.fetch(url, init)\n if (response.ok) return handleResponse(response, { ...initialOptions, ...options })\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n },\n }) as Service<T>\n}\n"],"names":[],"mappings":";;;;AAwCgB,SAAA,cAAgC,UAAuB,gBAAgD;AAC9G,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,IAAoB;AAClB,aAAA,OAAM,MAAc,YAA4B;AAG/C,cAAA,UAAU,aAAa,QAAQ,GAC/B,YAAY,iBAAiB,UAAU,EAAE,GACzC,eAAe,6BAA6B,UAAU,SAAS,GAG/D,EAAE,QAAQ,MAAM,YAAY,OAAO,WACnC,EAAE,KAAK,KAAA,IAAS,aAAa,MAAM,EAAE,QAAQ,SAAS,MAAM,GAAG,cAAc,GAAG,gBAAgB,GAAG,QAAS,CAAA,GAC5G,WAAW,MAAM,WAAW,MAAM,KAAK,IAAI;AAC7C,YAAA,SAAS,GAAI,QAAO,eAAe,UAAU,EAAE,GAAG,gBAAgB,GAAG,SAAS;AAG5E,cAAA,SAAS,SAAS,OAAO,SAAS;AACxC,cAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,MACrC;AAAA,IAAA;AAAA,EACF,CACD;AACH;"}
|
package/dist/index.cjs
CHANGED
@@ -1,13 +1,13 @@
|
|
1
1
|
"use strict";
|
2
2
|
var createClient = require("./createClient.cjs"), createService = require("./createService.cjs"), HttpHeaders = require("./HttpHeaders.cjs"), HttpMethods = require("./HttpMethods.cjs"), HttpStatusCodes = require("./HttpStatusCodes.cjs");
|
3
3
|
require("@unshared/functions/attempt");
|
4
|
-
require("./chunks/
|
5
|
-
require("./chunks/
|
4
|
+
require("./chunks/DXrQkl1A.cjs");
|
5
|
+
require("./chunks/CVzmr2NA.cjs");
|
6
|
+
require("./chunks/BDxlAULu.cjs");
|
6
7
|
require("@unshared/functions/awaitable");
|
7
|
-
require("./chunks/
|
8
|
-
require("./chunks/BMbsYNBd.cjs");
|
8
|
+
require("./chunks/BdFNzMcu.cjs");
|
9
9
|
require("@unshared/functions");
|
10
|
-
require("./chunks/
|
10
|
+
require("./chunks/DEyigyGy.cjs");
|
11
11
|
exports.Client = createClient.Client;
|
12
12
|
exports.createClient = createClient.createClient;
|
13
13
|
exports.createService = createService.createService;
|
package/dist/index.d.ts
CHANGED
@@ -5,8 +5,8 @@ export { HttpMethod } from './HttpMethods.js';
|
|
5
5
|
export { HttpStatusCode } from './HttpStatusCodes.js';
|
6
6
|
import '@unshared/functions';
|
7
7
|
import '@unshared/functions/attempt';
|
8
|
-
import './chunks/
|
8
|
+
import './chunks/Nc32BOzg.js';
|
9
9
|
import '@unshared/types';
|
10
|
-
import './chunks/
|
10
|
+
import './chunks/5p4H9ZaI.js';
|
11
11
|
import 'openapi-types';
|
12
12
|
import './websocket.js';
|
package/dist/index.js
CHANGED
@@ -4,13 +4,13 @@ import { HttpHeader } from "./HttpHeaders.js";
|
|
4
4
|
import { HttpMethod } from "./HttpMethods.js";
|
5
5
|
import { HttpStatusCode } from "./HttpStatusCodes.js";
|
6
6
|
import "@unshared/functions/attempt";
|
7
|
-
import "./chunks/
|
8
|
-
import "./chunks/
|
7
|
+
import "./chunks/D1QsGr3A.js";
|
8
|
+
import "./chunks/CS5r-m4U.js";
|
9
|
+
import "./chunks/B6pUErTM.js";
|
9
10
|
import "@unshared/functions/awaitable";
|
10
|
-
import "./chunks/
|
11
|
-
import "./chunks/6IxvRpmY.js";
|
11
|
+
import "./chunks/Bys4-xE2.js";
|
12
12
|
import "@unshared/functions";
|
13
|
-
import "./chunks/
|
13
|
+
import "./chunks/B_Gz6Yz8.js";
|
14
14
|
export {
|
15
15
|
Client,
|
16
16
|
HttpHeader,
|
package/dist/openapi.cjs
CHANGED
@@ -1,5 +1,11 @@
|
|
1
1
|
"use strict";
|
2
|
-
var
|
2
|
+
var resolveOperationTokenOptions = require("./chunks/DEyigyGy.cjs");
|
3
|
+
function isOpenAPIV2(value) {
|
4
|
+
return typeof value == "object" && value !== null && "swagger" in value && value.swagger === "2.0";
|
5
|
+
}
|
6
|
+
function isOpenAPIV3_1(value) {
|
7
|
+
return typeof value == "object" && value !== null && "openapi" in value && value.openapi === "3.1.0";
|
8
|
+
}
|
3
9
|
function isReferenceObject(value) {
|
4
10
|
return typeof value == "object" && value !== null && "$ref" in value && typeof value.$ref == "string";
|
5
11
|
}
|
@@ -27,8 +33,12 @@ function resolveDocument(value, document = value) {
|
|
27
33
|
}
|
28
34
|
});
|
29
35
|
}
|
30
|
-
exports.getServerUrl =
|
31
|
-
exports.
|
36
|
+
exports.getServerUrl = resolveOperationTokenOptions.getServerUrl;
|
37
|
+
exports.isOpenAPIV3 = resolveOperationTokenOptions.isOpenAPIV3;
|
38
|
+
exports.resolveOperation = resolveOperationTokenOptions.resolveOperation;
|
39
|
+
exports.resolveOperationTokenOptions = resolveOperationTokenOptions.resolveOperationTokenOptions;
|
40
|
+
exports.isOpenAPIV2 = isOpenAPIV2;
|
41
|
+
exports.isOpenAPIV3_1 = isOpenAPIV3_1;
|
32
42
|
exports.isReferenceObject = isReferenceObject;
|
33
43
|
exports.resolveDocument = resolveDocument;
|
34
44
|
exports.resolveReference = resolveReference;
|
package/dist/openapi.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"openapi.cjs","sources":["../openapi/isReferenceObject.ts","../openapi/resolveReference.ts","../openapi/resolveDocument.ts"],"sourcesContent":["import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\n\nexport type OpenAPIReference =\n | OpenAPIV2.ReferenceObject\n | OpenAPIV3.ReferenceObject\n | OpenAPIV3_1.ReferenceObject\n\n/**\n * Check if a value is an {@linkcode OpenAPIReference}.\n *\n * @param value The value to check.\n * @returns `true` if the value is a reference object.\n * @example isReferenceObject({ $ref: '#/components/schemas/MySchema' }) // true\n */\nexport function isReferenceObject<T extends OpenAPIReference>(value: unknown): value is T {\n return typeof value === 'object'\n && value !== null\n && '$ref' in value\n && typeof value.$ref === 'string'\n}\n","import type { StringJoin, StringReplace, WriteableDeep } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport { isReferenceObject } from './isReferenceObject'\n\n/**\n * Decode an OpenAPI reference path by replacing the encoded characters with\n * their original values. This function will replace `~0` with `~` and `~1`\n * with `/`.\n *\n * @example DecodeReference<'#/foo~1bar~0baz'> // '#/foo/bar~baz'\n */\nexport type OpenAPIReferenceDecoded<T extends string> =\n StringReplace<StringReplace<T, '~0', '~'>, '~1', '/'>\n\n/**\n * Extract the parts of a reference path as a tuple.\n *\n * @example OpenAPIV3ReferencePath<'#/paths/~1users~1{username}'> // ['paths', '/users/{username}']\n */\nexport type OpenAPIReferencePath<T extends string> =\n T extends `#/${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `#/${infer P}` ? [P]\n : T extends `${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `${infer P}` ? [P]\n : []\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The result type.\n * @example Resolved<{ $ref: '#/info' }, { info: { title: string } }> // { title: string }\n */\nexport type OpenAPIReferenceResolved<\n T extends OpenAPIReference,\n D extends object,\n> =\n D extends object\n ? T extends { $ref: infer R extends string }\n\n // --- Match last part of the reference.\n ? OpenAPIReferencePath<R> extends [infer P extends string]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? WriteableDeep<Omit<D[OpenAPIReferenceDecoded<P>], keyof T>>\n : never\n : never\n\n // --- Match middle part of the reference.\n : OpenAPIReferencePath<R> extends [infer P extends string, ...infer Rest extends string[]]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? OpenAPIReferenceResolved<{ $ref: StringJoin<Rest, '/'> }, D[OpenAPIReferenceDecoded<P>]>\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Resolve an OpenAPI `ReferenceObject` to the component it references. If the\n * source is not a reference, the source will be returned.\n *\n * @private\n * @param reference The reference object to resolve.\n * @param document The OpenAPI document to resolve the reference from.\n * @returns The result component.\n * @example resolveReference({ $ref: '#/components/schemas/User' }, document)\n */\nexport function resolveReference<\n T extends OpenAPIReference,\n D extends object,\n>(reference: Readonly<T>, document: Readonly<D>): OpenAPIReferenceResolved<T, D> {\n\n // --- Return the source if it is not a reference.\n if (!isReferenceObject(reference))\n throw new TypeError('Expected value to be an OpenAPI reference object.')\n\n // --- Assert that the parameters are valid.\n if (typeof document !== 'object' || document === null)\n throw new TypeError('Expected OpenAPI specification to be an object.')\n\n // --- Resolve the component with it's reference path.\n const referenceParts = reference.$ref.replace(/^#\\//, '').split('/')\n let result = document\n for (const part of referenceParts) {\n if (result === undefined) break\n if (typeof result !== 'object' || result === null) break\n const key = part.replaceAll('~1', '/').replaceAll('~0', '~')\n // @ts-expect-error: assume the part is a key of the object.\n result = result[key] as unknown\n }\n\n // --- Throw an error if the component could not be result.\n if (result === undefined)\n throw new Error(`Could not resolve OpenAPI component: ${reference.$ref}`)\n\n // --- Return the result component.\n return result as OpenAPIReferenceResolved<T, D>\n}\n","import type { ObjectLike, Substract } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport type { OpenAPIReferenceResolved } from './resolveReference'\nimport { isReferenceObject } from './isReferenceObject'\nimport { resolveReference as resolveReference } from './resolveReference'\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The resolved type.\n * @example\n * type Resolved = OpenAPIResolved<{\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' }\n * }\n * }\n * }>\n */\nexport type OpenAPIResolved<T, D = T, N extends number = 8> =\n N extends 0 ? T\n : T extends OpenAPIReference\n ? D extends object ? OpenAPIResolved<OpenAPIReferenceResolved<T, D>, D, Substract<N, 1>> : never\n : T extends object ? { -readonly [K in keyof T]: OpenAPIResolved<T[K], D, N> } : T\n\n/**\n * Recursively resolve all references in an OpenAPI specification. This function\n * will return a `Proxy` object that will resolve references on the fly.\n *\n * @param value The OpenAPI specification.\n * @returns The resolved OpenAPI specification.\n * @example\n * const resolved = resolveReferences({\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' },\n * },\n * },\n * })\n */\nexport function resolveDocument<T extends object>(value: Readonly<T>): OpenAPIResolved<T>\nexport function resolveDocument<T extends object, D>(value: Readonly<T>, document: Readonly<D>): OpenAPIResolved<T, D>\nexport function resolveDocument(value: Readonly<ObjectLike>, document = value): unknown {\n return new Proxy(value, {\n get(target, property: string) {\n let value = target[property]\n\n // --- Abort if no document is provided.\n if (!document) return value\n\n // --- Resolve the reference if it is a reference object.\n if (isReferenceObject(value))\n value = resolveReference(value, document)\n\n // --- Recursively resolve references in objects.\n if (typeof value === 'object' && value !== null)\n return resolveDocument(value as ObjectLike, document)\n\n // --- Return the value as is.\n return value\n },\n })\n}\n"],"names":["value"],"mappings":";;
|
1
|
+
{"version":3,"file":"openapi.cjs","sources":["../openapi/isOpenAPIV2.ts","../openapi/isOpenAPIV3_1.ts","../openapi/isReferenceObject.ts","../openapi/resolveReference.ts","../openapi/resolveDocument.ts"],"sourcesContent":["/* eslint-disable unicorn/filename-case */\nimport type { OpenAPIV2 } from 'openapi-types'\n\n/**\n * Check if the given document is an OpenAPI v2 specification.\n *\n * @param value The document to check.\n * @returns `true` if the document is an OpenAPI v2 specification, `false` otherwise.\n * @example isOpenAPIV2({ swagger: '2.0', info: { title: 'Test API', version: '1.0.0' } }) // => true\n */\nexport function isOpenAPIV2(value: unknown): value is OpenAPIV2.Document {\n return typeof value === 'object'\n && value !== null\n && 'swagger' in value\n && value.swagger === '2.0'\n}\n","/* eslint-disable unicorn/filename-case */\nimport type { OpenAPIV3_1 } from 'openapi-types'\n\n/**\n * Check if the given document is an OpenAPI v3.1 specification.\n *\n * @param value The document to check.\n * @returns `true` if the document is an OpenAPI v3.1 specification, `false` otherwise.\n * @example isOpenAPIV3_1({ openapi: '3.1.0', info: { title: 'Test API', version: '1.0.0' } }) // => true\n */\nexport function isOpenAPIV3_1(value: unknown): value is OpenAPIV3_1.Document {\n return typeof value === 'object'\n && value !== null\n && 'openapi' in value\n && value.openapi === '3.1.0'\n}\n","import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\n\nexport type OpenAPIReference =\n | OpenAPIV2.ReferenceObject\n | OpenAPIV3.ReferenceObject\n | OpenAPIV3_1.ReferenceObject\n\n/**\n * Check if a value is an {@linkcode OpenAPIReference}.\n *\n * @param value The value to check.\n * @returns `true` if the value is a reference object.\n * @example isReferenceObject({ $ref: '#/components/schemas/MySchema' }) // true\n */\nexport function isReferenceObject<T extends OpenAPIReference>(value: unknown): value is T {\n return typeof value === 'object'\n && value !== null\n && '$ref' in value\n && typeof value.$ref === 'string'\n}\n","import type { StringJoin, StringReplace, WriteableDeep } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport { isReferenceObject } from './isReferenceObject'\n\n/**\n * Decode an OpenAPI reference path by replacing the encoded characters with\n * their original values. This function will replace `~0` with `~` and `~1`\n * with `/`.\n *\n * @example DecodeReference<'#/foo~1bar~0baz'> // '#/foo/bar~baz'\n */\nexport type OpenAPIReferenceDecoded<T extends string> =\n StringReplace<StringReplace<T, '~0', '~'>, '~1', '/'>\n\n/**\n * Extract the parts of a reference path as a tuple.\n *\n * @example OpenAPIV3ReferencePath<'#/paths/~1users~1{username}'> // ['paths', '/users/{username}']\n */\nexport type OpenAPIReferencePath<T extends string> =\n T extends `#/${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `#/${infer P}` ? [P]\n : T extends `${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `${infer P}` ? [P]\n : []\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The result type.\n * @example Resolved<{ $ref: '#/info' }, { info: { title: string } }> // { title: string }\n */\nexport type OpenAPIReferenceResolved<\n T extends OpenAPIReference,\n D extends object,\n> =\n D extends object\n ? T extends { $ref: infer R extends string }\n\n // --- Match last part of the reference.\n ? OpenAPIReferencePath<R> extends [infer P extends string]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? WriteableDeep<Omit<D[OpenAPIReferenceDecoded<P>], keyof T>>\n : never\n : never\n\n // --- Match middle part of the reference.\n : OpenAPIReferencePath<R> extends [infer P extends string, ...infer Rest extends string[]]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? OpenAPIReferenceResolved<{ $ref: StringJoin<Rest, '/'> }, D[OpenAPIReferenceDecoded<P>]>\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Resolve an OpenAPI `ReferenceObject` to the component it references. If the\n * source is not a reference, the source will be returned.\n *\n * @private\n * @param reference The reference object to resolve.\n * @param document The OpenAPI document to resolve the reference from.\n * @returns The result component.\n * @example resolveReference({ $ref: '#/components/schemas/User' }, document)\n */\nexport function resolveReference<\n T extends OpenAPIReference,\n D extends object,\n>(reference: Readonly<T>, document: Readonly<D>): OpenAPIReferenceResolved<T, D> {\n\n // --- Return the source if it is not a reference.\n if (!isReferenceObject(reference))\n throw new TypeError('Expected value to be an OpenAPI reference object.')\n\n // --- Assert that the parameters are valid.\n if (typeof document !== 'object' || document === null)\n throw new TypeError('Expected OpenAPI specification to be an object.')\n\n // --- Resolve the component with it's reference path.\n const referenceParts = reference.$ref.replace(/^#\\//, '').split('/')\n let result = document\n for (const part of referenceParts) {\n if (result === undefined) break\n if (typeof result !== 'object' || result === null) break\n const key = part.replaceAll('~1', '/').replaceAll('~0', '~')\n // @ts-expect-error: assume the part is a key of the object.\n result = result[key] as unknown\n }\n\n // --- Throw an error if the component could not be result.\n if (result === undefined)\n throw new Error(`Could not resolve OpenAPI component: ${reference.$ref}`)\n\n // --- Return the result component.\n return result as OpenAPIReferenceResolved<T, D>\n}\n","import type { ObjectLike, Substract } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport type { OpenAPIReferenceResolved } from './resolveReference'\nimport { isReferenceObject } from './isReferenceObject'\nimport { resolveReference as resolveReference } from './resolveReference'\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The resolved type.\n * @example\n * type Resolved = OpenAPIResolved<{\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' }\n * }\n * }\n * }>\n */\nexport type OpenAPIResolved<T, D = T, N extends number = 8> =\n N extends 0 ? T\n : T extends OpenAPIReference\n ? D extends object ? OpenAPIResolved<OpenAPIReferenceResolved<T, D>, D, Substract<N, 1>> : never\n : T extends object ? { -readonly [K in keyof T]: OpenAPIResolved<T[K], D, N> } : T\n\n/**\n * Recursively resolve all references in an OpenAPI specification. This function\n * will return a `Proxy` object that will resolve references on the fly.\n *\n * @param value The OpenAPI specification.\n * @returns The resolved OpenAPI specification.\n * @example\n * const resolved = resolveReferences({\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' },\n * },\n * },\n * })\n */\nexport function resolveDocument<T extends object>(value: Readonly<T>): OpenAPIResolved<T>\nexport function resolveDocument<T extends object, D>(value: Readonly<T>, document: Readonly<D>): OpenAPIResolved<T, D>\nexport function resolveDocument(value: Readonly<ObjectLike>, document = value): unknown {\n return new Proxy(value, {\n get(target, property: string) {\n let value = target[property]\n\n // --- Abort if no document is provided.\n if (!document) return value\n\n // --- Resolve the reference if it is a reference object.\n if (isReferenceObject(value))\n value = resolveReference(value, document)\n\n // --- Recursively resolve references in objects.\n if (typeof value === 'object' && value !== null)\n return resolveDocument(value as ObjectLike, document)\n\n // --- Return the value as is.\n return value\n },\n })\n}\n"],"names":["value"],"mappings":";;AAUO,SAAS,YAAY,OAA6C;AAChE,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,aAAa,SACb,MAAM,YAAY;AACzB;ACLO,SAAS,cAAc,OAA+C;AACpE,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,aAAa,SACb,MAAM,YAAY;AACzB;ACDO,SAAS,kBAA8C,OAA4B;AACjF,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,UAAU,SACV,OAAO,MAAM,QAAS;AAC7B;ACmDgB,SAAA,iBAGd,WAAwB,UAAuD;AAG3E,MAAA,CAAC,kBAAkB,SAAS;AACxB,UAAA,IAAI,UAAU,mDAAmD;AAGrE,MAAA,OAAO,YAAa,YAAY,aAAa;AACzC,UAAA,IAAI,UAAU,iDAAiD;AAGjE,QAAA,iBAAiB,UAAU,KAAK,QAAQ,QAAQ,EAAE,EAAE,MAAM,GAAG;AACnE,MAAI,SAAS;AACb,aAAW,QAAQ,gBAAgB;AAEjC,QADI,WAAW,UACX,OAAO,UAAW,YAAY,WAAW,KAAM;AAC7C,UAAA,MAAM,KAAK,WAAW,MAAM,GAAG,EAAE,WAAW,MAAM,GAAG;AAE3D,aAAS,OAAO,GAAG;AAAA,EAAA;AAIrB,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,wCAAwC,UAAU,IAAI,EAAE;AAGnE,SAAA;AACT;ACtDgB,SAAA,gBAAgB,OAA6B,WAAW,OAAgB;AAC/E,SAAA,IAAI,MAAM,OAAO;AAAA,IACtB,IAAI,QAAQ,UAAkB;AACxBA,UAAAA,SAAQ,OAAO,QAAQ;AAG3B,aAAK,YAGD,kBAAkBA,MAAK,MACzBA,SAAQ,iBAAiBA,QAAO,QAAQ,IAGtC,OAAOA,UAAU,YAAYA,WAAU,OAClC,gBAAgBA,QAAqB,QAAQ,IAG/CA,UAXeA;AAAAA,IAAA;AAAA,EAYxB,CACD;AACH;;;;;;;;;;"}
|
package/dist/openapi.d.ts
CHANGED
@@ -1,10 +1,37 @@
|
|
1
|
-
export { O as OpenAPILike, a as OpenAPIOptionsMap, h as OpenAPIV2, j as OpenAPIV2Like, f as OpenAPIV3, k as OpenAPIV3Like, i as Operation, c as OperationById, n as OperationByRoute, b as OperationId, d as OperationOptions, l as OperationResponse, e as OperationResult, m as OperationRoute, S as ServerUrl, g as getServerUrl, r as resolveOperation } from './chunks/
|
2
|
-
import { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';
|
1
|
+
export { O as OpenAPILike, a as OpenAPIOptionsMap, h as OpenAPIV2, j as OpenAPIV2Like, f as OpenAPIV3, k as OpenAPIV3Like, i as Operation, c as OperationById, n as OperationByRoute, b as OperationId, d as OperationOptions, l as OperationResponse, e as OperationResult, m as OperationRoute, S as ServerUrl, g as getServerUrl, r as resolveOperation } from './chunks/5p4H9ZaI.js';
|
2
|
+
import { OpenAPIV2, OpenAPIV3, OpenAPIV3_1, OpenAPI } from 'openapi-types';
|
3
3
|
import { StringReplace, WriteableDeep, StringJoin, Substract } from '@unshared/types';
|
4
|
-
import './chunks/
|
4
|
+
import './chunks/Nc32BOzg.js';
|
5
5
|
import './HttpHeaders.js';
|
6
6
|
import './HttpMethods.js';
|
7
7
|
|
8
|
+
/**
|
9
|
+
* Check if the given document is an OpenAPI v2 specification.
|
10
|
+
*
|
11
|
+
* @param value The document to check.
|
12
|
+
* @returns `true` if the document is an OpenAPI v2 specification, `false` otherwise.
|
13
|
+
* @example isOpenAPIV2({ swagger: '2.0', info: { title: 'Test API', version: '1.0.0' } }) // => true
|
14
|
+
*/
|
15
|
+
declare function isOpenAPIV2(value: unknown): value is OpenAPIV2.Document;
|
16
|
+
|
17
|
+
/**
|
18
|
+
* Check if the given document is an OpenAPI v3.0 specification.
|
19
|
+
*
|
20
|
+
* @param value The document to check.
|
21
|
+
* @returns `true` if the document is an OpenAPI v3.0 specification, `false` otherwise.
|
22
|
+
* @example isOpenAPIV3({ openapi: '3.0.0', info: { title: 'Test API', version: '1.0.0' } }) // => true
|
23
|
+
*/
|
24
|
+
declare function isOpenAPIV3(value: unknown): value is OpenAPIV3.Document;
|
25
|
+
|
26
|
+
/**
|
27
|
+
* Check if the given document is an OpenAPI v3.1 specification.
|
28
|
+
*
|
29
|
+
* @param value The document to check.
|
30
|
+
* @returns `true` if the document is an OpenAPI v3.1 specification, `false` otherwise.
|
31
|
+
* @example isOpenAPIV3_1({ openapi: '3.1.0', info: { title: 'Test API', version: '1.0.0' } }) // => true
|
32
|
+
*/
|
33
|
+
declare function isOpenAPIV3_1(value: unknown): value is OpenAPIV3_1.Document;
|
34
|
+
|
8
35
|
type OpenAPIReference = OpenAPIV2.ReferenceObject | OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject;
|
9
36
|
/**
|
10
37
|
* Check if a value is an {@linkcode OpenAPIReference}.
|
@@ -92,4 +119,18 @@ type OpenAPIResolved<T, D = T, N extends number = 8> = N extends 0 ? T : T exten
|
|
92
119
|
declare function resolveDocument<T extends object>(value: Readonly<T>): OpenAPIResolved<T>;
|
93
120
|
declare function resolveDocument<T extends object, D>(value: Readonly<T>, document: Readonly<D>): OpenAPIResolved<T, D>;
|
94
121
|
|
95
|
-
|
122
|
+
interface TokenOptions {
|
123
|
+
tokenLocation?: 'cookie' | 'header' | 'query';
|
124
|
+
tokenProperty?: string;
|
125
|
+
}
|
126
|
+
/**
|
127
|
+
* Resolve the location of the apiKey token based on the OpenAPI specification.
|
128
|
+
*
|
129
|
+
* @param document The OpenAPI specification document.
|
130
|
+
* @param operation The OpenAPI operation object.
|
131
|
+
* @returns The location of the apiKey token ('query' | 'cookie' | 'header').
|
132
|
+
* @example resolveOperationTokenOptions(document, operation) // => { tokenLocation: 'header', tokenProperty: 'X-API-Key' }
|
133
|
+
*/
|
134
|
+
declare function resolveOperationTokenOptions(document: object, operation: OpenAPI.Operation): TokenOptions;
|
135
|
+
|
136
|
+
export { type OpenAPIReference, type OpenAPIReferenceDecoded, type OpenAPIReferencePath, type OpenAPIReferenceResolved, type OpenAPIResolved, type TokenOptions, isOpenAPIV2, isOpenAPIV3, isOpenAPIV3_1, isReferenceObject, resolveDocument, resolveOperationTokenOptions, resolveReference };
|
package/dist/openapi.js
CHANGED
@@ -1,4 +1,10 @@
|
|
1
|
-
import { g, r } from "./chunks/
|
1
|
+
import { g, i, r, a } from "./chunks/B_Gz6Yz8.js";
|
2
|
+
function isOpenAPIV2(value) {
|
3
|
+
return typeof value == "object" && value !== null && "swagger" in value && value.swagger === "2.0";
|
4
|
+
}
|
5
|
+
function isOpenAPIV3_1(value) {
|
6
|
+
return typeof value == "object" && value !== null && "openapi" in value && value.openapi === "3.1.0";
|
7
|
+
}
|
2
8
|
function isReferenceObject(value) {
|
3
9
|
return typeof value == "object" && value !== null && "$ref" in value && typeof value.$ref == "string";
|
4
10
|
}
|
@@ -28,9 +34,13 @@ function resolveDocument(value, document = value) {
|
|
28
34
|
}
|
29
35
|
export {
|
30
36
|
g as getServerUrl,
|
37
|
+
isOpenAPIV2,
|
38
|
+
i as isOpenAPIV3,
|
39
|
+
isOpenAPIV3_1,
|
31
40
|
isReferenceObject,
|
32
41
|
resolveDocument,
|
33
42
|
r as resolveOperation,
|
43
|
+
a as resolveOperationTokenOptions,
|
34
44
|
resolveReference
|
35
45
|
};
|
36
46
|
//# sourceMappingURL=openapi.js.map
|
package/dist/openapi.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"openapi.js","sources":["../openapi/isReferenceObject.ts","../openapi/resolveReference.ts","../openapi/resolveDocument.ts"],"sourcesContent":["import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\n\nexport type OpenAPIReference =\n | OpenAPIV2.ReferenceObject\n | OpenAPIV3.ReferenceObject\n | OpenAPIV3_1.ReferenceObject\n\n/**\n * Check if a value is an {@linkcode OpenAPIReference}.\n *\n * @param value The value to check.\n * @returns `true` if the value is a reference object.\n * @example isReferenceObject({ $ref: '#/components/schemas/MySchema' }) // true\n */\nexport function isReferenceObject<T extends OpenAPIReference>(value: unknown): value is T {\n return typeof value === 'object'\n && value !== null\n && '$ref' in value\n && typeof value.$ref === 'string'\n}\n","import type { StringJoin, StringReplace, WriteableDeep } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport { isReferenceObject } from './isReferenceObject'\n\n/**\n * Decode an OpenAPI reference path by replacing the encoded characters with\n * their original values. This function will replace `~0` with `~` and `~1`\n * with `/`.\n *\n * @example DecodeReference<'#/foo~1bar~0baz'> // '#/foo/bar~baz'\n */\nexport type OpenAPIReferenceDecoded<T extends string> =\n StringReplace<StringReplace<T, '~0', '~'>, '~1', '/'>\n\n/**\n * Extract the parts of a reference path as a tuple.\n *\n * @example OpenAPIV3ReferencePath<'#/paths/~1users~1{username}'> // ['paths', '/users/{username}']\n */\nexport type OpenAPIReferencePath<T extends string> =\n T extends `#/${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `#/${infer P}` ? [P]\n : T extends `${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `${infer P}` ? [P]\n : []\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The result type.\n * @example Resolved<{ $ref: '#/info' }, { info: { title: string } }> // { title: string }\n */\nexport type OpenAPIReferenceResolved<\n T extends OpenAPIReference,\n D extends object,\n> =\n D extends object\n ? T extends { $ref: infer R extends string }\n\n // --- Match last part of the reference.\n ? OpenAPIReferencePath<R> extends [infer P extends string]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? WriteableDeep<Omit<D[OpenAPIReferenceDecoded<P>], keyof T>>\n : never\n : never\n\n // --- Match middle part of the reference.\n : OpenAPIReferencePath<R> extends [infer P extends string, ...infer Rest extends string[]]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? OpenAPIReferenceResolved<{ $ref: StringJoin<Rest, '/'> }, D[OpenAPIReferenceDecoded<P>]>\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Resolve an OpenAPI `ReferenceObject` to the component it references. If the\n * source is not a reference, the source will be returned.\n *\n * @private\n * @param reference The reference object to resolve.\n * @param document The OpenAPI document to resolve the reference from.\n * @returns The result component.\n * @example resolveReference({ $ref: '#/components/schemas/User' }, document)\n */\nexport function resolveReference<\n T extends OpenAPIReference,\n D extends object,\n>(reference: Readonly<T>, document: Readonly<D>): OpenAPIReferenceResolved<T, D> {\n\n // --- Return the source if it is not a reference.\n if (!isReferenceObject(reference))\n throw new TypeError('Expected value to be an OpenAPI reference object.')\n\n // --- Assert that the parameters are valid.\n if (typeof document !== 'object' || document === null)\n throw new TypeError('Expected OpenAPI specification to be an object.')\n\n // --- Resolve the component with it's reference path.\n const referenceParts = reference.$ref.replace(/^#\\//, '').split('/')\n let result = document\n for (const part of referenceParts) {\n if (result === undefined) break\n if (typeof result !== 'object' || result === null) break\n const key = part.replaceAll('~1', '/').replaceAll('~0', '~')\n // @ts-expect-error: assume the part is a key of the object.\n result = result[key] as unknown\n }\n\n // --- Throw an error if the component could not be result.\n if (result === undefined)\n throw new Error(`Could not resolve OpenAPI component: ${reference.$ref}`)\n\n // --- Return the result component.\n return result as OpenAPIReferenceResolved<T, D>\n}\n","import type { ObjectLike, Substract } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport type { OpenAPIReferenceResolved } from './resolveReference'\nimport { isReferenceObject } from './isReferenceObject'\nimport { resolveReference as resolveReference } from './resolveReference'\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The resolved type.\n * @example\n * type Resolved = OpenAPIResolved<{\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' }\n * }\n * }\n * }>\n */\nexport type OpenAPIResolved<T, D = T, N extends number = 8> =\n N extends 0 ? T\n : T extends OpenAPIReference\n ? D extends object ? OpenAPIResolved<OpenAPIReferenceResolved<T, D>, D, Substract<N, 1>> : never\n : T extends object ? { -readonly [K in keyof T]: OpenAPIResolved<T[K], D, N> } : T\n\n/**\n * Recursively resolve all references in an OpenAPI specification. This function\n * will return a `Proxy` object that will resolve references on the fly.\n *\n * @param value The OpenAPI specification.\n * @returns The resolved OpenAPI specification.\n * @example\n * const resolved = resolveReferences({\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' },\n * },\n * },\n * })\n */\nexport function resolveDocument<T extends object>(value: Readonly<T>): OpenAPIResolved<T>\nexport function resolveDocument<T extends object, D>(value: Readonly<T>, document: Readonly<D>): OpenAPIResolved<T, D>\nexport function resolveDocument(value: Readonly<ObjectLike>, document = value): unknown {\n return new Proxy(value, {\n get(target, property: string) {\n let value = target[property]\n\n // --- Abort if no document is provided.\n if (!document) return value\n\n // --- Resolve the reference if it is a reference object.\n if (isReferenceObject(value))\n value = resolveReference(value, document)\n\n // --- Recursively resolve references in objects.\n if (typeof value === 'object' && value !== null)\n return resolveDocument(value as ObjectLike, document)\n\n // --- Return the value as is.\n return value\n },\n })\n}\n"],"names":["value"],"mappings":";
|
1
|
+
{"version":3,"file":"openapi.js","sources":["../openapi/isOpenAPIV2.ts","../openapi/isOpenAPIV3_1.ts","../openapi/isReferenceObject.ts","../openapi/resolveReference.ts","../openapi/resolveDocument.ts"],"sourcesContent":["/* eslint-disable unicorn/filename-case */\nimport type { OpenAPIV2 } from 'openapi-types'\n\n/**\n * Check if the given document is an OpenAPI v2 specification.\n *\n * @param value The document to check.\n * @returns `true` if the document is an OpenAPI v2 specification, `false` otherwise.\n * @example isOpenAPIV2({ swagger: '2.0', info: { title: 'Test API', version: '1.0.0' } }) // => true\n */\nexport function isOpenAPIV2(value: unknown): value is OpenAPIV2.Document {\n return typeof value === 'object'\n && value !== null\n && 'swagger' in value\n && value.swagger === '2.0'\n}\n","/* eslint-disable unicorn/filename-case */\nimport type { OpenAPIV3_1 } from 'openapi-types'\n\n/**\n * Check if the given document is an OpenAPI v3.1 specification.\n *\n * @param value The document to check.\n * @returns `true` if the document is an OpenAPI v3.1 specification, `false` otherwise.\n * @example isOpenAPIV3_1({ openapi: '3.1.0', info: { title: 'Test API', version: '1.0.0' } }) // => true\n */\nexport function isOpenAPIV3_1(value: unknown): value is OpenAPIV3_1.Document {\n return typeof value === 'object'\n && value !== null\n && 'openapi' in value\n && value.openapi === '3.1.0'\n}\n","import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\n\nexport type OpenAPIReference =\n | OpenAPIV2.ReferenceObject\n | OpenAPIV3.ReferenceObject\n | OpenAPIV3_1.ReferenceObject\n\n/**\n * Check if a value is an {@linkcode OpenAPIReference}.\n *\n * @param value The value to check.\n * @returns `true` if the value is a reference object.\n * @example isReferenceObject({ $ref: '#/components/schemas/MySchema' }) // true\n */\nexport function isReferenceObject<T extends OpenAPIReference>(value: unknown): value is T {\n return typeof value === 'object'\n && value !== null\n && '$ref' in value\n && typeof value.$ref === 'string'\n}\n","import type { StringJoin, StringReplace, WriteableDeep } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport { isReferenceObject } from './isReferenceObject'\n\n/**\n * Decode an OpenAPI reference path by replacing the encoded characters with\n * their original values. This function will replace `~0` with `~` and `~1`\n * with `/`.\n *\n * @example DecodeReference<'#/foo~1bar~0baz'> // '#/foo/bar~baz'\n */\nexport type OpenAPIReferenceDecoded<T extends string> =\n StringReplace<StringReplace<T, '~0', '~'>, '~1', '/'>\n\n/**\n * Extract the parts of a reference path as a tuple.\n *\n * @example OpenAPIV3ReferencePath<'#/paths/~1users~1{username}'> // ['paths', '/users/{username}']\n */\nexport type OpenAPIReferencePath<T extends string> =\n T extends `#/${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `#/${infer P}` ? [P]\n : T extends `${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `${infer P}` ? [P]\n : []\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The result type.\n * @example Resolved<{ $ref: '#/info' }, { info: { title: string } }> // { title: string }\n */\nexport type OpenAPIReferenceResolved<\n T extends OpenAPIReference,\n D extends object,\n> =\n D extends object\n ? T extends { $ref: infer R extends string }\n\n // --- Match last part of the reference.\n ? OpenAPIReferencePath<R> extends [infer P extends string]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? WriteableDeep<Omit<D[OpenAPIReferenceDecoded<P>], keyof T>>\n : never\n : never\n\n // --- Match middle part of the reference.\n : OpenAPIReferencePath<R> extends [infer P extends string, ...infer Rest extends string[]]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? OpenAPIReferenceResolved<{ $ref: StringJoin<Rest, '/'> }, D[OpenAPIReferenceDecoded<P>]>\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Resolve an OpenAPI `ReferenceObject` to the component it references. If the\n * source is not a reference, the source will be returned.\n *\n * @private\n * @param reference The reference object to resolve.\n * @param document The OpenAPI document to resolve the reference from.\n * @returns The result component.\n * @example resolveReference({ $ref: '#/components/schemas/User' }, document)\n */\nexport function resolveReference<\n T extends OpenAPIReference,\n D extends object,\n>(reference: Readonly<T>, document: Readonly<D>): OpenAPIReferenceResolved<T, D> {\n\n // --- Return the source if it is not a reference.\n if (!isReferenceObject(reference))\n throw new TypeError('Expected value to be an OpenAPI reference object.')\n\n // --- Assert that the parameters are valid.\n if (typeof document !== 'object' || document === null)\n throw new TypeError('Expected OpenAPI specification to be an object.')\n\n // --- Resolve the component with it's reference path.\n const referenceParts = reference.$ref.replace(/^#\\//, '').split('/')\n let result = document\n for (const part of referenceParts) {\n if (result === undefined) break\n if (typeof result !== 'object' || result === null) break\n const key = part.replaceAll('~1', '/').replaceAll('~0', '~')\n // @ts-expect-error: assume the part is a key of the object.\n result = result[key] as unknown\n }\n\n // --- Throw an error if the component could not be result.\n if (result === undefined)\n throw new Error(`Could not resolve OpenAPI component: ${reference.$ref}`)\n\n // --- Return the result component.\n return result as OpenAPIReferenceResolved<T, D>\n}\n","import type { ObjectLike, Substract } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport type { OpenAPIReferenceResolved } from './resolveReference'\nimport { isReferenceObject } from './isReferenceObject'\nimport { resolveReference as resolveReference } from './resolveReference'\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The resolved type.\n * @example\n * type Resolved = OpenAPIResolved<{\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' }\n * }\n * }\n * }>\n */\nexport type OpenAPIResolved<T, D = T, N extends number = 8> =\n N extends 0 ? T\n : T extends OpenAPIReference\n ? D extends object ? OpenAPIResolved<OpenAPIReferenceResolved<T, D>, D, Substract<N, 1>> : never\n : T extends object ? { -readonly [K in keyof T]: OpenAPIResolved<T[K], D, N> } : T\n\n/**\n * Recursively resolve all references in an OpenAPI specification. This function\n * will return a `Proxy` object that will resolve references on the fly.\n *\n * @param value The OpenAPI specification.\n * @returns The resolved OpenAPI specification.\n * @example\n * const resolved = resolveReferences({\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' },\n * },\n * },\n * })\n */\nexport function resolveDocument<T extends object>(value: Readonly<T>): OpenAPIResolved<T>\nexport function resolveDocument<T extends object, D>(value: Readonly<T>, document: Readonly<D>): OpenAPIResolved<T, D>\nexport function resolveDocument(value: Readonly<ObjectLike>, document = value): unknown {\n return new Proxy(value, {\n get(target, property: string) {\n let value = target[property]\n\n // --- Abort if no document is provided.\n if (!document) return value\n\n // --- Resolve the reference if it is a reference object.\n if (isReferenceObject(value))\n value = resolveReference(value, document)\n\n // --- Recursively resolve references in objects.\n if (typeof value === 'object' && value !== null)\n return resolveDocument(value as ObjectLike, document)\n\n // --- Return the value as is.\n return value\n },\n })\n}\n"],"names":["value"],"mappings":";AAUO,SAAS,YAAY,OAA6C;AAChE,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,aAAa,SACb,MAAM,YAAY;AACzB;ACLO,SAAS,cAAc,OAA+C;AACpE,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,aAAa,SACb,MAAM,YAAY;AACzB;ACDO,SAAS,kBAA8C,OAA4B;AACjF,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,UAAU,SACV,OAAO,MAAM,QAAS;AAC7B;ACmDgB,SAAA,iBAGd,WAAwB,UAAuD;AAG3E,MAAA,CAAC,kBAAkB,SAAS;AACxB,UAAA,IAAI,UAAU,mDAAmD;AAGrE,MAAA,OAAO,YAAa,YAAY,aAAa;AACzC,UAAA,IAAI,UAAU,iDAAiD;AAGjE,QAAA,iBAAiB,UAAU,KAAK,QAAQ,QAAQ,EAAE,EAAE,MAAM,GAAG;AACnE,MAAI,SAAS;AACb,aAAW,QAAQ,gBAAgB;AAEjC,QADI,WAAW,UACX,OAAO,UAAW,YAAY,WAAW,KAAM;AAC7C,UAAA,MAAM,KAAK,WAAW,MAAM,GAAG,EAAE,WAAW,MAAM,GAAG;AAE3D,aAAS,OAAO,GAAG;AAAA,EAAA;AAIrB,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,wCAAwC,UAAU,IAAI,EAAE;AAGnE,SAAA;AACT;ACtDgB,SAAA,gBAAgB,OAA6B,WAAW,OAAgB;AAC/E,SAAA,IAAI,MAAM,OAAO;AAAA,IACtB,IAAI,QAAQ,UAAkB;AACxBA,UAAAA,SAAQ,OAAO,QAAQ;AAG3B,aAAK,YAGD,kBAAkBA,MAAK,MACzBA,SAAQ,iBAAiBA,QAAO,QAAQ,IAGtC,OAAOA,UAAU,YAAYA,WAAU,OAClC,gBAAgBA,QAAqB,QAAQ,IAG/CA,UAXeA;AAAAA,IAAA;AAAA,EAYxB,CACD;AACH;"}
|