vovk 3.0.0-draft.48 → 3.0.0-draft.50
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/.DS_Store +0 -0
- package/.npmignore +2 -1
- package/.turbo/turbo-build.log +6 -0
- package/.turbo/turbo-ncu.log +9 -0
- package/.turbo/turbo-tsc.log +6 -0
- package/README.md +1 -112
- package/{StreamJSONResponse.d.ts → dist/StreamJSONResponse.d.ts} +1 -1
- package/dist/client/createRPC.d.ts +4 -0
- package/{client/clientizeController.js → dist/client/createRPC.js} +3 -3
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.js +5 -0
- package/{index.d.ts → dist/index.d.ts} +5 -4
- package/{index.js → dist/index.js} +6 -1
- package/{utils → dist/utils}/generateStaticAPI.d.ts +1 -1
- package/{utils → dist/utils}/getSchema.d.ts +1 -1
- package/{utils → dist/utils}/reqForm.d.ts +1 -2
- package/{utils → dist/utils}/reqMeta.d.ts +1 -2
- package/{utils → dist/utils}/reqQuery.d.ts +1 -2
- package/{utils → dist/utils}/reqQuery.js +3 -3
- package/dist/utils/setClientValidatorsForHandler.d.ts +5 -0
- package/{utils → dist/utils}/setClientValidatorsForHandler.js +2 -1
- package/dist/worker/createWPC.d.ts +2 -0
- package/{worker/promisifyWorker.js → dist/worker/createWPC.js} +3 -3
- package/dist/worker/index.d.ts +3 -0
- package/dist/worker/index.js +7 -0
- package/package.json +4 -2
- package/src/HttpException.ts +16 -0
- package/src/StreamJSONResponse.ts +62 -0
- package/src/VovkApp.ts +242 -0
- package/src/client/createRPC.ts +133 -0
- package/src/client/defaultFetcher.ts +57 -0
- package/src/client/defaultHandler.ts +23 -0
- package/src/client/defaultStreamHandler.ts +88 -0
- package/src/client/index.ts +5 -0
- package/src/client/types.ts +115 -0
- package/src/createDecorator.ts +60 -0
- package/src/createVovkApp.ts +167 -0
- package/src/index.ts +66 -0
- package/src/types.ts +215 -0
- package/src/utils/generateStaticAPI.ts +18 -0
- package/src/utils/getSchema.ts +48 -0
- package/src/utils/reqForm.ts +16 -0
- package/src/utils/reqMeta.ts +16 -0
- package/src/utils/reqQuery.ts +26 -0
- package/src/utils/setClientValidatorsForHandler.ts +45 -0
- package/src/utils/shim.ts +17 -0
- package/src/worker/createWPC.ts +156 -0
- package/src/worker/index.ts +4 -0
- package/src/worker/types.ts +45 -0
- package/src/worker/worker.ts +53 -0
- package/client/clientizeController.d.ts +0 -4
- package/client/index.d.ts +0 -4
- package/client/index.js +0 -5
- package/utils/setClientValidatorsForHandler.d.ts +0 -5
- package/worker/index.d.ts +0 -3
- package/worker/index.js +0 -7
- package/worker/promisifyWorker.d.ts +0 -2
- /package/{HttpException.d.ts → dist/HttpException.d.ts} +0 -0
- /package/{HttpException.js → dist/HttpException.js} +0 -0
- /package/{StreamJSONResponse.js → dist/StreamJSONResponse.js} +0 -0
- /package/{VovkApp.d.ts → dist/VovkApp.d.ts} +0 -0
- /package/{VovkApp.js → dist/VovkApp.js} +0 -0
- /package/{client → dist/client}/defaultFetcher.d.ts +0 -0
- /package/{client → dist/client}/defaultFetcher.js +0 -0
- /package/{client → dist/client}/defaultHandler.d.ts +0 -0
- /package/{client → dist/client}/defaultHandler.js +0 -0
- /package/{client → dist/client}/defaultStreamHandler.d.ts +0 -0
- /package/{client → dist/client}/defaultStreamHandler.js +0 -0
- /package/{client → dist/client}/types.d.ts +0 -0
- /package/{client → dist/client}/types.js +0 -0
- /package/{createDecorator.d.ts → dist/createDecorator.d.ts} +0 -0
- /package/{createDecorator.js → dist/createDecorator.js} +0 -0
- /package/{createVovkApp.d.ts → dist/createVovkApp.d.ts} +0 -0
- /package/{createVovkApp.js → dist/createVovkApp.js} +0 -0
- /package/{types.d.ts → dist/types.d.ts} +0 -0
- /package/{types.js → dist/types.js} +0 -0
- /package/{utils → dist/utils}/generateStaticAPI.js +0 -0
- /package/{utils → dist/utils}/getSchema.js +0 -0
- /package/{utils → dist/utils}/reqForm.js +0 -0
- /package/{utils → dist/utils}/reqMeta.js +0 -0
- /package/{utils → dist/utils}/shim.d.ts +0 -0
- /package/{utils → dist/utils}/shim.js +0 -0
- /package/{worker → dist/worker}/types.d.ts +0 -0
- /package/{worker → dist/worker}/types.js +0 -0
- /package/{worker → dist/worker}/worker.d.ts +0 -0
- /package/{worker → dist/worker}/worker.js +0 -0
package/src/VovkApp.ts
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import {
|
|
2
|
+
HttpMethod,
|
|
3
|
+
HttpStatus,
|
|
4
|
+
type RouteHandler,
|
|
5
|
+
type VovkErrorResponse,
|
|
6
|
+
type VovkController,
|
|
7
|
+
type DecoratorOptions,
|
|
8
|
+
type VovkRequest,
|
|
9
|
+
type KnownAny,
|
|
10
|
+
} from './types';
|
|
11
|
+
import { HttpException as HttpException } from './HttpException';
|
|
12
|
+
import { StreamJSONResponse } from './StreamJSONResponse';
|
|
13
|
+
import reqQuery from './utils/reqQuery';
|
|
14
|
+
import reqMeta from './utils/reqMeta';
|
|
15
|
+
import reqForm from './utils/reqForm';
|
|
16
|
+
|
|
17
|
+
export class VovkApp {
|
|
18
|
+
private static getHeadersFromOptions(options?: DecoratorOptions) {
|
|
19
|
+
if (!options) return {};
|
|
20
|
+
|
|
21
|
+
const corsHeaders = {
|
|
22
|
+
'Access-Control-Allow-Origin': '*',
|
|
23
|
+
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
|
|
24
|
+
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const headers = {
|
|
28
|
+
...(options.cors ? corsHeaders : {}),
|
|
29
|
+
...(options.headers ?? {}),
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
return headers;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
routes: Record<HttpMethod, Map<VovkController, Record<string, RouteHandler>>> = {
|
|
36
|
+
GET: new Map(),
|
|
37
|
+
POST: new Map(),
|
|
38
|
+
PUT: new Map(),
|
|
39
|
+
PATCH: new Map(),
|
|
40
|
+
DELETE: new Map(),
|
|
41
|
+
HEAD: new Map(),
|
|
42
|
+
OPTIONS: new Map(),
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
GET = async (req: VovkRequest, data: { params: Promise<Record<string, string[]>> }) =>
|
|
46
|
+
this.#callMethod(HttpMethod.GET, req, await data.params);
|
|
47
|
+
|
|
48
|
+
POST = async (req: VovkRequest, data: { params: Promise<Record<string, string[]>> }) =>
|
|
49
|
+
this.#callMethod(HttpMethod.POST, req, await data.params);
|
|
50
|
+
|
|
51
|
+
PUT = async (req: VovkRequest, data: { params: Promise<Record<string, string[]>> }) =>
|
|
52
|
+
this.#callMethod(HttpMethod.PUT, req, await data.params);
|
|
53
|
+
|
|
54
|
+
PATCH = async (req: VovkRequest, data: { params: Promise<Record<string, string[]>> }) =>
|
|
55
|
+
this.#callMethod(HttpMethod.PATCH, req, await data.params);
|
|
56
|
+
|
|
57
|
+
DELETE = async (req: VovkRequest, data: { params: Promise<Record<string, string[]>> }) =>
|
|
58
|
+
this.#callMethod(HttpMethod.DELETE, req, await data.params);
|
|
59
|
+
|
|
60
|
+
HEAD = async (req: VovkRequest, data: { params: Promise<Record<string, string[]>> }) =>
|
|
61
|
+
this.#callMethod(HttpMethod.HEAD, req, await data.params);
|
|
62
|
+
|
|
63
|
+
OPTIONS = async (req: VovkRequest, data: { params: Promise<Record<string, string[]>> }) =>
|
|
64
|
+
this.#callMethod(HttpMethod.OPTIONS, req, await data.params);
|
|
65
|
+
|
|
66
|
+
respond = (status: HttpStatus, body: unknown, options?: DecoratorOptions) => {
|
|
67
|
+
return new Response(JSON.stringify(body), {
|
|
68
|
+
status,
|
|
69
|
+
headers: {
|
|
70
|
+
'Content-Type': 'application/json',
|
|
71
|
+
...VovkApp.getHeadersFromOptions(options),
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
#respondWithError = (statusCode: HttpStatus, message: string, options?: DecoratorOptions, cause?: unknown) => {
|
|
77
|
+
return this.respond(
|
|
78
|
+
statusCode,
|
|
79
|
+
{
|
|
80
|
+
cause,
|
|
81
|
+
statusCode,
|
|
82
|
+
message,
|
|
83
|
+
isError: true,
|
|
84
|
+
} satisfies VovkErrorResponse,
|
|
85
|
+
options
|
|
86
|
+
);
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
#callMethod = async (
|
|
90
|
+
httpMethod: HttpMethod,
|
|
91
|
+
req: VovkRequest<KnownAny, KnownAny>,
|
|
92
|
+
params: Record<string, string[]>
|
|
93
|
+
) => {
|
|
94
|
+
const controllers = this.routes[httpMethod];
|
|
95
|
+
const methodParams: Record<string, string> = {};
|
|
96
|
+
const path = params[Object.keys(params)[0]];
|
|
97
|
+
|
|
98
|
+
const handlers: Record<string, { staticMethod: RouteHandler; controller: VovkController }> = {};
|
|
99
|
+
controllers.forEach((staticMethods, controller) => {
|
|
100
|
+
const prefix = controller._prefix ?? '';
|
|
101
|
+
|
|
102
|
+
if (!controller._activated) {
|
|
103
|
+
throw new HttpException(
|
|
104
|
+
HttpStatus.INTERNAL_SERVER_ERROR,
|
|
105
|
+
`Controller "${controller.name}" found but not activated`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
Object.entries(staticMethods).forEach(([path, staticMethod]) => {
|
|
110
|
+
const fullPath = [prefix, path].filter(Boolean).join('/');
|
|
111
|
+
handlers[fullPath] = { staticMethod, controller };
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const getHandler = () => {
|
|
116
|
+
if (Object.keys(params).length === 0) {
|
|
117
|
+
return handlers[''];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const allMethodKeys = Object.keys(handlers);
|
|
121
|
+
|
|
122
|
+
let methodKeys: string[] = [];
|
|
123
|
+
|
|
124
|
+
methodKeys = allMethodKeys
|
|
125
|
+
// First, try to match literal routes exactly.
|
|
126
|
+
.filter((p) => {
|
|
127
|
+
if (p.includes(':')) return false; // Skip parameterized paths
|
|
128
|
+
return p === path.join('/');
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
if (!methodKeys.length) {
|
|
132
|
+
methodKeys = allMethodKeys.filter((p) => {
|
|
133
|
+
const routeSegments = p.split('/');
|
|
134
|
+
if (routeSegments.length !== path.length) return false;
|
|
135
|
+
|
|
136
|
+
for (let i = 0; i < routeSegments.length; i++) {
|
|
137
|
+
const routeSegment = routeSegments[i];
|
|
138
|
+
const pathSegment = path[i];
|
|
139
|
+
|
|
140
|
+
if (routeSegment.startsWith(':')) {
|
|
141
|
+
const parameter = routeSegment.slice(1);
|
|
142
|
+
|
|
143
|
+
if (parameter in methodParams) {
|
|
144
|
+
throw new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, `Duplicate parameter "${parameter}"`);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// If it's a parameterized segment, capture the parameter value.
|
|
148
|
+
methodParams[parameter] = pathSegment;
|
|
149
|
+
} else if (routeSegment !== pathSegment) {
|
|
150
|
+
// If it's a literal segment and it does not match the corresponding path segment, return false.
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return true;
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (methodKeys.length > 1) {
|
|
159
|
+
throw new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, `Conflicting routes found: ${methodKeys.join(', ')}`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const [methodKey] = methodKeys;
|
|
163
|
+
|
|
164
|
+
if (methodKey) {
|
|
165
|
+
return handlers[methodKey];
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return null;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
const handler = getHandler();
|
|
172
|
+
|
|
173
|
+
if (!handler) {
|
|
174
|
+
return this.#respondWithError(HttpStatus.NOT_FOUND, `Route ${path.join('/')} is not found`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const { staticMethod, controller } = handler;
|
|
178
|
+
|
|
179
|
+
req.vovk = {
|
|
180
|
+
body: () => req.json(),
|
|
181
|
+
query: () => reqQuery(req),
|
|
182
|
+
meta: <T = KnownAny>(meta?: T | null) => reqMeta<T>(req, meta),
|
|
183
|
+
form: <T = KnownAny>() => reqForm<T>(req),
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
try {
|
|
187
|
+
const result = await staticMethod.call(controller, req, methodParams);
|
|
188
|
+
|
|
189
|
+
const isIterator =
|
|
190
|
+
typeof result === 'object' &&
|
|
191
|
+
!!result &&
|
|
192
|
+
((Reflect.has(result, Symbol.iterator) &&
|
|
193
|
+
typeof (result as Iterable<unknown>)[Symbol.iterator] === 'function') ||
|
|
194
|
+
(Reflect.has(result, Symbol.asyncIterator) &&
|
|
195
|
+
typeof (result as AsyncIterable<unknown>)[Symbol.asyncIterator] === 'function'));
|
|
196
|
+
|
|
197
|
+
if (isIterator && !(result instanceof Array)) {
|
|
198
|
+
const streamResponse = new StreamJSONResponse({
|
|
199
|
+
headers: {
|
|
200
|
+
...StreamJSONResponse.defaultHeaders,
|
|
201
|
+
...VovkApp.getHeadersFromOptions(staticMethod._options),
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
void (async () => {
|
|
206
|
+
try {
|
|
207
|
+
for await (const chunk of result as AsyncGenerator<unknown>) {
|
|
208
|
+
streamResponse.send(chunk);
|
|
209
|
+
}
|
|
210
|
+
} catch (e) {
|
|
211
|
+
return streamResponse.throw(e);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return streamResponse.close();
|
|
215
|
+
})();
|
|
216
|
+
|
|
217
|
+
return streamResponse;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (result instanceof Response) {
|
|
221
|
+
return result;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return this.respond(200, result ?? null, staticMethod._options);
|
|
225
|
+
} catch (e) {
|
|
226
|
+
const err = e as HttpException;
|
|
227
|
+
try {
|
|
228
|
+
await controller._onError?.(err, req);
|
|
229
|
+
} catch (onErrorError) {
|
|
230
|
+
// eslint-disable-next-line no-console
|
|
231
|
+
console.error(onErrorError);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (err.message !== 'NEXT_REDIRECT' && err.message !== 'NEXT_NOT_FOUND') {
|
|
235
|
+
const statusCode = err.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR;
|
|
236
|
+
return this.#respondWithError(statusCode, err.message, staticMethod._options, err.cause);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
throw e; // if NEXT_REDIRECT or NEXT_NOT_FOUND, rethrow it
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type VovkControllerSchema,
|
|
3
|
+
type ControllerStaticMethod,
|
|
4
|
+
type VovkControllerParams,
|
|
5
|
+
type VovkControllerQuery,
|
|
6
|
+
type KnownAny,
|
|
7
|
+
} from '../types';
|
|
8
|
+
import { type VovkClientOptions, type VovkClient, type VovkDefaultFetcherOptions, VovkValidateOnClient } from './types';
|
|
9
|
+
|
|
10
|
+
import defaultFetcher from './defaultFetcher';
|
|
11
|
+
import { defaultHandler } from './defaultHandler';
|
|
12
|
+
import { defaultStreamHandler } from './defaultStreamHandler';
|
|
13
|
+
|
|
14
|
+
// TODO Ugly workaround. Need your ideas how to distinguish between array and non-array query params
|
|
15
|
+
export const ARRAY_QUERY_KEY = '_vovkarr';
|
|
16
|
+
|
|
17
|
+
const trimPath = (path: string) => path.trim().replace(/^\/|\/$/g, '');
|
|
18
|
+
|
|
19
|
+
const getHandlerPath = <T extends ControllerStaticMethod>(
|
|
20
|
+
endpoint: string,
|
|
21
|
+
params?: VovkControllerParams<T>,
|
|
22
|
+
query?: VovkControllerQuery<T>
|
|
23
|
+
) => {
|
|
24
|
+
let result = endpoint;
|
|
25
|
+
for (const [key, value] of Object.entries(params ?? {})) {
|
|
26
|
+
result = result.replace(`:${key}`, value as string);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const searchParams = new URLSearchParams();
|
|
30
|
+
let hasQuery = false;
|
|
31
|
+
const arrayKeys: string[] = [];
|
|
32
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
33
|
+
if (typeof value === 'undefined') continue;
|
|
34
|
+
if (value instanceof Array) {
|
|
35
|
+
arrayKeys.push(key);
|
|
36
|
+
for (const val of value) {
|
|
37
|
+
searchParams.append(key, val);
|
|
38
|
+
}
|
|
39
|
+
} else {
|
|
40
|
+
searchParams.set(key, value);
|
|
41
|
+
}
|
|
42
|
+
hasQuery = true;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (arrayKeys.length) {
|
|
46
|
+
searchParams.set(ARRAY_QUERY_KEY, arrayKeys.join(','));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return `${result}${hasQuery ? '?' : ''}${searchParams.toString()}`;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export const createRPC = <T, OPTS extends Record<string, KnownAny> = VovkDefaultFetcherOptions>(
|
|
53
|
+
controllerSchema: VovkControllerSchema,
|
|
54
|
+
segmentName?: string,
|
|
55
|
+
options?: VovkClientOptions<OPTS>
|
|
56
|
+
): VovkClient<T, OPTS> => {
|
|
57
|
+
const schema = controllerSchema as T & VovkControllerSchema;
|
|
58
|
+
const client = {} as VovkClient<T, OPTS>;
|
|
59
|
+
if (!schema) throw new Error(`Unable to clientize. Controller schema is not provided`);
|
|
60
|
+
if (!schema.handlers)
|
|
61
|
+
throw new Error(`Unable to clientize. No schema for controller ${String(schema?.controllerName)} provided`);
|
|
62
|
+
const controllerPrefix = trimPath(schema.prefix ?? '');
|
|
63
|
+
const { fetcher: settingsFetcher = defaultFetcher } = options ?? {};
|
|
64
|
+
|
|
65
|
+
for (const [staticMethodName, { path, httpMethod, validation }] of Object.entries(schema.handlers)) {
|
|
66
|
+
const getEndpoint = ({
|
|
67
|
+
apiRoot,
|
|
68
|
+
params,
|
|
69
|
+
query,
|
|
70
|
+
}: {
|
|
71
|
+
apiRoot: string;
|
|
72
|
+
params: { [key: string]: string };
|
|
73
|
+
query: { [key: string]: string };
|
|
74
|
+
}) => {
|
|
75
|
+
const mainPrefix =
|
|
76
|
+
(apiRoot.startsWith('http://') || apiRoot.startsWith('https://') || apiRoot.startsWith('/') ? '' : '/') +
|
|
77
|
+
(apiRoot.endsWith('/') ? apiRoot : `${apiRoot}/`) +
|
|
78
|
+
(segmentName ? `${segmentName}/` : '');
|
|
79
|
+
return mainPrefix + getHandlerPath([controllerPrefix, path].filter(Boolean).join('/'), params, query);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const handler = (
|
|
83
|
+
input: {
|
|
84
|
+
body?: unknown;
|
|
85
|
+
query?: { [key: string]: string };
|
|
86
|
+
params?: { [key: string]: string };
|
|
87
|
+
validateOnClient?: VovkValidateOnClient;
|
|
88
|
+
fetcher?: VovkClientOptions<OPTS>['fetcher'];
|
|
89
|
+
transform?: (response: unknown) => unknown;
|
|
90
|
+
} & OPTS = {} as OPTS
|
|
91
|
+
) => {
|
|
92
|
+
const fetcher = input.fetcher ?? settingsFetcher;
|
|
93
|
+
const validate = async ({ body, query, endpoint }: { body?: unknown; query?: unknown; endpoint: string }) => {
|
|
94
|
+
await (input.validateOnClient ?? options?.validateOnClient)?.({ body, query, endpoint }, validation ?? {});
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const internalOptions: Parameters<typeof fetcher>[0] = {
|
|
98
|
+
name: staticMethodName as keyof T,
|
|
99
|
+
httpMethod,
|
|
100
|
+
getEndpoint,
|
|
101
|
+
validate,
|
|
102
|
+
defaultHandler,
|
|
103
|
+
defaultStreamHandler,
|
|
104
|
+
};
|
|
105
|
+
const internalInput = {
|
|
106
|
+
...options?.defaultOptions,
|
|
107
|
+
...input,
|
|
108
|
+
body: input.body ?? null,
|
|
109
|
+
query: input.query ?? {},
|
|
110
|
+
params: input.params ?? {},
|
|
111
|
+
// TS workaround
|
|
112
|
+
fetcher: undefined,
|
|
113
|
+
validateOnClient: undefined,
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
delete internalInput.fetcher;
|
|
117
|
+
delete internalInput.validateOnClient;
|
|
118
|
+
|
|
119
|
+
if (!fetcher) throw new Error('Fetcher is not provided');
|
|
120
|
+
|
|
121
|
+
const fetcherPromise = fetcher(internalOptions, internalInput) as Promise<unknown>;
|
|
122
|
+
|
|
123
|
+
if (!(fetcherPromise instanceof Promise)) return Promise.resolve(fetcherPromise);
|
|
124
|
+
|
|
125
|
+
return input.transform ? fetcherPromise.then(input.transform) : fetcherPromise;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
// @ts-expect-error TODO
|
|
129
|
+
client[staticMethodName] = handler;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return client;
|
|
133
|
+
};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { VovkDefaultFetcherOptions, VovkClientFetcher } from './types';
|
|
2
|
+
import { HttpStatus } from '../types';
|
|
3
|
+
import { HttpException } from '../HttpException';
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_ERROR_MESSAGE = 'Unknown error at the defaultFetcher';
|
|
6
|
+
|
|
7
|
+
// defaultFetcher uses HttpException class to throw errors of fake HTTP status 0 if client-side error occurs
|
|
8
|
+
// For normal HTTP errors, it uses message and status code from the response of VovkErrorResponse type
|
|
9
|
+
const defaultFetcher: VovkClientFetcher<VovkDefaultFetcherOptions> = async (
|
|
10
|
+
{ httpMethod, getEndpoint, validate, defaultHandler, defaultStreamHandler },
|
|
11
|
+
{ params, query, body, apiRoot = '/api', ...options }
|
|
12
|
+
) => {
|
|
13
|
+
const endpoint = getEndpoint({ apiRoot, params, query });
|
|
14
|
+
|
|
15
|
+
if (!options.disableClientValidation) {
|
|
16
|
+
try {
|
|
17
|
+
await validate({ body, query, endpoint });
|
|
18
|
+
} catch (e) {
|
|
19
|
+
// if HttpException is thrown, rethrow it
|
|
20
|
+
if (e instanceof HttpException) throw e;
|
|
21
|
+
// otherwise, throw HttpException with status 0
|
|
22
|
+
throw new HttpException(HttpStatus.NULL, (e as Error).message ?? DEFAULT_ERROR_MESSAGE);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const init: RequestInit = {
|
|
27
|
+
method: httpMethod,
|
|
28
|
+
...options,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
if (body instanceof FormData) {
|
|
32
|
+
init.body = body as BodyInit;
|
|
33
|
+
} else if (body) {
|
|
34
|
+
init.body = JSON.stringify(body);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
let response: Response;
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
response = await fetch(endpoint, init);
|
|
41
|
+
} catch (e) {
|
|
42
|
+
// handle network errors
|
|
43
|
+
throw new HttpException(HttpStatus.NULL, (e as Error)?.message ?? DEFAULT_ERROR_MESSAGE);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (response.headers.get('content-type')?.includes('application/json')) {
|
|
47
|
+
return defaultHandler(response);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (response.headers.get('x-vovk-stream') === 'true') {
|
|
51
|
+
return defaultStreamHandler(response);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return response;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export default defaultFetcher;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type VovkErrorResponse } from '../types';
|
|
2
|
+
import { HttpException } from '../HttpException';
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_ERROR_MESSAGE = 'Unknown error at defaultHandler';
|
|
5
|
+
|
|
6
|
+
export const defaultHandler = async (response: Response) => {
|
|
7
|
+
let result: unknown;
|
|
8
|
+
|
|
9
|
+
try {
|
|
10
|
+
result = await response.json();
|
|
11
|
+
} catch (e) {
|
|
12
|
+
// handle parsing errors
|
|
13
|
+
throw new HttpException(response.status, (e as Error)?.message ?? DEFAULT_ERROR_MESSAGE);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
if (!response.ok) {
|
|
17
|
+
// handle server errors
|
|
18
|
+
const errorResponse = result as VovkErrorResponse;
|
|
19
|
+
throw new HttpException(response.status, errorResponse?.message ?? DEFAULT_ERROR_MESSAGE, errorResponse?.cause);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
return result;
|
|
23
|
+
};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { HttpStatus, type VovkErrorResponse } from '../types';
|
|
2
|
+
import type { StreamAsyncIterator } from './types';
|
|
3
|
+
import { HttpException } from '../HttpException';
|
|
4
|
+
import '../utils/shim';
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_ERROR_MESSAGE = 'Unknown error at defaultStreamHandler';
|
|
7
|
+
|
|
8
|
+
export const defaultStreamHandler = async (response: Response): Promise<StreamAsyncIterator<unknown>> => {
|
|
9
|
+
if (!response.ok) {
|
|
10
|
+
let result: unknown;
|
|
11
|
+
try {
|
|
12
|
+
result = await response.json();
|
|
13
|
+
} catch {
|
|
14
|
+
// ignore parsing errors
|
|
15
|
+
}
|
|
16
|
+
// handle server errors
|
|
17
|
+
throw new HttpException(response.status, (result as VovkErrorResponse).message ?? DEFAULT_ERROR_MESSAGE);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (!response.body) throw new HttpException(HttpStatus.NULL, 'Stream body is falsy. Check your controller code.');
|
|
21
|
+
|
|
22
|
+
const reader = response.body.getReader();
|
|
23
|
+
|
|
24
|
+
// if streaming is too rapid, we need to make sure that the loop is stopped
|
|
25
|
+
let canceled = false;
|
|
26
|
+
|
|
27
|
+
async function* asyncIterator() {
|
|
28
|
+
let prepend = '';
|
|
29
|
+
|
|
30
|
+
while (true) {
|
|
31
|
+
let value: Uint8Array | undefined;
|
|
32
|
+
let done = false;
|
|
33
|
+
|
|
34
|
+
try {
|
|
35
|
+
({ value, done } = await reader.read());
|
|
36
|
+
} catch (error) {
|
|
37
|
+
await reader.cancel();
|
|
38
|
+
const err = new Error('Stream error. ' + String(error));
|
|
39
|
+
err.cause = error;
|
|
40
|
+
throw err;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (done) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// typeof value === 'number' is a workaround for React Native
|
|
48
|
+
const string = typeof value === 'number' ? String.fromCharCode(value) : new TextDecoder().decode(value);
|
|
49
|
+
prepend += string;
|
|
50
|
+
const lines = prepend.split('\n').filter(Boolean);
|
|
51
|
+
for (const line of lines) {
|
|
52
|
+
let data;
|
|
53
|
+
try {
|
|
54
|
+
data = JSON.parse(line) as object;
|
|
55
|
+
prepend = '';
|
|
56
|
+
} catch {
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (data) {
|
|
61
|
+
if ('isError' in data && 'reason' in data) {
|
|
62
|
+
const upcomingError = data.reason;
|
|
63
|
+
await reader.cancel();
|
|
64
|
+
|
|
65
|
+
if (typeof upcomingError === 'string') {
|
|
66
|
+
throw new Error(upcomingError);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
throw upcomingError;
|
|
70
|
+
} else if (!canceled) {
|
|
71
|
+
yield data;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
status: response.status,
|
|
80
|
+
[Symbol.asyncIterator]: asyncIterator,
|
|
81
|
+
[Symbol.dispose]: () => reader.cancel(),
|
|
82
|
+
[Symbol.asyncDispose]: () => reader.cancel(),
|
|
83
|
+
cancel: () => {
|
|
84
|
+
canceled = true;
|
|
85
|
+
return reader.cancel();
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { createRPC } from './createRPC';
|
|
2
|
+
import type { VovkClientFetcher, VovkClientOptions, VovkDefaultFetcherOptions, VovkValidateOnClient } from './types';
|
|
3
|
+
|
|
4
|
+
export { createRPC };
|
|
5
|
+
export type { VovkClientFetcher, VovkClientOptions, VovkDefaultFetcherOptions, VovkValidateOnClient };
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
KnownAny,
|
|
3
|
+
HttpMethod,
|
|
4
|
+
ControllerStaticMethod,
|
|
5
|
+
VovkControllerBody,
|
|
6
|
+
VovkControllerQuery,
|
|
7
|
+
VovkControllerParams,
|
|
8
|
+
} from '../types';
|
|
9
|
+
import type { StreamJSONResponse } from '../StreamJSONResponse';
|
|
10
|
+
import type { NextResponse } from 'next/server';
|
|
11
|
+
|
|
12
|
+
export type StaticMethodInput<T extends ControllerStaticMethod> = (VovkControllerBody<T> extends undefined | void
|
|
13
|
+
? { body?: undefined }
|
|
14
|
+
: VovkControllerBody<T> extends null
|
|
15
|
+
? { body?: null }
|
|
16
|
+
: { body: VovkControllerBody<T> }) &
|
|
17
|
+
(VovkControllerQuery<T> extends undefined | void ? { query?: undefined } : { query: VovkControllerQuery<T> }) &
|
|
18
|
+
(VovkControllerParams<T> extends undefined | void ? { params?: undefined } : { params: VovkControllerParams<T> });
|
|
19
|
+
|
|
20
|
+
type ToPromise<T> = T extends PromiseLike<unknown> ? T : Promise<T>;
|
|
21
|
+
|
|
22
|
+
export type StreamAsyncIterator<T> = {
|
|
23
|
+
status: number;
|
|
24
|
+
[Symbol.dispose](): Promise<void> | void;
|
|
25
|
+
[Symbol.asyncDispose](): Promise<void> | void;
|
|
26
|
+
[Symbol.asyncIterator](): AsyncIterator<T>;
|
|
27
|
+
cancel: () => Promise<void> | void;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
type StaticMethodReturn<T extends ControllerStaticMethod> =
|
|
31
|
+
ReturnType<T> extends NextResponse<infer U> | Promise<NextResponse<infer U>>
|
|
32
|
+
? U
|
|
33
|
+
: ReturnType<T> extends Response | Promise<Response>
|
|
34
|
+
? Awaited<ReturnType<T>>
|
|
35
|
+
: ReturnType<T>;
|
|
36
|
+
|
|
37
|
+
type StaticMethodReturnPromise<T extends ControllerStaticMethod> = ToPromise<StaticMethodReturn<T>>;
|
|
38
|
+
|
|
39
|
+
type ClientMethod<
|
|
40
|
+
T extends (...args: KnownAny[]) => void | object | StreamJSONResponse<STREAM> | Promise<StreamJSONResponse<STREAM>>,
|
|
41
|
+
OPTS extends Record<string, KnownAny>,
|
|
42
|
+
STREAM extends KnownAny = unknown,
|
|
43
|
+
> = <R>(
|
|
44
|
+
options: (StaticMethodInput<T> extends { body?: undefined | null; query?: undefined; params?: undefined }
|
|
45
|
+
? unknown
|
|
46
|
+
: Parameters<T>[0] extends void
|
|
47
|
+
? StaticMethodInput<T>['params'] extends object
|
|
48
|
+
? { params: StaticMethodInput<T>['params'] }
|
|
49
|
+
: unknown
|
|
50
|
+
: StaticMethodInput<T>) &
|
|
51
|
+
(Partial<
|
|
52
|
+
OPTS & {
|
|
53
|
+
transform: (staticMethodReturn: Awaited<StaticMethodReturn<T>>) => R;
|
|
54
|
+
}
|
|
55
|
+
> | void)
|
|
56
|
+
) => ReturnType<T> extends
|
|
57
|
+
| Promise<StreamJSONResponse<infer U>>
|
|
58
|
+
| StreamJSONResponse<infer U>
|
|
59
|
+
| Iterator<infer U>
|
|
60
|
+
| AsyncIterator<infer U>
|
|
61
|
+
? Promise<StreamAsyncIterator<U>>
|
|
62
|
+
: R extends object
|
|
63
|
+
? Promise<R>
|
|
64
|
+
: StaticMethodReturnPromise<T>;
|
|
65
|
+
|
|
66
|
+
type OmitNever<T> = {
|
|
67
|
+
[K in keyof T as T[K] extends never ? never : K]: T[K];
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
type VovkClientWithNever<T, OPTS extends { [key: string]: KnownAny }> = {
|
|
71
|
+
[K in keyof T]: T[K] extends (...args: KnownAny) => KnownAny ? ClientMethod<T[K], OPTS> : never;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export type VovkClient<T, OPTS extends { [key: string]: KnownAny }> = OmitNever<VovkClientWithNever<T, OPTS>>;
|
|
75
|
+
|
|
76
|
+
export type VovkClientFetcher<OPTS extends Record<string, KnownAny> = Record<string, never>, T = KnownAny> = (
|
|
77
|
+
options: {
|
|
78
|
+
name: keyof T;
|
|
79
|
+
httpMethod: HttpMethod;
|
|
80
|
+
getEndpoint: (data: {
|
|
81
|
+
apiRoot: string;
|
|
82
|
+
params: { [key: string]: string };
|
|
83
|
+
query: { [key: string]: string };
|
|
84
|
+
}) => string;
|
|
85
|
+
validate: (input: { body?: unknown; query?: unknown; endpoint: string }) => void | Promise<void>;
|
|
86
|
+
defaultStreamHandler: (response: Response) => Promise<StreamAsyncIterator<unknown>>;
|
|
87
|
+
defaultHandler: (response: Response) => Promise<unknown>;
|
|
88
|
+
},
|
|
89
|
+
input: {
|
|
90
|
+
body: unknown;
|
|
91
|
+
query: { [key: string]: string };
|
|
92
|
+
params: { [key: string]: string };
|
|
93
|
+
} & OPTS
|
|
94
|
+
) => KnownAny;
|
|
95
|
+
|
|
96
|
+
// `RequestInit` is the type of options passed to fetch function
|
|
97
|
+
export interface VovkDefaultFetcherOptions extends Omit<RequestInit, 'body' | 'method'> {
|
|
98
|
+
reactNative?: { textStreaming: boolean };
|
|
99
|
+
apiRoot?: string;
|
|
100
|
+
segmentName?: string;
|
|
101
|
+
disableClientValidation?: boolean;
|
|
102
|
+
validateOnClient?: VovkValidateOnClient;
|
|
103
|
+
fetcher?: VovkClientFetcher;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export type VovkValidateOnClient = (
|
|
107
|
+
input: { body?: unknown; query?: unknown; endpoint: string },
|
|
108
|
+
validators: { body?: unknown; query?: unknown }
|
|
109
|
+
) => void | Promise<void>;
|
|
110
|
+
|
|
111
|
+
export type VovkClientOptions<OPTS extends Record<string, KnownAny> = Record<string, never>> = {
|
|
112
|
+
fetcher?: VovkClientFetcher<OPTS>;
|
|
113
|
+
validateOnClient?: VovkValidateOnClient;
|
|
114
|
+
defaultOptions?: Partial<OPTS>;
|
|
115
|
+
};
|