vovk 3.0.0-draft.13 → 3.0.0-draft.135

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 (127) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +8 -96
  3. package/{HttpException.d.ts → cjs/HttpException.d.ts} +2 -2
  4. package/{HttpException.js → cjs/HttpException.js} +3 -3
  5. package/cjs/JSONLinesResponse.d.ts +14 -0
  6. package/{StreamResponse.js → cjs/JSONLinesResponse.js} +15 -9
  7. package/{Segment.d.ts → cjs/VovkApp.d.ts} +11 -10
  8. package/cjs/VovkApp.js +189 -0
  9. package/cjs/client/createRPC.d.ts +3 -0
  10. package/cjs/client/createRPC.js +86 -0
  11. package/{client → cjs/client}/defaultHandler.d.ts +1 -1
  12. package/cjs/client/defaultHandler.js +22 -0
  13. package/cjs/client/defaultStreamHandler.d.ts +4 -0
  14. package/{client → cjs/client}/defaultStreamHandler.js +8 -8
  15. package/cjs/client/fetcher.d.ts +8 -0
  16. package/cjs/client/fetcher.js +88 -0
  17. package/cjs/client/index.d.ts +3 -0
  18. package/cjs/client/index.js +8 -0
  19. package/cjs/client/types.d.ts +113 -0
  20. package/cjs/createDecorator.d.ts +6 -0
  21. package/{createDecorator.js → cjs/createDecorator.js} +21 -16
  22. package/{createSegment.d.ts → cjs/createVovkApp.d.ts} +10 -10
  23. package/cjs/createVovkApp.js +129 -0
  24. package/cjs/index.d.ts +60 -0
  25. package/cjs/index.js +25 -0
  26. package/cjs/types.d.ts +277 -0
  27. package/cjs/types.js +72 -0
  28. package/cjs/utils/generateStaticAPI.d.ts +4 -0
  29. package/cjs/utils/generateStaticAPI.js +30 -0
  30. package/cjs/utils/getSchema.d.ts +20 -0
  31. package/cjs/utils/getSchema.js +35 -0
  32. package/cjs/utils/parseQuery.d.ts +25 -0
  33. package/cjs/utils/parseQuery.js +156 -0
  34. package/cjs/utils/reqForm.d.ts +2 -0
  35. package/cjs/utils/reqForm.js +32 -0
  36. package/{utils → cjs/utils}/reqMeta.d.ts +1 -2
  37. package/{utils → cjs/utils}/reqQuery.d.ts +1 -2
  38. package/cjs/utils/reqQuery.js +10 -0
  39. package/cjs/utils/serializeQuery.d.ts +13 -0
  40. package/cjs/utils/serializeQuery.js +65 -0
  41. package/cjs/utils/setHandlerSchema.d.ts +4 -0
  42. package/cjs/utils/setHandlerSchema.js +15 -0
  43. package/cjs/utils/withValidation.d.ts +21 -0
  44. package/cjs/utils/withValidation.js +88 -0
  45. package/mjs/HttpException.d.ts +7 -0
  46. package/mjs/HttpException.js +15 -0
  47. package/mjs/JSONLinesResponse.d.ts +14 -0
  48. package/mjs/JSONLinesResponse.js +59 -0
  49. package/mjs/VovkApp.d.ts +29 -0
  50. package/mjs/VovkApp.js +189 -0
  51. package/mjs/client/createRPC.d.ts +3 -0
  52. package/mjs/client/createRPC.js +86 -0
  53. package/mjs/client/defaultHandler.d.ts +2 -0
  54. package/mjs/client/defaultHandler.js +22 -0
  55. package/mjs/client/defaultStreamHandler.d.ts +4 -0
  56. package/mjs/client/defaultStreamHandler.js +82 -0
  57. package/mjs/client/fetcher.d.ts +8 -0
  58. package/mjs/client/fetcher.js +88 -0
  59. package/mjs/client/index.d.ts +3 -0
  60. package/mjs/client/index.js +8 -0
  61. package/mjs/client/types.d.ts +113 -0
  62. package/mjs/createDecorator.d.ts +6 -0
  63. package/mjs/createDecorator.js +43 -0
  64. package/mjs/createVovkApp.d.ts +62 -0
  65. package/mjs/createVovkApp.js +129 -0
  66. package/mjs/index.d.ts +60 -0
  67. package/mjs/index.js +25 -0
  68. package/mjs/types.d.ts +277 -0
  69. package/mjs/types.js +72 -0
  70. package/mjs/utils/generateStaticAPI.d.ts +4 -0
  71. package/mjs/utils/generateStaticAPI.js +30 -0
  72. package/mjs/utils/getSchema.d.ts +20 -0
  73. package/mjs/utils/getSchema.js +35 -0
  74. package/mjs/utils/parseQuery.d.ts +25 -0
  75. package/mjs/utils/parseQuery.js +156 -0
  76. package/mjs/utils/reqForm.d.ts +2 -0
  77. package/mjs/utils/reqForm.js +32 -0
  78. package/mjs/utils/reqMeta.d.ts +2 -0
  79. package/mjs/utils/reqMeta.js +13 -0
  80. package/mjs/utils/reqQuery.d.ts +2 -0
  81. package/mjs/utils/reqQuery.js +10 -0
  82. package/mjs/utils/serializeQuery.d.ts +13 -0
  83. package/mjs/utils/serializeQuery.js +65 -0
  84. package/mjs/utils/setHandlerSchema.d.ts +4 -0
  85. package/mjs/utils/setHandlerSchema.js +15 -0
  86. package/mjs/utils/shim.d.ts +1 -0
  87. package/mjs/utils/shim.js +18 -0
  88. package/mjs/utils/withValidation.d.ts +21 -0
  89. package/mjs/utils/withValidation.js +88 -0
  90. package/package.json +15 -5
  91. package/.npmignore +0 -2
  92. package/Segment.js +0 -182
  93. package/StreamResponse.d.ts +0 -16
  94. package/client/clientizeController.d.ts +0 -4
  95. package/client/clientizeController.js +0 -93
  96. package/client/defaultFetcher.d.ts +0 -4
  97. package/client/defaultFetcher.js +0 -49
  98. package/client/defaultHandler.js +0 -21
  99. package/client/defaultStreamHandler.d.ts +0 -4
  100. package/client/index.d.ts +0 -4
  101. package/client/index.js +0 -5
  102. package/client/types.d.ts +0 -100
  103. package/createDecorator.d.ts +0 -4
  104. package/createSegment.js +0 -118
  105. package/generateStaticAPI.d.ts +0 -4
  106. package/generateStaticAPI.js +0 -18
  107. package/index.d.ts +0 -60
  108. package/index.js +0 -20
  109. package/types.d.ts +0 -186
  110. package/types.js +0 -65
  111. package/utils/getSchema.d.ts +0 -8
  112. package/utils/getSchema.js +0 -38
  113. package/utils/reqQuery.js +0 -25
  114. package/utils/setClientValidatorsForHandler.d.ts +0 -5
  115. package/utils/setClientValidatorsForHandler.js +0 -28
  116. package/worker/index.d.ts +0 -3
  117. package/worker/index.js +0 -7
  118. package/worker/promisifyWorker.d.ts +0 -2
  119. package/worker/promisifyWorker.js +0 -143
  120. package/worker/types.d.ts +0 -31
  121. package/worker/worker.d.ts +0 -1
  122. package/worker/worker.js +0 -44
  123. /package/{client → cjs/client}/types.js +0 -0
  124. /package/{utils → cjs/utils}/reqMeta.js +0 -0
  125. /package/{utils → cjs/utils}/shim.d.ts +0 -0
  126. /package/{utils → cjs/utils}/shim.js +0 -0
  127. /package/{worker → mjs/client}/types.js +0 -0
@@ -0,0 +1,4 @@
1
+ import type { VovkStreamAsyncIterable } from './types.js';
2
+ import '../utils/shim.js';
3
+ export declare const DEFAULT_ERROR_MESSAGE = "Unknown error at defaultStreamHandler";
4
+ export declare const defaultStreamHandler: (response: Response) => Promise<VovkStreamAsyncIterable<unknown>>;
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultStreamHandler = exports.DEFAULT_ERROR_MESSAGE = void 0;
4
+ const types_js_1 = require("../types.js");
5
+ const HttpException_js_1 = require("../HttpException.js");
6
+ require("../utils/shim.js");
7
+ exports.DEFAULT_ERROR_MESSAGE = 'Unknown error at defaultStreamHandler';
8
+ const defaultStreamHandler = async (response) => {
9
+ if (!response.ok) {
10
+ let result;
11
+ try {
12
+ result = await response.json();
13
+ }
14
+ catch {
15
+ // ignore parsing errors
16
+ }
17
+ // handle server errors
18
+ throw new HttpException_js_1.HttpException(response.status, result.message ?? exports.DEFAULT_ERROR_MESSAGE);
19
+ }
20
+ if (!response.body)
21
+ throw new HttpException_js_1.HttpException(types_js_1.HttpStatus.NULL, 'Stream body is falsy. Check your controller code.');
22
+ const reader = response.body.getReader();
23
+ // if streaming is too rapid, we need to make sure that the loop is stopped
24
+ let canceled = false;
25
+ async function* asyncIterator() {
26
+ let prepend = '';
27
+ while (true) {
28
+ let value;
29
+ let done = false;
30
+ try {
31
+ ({ value, done } = await reader.read());
32
+ }
33
+ catch (error) {
34
+ await reader.cancel();
35
+ const err = new Error('Stream error. ' + String(error));
36
+ err.cause = error;
37
+ throw err;
38
+ }
39
+ if (done) {
40
+ return;
41
+ }
42
+ // typeof value === 'number' is a workaround for React Native
43
+ const string = typeof value === 'number' ? String.fromCharCode(value) : new TextDecoder().decode(value);
44
+ prepend += string;
45
+ const lines = prepend.split('\n').filter(Boolean);
46
+ for (const line of lines) {
47
+ let data;
48
+ try {
49
+ data = JSON.parse(line);
50
+ prepend = '';
51
+ }
52
+ catch {
53
+ break;
54
+ }
55
+ if (data) {
56
+ if ('isError' in data && 'reason' in data) {
57
+ const upcomingError = data.reason;
58
+ await reader.cancel();
59
+ if (typeof upcomingError === 'string') {
60
+ throw new Error(upcomingError);
61
+ }
62
+ throw upcomingError;
63
+ }
64
+ else if (!canceled) {
65
+ yield data;
66
+ }
67
+ }
68
+ }
69
+ }
70
+ }
71
+ return {
72
+ status: response.status,
73
+ [Symbol.asyncIterator]: asyncIterator,
74
+ [Symbol.dispose]: () => reader.cancel(),
75
+ [Symbol.asyncDispose]: () => reader.cancel(),
76
+ cancel: () => {
77
+ canceled = true;
78
+ return reader.cancel();
79
+ },
80
+ };
81
+ };
82
+ exports.defaultStreamHandler = defaultStreamHandler;
@@ -0,0 +1,8 @@
1
+ import type { VovkDefaultFetcherOptions, VovkClientFetcher } from './types.js';
2
+ import { KnownAny } from '../types.js';
3
+ export declare const DEFAULT_ERROR_MESSAGE = "Unknown error at default fetcher";
4
+ export declare function createFetcher<T extends Record<string, KnownAny> = Record<string, never>>({ prepareRequestInit, transformResponse, }?: {
5
+ prepareRequestInit?: (init: RequestInit, options: VovkDefaultFetcherOptions<T> & T) => RequestInit | Promise<RequestInit> | void | Promise<void>;
6
+ transformResponse?: (resp: unknown, options: VovkDefaultFetcherOptions<T> & T, init: RequestInit) => unknown;
7
+ }): VovkClientFetcher<VovkDefaultFetcherOptions<T>>;
8
+ export declare const fetcher: VovkClientFetcher<VovkDefaultFetcherOptions<Record<string, never>>>;
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetcher = exports.DEFAULT_ERROR_MESSAGE = void 0;
4
+ exports.createFetcher = createFetcher;
5
+ const types_js_1 = require("../types.js");
6
+ const HttpException_js_1 = require("../HttpException.js");
7
+ exports.DEFAULT_ERROR_MESSAGE = 'Unknown error at default fetcher';
8
+ function createFetcher({ prepareRequestInit, transformResponse, } = {}) {
9
+ // fetcher uses HttpException class to throw errors of fake HTTP status 0 if client-side error occurs
10
+ // For normal HTTP errors, it uses message and status code from the response of VovkErrorResponse type
11
+ const newFetcher = async ({ httpMethod, getEndpoint, validate, defaultHandler, defaultStreamHandler }, options) => {
12
+ const { params, query, body, apiRoot = '/api', disableClientValidation, init, interpretAs } = options;
13
+ const endpoint = getEndpoint({ apiRoot, params, query });
14
+ const unusedParams = new URL(endpoint).pathname.split('/').filter((segment) => segment.startsWith(':'));
15
+ if (unusedParams.length) {
16
+ throw new HttpException_js_1.HttpException(types_js_1.HttpStatus.NULL, `Unused params: ${unusedParams.join(', ')} in ${endpoint}`, {
17
+ body,
18
+ query,
19
+ params,
20
+ endpoint,
21
+ });
22
+ }
23
+ if (!disableClientValidation) {
24
+ try {
25
+ await validate({ body, query, params, endpoint });
26
+ }
27
+ catch (e) {
28
+ // if HttpException is thrown, rethrow it
29
+ if (e instanceof HttpException_js_1.HttpException)
30
+ throw e;
31
+ // otherwise, throw HttpException with status 0
32
+ throw new HttpException_js_1.HttpException(types_js_1.HttpStatus.NULL, e.message ?? exports.DEFAULT_ERROR_MESSAGE, {
33
+ body,
34
+ query,
35
+ params,
36
+ endpoint,
37
+ });
38
+ }
39
+ }
40
+ let requestInit = {
41
+ method: httpMethod,
42
+ ...init,
43
+ headers: {
44
+ accept: 'application/jsonl, application/json',
45
+ ...init?.headers,
46
+ },
47
+ };
48
+ if (body instanceof FormData) {
49
+ requestInit.body = body;
50
+ }
51
+ else if (body) {
52
+ requestInit.body = JSON.stringify(body);
53
+ }
54
+ requestInit = prepareRequestInit
55
+ ? ((await prepareRequestInit(requestInit, options)) ?? requestInit)
56
+ : requestInit;
57
+ let response;
58
+ try {
59
+ response = await fetch(endpoint, requestInit);
60
+ }
61
+ catch (e) {
62
+ // handle network errors
63
+ throw new HttpException_js_1.HttpException(types_js_1.HttpStatus.NULL, e?.message ?? exports.DEFAULT_ERROR_MESSAGE, {
64
+ body,
65
+ query,
66
+ params,
67
+ endpoint,
68
+ });
69
+ }
70
+ const contentType = interpretAs ?? response.headers.get('content-type');
71
+ let resp;
72
+ if (contentType?.startsWith('application/jsonl')) {
73
+ resp = defaultStreamHandler(response);
74
+ }
75
+ else if (contentType?.startsWith('application/json')) {
76
+ resp = defaultHandler(response);
77
+ }
78
+ else {
79
+ resp = response;
80
+ }
81
+ resp = await resp;
82
+ return transformResponse
83
+ ? ((await transformResponse(resp, options, requestInit)) ?? resp)
84
+ : resp;
85
+ };
86
+ return newFetcher;
87
+ }
88
+ exports.fetcher = createFetcher();
@@ -0,0 +1,3 @@
1
+ export { createRPC } from './createRPC.js';
2
+ export { fetcher, createFetcher } from './fetcher.js';
3
+ export type { VovkClient, VovkClientFetcher, VovkClientOptions, VovkDefaultFetcherOptions, VovkValidateOnClient, VovkStreamAsyncIterable, } from './types.js';
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createFetcher = exports.fetcher = exports.createRPC = void 0;
4
+ var createRPC_js_1 = require("./createRPC.js");
5
+ Object.defineProperty(exports, "createRPC", { enumerable: true, get: function () { return createRPC_js_1.createRPC; } });
6
+ var fetcher_js_1 = require("./fetcher.js");
7
+ Object.defineProperty(exports, "fetcher", { enumerable: true, get: function () { return fetcher_js_1.fetcher; } });
8
+ Object.defineProperty(exports, "createFetcher", { enumerable: true, get: function () { return fetcher_js_1.createFetcher; } });
@@ -0,0 +1,113 @@
1
+ import type { KnownAny, HttpMethod, ControllerStaticMethod, VovkControllerBody, VovkControllerQuery, VovkControllerParams, VovkHandlerSchema, VovkControllerSchema, VovkSegmentSchema, VovkSchema } from '../types.js';
2
+ import type { JSONLinesResponse } from '../JSONLinesResponse.js';
3
+ import type { NextResponse } from 'next/server';
4
+ export type StaticMethodInput<T extends ControllerStaticMethod> = (VovkControllerBody<T> extends undefined | void ? {
5
+ body?: undefined;
6
+ } : VovkControllerBody<T> extends null ? {
7
+ body?: null;
8
+ } : {
9
+ body: VovkControllerBody<T>;
10
+ }) & (VovkControllerQuery<T> extends undefined | void ? {
11
+ query?: undefined;
12
+ } : {
13
+ query: VovkControllerQuery<T>;
14
+ }) & (VovkControllerParams<T> extends undefined | void ? {
15
+ params?: undefined;
16
+ } : {
17
+ params: VovkControllerParams<T>;
18
+ });
19
+ type ToPromise<T> = T extends PromiseLike<unknown> ? T : Promise<T>;
20
+ export type VovkStreamAsyncIterable<T> = {
21
+ status: number;
22
+ [Symbol.dispose](): Promise<void> | void;
23
+ [Symbol.asyncDispose](): Promise<void> | void;
24
+ [Symbol.asyncIterator](): AsyncIterator<T>;
25
+ cancel: () => Promise<void> | void;
26
+ };
27
+ type StaticMethodReturn<T extends ControllerStaticMethod> = ReturnType<T> extends NextResponse<infer U> | Promise<NextResponse<infer U>> ? U : ReturnType<T> extends Response | Promise<Response> ? Awaited<ReturnType<T>> : ReturnType<T>;
28
+ type StaticMethodReturnPromise<T extends ControllerStaticMethod> = ToPromise<StaticMethodReturn<T>>;
29
+ type StaticMethodOption<T extends ((...args: KnownAny[]) => void | object | JSONLinesResponse<STREAM> | Promise<JSONLinesResponse<STREAM>>) & {
30
+ __output?: KnownAny;
31
+ __iteration?: KnownAny;
32
+ }, OPTS extends Record<string, KnownAny>, STREAM extends KnownAny = unknown, R = KnownAny, F extends VovkDefaultFetcherOptions<KnownAny> = VovkDefaultFetcherOptions<KnownAny>> = (StaticMethodInput<T> extends {
33
+ body?: undefined | null;
34
+ query?: undefined;
35
+ params?: undefined;
36
+ } ? unknown : Parameters<T>[0] extends void ? StaticMethodInput<T>['params'] extends object ? {
37
+ params: StaticMethodInput<T>['params'];
38
+ } : unknown : StaticMethodInput<T>) & (Partial<OPTS & {
39
+ transform: (staticMethodReturn: Awaited<StaticMethodReturn<T>>) => R;
40
+ fetcher: VovkClientFetcher<F>;
41
+ }> | void) & (Partial<F extends VovkDefaultFetcherOptions<infer U> ? Omit<U, keyof VovkDefaultFetcherOptions<OPTS>> : void> | void);
42
+ type ClientMethod<T extends ((...args: KnownAny[]) => void | object | JSONLinesResponse<STREAM> | Promise<JSONLinesResponse<STREAM>>) & {
43
+ __output?: KnownAny;
44
+ __iteration?: KnownAny;
45
+ }, OPTS extends Record<string, KnownAny>, STREAM extends KnownAny = unknown> = (<R, F extends VovkDefaultFetcherOptions<KnownAny> = VovkDefaultFetcherOptions<OPTS>>(options: StaticMethodOption<T, OPTS, STREAM, R, F>) => ReturnType<T> extends Promise<JSONLinesResponse<infer U>> | JSONLinesResponse<infer U> | Iterator<infer U> | AsyncIterator<infer U> ? Promise<VovkStreamAsyncIterable<U>> : R extends object ? Promise<R> : StaticMethodReturnPromise<T>) & {
46
+ isRPC: true;
47
+ schema: VovkHandlerSchema;
48
+ controllerSchema: VovkControllerSchema;
49
+ segmentSchema: VovkSegmentSchema;
50
+ fullSchema: VovkSchema;
51
+ __output: T['__output'];
52
+ __iteration: T['__iteration'];
53
+ };
54
+ type OmitNever<T> = {
55
+ [K in keyof T as T[K] extends never ? never : K]: T[K];
56
+ };
57
+ type VovkClientWithNever<T, OPTS extends {
58
+ [key: string]: KnownAny;
59
+ }> = {
60
+ [K in keyof T]: T[K] extends (...args: KnownAny) => KnownAny ? ClientMethod<T[K], OPTS> : never;
61
+ };
62
+ export type VovkClient<T, OPTS extends {
63
+ [key: string]: KnownAny;
64
+ }> = OmitNever<VovkClientWithNever<T, OPTS>>;
65
+ export type VovkClientFetcher<OPTS, T = KnownAny> = (options: {
66
+ name: keyof T;
67
+ httpMethod: HttpMethod;
68
+ getEndpoint: (data: {
69
+ apiRoot: string;
70
+ params: {
71
+ [key: string]: string;
72
+ };
73
+ query: {
74
+ [key: string]: string;
75
+ };
76
+ }) => string;
77
+ validate: (input: {
78
+ body?: unknown;
79
+ query?: unknown;
80
+ params?: unknown;
81
+ endpoint: string;
82
+ }) => void | Promise<void>;
83
+ defaultStreamHandler: (response: Response) => Promise<VovkStreamAsyncIterable<unknown>>;
84
+ defaultHandler: (response: Response) => Promise<unknown>;
85
+ }, input: {
86
+ body: unknown;
87
+ query: {
88
+ [key: string]: string;
89
+ };
90
+ params: {
91
+ [key: string]: string;
92
+ };
93
+ } & OPTS) => KnownAny;
94
+ export interface VovkDefaultFetcherOptions<T> {
95
+ apiRoot?: string;
96
+ disableClientValidation?: boolean;
97
+ validateOnClient?: VovkValidateOnClient;
98
+ fetcher?: VovkClientFetcher<T>;
99
+ interpretAs?: string;
100
+ init?: RequestInit;
101
+ }
102
+ export type VovkValidateOnClient = (input: {
103
+ body?: unknown;
104
+ query?: unknown;
105
+ params?: unknown;
106
+ endpoint: string;
107
+ }, validation: Omit<Exclude<VovkHandlerSchema['validation'], undefined>, 'output' | 'iteration'>, fullSchema: VovkSchema) => void | Promise<void>;
108
+ export type VovkClientOptions<OPTS extends Record<string, KnownAny> = Record<string, never>> = {
109
+ fetcher?: VovkClientFetcher<OPTS>;
110
+ validateOnClient?: VovkValidateOnClient;
111
+ defaultOptions?: Partial<OPTS>;
112
+ };
113
+ export {};
@@ -0,0 +1,6 @@
1
+ import type { VovkHandlerSchema, KnownAny, VovkController, VovkRequest } from './types.js';
2
+ type Next = () => Promise<unknown>;
3
+ export declare function createDecorator<ARGS extends unknown[], REQUEST = VovkRequest>(handler: null | ((this: VovkController, req: REQUEST, next: Next, ...args: ARGS) => unknown), initHandler?: (this: VovkController, ...args: ARGS) => Omit<VovkHandlerSchema, 'path' | 'httpMethod'> | ((handlerSchema: VovkHandlerSchema | null, options: {
4
+ handlerName: string;
5
+ }) => Omit<Partial<VovkHandlerSchema>, 'path' | 'httpMethod'>) | null | undefined): (...args: ARGS) => (target: KnownAny, propertyKey: string) => void;
6
+ export {};
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createDecorator = createDecorator;
4
+ function createDecorator(handler, initHandler) {
5
+ return function decoratorCreator(...args) {
6
+ return function decorator(target, propertyKey) {
7
+ const controller = target;
8
+ const originalMethod = controller[propertyKey];
9
+ if (typeof originalMethod !== 'function') {
10
+ throw new Error(`Unable to decorate: ${propertyKey} is not a function`);
11
+ }
12
+ const sourceMethod = originalMethod._sourceMethod ?? originalMethod;
13
+ const method = function method(req, params) {
14
+ const next = async () => {
15
+ return (await originalMethod.call(controller, req, params));
16
+ };
17
+ return handler ? handler.call(controller, req, next, ...args) : next();
18
+ };
19
+ controller[propertyKey] = method;
20
+ method._controller = controller;
21
+ method._sourceMethod = sourceMethod;
22
+ // TODO define internal method type
23
+ originalMethod._controller = controller;
24
+ const handlerSchema = controller._handlers?.[propertyKey] ?? null;
25
+ const initResultReturn = initHandler?.call(controller, ...args);
26
+ const initResult = typeof initResultReturn === 'function'
27
+ ? initResultReturn(handlerSchema, {
28
+ handlerName: propertyKey,
29
+ })
30
+ : initResultReturn;
31
+ controller._handlers = {
32
+ ...controller._handlers,
33
+ [propertyKey]: {
34
+ ...handlerSchema,
35
+ // avoid override of path and httpMethod
36
+ ...(initResult?.validation ? { validation: initResult.validation } : {}),
37
+ ...(initResult?.openapi ? { openapi: initResult.openapi } : {}),
38
+ ...(initResult?.misc ? { misc: initResult.misc } : {}),
39
+ },
40
+ };
41
+ };
42
+ };
43
+ }
@@ -0,0 +1,62 @@
1
+ import type { NextRequest } from 'next/server';
2
+ import { type KnownAny, type DecoratorOptions, type VovkRequest, type StaticClass } from './types.js';
3
+ export declare function createVovkApp(): {
4
+ get: {
5
+ (givenPath?: string | undefined, options?: DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
6
+ auto: (options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
7
+ };
8
+ post: {
9
+ (givenPath?: string | undefined, options?: DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
10
+ auto: (options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
11
+ };
12
+ put: {
13
+ (givenPath?: string | undefined, options?: DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
14
+ auto: (options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
15
+ };
16
+ patch: {
17
+ (givenPath?: string | undefined, options?: DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
18
+ auto: (options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
19
+ };
20
+ del: {
21
+ (givenPath?: string | undefined, options?: DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
22
+ auto: (options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
23
+ };
24
+ head: {
25
+ (givenPath?: string | undefined, options?: DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
26
+ auto: (options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
27
+ };
28
+ options: {
29
+ (givenPath?: string | undefined, options?: DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
30
+ auto: (options?: DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
31
+ };
32
+ prefix: (givenPath?: string) => (givenTarget: KnownAny) => any;
33
+ initVovk: (options: {
34
+ segmentName?: string;
35
+ controllers: Record<string, StaticClass>;
36
+ exposeValidation?: boolean;
37
+ emitSchema?: boolean;
38
+ onError?: (err: Error, req: VovkRequest) => void | Promise<void>;
39
+ }) => {
40
+ GET: (req: NextRequest, data: {
41
+ params: Promise<Record<string, string[]>>;
42
+ }) => Promise<Response>;
43
+ POST: (req: NextRequest, data: {
44
+ params: Promise<Record<string, string[]>>;
45
+ }) => Promise<Response>;
46
+ PUT: (req: NextRequest, data: {
47
+ params: Promise<Record<string, string[]>>;
48
+ }) => Promise<Response>;
49
+ PATCH: (req: NextRequest, data: {
50
+ params: Promise<Record<string, string[]>>;
51
+ }) => Promise<Response>;
52
+ DELETE: (req: NextRequest, data: {
53
+ params: Promise<Record<string, string[]>>;
54
+ }) => Promise<Response>;
55
+ HEAD: (req: NextRequest, data: {
56
+ params: Promise<Record<string, string[]>>;
57
+ }) => Promise<Response>;
58
+ OPTIONS: (req: NextRequest, data: {
59
+ params: Promise<Record<string, string[]>>;
60
+ }) => Promise<Response>;
61
+ };
62
+ };
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createVovkApp = createVovkApp;
7
+ const VovkApp_js_1 = require("./VovkApp.js");
8
+ const types_js_1 = require("./types.js");
9
+ const getSchema_js_1 = __importDefault(require("./utils/getSchema.js"));
10
+ const trimPath = (path) => path.trim().replace(/^\/|\/$/g, '');
11
+ const isClass = (func) => typeof func === 'function' && /class/.test(func.toString());
12
+ const toKebabCase = (str) => str
13
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2') // Add hyphen between lowercase/digit and uppercase
14
+ .replace(/([A-Z])([A-Z])(?=[a-z])/g, '$1-$2') // Add hyphen between uppercase letters if the second one is followed by a lowercase
15
+ .toLowerCase()
16
+ .replace(/^-/, ''); // Remove leading hyphen
17
+ const assignSchema = ({ controller, propertyKey, path, options, httpMethod, vovkApp, }) => {
18
+ if (typeof window !== 'undefined') {
19
+ throw new Error('Decorators are intended for server-side use only. You have probably imported a controller on the client-side.');
20
+ }
21
+ if (!isClass(controller)) {
22
+ let decoratorName = httpMethod.toLowerCase();
23
+ if (decoratorName === 'delete')
24
+ decoratorName = 'del';
25
+ throw new Error(`Decorator must be used on a static class method. Check the controller method named "${propertyKey}" used with @${decoratorName}().`);
26
+ }
27
+ const methods = vovkApp.routes[httpMethod].get(controller) ?? {};
28
+ vovkApp.routes[httpMethod].set(controller, methods);
29
+ const originalMethod = controller[propertyKey];
30
+ originalMethod._controller = controller;
31
+ originalMethod._sourceMethod = originalMethod._sourceMethod ?? originalMethod;
32
+ const schema = originalMethod._sourceMethod._getSchema?.(controller);
33
+ controller._handlers = {
34
+ ...controller._handlers,
35
+ [propertyKey]: {
36
+ ...schema,
37
+ ...(controller._handlers ?? {})[propertyKey],
38
+ path,
39
+ httpMethod,
40
+ },
41
+ };
42
+ methods[path] = controller[propertyKey];
43
+ methods[path]._options = options;
44
+ controller._handlersMetadata = {
45
+ ...controller._handlersMetadata,
46
+ [propertyKey]: {
47
+ ...(controller._handlersMetadata ?? {})[propertyKey],
48
+ staticParams: options?.staticParams,
49
+ },
50
+ };
51
+ };
52
+ function createVovkApp() {
53
+ const vovkApp = new VovkApp_js_1.VovkApp();
54
+ const createHTTPDecorator = (httpMethod) => {
55
+ function decoratorCreator(givenPath = '', options) {
56
+ const path = trimPath(givenPath);
57
+ function decorator(givenTarget, propertyKey) {
58
+ const controller = givenTarget;
59
+ assignSchema({ controller, propertyKey, path, options, httpMethod, vovkApp });
60
+ }
61
+ return decorator;
62
+ }
63
+ const auto = (options) => {
64
+ function decorator(givenTarget, propertyKey) {
65
+ const controller = givenTarget;
66
+ const methods = vovkApp.routes[httpMethod].get(controller) ?? {};
67
+ vovkApp.routes[httpMethod].set(controller, methods);
68
+ controller._handlers = {
69
+ ...controller._handlers,
70
+ [propertyKey]: {
71
+ ...(controller._handlers ?? {})[propertyKey],
72
+ httpMethod,
73
+ },
74
+ };
75
+ const properties = Object.keys(controller._handlers[propertyKey]?.validation?.params?.properties ?? {});
76
+ const kebab = toKebabCase(propertyKey); // 🥙
77
+ const path = properties.length ? `${kebab}/${properties.map((prop) => `:${prop}`).join('/')}` : kebab;
78
+ assignSchema({ controller, propertyKey, path, options, httpMethod, vovkApp });
79
+ }
80
+ return decorator;
81
+ };
82
+ const enhancedDecoratorCreator = decoratorCreator;
83
+ enhancedDecoratorCreator.auto = auto;
84
+ return enhancedDecoratorCreator;
85
+ };
86
+ const prefix = (givenPath = '') => {
87
+ const path = trimPath(givenPath);
88
+ return (givenTarget) => {
89
+ const controller = givenTarget;
90
+ controller._prefix = path;
91
+ return givenTarget;
92
+ };
93
+ };
94
+ const initVovk = (options) => {
95
+ for (const [rpcModuleName, controller] of Object.entries(options.controllers)) {
96
+ controller._rpcModuleName = rpcModuleName;
97
+ controller._activated = true;
98
+ controller._onError = options?.onError;
99
+ }
100
+ async function GET_DEV(req, data) {
101
+ const params = await data.params;
102
+ if (params[Object.keys(params)[0]]?.[0] === '_schema_') {
103
+ const schema = (0, getSchema_js_1.default)(options);
104
+ return vovkApp.respond(200, { schema });
105
+ }
106
+ return vovkApp.GET(req, data);
107
+ }
108
+ return {
109
+ GET: process.env.NODE_ENV === 'development' ? GET_DEV : vovkApp.GET,
110
+ POST: vovkApp.POST,
111
+ PUT: vovkApp.PUT,
112
+ PATCH: vovkApp.PATCH,
113
+ DELETE: vovkApp.DELETE,
114
+ HEAD: vovkApp.HEAD,
115
+ OPTIONS: vovkApp.OPTIONS,
116
+ };
117
+ };
118
+ return {
119
+ get: createHTTPDecorator(types_js_1.HttpMethod.GET),
120
+ post: createHTTPDecorator(types_js_1.HttpMethod.POST),
121
+ put: createHTTPDecorator(types_js_1.HttpMethod.PUT),
122
+ patch: createHTTPDecorator(types_js_1.HttpMethod.PATCH),
123
+ del: createHTTPDecorator(types_js_1.HttpMethod.DELETE),
124
+ head: createHTTPDecorator(types_js_1.HttpMethod.HEAD),
125
+ options: createHTTPDecorator(types_js_1.HttpMethod.OPTIONS),
126
+ prefix,
127
+ initVovk,
128
+ };
129
+ }
package/mjs/index.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ import { createVovkApp } from './createVovkApp.js';
2
+ import { HttpStatus, HttpMethod, VovkSchemaIdEnum, // TODO: not documented
3
+ type KnownAny, type VovkErrorResponse, type VovkRequest, type VovkBody, type VovkQuery, type VovkParams, type VovkReturnType, type VovkYieldType, type VovkOutput, type VovkIteration, type VovkSegmentSchema, type VovkControllerSchema, type VovkHandlerSchema, type VovkSchema, type VovkConfig, type VovkStrictConfig, type VovkValidationType } from './types.js';
4
+ import { type VovkClient, type VovkClientOptions, type VovkClientFetcher, type VovkDefaultFetcherOptions, type VovkValidateOnClient, type VovkStreamAsyncIterable, createRPC, fetcher, createFetcher } from './client/index.js';
5
+ import { HttpException } from './HttpException.js';
6
+ import { createDecorator } from './createDecorator.js';
7
+ import { JSONLinesResponse } from './JSONLinesResponse.js';
8
+ import { generateStaticAPI } from './utils/generateStaticAPI.js';
9
+ import { withValidation } from './utils/withValidation.js';
10
+ export { type KnownAny, type VovkClient, type VovkClientFetcher, type VovkDefaultFetcherOptions, type VovkStreamAsyncIterable, type VovkValidateOnClient, type VovkSegmentSchema, type VovkErrorResponse, type VovkRequest, type VovkOutput, type VovkIteration, type VovkBody, type VovkQuery, type VovkParams, type VovkYieldType, type VovkReturnType, type VovkClientOptions, type VovkControllerSchema, type VovkHandlerSchema, type VovkSchema, type VovkConfig, type VovkStrictConfig, type VovkValidationType, VovkSchemaIdEnum, JSONLinesResponse, HttpException, HttpStatus, HttpMethod, createVovkApp, createDecorator, createRPC, fetcher, createFetcher, generateStaticAPI, withValidation, };
11
+ export declare const get: {
12
+ (givenPath?: string | undefined, options?: import("./types.js").DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
13
+ auto: (options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
14
+ }, post: {
15
+ (givenPath?: string | undefined, options?: import("./types.js").DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
16
+ auto: (options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
17
+ }, put: {
18
+ (givenPath?: string | undefined, options?: import("./types.js").DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
19
+ auto: (options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
20
+ }, patch: {
21
+ (givenPath?: string | undefined, options?: import("./types.js").DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
22
+ auto: (options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
23
+ }, del: {
24
+ (givenPath?: string | undefined, options?: import("./types.js").DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
25
+ auto: (options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
26
+ }, head: {
27
+ (givenPath?: string | undefined, options?: import("./types.js").DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
28
+ auto: (options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
29
+ }, options: {
30
+ (givenPath?: string | undefined, options?: import("./types.js").DecoratorOptions | undefined): ReturnType<(givenPath?: string, options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void>;
31
+ auto: (options?: import("./types.js").DecoratorOptions) => (givenTarget: KnownAny, propertyKey: string) => void;
32
+ }, prefix: (givenPath?: string) => (givenTarget: KnownAny) => any, initVovk: (options: {
33
+ segmentName?: string;
34
+ controllers: Record<string, import("./types.js").StaticClass>;
35
+ exposeValidation?: boolean;
36
+ emitSchema?: boolean;
37
+ onError?: (err: Error, req: VovkRequest) => void | Promise<void>;
38
+ }) => {
39
+ GET: (req: import("next/server.js").NextRequest, data: {
40
+ params: Promise<Record<string, string[]>>;
41
+ }) => Promise<Response>;
42
+ POST: (req: import("next/server.js").NextRequest, data: {
43
+ params: Promise<Record<string, string[]>>;
44
+ }) => Promise<Response>;
45
+ PUT: (req: import("next/server.js").NextRequest, data: {
46
+ params: Promise<Record<string, string[]>>;
47
+ }) => Promise<Response>;
48
+ PATCH: (req: import("next/server.js").NextRequest, data: {
49
+ params: Promise<Record<string, string[]>>;
50
+ }) => Promise<Response>;
51
+ DELETE: (req: import("next/server.js").NextRequest, data: {
52
+ params: Promise<Record<string, string[]>>;
53
+ }) => Promise<Response>;
54
+ HEAD: (req: import("next/server.js").NextRequest, data: {
55
+ params: Promise<Record<string, string[]>>;
56
+ }) => Promise<Response>;
57
+ OPTIONS: (req: import("next/server.js").NextRequest, data: {
58
+ params: Promise<Record<string, string[]>>;
59
+ }) => Promise<Response>;
60
+ };
package/mjs/index.js ADDED
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.initVovk = exports.prefix = exports.options = exports.head = exports.del = exports.patch = exports.put = exports.post = exports.get = exports.withValidation = exports.generateStaticAPI = exports.createFetcher = exports.fetcher = exports.createRPC = exports.createDecorator = exports.createVovkApp = exports.HttpMethod = exports.HttpStatus = exports.HttpException = exports.JSONLinesResponse = exports.VovkSchemaIdEnum = void 0;
5
+ const createVovkApp_js_1 = require("./createVovkApp.js");
6
+ Object.defineProperty(exports, "createVovkApp", { enumerable: true, get: function () { return createVovkApp_js_1.createVovkApp; } });
7
+ const types_js_1 = require("./types.js");
8
+ Object.defineProperty(exports, "HttpStatus", { enumerable: true, get: function () { return types_js_1.HttpStatus; } });
9
+ Object.defineProperty(exports, "HttpMethod", { enumerable: true, get: function () { return types_js_1.HttpMethod; } });
10
+ Object.defineProperty(exports, "VovkSchemaIdEnum", { enumerable: true, get: function () { return types_js_1.VovkSchemaIdEnum; } });
11
+ const index_js_1 = require("./client/index.js");
12
+ Object.defineProperty(exports, "createRPC", { enumerable: true, get: function () { return index_js_1.createRPC; } });
13
+ Object.defineProperty(exports, "fetcher", { enumerable: true, get: function () { return index_js_1.fetcher; } });
14
+ Object.defineProperty(exports, "createFetcher", { enumerable: true, get: function () { return index_js_1.createFetcher; } });
15
+ const HttpException_js_1 = require("./HttpException.js");
16
+ Object.defineProperty(exports, "HttpException", { enumerable: true, get: function () { return HttpException_js_1.HttpException; } });
17
+ const createDecorator_js_1 = require("./createDecorator.js");
18
+ Object.defineProperty(exports, "createDecorator", { enumerable: true, get: function () { return createDecorator_js_1.createDecorator; } });
19
+ const JSONLinesResponse_js_1 = require("./JSONLinesResponse.js");
20
+ Object.defineProperty(exports, "JSONLinesResponse", { enumerable: true, get: function () { return JSONLinesResponse_js_1.JSONLinesResponse; } });
21
+ const generateStaticAPI_js_1 = require("./utils/generateStaticAPI.js");
22
+ Object.defineProperty(exports, "generateStaticAPI", { enumerable: true, get: function () { return generateStaticAPI_js_1.generateStaticAPI; } });
23
+ const withValidation_js_1 = require("./utils/withValidation.js");
24
+ Object.defineProperty(exports, "withValidation", { enumerable: true, get: function () { return withValidation_js_1.withValidation; } });
25
+ _a = (0, createVovkApp_js_1.createVovkApp)(), exports.get = _a.get, exports.post = _a.post, exports.put = _a.put, exports.patch = _a.patch, exports.del = _a.del, exports.head = _a.head, exports.options = _a.options, exports.prefix = _a.prefix, exports.initVovk = _a.initVovk;