fets 0.4.14 → 0.4.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/cjs/Response.js +80 -0
  2. package/cjs/client/auth/oauth.js +34 -0
  3. package/cjs/client/createClient.js +133 -0
  4. package/cjs/client/index.js +6 -0
  5. package/cjs/client/plugins/useClientCookieStore.js +31 -0
  6. package/cjs/client/types.js +0 -0
  7. package/cjs/createRouter.js +299 -0
  8. package/cjs/index.js +16 -0
  9. package/cjs/plugins/ajv.js +213 -0
  10. package/cjs/plugins/openapi.js +171 -0
  11. package/cjs/plugins/utils.js +31 -0
  12. package/cjs/swagger-ui-html.js +3 -0
  13. package/cjs/typed-fetch.js +0 -0
  14. package/cjs/types.js +0 -0
  15. package/cjs/utils.js +73 -0
  16. package/cjs/zod/types.js +7 -0
  17. package/cjs/zod/zod.js +92 -0
  18. package/esm/Response.js +74 -0
  19. package/esm/client/auth/oauth.js +31 -0
  20. package/esm/client/createClient.js +128 -0
  21. package/esm/client/index.js +3 -0
  22. package/esm/client/plugins/useClientCookieStore.js +27 -0
  23. package/esm/client/types.js +0 -0
  24. package/esm/createRouter.js +293 -0
  25. package/esm/index.js +7 -0
  26. package/esm/plugins/ajv.js +208 -0
  27. package/esm/plugins/openapi.js +166 -0
  28. package/esm/plugins/utils.js +27 -0
  29. package/esm/swagger-ui-html.js +1 -0
  30. package/esm/typed-fetch.js +0 -0
  31. package/esm/types.js +0 -0
  32. package/esm/utils.js +69 -0
  33. package/esm/zod/types.js +3 -0
  34. package/esm/zod/zod.js +88 -0
  35. package/package.json +1 -1
  36. package/typings/Response.d.cts +28 -0
  37. package/typings/Response.d.ts +28 -0
  38. package/typings/client/auth/oauth.d.cts +150 -0
  39. package/typings/client/auth/oauth.d.ts +150 -0
  40. package/typings/client/createClient.d.cts +34 -0
  41. package/typings/client/createClient.d.ts +34 -0
  42. package/typings/client/index.d.cts +3 -0
  43. package/typings/client/index.d.ts +3 -0
  44. package/typings/client/plugins/useClientCookieStore.d.cts +3 -0
  45. package/typings/client/plugins/useClientCookieStore.d.ts +3 -0
  46. package/typings/client/types.d.cts +426 -0
  47. package/typings/client/types.d.ts +426 -0
  48. package/typings/createRouter.d.cts +6 -0
  49. package/typings/createRouter.d.ts +6 -0
  50. package/typings/index.d.cts +7 -0
  51. package/typings/index.d.ts +7 -0
  52. package/typings/plugins/ajv.d.cts +4 -0
  53. package/typings/plugins/ajv.d.ts +4 -0
  54. package/typings/plugins/openapi.d.cts +33 -0
  55. package/typings/plugins/openapi.d.ts +33 -0
  56. package/typings/plugins/utils.d.cts +1 -0
  57. package/typings/plugins/utils.d.ts +1 -0
  58. package/typings/swagger-ui-html.d.cts +2 -0
  59. package/typings/swagger-ui-html.d.ts +2 -0
  60. package/typings/typed-fetch.d.cts +232 -0
  61. package/typings/typed-fetch.d.ts +232 -0
  62. package/typings/types.d.cts +261 -0
  63. package/typings/types.d.ts +261 -0
  64. package/typings/utils.d.cts +31 -0
  65. package/typings/utils.d.ts +31 -0
  66. package/typings/zod/types.d.cts +39 -0
  67. package/typings/zod/types.d.ts +39 -0
  68. package/typings/zod/zod.d.cts +2 -0
  69. package/typings/zod/zod.d.ts +2 -0
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Response = exports.createLazySerializedResponse = exports.isLazySerializedResponse = exports.defaultSerializer = exports.LAZY_SERIALIZED_RESPONSE = void 0;
4
+ const fetch_1 = require("@whatwg-node/fetch");
5
+ exports.LAZY_SERIALIZED_RESPONSE = Symbol('LAZY_SERIALIZED_RESPONSE');
6
+ const defaultSerializer = obj => JSON.stringify(obj);
7
+ exports.defaultSerializer = defaultSerializer;
8
+ function isLazySerializedResponse(response) {
9
+ return response[exports.LAZY_SERIALIZED_RESPONSE];
10
+ }
11
+ exports.isLazySerializedResponse = isLazySerializedResponse;
12
+ function isHeadersLike(headers) {
13
+ return headers?.get && headers?.forEach;
14
+ }
15
+ const JSON_CONTENT_TYPE = 'application/json; charset=utf-8';
16
+ function getHeadersFromHeadersInit(init) {
17
+ let headers;
18
+ if (isHeadersLike(init)) {
19
+ headers = init;
20
+ }
21
+ else {
22
+ headers = new fetch_1.Headers(init);
23
+ }
24
+ if (!headers.has('content-type')) {
25
+ headers.set('content-type', JSON_CONTENT_TYPE);
26
+ }
27
+ return headers;
28
+ }
29
+ function createLazySerializedResponse(jsonObj, init = {}) {
30
+ let actualResponse;
31
+ let headers;
32
+ function getHeaders() {
33
+ if (headers == null) {
34
+ headers = getHeadersFromHeadersInit(init.headers);
35
+ }
36
+ return headers;
37
+ }
38
+ return {
39
+ jsonObj,
40
+ get actualResponse() {
41
+ return actualResponse;
42
+ },
43
+ [exports.LAZY_SERIALIZED_RESPONSE]: true,
44
+ init,
45
+ resolveWithSerializer(serializer) {
46
+ const serialized = serializer(jsonObj);
47
+ init.headers = getHeaders();
48
+ actualResponse = new fetch_1.Response(serialized, init);
49
+ },
50
+ json() {
51
+ return Promise.resolve(jsonObj);
52
+ },
53
+ get status() {
54
+ return (init?.status || 200);
55
+ },
56
+ get headers() {
57
+ return getHeaders();
58
+ },
59
+ };
60
+ }
61
+ exports.createLazySerializedResponse = createLazySerializedResponse;
62
+ // This allows us to hook into serialization of the response body
63
+ /**
64
+ * The Response interface of the Fetch API represents the response to a request.
65
+ * It contains the status of the response, as well as the response headers, and
66
+ * an optional response body.
67
+ *
68
+ * @param body An object defining a body for the response. This can be null (which is the default value), or a Blob, BufferSource, FormData, Node.js Readable stream, URLSearchParams, or USVString object. The USVString is handled as UTF-8.
69
+ * @param options An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value).
70
+ *
71
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Response
72
+ */
73
+ exports.Response = new Proxy(fetch_1.Response, {
74
+ get(OriginalResponse, prop, receiver) {
75
+ if (prop === 'json') {
76
+ return createLazySerializedResponse;
77
+ }
78
+ return Reflect.get(OriginalResponse, prop, receiver);
79
+ },
80
+ });
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OAuthPathErrorType = void 0;
4
+ var OAuthPathErrorType;
5
+ (function (OAuthPathErrorType) {
6
+ /**
7
+ * The request is missing a parameter so the server can’t proceed with the request.
8
+ * This may also be returned if the request includes an unsupported parameter or repeats a parameter.
9
+ */
10
+ OAuthPathErrorType["invalid_request"] = "invalid_request";
11
+ /**
12
+ * Client authentication failed, such as if the request contains an invalid client ID or secret.
13
+ * Send an HTTP 401 response in this case.
14
+ */
15
+ OAuthPathErrorType["invalid_client"] = "invalid_client";
16
+ /**
17
+ * The authorization code (or user’s password for the password grant type) is invalid or expired.
18
+ * This is also the error you would return if the redirect URL given in the authorization grant does not match the URL provided in this access token request.
19
+ */
20
+ OAuthPathErrorType["invalid_grant"] = "invalid_grant";
21
+ /**
22
+ * For access token requests that include a scope (password or client_credentials grants), this error indicates an invalid scope value in the request.
23
+ */
24
+ OAuthPathErrorType["invalid_scope"] = "invalid_scope";
25
+ /**
26
+ * This client is not authorized to use the requested grant type. For example, if you restrict which applications can use the Implicit grant, you would return this error for the other apps.
27
+ */
28
+ OAuthPathErrorType["unauthorized_client"] = "unauthorized_client";
29
+ /**
30
+ * If a grant type is requested that the authorization server doesn’t recognize, use this code.
31
+ * Note that unknown grant types also use this specific error code rather than using the `invalid_request` above.
32
+ */
33
+ OAuthPathErrorType["unsupported_grant_type"] = "unsupported_grant_type";
34
+ })(OAuthPathErrorType || (exports.OAuthPathErrorType = OAuthPathErrorType = {}));
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createClient = exports.ClientValidationError = void 0;
4
+ const qs_1 = require("qs");
5
+ const fetch_1 = require("@whatwg-node/fetch");
6
+ const qsOptions = {
7
+ indices: false,
8
+ arrayFormat: 'repeat',
9
+ };
10
+ class ClientValidationError extends Error {
11
+ constructor(path, method, errors, response) {
12
+ super(`Validation failed for ${method} ${path}`);
13
+ this.path = path;
14
+ this.method = method;
15
+ this.errors = errors;
16
+ this.response = response;
17
+ }
18
+ [Symbol.iterator]() {
19
+ return this.errors[Symbol.iterator]();
20
+ }
21
+ }
22
+ exports.ClientValidationError = ClientValidationError;
23
+ function useValidationErrors() {
24
+ return {
25
+ async onResponse({ path, method, response }) {
26
+ if (response.status === 400 && response.headers.get('x-error-type') === 'validation') {
27
+ const resJson = await response.json();
28
+ if (resJson.errors) {
29
+ throw new ClientValidationError(path, method, resJson.errors, response);
30
+ }
31
+ }
32
+ },
33
+ };
34
+ }
35
+ function createClient({ endpoint, fetchFn = fetch_1.fetch, plugins = [] }) {
36
+ plugins.unshift(useValidationErrors());
37
+ const onRequestInitHooks = [];
38
+ const onFetchHooks = [];
39
+ const onResponseHooks = [];
40
+ for (const plugin of plugins) {
41
+ if (plugin.onRequestInit) {
42
+ onRequestInitHooks.push(plugin.onRequestInit);
43
+ }
44
+ if (plugin.onFetch) {
45
+ onFetchHooks.push(plugin.onFetch);
46
+ }
47
+ if (plugin.onResponse) {
48
+ onResponseHooks.push(plugin.onResponse);
49
+ }
50
+ }
51
+ return new Proxy({}, {
52
+ get(_target, path) {
53
+ return new Proxy({}, {
54
+ get(_target, method) {
55
+ return async function (requestParams = {}) {
56
+ for (const pathParamKey in requestParams?.params || {}) {
57
+ const value = requestParams?.params?.[pathParamKey];
58
+ if (value) {
59
+ path = path.replace(`{${pathParamKey}}`, value).replace(`:${pathParamKey}`, value);
60
+ }
61
+ }
62
+ if (!path.startsWith('/') && !path.startsWith('http')) {
63
+ path = `/${path}`;
64
+ }
65
+ const requestInit = {
66
+ method,
67
+ headers: requestParams?.headers || {},
68
+ };
69
+ if (requestParams?.json) {
70
+ requestInit.body = JSON.stringify(requestParams.json);
71
+ requestInit.headers['Content-Type'] = 'application/json';
72
+ }
73
+ if (requestParams?.formData) {
74
+ requestInit.body = requestParams.formData;
75
+ }
76
+ if (requestParams?.formUrlEncoded) {
77
+ requestInit.body = (0, qs_1.stringify)(requestParams.formUrlEncoded, qsOptions);
78
+ requestInit.headers['Content-Type'] = 'application/x-www-form-urlencoded';
79
+ }
80
+ let response;
81
+ for (const onRequestParamsHook of onRequestInitHooks) {
82
+ await onRequestParamsHook({
83
+ path,
84
+ method,
85
+ requestParams,
86
+ requestInit,
87
+ endResponse(res) {
88
+ response = res;
89
+ },
90
+ });
91
+ }
92
+ let finalUrl = path;
93
+ if (endpoint && !path.startsWith('http')) {
94
+ finalUrl = `${endpoint}${path}`;
95
+ }
96
+ if (requestParams?.query) {
97
+ const searchParams = (0, qs_1.stringify)(requestParams.query, qsOptions);
98
+ if (finalUrl.includes('?')) {
99
+ finalUrl += '&' + searchParams;
100
+ }
101
+ else {
102
+ finalUrl += '?' + searchParams;
103
+ }
104
+ }
105
+ let currentFetchFn = fetchFn;
106
+ for (const onFetchHook of onFetchHooks) {
107
+ await onFetchHook({
108
+ url: finalUrl,
109
+ init: requestInit,
110
+ fetchFn: currentFetchFn,
111
+ setFetchFn(newFetchFn) {
112
+ currentFetchFn = newFetchFn;
113
+ },
114
+ });
115
+ }
116
+ response ||= await currentFetchFn(finalUrl, requestInit);
117
+ for (const onResponseHook of onResponseHooks) {
118
+ await onResponseHook({
119
+ path,
120
+ method,
121
+ requestParams,
122
+ requestInit,
123
+ response,
124
+ });
125
+ }
126
+ return response;
127
+ };
128
+ },
129
+ });
130
+ },
131
+ });
132
+ }
133
+ exports.createClient = createClient;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./createClient.js"), exports);
5
+ tslib_1.__exportStar(require("./types.js"), exports);
6
+ tslib_1.__exportStar(require("./plugins/useClientCookieStore.js"), exports);
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useClientCookieStore = void 0;
4
+ const cookie_store_1 = require("@whatwg-node/cookie-store");
5
+ const fetch_1 = require("@whatwg-node/fetch");
6
+ function useClientCookieStore(cookieStore) {
7
+ return {
8
+ async onRequestInit({ requestInit }) {
9
+ requestInit.headers = new fetch_1.Headers(requestInit.headers);
10
+ let cookieHeader = requestInit.headers.get('cookie') || '';
11
+ if (cookieHeader) {
12
+ cookieHeader += '; ';
13
+ }
14
+ const cookies = await cookieStore.getAll();
15
+ cookieHeader += cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; ');
16
+ requestInit.headers.set('cookie', cookieHeader);
17
+ },
18
+ onResponse({ response }) {
19
+ const setCookies = response.headers.getSetCookie?.();
20
+ if (setCookies) {
21
+ for (const setCookie of setCookies) {
22
+ const cookieMap = (0, cookie_store_1.parse)(setCookie);
23
+ for (const [, cookie] of cookieMap) {
24
+ cookieStore.set(cookie);
25
+ }
26
+ }
27
+ }
28
+ },
29
+ };
30
+ }
31
+ exports.useClientCookieStore = useClientCookieStore;
File without changes
@@ -0,0 +1,299 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createRouter = exports.createRouterBase = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const DefaultFetchAPI = tslib_1.__importStar(require("@whatwg-node/fetch"));
6
+ const server_1 = require("@whatwg-node/server");
7
+ const openapi_js_1 = require("./plugins/openapi.js");
8
+ const Response_js_1 = require("./Response.js");
9
+ const utils_js_1 = require("./utils.js");
10
+ const zod_js_1 = require("./zod/zod.js");
11
+ const HTTP_METHODS = [
12
+ 'GET',
13
+ 'HEAD',
14
+ 'POST',
15
+ 'PUT',
16
+ 'DELETE',
17
+ 'CONNECT',
18
+ 'OPTIONS',
19
+ 'TRACE',
20
+ 'PATCH',
21
+ ];
22
+ const EMPTY_OBJECT = {};
23
+ const EMPTY_MATCH = { pathname: { groups: {} } };
24
+ function createRouterBase({ fetchAPI: givenFetchAPI, base: basePath = '/', plugins = [], swaggerUI, } = {}, openAPIDocument) {
25
+ const fetchAPI = {
26
+ ...DefaultFetchAPI,
27
+ ...givenFetchAPI,
28
+ };
29
+ const __onRouterInitHooks = [];
30
+ const onRouteHooks = [];
31
+ const onSerializeResponseHooks = [];
32
+ for (const plugin of plugins) {
33
+ if (plugin.onRouterInit) {
34
+ __onRouterInitHooks.push(plugin.onRouterInit);
35
+ }
36
+ if (plugin.onRoute) {
37
+ onRouteHooks.push(plugin.onRoute);
38
+ }
39
+ if (plugin.onSerializeResponse) {
40
+ onSerializeResponseHooks.push(plugin.onSerializeResponse);
41
+ }
42
+ }
43
+ const handlersByPatternByMethod = new Map();
44
+ const internalPatternsByMethod = new Map();
45
+ // Use this in `handle` for iteration to get better performance
46
+ const patternHandlerObjByMethod = new Map();
47
+ function handleUnhandledRoute() {
48
+ if (swaggerUI?.endpoint) {
49
+ return new fetchAPI.Response(null, {
50
+ status: 302,
51
+ headers: {
52
+ location: swaggerUI.endpoint,
53
+ },
54
+ });
55
+ }
56
+ return new fetchAPI.Response(null, { status: 404 });
57
+ }
58
+ function processHandlerResult(handlerResult, opts) {
59
+ if (handlerResult) {
60
+ if ((0, Response_js_1.isLazySerializedResponse)(handlerResult)) {
61
+ const onSerializeResponseHookPayload = {
62
+ request: opts.routerRequest,
63
+ path: opts.pattern.pathname,
64
+ lazyResponse: handlerResult,
65
+ serverContext: opts.context,
66
+ };
67
+ for (const onSerializeResponseHook of onSerializeResponseHooks) {
68
+ onSerializeResponseHook(onSerializeResponseHookPayload);
69
+ }
70
+ return (handlerResult.actualResponse ||
71
+ fetchAPI.Response.json(handlerResult.jsonObj, handlerResult.init));
72
+ }
73
+ return handlerResult;
74
+ }
75
+ }
76
+ function asyncIterationUntilReturn(iterable, callback) {
77
+ const iterator = iterable[Symbol.iterator]();
78
+ function iterate() {
79
+ const { value, done } = iterator.next();
80
+ if (done) {
81
+ return;
82
+ }
83
+ if (value) {
84
+ const callbackResult$ = callback(value);
85
+ if ((0, server_1.isPromise)(callbackResult$)) {
86
+ return callbackResult$.then(callbackResult => {
87
+ if (callbackResult) {
88
+ return callbackResult;
89
+ }
90
+ return iterate();
91
+ });
92
+ }
93
+ if (callbackResult$) {
94
+ return callbackResult$;
95
+ }
96
+ return iterate();
97
+ }
98
+ }
99
+ return iterate();
100
+ }
101
+ return {
102
+ openAPIDocument,
103
+ handle(request, context) {
104
+ let url = new Proxy(EMPTY_OBJECT, {
105
+ get(_target, prop, _receiver) {
106
+ url = new fetchAPI.URL(request.url, 'http://localhost');
107
+ return Reflect.get(url, prop, url);
108
+ },
109
+ });
110
+ const methodPatternMaps = patternHandlerObjByMethod.get(request.method);
111
+ if (methodPatternMaps) {
112
+ const queryProxy = new Proxy({}, {
113
+ get(_, prop) {
114
+ if (prop !== 'then' && !url.searchParams.has(prop)) {
115
+ return undefined;
116
+ }
117
+ const allQueries = url.searchParams.getAll(prop.toString());
118
+ if (allQueries.length === 0) {
119
+ return '';
120
+ }
121
+ return allQueries.length === 1 ? allQueries[0] : allQueries;
122
+ },
123
+ has(_, prop) {
124
+ return url.searchParams.has(prop.toString());
125
+ },
126
+ });
127
+ const iterationResult$ = asyncIterationUntilReturn(methodPatternMaps, ({ pattern, handlers }) => {
128
+ // Do not parse URL if not needed
129
+ let match = null;
130
+ if (pattern.isPattern) {
131
+ match = pattern.exec(url);
132
+ }
133
+ else if (request.url.endsWith(pattern.pathname) ||
134
+ url.pathname === pattern.pathname) {
135
+ match = EMPTY_MATCH;
136
+ }
137
+ if (match != null) {
138
+ const routerRequest = new Proxy(request, {
139
+ get(target, prop) {
140
+ if (prop === 'parsedUrl') {
141
+ return url;
142
+ }
143
+ if (prop === 'params') {
144
+ return new Proxy(match.pathname.groups, {
145
+ get(_, prop) {
146
+ const value = match.pathname.groups[prop.toString()];
147
+ if (value != null) {
148
+ return decodeURIComponent(value);
149
+ }
150
+ return value;
151
+ },
152
+ });
153
+ }
154
+ if (prop === 'query') {
155
+ return queryProxy;
156
+ }
157
+ const targetProp = target[prop];
158
+ if (typeof targetProp === 'function') {
159
+ return targetProp.bind(target);
160
+ }
161
+ return targetProp;
162
+ },
163
+ has(target, prop) {
164
+ return (prop in target || prop === 'parsedUrl' || prop === 'params' || prop === 'query');
165
+ },
166
+ });
167
+ return asyncIterationUntilReturn(handlers, handler => {
168
+ const handlerResult$ = handler(routerRequest, context);
169
+ if ((0, server_1.isPromise)(handlerResult$)) {
170
+ return handlerResult$.then(handlerResult => {
171
+ if (handlerResult) {
172
+ return processHandlerResult(handlerResult, {
173
+ routerRequest,
174
+ context,
175
+ pattern,
176
+ });
177
+ }
178
+ });
179
+ }
180
+ if (handlerResult$) {
181
+ return processHandlerResult(handlerResult$, {
182
+ routerRequest,
183
+ context,
184
+ pattern,
185
+ });
186
+ }
187
+ });
188
+ }
189
+ });
190
+ if ((0, server_1.isPromise)(iterationResult$)) {
191
+ return iterationResult$.then(iterationResult => {
192
+ if (iterationResult) {
193
+ return iterationResult;
194
+ }
195
+ return handleUnhandledRoute();
196
+ });
197
+ }
198
+ if (iterationResult$) {
199
+ return iterationResult$;
200
+ }
201
+ }
202
+ return handleUnhandledRoute();
203
+ },
204
+ route(opts) {
205
+ const { operationId, description, method, path, schemas, tags, internal, handler } = opts;
206
+ const handlers = Array.isArray(handler) ? handler : [handler];
207
+ if (!method) {
208
+ for (const method of HTTP_METHODS) {
209
+ (0, utils_js_1.addHandlersToMethod)({
210
+ operationId,
211
+ description,
212
+ method,
213
+ path,
214
+ schemas,
215
+ handlers,
216
+ tags,
217
+ internal,
218
+ // Router specific
219
+ onRouteHooks,
220
+ openAPIDocument,
221
+ basePath,
222
+ fetchAPI,
223
+ handlersByPatternByMethod,
224
+ internalPatternsByMethod,
225
+ patternHandlerObjByMethod,
226
+ });
227
+ }
228
+ }
229
+ else {
230
+ (0, utils_js_1.addHandlersToMethod)({
231
+ operationId,
232
+ description,
233
+ method,
234
+ path,
235
+ schemas,
236
+ handlers,
237
+ tags,
238
+ internal,
239
+ // Router specific
240
+ onRouteHooks,
241
+ openAPIDocument,
242
+ basePath,
243
+ fetchAPI,
244
+ handlersByPatternByMethod,
245
+ internalPatternsByMethod,
246
+ patternHandlerObjByMethod,
247
+ });
248
+ }
249
+ return this;
250
+ },
251
+ __client: {},
252
+ __onRouterInitHooks,
253
+ };
254
+ }
255
+ exports.createRouterBase = createRouterBase;
256
+ function createRouter(options = {}) {
257
+ const { openAPI: { endpoint: oasEndpoint = '/openapi.json', ...openAPIDocument } = {}, swaggerUI: { endpoint: swaggerUIEndpoint = '/docs', ...swaggerUIOpts } = {}, plugins: userPlugins = [], base = '/', } = options;
258
+ openAPIDocument.openapi = openAPIDocument.openapi || '3.0.1';
259
+ const oasInfo = (openAPIDocument.info ||= {});
260
+ oasInfo.title ||= 'feTS API';
261
+ oasInfo.description ||= 'An API written with feTS';
262
+ oasInfo.version ||= '1.0.0';
263
+ if (base !== '/') {
264
+ openAPIDocument.servers = openAPIDocument.servers || [
265
+ {
266
+ url: base,
267
+ },
268
+ ];
269
+ }
270
+ const plugins = [
271
+ ...(oasEndpoint || swaggerUIEndpoint
272
+ ? [
273
+ (0, openapi_js_1.useOpenAPI)({
274
+ oasEndpoint,
275
+ swaggerUIEndpoint,
276
+ swaggerUIOpts,
277
+ }),
278
+ ]
279
+ : []),
280
+ (0, zod_js_1.useZod)(),
281
+ ...userPlugins,
282
+ ];
283
+ const finalOpts = {
284
+ ...options,
285
+ swaggerUI: {
286
+ endpoint: swaggerUIEndpoint,
287
+ ...swaggerUIOpts,
288
+ },
289
+ base,
290
+ plugins,
291
+ };
292
+ const routerBaseObject = createRouterBase(finalOpts, openAPIDocument);
293
+ const router = (0, server_1.createServerAdapter)(routerBaseObject, finalOpts);
294
+ for (const onRouterInitHook of routerBaseObject.__onRouterInitHooks) {
295
+ onRouterInitHook(router);
296
+ }
297
+ return router;
298
+ }
299
+ exports.createRouter = createRouter;
package/cjs/index.js ADDED
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAjv = exports.HTTPError = exports.useErrorHandling = exports.useCORS = exports.URLPattern = void 0;
4
+ const tslib_1 = require("tslib");
5
+ tslib_1.__exportStar(require("./types.js"), exports);
6
+ tslib_1.__exportStar(require("./createRouter.js"), exports);
7
+ var fetch_1 = require("@whatwg-node/fetch");
8
+ Object.defineProperty(exports, "URLPattern", { enumerable: true, get: function () { return fetch_1.URLPattern; } });
9
+ var server_1 = require("@whatwg-node/server");
10
+ Object.defineProperty(exports, "useCORS", { enumerable: true, get: function () { return server_1.useCORS; } });
11
+ Object.defineProperty(exports, "useErrorHandling", { enumerable: true, get: function () { return server_1.useErrorHandling; } });
12
+ Object.defineProperty(exports, "HTTPError", { enumerable: true, get: function () { return server_1.HTTPError; } });
13
+ tslib_1.__exportStar(require("./client/index.js"), exports);
14
+ tslib_1.__exportStar(require("./Response.js"), exports);
15
+ var ajv_js_1 = require("./plugins/ajv.js");
16
+ Object.defineProperty(exports, "useAjv", { enumerable: true, get: function () { return ajv_js_1.useAjv; } });