vovk 3.0.0-draft.8 → 3.0.0-draft.80

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 (78) hide show
  1. package/README.md +8 -95
  2. package/{HttpException.d.ts → dist/HttpException.d.ts} +2 -2
  3. package/{HttpException.js → dist/HttpException.js} +3 -3
  4. package/{StreamResponse.d.ts → dist/StreamJSONResponse.d.ts} +3 -3
  5. package/{StreamResponse.js → dist/StreamJSONResponse.js} +5 -5
  6. package/{Segment.d.ts → dist/VovkApp.d.ts} +11 -10
  7. package/{Segment.js → dist/VovkApp.js} +28 -24
  8. package/dist/client/createRPC.d.ts +4 -0
  9. package/{client/clientizeController.js → dist/client/createRPC.js} +22 -40
  10. package/dist/client/defaultFetcher.d.ts +4 -0
  11. package/{client → dist/client}/defaultFetcher.js +19 -8
  12. package/{client → dist/client}/defaultHandler.d.ts +1 -1
  13. package/dist/client/defaultHandler.js +22 -0
  14. package/dist/client/defaultStreamHandler.d.ts +4 -0
  15. package/{client → dist/client}/defaultStreamHandler.js +5 -5
  16. package/dist/client/index.d.ts +2 -0
  17. package/dist/client/index.js +8 -0
  18. package/dist/client/types.d.ts +100 -0
  19. package/dist/createDecorator.d.ts +4 -0
  20. package/{createDecorator.js → dist/createDecorator.js} +16 -15
  21. package/{createSegment.d.ts → dist/createVovkApp.d.ts} +10 -10
  22. package/{createSegment.js → dist/createVovkApp.js} +30 -30
  23. package/dist/index.d.ts +60 -0
  24. package/dist/index.js +24 -0
  25. package/dist/openapi/fromSchema.d.ts +3 -0
  26. package/dist/openapi/fromSchema.js +26 -0
  27. package/dist/openapi/index.d.ts +1 -0
  28. package/dist/openapi/index.js +5 -0
  29. package/dist/openapi/openapi.d.ts +11 -0
  30. package/dist/openapi/openapi.js +70 -0
  31. package/dist/types.d.ts +148 -0
  32. package/dist/types.js +65 -0
  33. package/dist/utils/generateStaticAPI.d.ts +4 -0
  34. package/{generateStaticAPI.js → dist/utils/generateStaticAPI.js} +3 -3
  35. package/{utils → dist/utils}/getSchema.d.ts +1 -2
  36. package/dist/utils/getSchema.js +29 -0
  37. package/dist/utils/parseQuery.d.ts +25 -0
  38. package/dist/utils/parseQuery.js +156 -0
  39. package/dist/utils/reqForm.d.ts +2 -0
  40. package/dist/utils/reqForm.js +13 -0
  41. package/{utils → dist/utils}/reqMeta.d.ts +1 -2
  42. package/{utils → dist/utils}/reqQuery.d.ts +1 -2
  43. package/dist/utils/reqQuery.js +10 -0
  44. package/dist/utils/serializeQuery.d.ts +13 -0
  45. package/dist/utils/serializeQuery.js +65 -0
  46. package/dist/utils/setHandlerValidation.d.ts +4 -0
  47. package/dist/utils/setHandlerValidation.js +15 -0
  48. package/package.json +8 -2
  49. package/.npmignore +0 -2
  50. package/client/clientizeController.d.ts +0 -4
  51. package/client/defaultFetcher.d.ts +0 -4
  52. package/client/defaultHandler.js +0 -21
  53. package/client/defaultStreamHandler.d.ts +0 -4
  54. package/client/index.d.ts +0 -4
  55. package/client/index.js +0 -5
  56. package/client/types.d.ts +0 -100
  57. package/createDecorator.d.ts +0 -4
  58. package/generateStaticAPI.d.ts +0 -4
  59. package/index.d.ts +0 -60
  60. package/index.js +0 -20
  61. package/types.d.ts +0 -186
  62. package/types.js +0 -65
  63. package/utils/getSchema.js +0 -38
  64. package/utils/reqQuery.js +0 -25
  65. package/utils/setClientValidatorsForHandler.d.ts +0 -5
  66. package/utils/setClientValidatorsForHandler.js +0 -28
  67. package/worker/index.d.ts +0 -3
  68. package/worker/index.js +0 -7
  69. package/worker/promisifyWorker.d.ts +0 -2
  70. package/worker/promisifyWorker.js +0 -143
  71. package/worker/types.d.ts +0 -31
  72. package/worker/types.js +0 -2
  73. package/worker/worker.d.ts +0 -1
  74. package/worker/worker.js +0 -44
  75. /package/{client → dist/client}/types.js +0 -0
  76. /package/{utils → dist/utils}/reqMeta.js +0 -0
  77. /package/{utils → dist/utils}/shim.d.ts +0 -0
  78. /package/{utils → dist/utils}/shim.js +0 -0
@@ -0,0 +1,148 @@
1
+ import type { NextRequest } from 'next/server';
2
+ import type { OperationObject } from 'openapi3-ts/oas31';
3
+ import type { StreamJSONResponse } from './StreamJSONResponse';
4
+ import { VovkStreamAsyncIterable } from './client/types';
5
+ export type KnownAny = any;
6
+ export type StaticClass = Function;
7
+ export type VovkHandlerSchema = {
8
+ path: string;
9
+ httpMethod: string;
10
+ validation?: {
11
+ query?: KnownAny;
12
+ body?: KnownAny;
13
+ output?: KnownAny;
14
+ };
15
+ openapi?: OperationObject;
16
+ custom?: Record<string, KnownAny>;
17
+ };
18
+ export type VovkControllerSchema = {
19
+ controllerName: string;
20
+ originalControllerName: string;
21
+ prefix?: string;
22
+ handlers: Record<string, VovkHandlerSchema>;
23
+ };
24
+ export type VovkSchema = {
25
+ emitSchema: boolean;
26
+ segmentName: string;
27
+ controllers: Record<string, VovkControllerSchema>;
28
+ };
29
+ export type VovkErrorResponse = {
30
+ cause?: unknown;
31
+ statusCode: HttpStatus;
32
+ message: string;
33
+ isError: true;
34
+ };
35
+ export type VovkControllerInternal = {
36
+ _controllerName?: VovkControllerSchema['controllerName'];
37
+ _prefix?: VovkControllerSchema['prefix'];
38
+ _handlers: VovkControllerSchema['handlers'];
39
+ _activated?: true;
40
+ _onError?: (err: Error, req: VovkRequest) => void | Promise<void>;
41
+ };
42
+ export type VovkController = StaticClass & VovkControllerInternal & {
43
+ [key: string]: unknown;
44
+ };
45
+ export type DecoratorOptions = {
46
+ cors?: boolean;
47
+ headers?: Record<string, string>;
48
+ };
49
+ export type RouteHandler = ((req: VovkRequest, params: Record<string, string>) => Response | Promise<Response> | Iterable<unknown> | AsyncIterable<unknown>) & {
50
+ _options?: DecoratorOptions;
51
+ };
52
+ export interface VovkRequest<BODY = undefined, QUERY extends object | undefined = undefined> extends Omit<NextRequest, 'json' | 'nextUrl'> {
53
+ json: () => Promise<BODY>;
54
+ nextUrl: Omit<NextRequest['nextUrl'], 'searchParams'> & {
55
+ searchParams: Omit<NextRequest['nextUrl']['searchParams'], 'get' | 'getAll' | 'entries' | 'forEach' | 'keys' | 'values'> & {
56
+ get: <KEY extends keyof QUERY>(key: KEY) => QUERY[KEY] extends readonly (infer ITEM)[] ? ITEM : QUERY[KEY];
57
+ getAll: <KEY extends keyof QUERY>(key: KEY) => QUERY[KEY] extends KnownAny[] ? QUERY[KEY] : QUERY[KEY][];
58
+ entries: () => IterableIterator<[keyof QUERY, QUERY[keyof QUERY]]>;
59
+ forEach: (callbackfn: (value: QUERY[keyof QUERY], key: keyof QUERY, searchParams: NextRequest['nextUrl']['searchParams']) => void) => void;
60
+ keys: () => IterableIterator<keyof QUERY>;
61
+ values: () => IterableIterator<QUERY[keyof QUERY]>;
62
+ };
63
+ };
64
+ vovk: {
65
+ body: () => Promise<BODY>;
66
+ query: () => QUERY;
67
+ meta: <T = Record<KnownAny, KnownAny>>(meta?: T | null) => T;
68
+ form: <T = KnownAny>() => Promise<T>;
69
+ };
70
+ }
71
+ export type ControllerStaticMethod<REQ extends VovkRequest<KnownAny, KnownAny> = VovkRequest<undefined, Record<string, KnownAny>>, PARAMS extends {
72
+ [key: string]: string;
73
+ } = KnownAny> = ((req: REQ, params: PARAMS) => unknown) & {
74
+ _controller?: VovkController;
75
+ };
76
+ export type VovkControllerBody<T extends (...args: KnownAny) => KnownAny> = Awaited<ReturnType<Parameters<T>[0]['vovk']['body']>>;
77
+ export type VovkControllerQuery<T extends (...args: KnownAny) => KnownAny> = ReturnType<Parameters<T>[0]['vovk']['query']>;
78
+ export type VovkControllerParams<T extends (...args: KnownAny) => KnownAny> = Parameters<T>[1];
79
+ export type VovkControllerYieldType<T extends (req: VovkRequest<KnownAny, KnownAny>) => KnownAny> = T extends (...args: KnownAny[]) => AsyncGenerator<infer Y, KnownAny, KnownAny> ? Y : T extends (...args: KnownAny[]) => Generator<infer Y, KnownAny, KnownAny> ? Y : T extends (...args: KnownAny[]) => Promise<StreamJSONResponse<infer Y>> | StreamJSONResponse<infer Y> ? Y : never;
80
+ export type VovkBody<T extends (...args: KnownAny[]) => unknown> = Parameters<T>[0]['body'];
81
+ export type VovkQuery<T extends (...args: KnownAny[]) => unknown> = Parameters<T>[0]['query'];
82
+ export type VovkParams<T extends (...args: KnownAny[]) => unknown> = Parameters<T>[0]['params'];
83
+ export type VovkYieldType<T extends (...args: KnownAny[]) => unknown> = T extends (...args: KnownAny[]) => Promise<VovkStreamAsyncIterable<infer Y>> ? Y : never;
84
+ export type VovkReturnType<T extends (...args: KnownAny) => unknown> = Awaited<ReturnType<T>>;
85
+ export type StreamAbortMessage = {
86
+ isError: true;
87
+ reason: KnownAny;
88
+ };
89
+ export declare enum HttpMethod {
90
+ GET = "GET",
91
+ POST = "POST",
92
+ PUT = "PUT",
93
+ PATCH = "PATCH",
94
+ DELETE = "DELETE",
95
+ HEAD = "HEAD",
96
+ OPTIONS = "OPTIONS"
97
+ }
98
+ export declare enum HttpStatus {
99
+ NULL = 0,
100
+ CONTINUE = 100,
101
+ SWITCHING_PROTOCOLS = 101,
102
+ PROCESSING = 102,
103
+ EARLYHINTS = 103,
104
+ OK = 200,
105
+ CREATED = 201,
106
+ ACCEPTED = 202,
107
+ NON_AUTHORITATIVE_INFORMATION = 203,
108
+ NO_CONTENT = 204,
109
+ RESET_CONTENT = 205,
110
+ PARTIAL_CONTENT = 206,
111
+ AMBIGUOUS = 300,
112
+ MOVED_PERMANENTLY = 301,
113
+ FOUND = 302,
114
+ SEE_OTHER = 303,
115
+ NOT_MODIFIED = 304,
116
+ TEMPORARY_REDIRECT = 307,
117
+ PERMANENT_REDIRECT = 308,
118
+ BAD_REQUEST = 400,
119
+ UNAUTHORIZED = 401,
120
+ PAYMENT_REQUIRED = 402,
121
+ FORBIDDEN = 403,
122
+ NOT_FOUND = 404,
123
+ METHOD_NOT_ALLOWED = 405,
124
+ NOT_ACCEPTABLE = 406,
125
+ PROXY_AUTHENTICATION_REQUIRED = 407,
126
+ REQUEST_TIMEOUT = 408,
127
+ CONFLICT = 409,
128
+ GONE = 410,
129
+ LENGTH_REQUIRED = 411,
130
+ PRECONDITION_FAILED = 412,
131
+ PAYLOAD_TOO_LARGE = 413,
132
+ URI_TOO_LONG = 414,
133
+ UNSUPPORTED_MEDIA_TYPE = 415,
134
+ REQUESTED_RANGE_NOT_SATISFIABLE = 416,
135
+ EXPECTATION_FAILED = 417,
136
+ I_AM_A_TEAPOT = 418,
137
+ MISDIRECTED = 421,
138
+ UNPROCESSABLE_ENTITY = 422,
139
+ FAILED_DEPENDENCY = 424,
140
+ PRECONDITION_REQUIRED = 428,
141
+ TOO_MANY_REQUESTS = 429,
142
+ INTERNAL_SERVER_ERROR = 500,
143
+ NOT_IMPLEMENTED = 501,
144
+ BAD_GATEWAY = 502,
145
+ SERVICE_UNAVAILABLE = 503,
146
+ GATEWAY_TIMEOUT = 504,
147
+ HTTP_VERSION_NOT_SUPPORTED = 505
148
+ }
package/dist/types.js ADDED
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpStatus = exports.HttpMethod = void 0;
4
+ var HttpMethod;
5
+ (function (HttpMethod) {
6
+ HttpMethod["GET"] = "GET";
7
+ HttpMethod["POST"] = "POST";
8
+ HttpMethod["PUT"] = "PUT";
9
+ HttpMethod["PATCH"] = "PATCH";
10
+ HttpMethod["DELETE"] = "DELETE";
11
+ HttpMethod["HEAD"] = "HEAD";
12
+ HttpMethod["OPTIONS"] = "OPTIONS";
13
+ })(HttpMethod || (exports.HttpMethod = HttpMethod = {}));
14
+ var HttpStatus;
15
+ (function (HttpStatus) {
16
+ HttpStatus[HttpStatus["NULL"] = 0] = "NULL";
17
+ HttpStatus[HttpStatus["CONTINUE"] = 100] = "CONTINUE";
18
+ HttpStatus[HttpStatus["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS";
19
+ HttpStatus[HttpStatus["PROCESSING"] = 102] = "PROCESSING";
20
+ HttpStatus[HttpStatus["EARLYHINTS"] = 103] = "EARLYHINTS";
21
+ HttpStatus[HttpStatus["OK"] = 200] = "OK";
22
+ HttpStatus[HttpStatus["CREATED"] = 201] = "CREATED";
23
+ HttpStatus[HttpStatus["ACCEPTED"] = 202] = "ACCEPTED";
24
+ HttpStatus[HttpStatus["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION";
25
+ HttpStatus[HttpStatus["NO_CONTENT"] = 204] = "NO_CONTENT";
26
+ HttpStatus[HttpStatus["RESET_CONTENT"] = 205] = "RESET_CONTENT";
27
+ HttpStatus[HttpStatus["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
28
+ HttpStatus[HttpStatus["AMBIGUOUS"] = 300] = "AMBIGUOUS";
29
+ HttpStatus[HttpStatus["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY";
30
+ HttpStatus[HttpStatus["FOUND"] = 302] = "FOUND";
31
+ HttpStatus[HttpStatus["SEE_OTHER"] = 303] = "SEE_OTHER";
32
+ HttpStatus[HttpStatus["NOT_MODIFIED"] = 304] = "NOT_MODIFIED";
33
+ HttpStatus[HttpStatus["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT";
34
+ HttpStatus[HttpStatus["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT";
35
+ HttpStatus[HttpStatus["BAD_REQUEST"] = 400] = "BAD_REQUEST";
36
+ HttpStatus[HttpStatus["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
37
+ HttpStatus[HttpStatus["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED";
38
+ HttpStatus[HttpStatus["FORBIDDEN"] = 403] = "FORBIDDEN";
39
+ HttpStatus[HttpStatus["NOT_FOUND"] = 404] = "NOT_FOUND";
40
+ HttpStatus[HttpStatus["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
41
+ HttpStatus[HttpStatus["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
42
+ HttpStatus[HttpStatus["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED";
43
+ HttpStatus[HttpStatus["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
44
+ HttpStatus[HttpStatus["CONFLICT"] = 409] = "CONFLICT";
45
+ HttpStatus[HttpStatus["GONE"] = 410] = "GONE";
46
+ HttpStatus[HttpStatus["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED";
47
+ HttpStatus[HttpStatus["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
48
+ HttpStatus[HttpStatus["PAYLOAD_TOO_LARGE"] = 413] = "PAYLOAD_TOO_LARGE";
49
+ HttpStatus[HttpStatus["URI_TOO_LONG"] = 414] = "URI_TOO_LONG";
50
+ HttpStatus[HttpStatus["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
51
+ HttpStatus[HttpStatus["REQUESTED_RANGE_NOT_SATISFIABLE"] = 416] = "REQUESTED_RANGE_NOT_SATISFIABLE";
52
+ HttpStatus[HttpStatus["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED";
53
+ HttpStatus[HttpStatus["I_AM_A_TEAPOT"] = 418] = "I_AM_A_TEAPOT";
54
+ HttpStatus[HttpStatus["MISDIRECTED"] = 421] = "MISDIRECTED";
55
+ HttpStatus[HttpStatus["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
56
+ HttpStatus[HttpStatus["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY";
57
+ HttpStatus[HttpStatus["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED";
58
+ HttpStatus[HttpStatus["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
59
+ HttpStatus[HttpStatus["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
60
+ HttpStatus[HttpStatus["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
61
+ HttpStatus[HttpStatus["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
62
+ HttpStatus[HttpStatus["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
63
+ HttpStatus[HttpStatus["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT";
64
+ HttpStatus[HttpStatus["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED";
65
+ })(HttpStatus || (exports.HttpStatus = HttpStatus = {}));
@@ -0,0 +1,4 @@
1
+ import type { StaticClass } from '../types';
2
+ export declare function generateStaticAPI(c: Record<string, StaticClass>, slug?: string): {
3
+ [x: string]: string[];
4
+ }[];
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._generateStaticAPI = _generateStaticAPI;
4
- function _generateStaticAPI(c, slug = 'vovk') {
3
+ exports.generateStaticAPI = generateStaticAPI;
4
+ function generateStaticAPI(c, slug = 'vovk') {
5
5
  const controllers = c;
6
6
  return [
7
- { [slug]: ['_vovk-ping_'] },
7
+ { [slug]: ['_schema_'] },
8
8
  ...Object.values(controllers)
9
9
  .map((controller) => {
10
10
  const handlers = controller._handlers;
@@ -1,8 +1,7 @@
1
- import { _VovkSchema as VovkSchema, _StaticClass as StaticClass } from '../types';
1
+ import type { VovkSchema, StaticClass } from '../types';
2
2
  export default function getSchema(options: {
3
3
  emitSchema?: boolean;
4
4
  segmentName?: string;
5
5
  controllers: Record<string, StaticClass>;
6
- workers?: Record<string, StaticClass>;
7
6
  exposeValidation?: boolean;
8
7
  }): VovkSchema;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = getSchema;
4
+ function getSchema(options) {
5
+ const exposeValidation = options?.exposeValidation ?? true;
6
+ const emitSchema = options.emitSchema ?? true;
7
+ const schema = {
8
+ emitSchema,
9
+ segmentName: options.segmentName ?? '',
10
+ controllers: {},
11
+ };
12
+ if (!emitSchema)
13
+ return schema;
14
+ for (const [controllerName, controller] of Object.entries(options.controllers)) {
15
+ schema.controllers[controllerName] = {
16
+ controllerName: controllerName,
17
+ originalControllerName: controller.name,
18
+ prefix: controller._prefix ?? '',
19
+ handlers: {
20
+ ...(exposeValidation
21
+ ? controller._handlers
22
+ : Object.fromEntries(
23
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
24
+ Object.entries(controller._handlers ?? {}).map(([key, { validation: _v, ...value }]) => [key, value]))),
25
+ },
26
+ };
27
+ }
28
+ return schema;
29
+ }
@@ -0,0 +1,25 @@
1
+ import type { KnownAny } from '../types';
2
+ /**
3
+ * Deserialize a bracket-based query string into an object.
4
+ *
5
+ * Supports:
6
+ * - Key/value pairs with nested brackets (e.g. "a[b][0]=value")
7
+ * - Arrays with empty bracket (e.g. "arr[]=1&arr[]=2")
8
+ * - Mixed arrays of objects, etc.
9
+ *
10
+ * @example
11
+ * parseQuery("x=xx&y[0]=yy&y[1]=uu&z[f]=x&z[u][0]=uu&z[u][1]=xx&z[d][x]=ee")
12
+ * => {
13
+ * x: "xx",
14
+ * y: ["yy", "uu"],
15
+ * z: {
16
+ * f: "x",
17
+ * u: ["uu", "xx"],
18
+ * d: { x: "ee" }
19
+ * }
20
+ * }
21
+ *
22
+ * @param queryString - The raw query string (e.g. location.search.slice(1))
23
+ * @returns - A nested object representing the query params
24
+ */
25
+ export default function parseQuery(queryString: string): Record<string, KnownAny>;
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = parseQuery;
4
+ /**
5
+ * Parse a bracket-based key (e.g. "z[d][0][x]" or "arr[]")
6
+ * into an array of path segments (strings or special push-markers).
7
+ *
8
+ * Example: "z[d][0][x]" => ["z", "d", "0", "x"]
9
+ * Example: "arr[]" => ["arr", "" ] // "" indicates "push" onto array
10
+ */
11
+ function parseKey(key) {
12
+ // The first segment is everything up to the first '[' (or the entire key if no '[')
13
+ const segments = [];
14
+ const topKeyMatch = key.match(/^([^[\]]+)/);
15
+ if (topKeyMatch) {
16
+ segments.push(topKeyMatch[1]);
17
+ }
18
+ else {
19
+ // If it starts with brackets, treat it as empty? (edge case)
20
+ segments.push('');
21
+ }
22
+ // Now capture all bracket parts: [something], [0], []
23
+ const bracketRegex = /\[([^[\]]*)\]/g;
24
+ let match;
25
+ while ((match = bracketRegex.exec(key)) !== null) {
26
+ // match[1] is the content inside the brackets
27
+ segments.push(match[1]);
28
+ }
29
+ return segments;
30
+ }
31
+ /**
32
+ * Recursively set a value in a nested object/array, given a path of segments.
33
+ * - If segment is numeric => treat as array index
34
+ * - If segment is empty "" => push to array
35
+ * - Else => object property
36
+ */
37
+ function setValue(obj, path, value) {
38
+ let current = obj;
39
+ for (let i = 0; i < path.length; i++) {
40
+ const segment = path[i];
41
+ // If we're at the last segment, set the value
42
+ if (i === path.length - 1) {
43
+ if (segment === '') {
44
+ // Empty bracket => push
45
+ if (!Array.isArray(current)) {
46
+ current = [];
47
+ }
48
+ current.push(value);
49
+ }
50
+ else if (!isNaN(Number(segment))) {
51
+ // Numeric segment => array index
52
+ const idx = Number(segment);
53
+ if (!Array.isArray(current)) {
54
+ current = [];
55
+ }
56
+ current[idx] = value;
57
+ }
58
+ else {
59
+ // Object property
60
+ current[segment] = value;
61
+ }
62
+ }
63
+ else {
64
+ // Not the last segment: descend into existing structure or create it
65
+ const nextSegment = path[i + 1];
66
+ if (segment === '') {
67
+ // Empty bracket => push
68
+ if (!Array.isArray(current)) {
69
+ // Convert the current node into an array, if not one
70
+ current = [];
71
+ }
72
+ // If we are not at the last path, we need a placeholder object or array
73
+ // for the next segment. We'll push something and move current to that.
74
+ if (current.length === 0) {
75
+ // nothing in array yet
76
+ current.push(typeof nextSegment === 'string' && !isNaN(Number(nextSegment)) ? [] : {});
77
+ }
78
+ else if (typeof nextSegment === 'string' && !isNaN(Number(nextSegment))) {
79
+ // next is numeric => we want an array
80
+ if (!Array.isArray(current[current.length - 1])) {
81
+ current[current.length - 1] = [];
82
+ }
83
+ }
84
+ else {
85
+ // next is not numeric => we want an object
86
+ if (typeof current[current.length - 1] !== 'object') {
87
+ current[current.length - 1] = {};
88
+ }
89
+ }
90
+ current = current[current.length - 1];
91
+ }
92
+ else if (!isNaN(Number(segment))) {
93
+ // segment is numeric => array index
94
+ const idx = Number(segment);
95
+ if (!Array.isArray(current)) {
96
+ current = [];
97
+ }
98
+ if (current[idx] === undefined) {
99
+ // Create placeholder for next segment
100
+ current[idx] = typeof nextSegment === 'string' && !isNaN(Number(nextSegment)) ? [] : {};
101
+ }
102
+ current = current[idx];
103
+ }
104
+ else {
105
+ // segment is an object key
106
+ if (current[segment] === undefined) {
107
+ // Create placeholder
108
+ current[segment] = typeof nextSegment === 'string' && !isNaN(Number(nextSegment)) ? [] : {};
109
+ }
110
+ current = current[segment];
111
+ }
112
+ }
113
+ }
114
+ }
115
+ /**
116
+ * Deserialize a bracket-based query string into an object.
117
+ *
118
+ * Supports:
119
+ * - Key/value pairs with nested brackets (e.g. "a[b][0]=value")
120
+ * - Arrays with empty bracket (e.g. "arr[]=1&arr[]=2")
121
+ * - Mixed arrays of objects, etc.
122
+ *
123
+ * @example
124
+ * parseQuery("x=xx&y[0]=yy&y[1]=uu&z[f]=x&z[u][0]=uu&z[u][1]=xx&z[d][x]=ee")
125
+ * => {
126
+ * x: "xx",
127
+ * y: ["yy", "uu"],
128
+ * z: {
129
+ * f: "x",
130
+ * u: ["uu", "xx"],
131
+ * d: { x: "ee" }
132
+ * }
133
+ * }
134
+ *
135
+ * @param queryString - The raw query string (e.g. location.search.slice(1))
136
+ * @returns - A nested object representing the query params
137
+ */
138
+ function parseQuery(queryString) {
139
+ const result = {};
140
+ if (!queryString)
141
+ return result;
142
+ // Split into key=value pairs
143
+ const pairs = queryString
144
+ .replace(/^\?/, '') // Remove leading "?" if present
145
+ .split('&');
146
+ for (const pair of pairs) {
147
+ const [rawKey, rawVal = ''] = pair.split('=');
148
+ const decodedKey = decodeURIComponent(rawKey || '');
149
+ const decodedVal = decodeURIComponent(rawVal);
150
+ // Parse bracket notation
151
+ const pathSegments = parseKey(decodedKey);
152
+ // Insert into the result object
153
+ setValue(result, pathSegments, decodedVal);
154
+ }
155
+ return result;
156
+ }
@@ -0,0 +1,2 @@
1
+ import type { KnownAny, VovkRequest } from '../types';
2
+ export default function reqForm<T = KnownAny>(req: VovkRequest<KnownAny, KnownAny>): Promise<T>;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = reqForm;
4
+ const formMap = new WeakMap();
5
+ async function reqForm(req) {
6
+ if (formMap.has(req)) {
7
+ return formMap.get(req);
8
+ }
9
+ const body = await req.formData();
10
+ const formData = Object.fromEntries(body.entries());
11
+ formMap.set(req, formData);
12
+ return formData;
13
+ }
@@ -1,3 +1,2 @@
1
- import { VovkRequest } from 'vovk';
2
- import { _KnownAny as KnownAny } from '../types';
1
+ import type { KnownAny, VovkRequest } from '../types';
3
2
  export default function reqMeta<T = Record<KnownAny, KnownAny>>(req: VovkRequest<KnownAny, KnownAny>, meta?: T | null): T;
@@ -1,3 +1,2 @@
1
- import { _KnownAny as KnownAny } from '../types';
2
- import { VovkRequest } from 'vovk';
1
+ import type { KnownAny, VovkRequest } from '../types';
3
2
  export default function reqQuery<T extends object | undefined>(req: VovkRequest<KnownAny, T>): T;
@@ -0,0 +1,10 @@
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.default = reqQuery;
7
+ const parseQuery_1 = __importDefault(require("./parseQuery"));
8
+ function reqQuery(req) {
9
+ return (0, parseQuery_1.default)(req.nextUrl.search);
10
+ }
@@ -0,0 +1,13 @@
1
+ import type { KnownAny } from '../types';
2
+ /**
3
+ * Serialize a nested object (including arrays, arrays of objects, etc.)
4
+ * into a bracket-based query string.
5
+ *
6
+ * @example
7
+ * serializeQuery({ x: 'xx', y: [1, 2], z: { f: 'x' } })
8
+ * => "x=xx&y[0]=1&y[1]=2&z[f]=x"
9
+ *
10
+ * @param obj - The input object to be serialized
11
+ * @returns - A bracket-based query string (without leading "?")
12
+ */
13
+ export default function serializeQuery(obj: Record<string, KnownAny>): string;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = serializeQuery;
4
+ /**
5
+ * Recursively build query parameters from an object.
6
+ *
7
+ * @param key - The query key so far (e.g. 'user', 'user[0]', 'user[0][name]')
8
+ * @param value - The current value to serialize
9
+ * @returns - An array of `key=value` strings
10
+ */
11
+ function buildParams(key, value) {
12
+ if (value === null || value === undefined) {
13
+ return []; // skip null/undefined values entirely
14
+ }
15
+ // If value is an object or array, we need to recurse
16
+ if (typeof value === 'object') {
17
+ // Array case
18
+ if (Array.isArray(value)) {
19
+ /**
20
+ * We use index-based bracket notation here:
21
+ * e.g. for value = ['aa', 'bb'] and key = 'foo'
22
+ * => "foo[0]=aa&foo[1]=bb"
23
+ *
24
+ * If you prefer "foo[]=aa&foo[]=bb" style, replace:
25
+ * `${key}[${i}]`
26
+ * with:
27
+ * `${key}[]`
28
+ */
29
+ return value.flatMap((v, i) => {
30
+ const newKey = `${key}[${i}]`;
31
+ return buildParams(newKey, v);
32
+ });
33
+ }
34
+ // Plain object case
35
+ return Object.keys(value).flatMap((k) => {
36
+ const newKey = `${key}[${k}]`;
37
+ return buildParams(newKey, value[k]);
38
+ });
39
+ }
40
+ return [`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`];
41
+ }
42
+ /**
43
+ * Serialize a nested object (including arrays, arrays of objects, etc.)
44
+ * into a bracket-based query string.
45
+ *
46
+ * @example
47
+ * serializeQuery({ x: 'xx', y: [1, 2], z: { f: 'x' } })
48
+ * => "x=xx&y[0]=1&y[1]=2&z[f]=x"
49
+ *
50
+ * @param obj - The input object to be serialized
51
+ * @returns - A bracket-based query string (without leading "?")
52
+ */
53
+ function serializeQuery(obj) {
54
+ if (!obj || typeof obj !== 'object')
55
+ return '';
56
+ // Collect query segments
57
+ const segments = [];
58
+ for (const key in obj) {
59
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
60
+ const value = obj[key];
61
+ segments.push(...buildParams(key, value));
62
+ }
63
+ }
64
+ return segments.join('&');
65
+ }
@@ -0,0 +1,4 @@
1
+ import type { KnownAny, VovkController, VovkHandlerSchema } from '../types';
2
+ export declare function setHandlerValidation(h: ((...args: KnownAny[]) => KnownAny) & {
3
+ _getValidation?: (controller: VovkController) => void;
4
+ }, validation: Exclude<VovkHandlerSchema['validation'], undefined>): Promise<void>;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setHandlerValidation = setHandlerValidation;
4
+ async function setHandlerValidation(h, validation) {
5
+ h._getValidation = (controller) => {
6
+ if (!controller) {
7
+ throw new Error('Error setting client validators. Controller not found. Did you forget to use an HTTP decorator?');
8
+ }
9
+ const handlerName = Object.getOwnPropertyNames(controller).find((key) => controller[key]._sourceMethod === h);
10
+ if (!handlerName) {
11
+ throw new Error('Error setting client validators. Handler not found.');
12
+ }
13
+ return validation;
14
+ };
15
+ }
package/package.json CHANGED
@@ -1,14 +1,17 @@
1
1
  {
2
2
  "name": "vovk",
3
- "version": "3.0.0-draft.8",
3
+ "version": "3.0.0-draft.80",
4
+ "main": "dist/index.js",
4
5
  "description": "RESTful RPC for Next.js - Transforms Next.js into a powerful REST API platform with RPC capabilities.",
5
6
  "repository": {
6
7
  "type": "git",
7
8
  "url": "git+https://github.com/finom/vovk.git"
8
9
  },
9
10
  "scripts": {
10
- "build": "rm -rf dist && tsc && cp {package.json,LICENSE,.npmignore} dist && cp ../../README.md dist",
11
+ "build": "tsc",
12
+ "rm-dist": "shx rm -rf dist",
11
13
  "lint": "eslint . --fix",
14
+ "tsc": "tsc --noEmit",
12
15
  "npm-publish": "if [ -z \"$NPM_TAG\" ]; then echo 'Error: NPM_TAG is not set'; exit 1; fi; cd ./dist && npm publish --tag=$NPM_TAG && cd ..",
13
16
  "ncu": "npm-check-updates -u"
14
17
  },
@@ -24,5 +27,8 @@
24
27
  "homepage": "https://vovk.dev",
25
28
  "peerDependencies": {
26
29
  "next": "*"
30
+ },
31
+ "optionalDependencies": {
32
+ "openapi3-ts": "^4.4.0"
27
33
  }
28
34
  }
package/.npmignore DELETED
@@ -1,2 +0,0 @@
1
- !*
2
- tsconfig.*
@@ -1,4 +0,0 @@
1
- import { type _VovkControllerSchema as VovkControllerSchema, type _KnownAny as KnownAny } from '../types';
2
- import { type _VovkClientOptions as VovkClientOptions, type _VovkClient as VovkClient, type _VovkDefaultFetcherOptions as VovkDefaultFetcherOptions } from './types';
3
- export declare const ARRAY_QUERY_KEY = "_vovkarr";
4
- export declare const _clientizeController: <T, OPTS extends Record<string, KnownAny> = VovkDefaultFetcherOptions>(givenController: VovkControllerSchema, segmentName?: string, options?: VovkClientOptions<OPTS>) => VovkClient<T, OPTS>;
@@ -1,4 +0,0 @@
1
- import type { _VovkDefaultFetcherOptions as VovkDefaultFetcherOptions, _VovkClientFetcher as VovkClientFetcher } from './types';
2
- export declare const DEFAULT_ERROR_MESSAGE = "Unknown error at defaultFetcher";
3
- declare const defaultFetcher: VovkClientFetcher<VovkDefaultFetcherOptions>;
4
- export default defaultFetcher;