vovk 3.0.0-draft.46 → 3.0.0-draft.460

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 (207) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +8 -96
  3. package/bin/index.mjs +8 -0
  4. package/cjs/JSONLinesResponse.d.ts +19 -0
  5. package/cjs/JSONLinesResponse.js +95 -0
  6. package/{VovkApp.d.ts → cjs/VovkApp.d.ts} +14 -8
  7. package/cjs/VovkApp.js +304 -0
  8. package/cjs/client/createRPC.d.ts +5 -0
  9. package/cjs/client/createRPC.js +116 -0
  10. package/cjs/client/defaultHandler.d.ts +6 -0
  11. package/{client → cjs/client}/defaultHandler.js +9 -2
  12. package/cjs/client/defaultStreamHandler.d.ts +9 -0
  13. package/{client → cjs/client}/defaultStreamHandler.js +49 -26
  14. package/cjs/client/fetcher.d.ts +18 -0
  15. package/cjs/client/fetcher.js +97 -0
  16. package/cjs/client/index.d.ts +4 -0
  17. package/cjs/client/index.js +10 -0
  18. package/cjs/client/progressive.d.ts +9 -0
  19. package/cjs/client/progressive.js +54 -0
  20. package/cjs/client/types.d.ts +120 -0
  21. package/{createVovkApp.d.ts → cjs/createVovkApp.d.ts} +19 -16
  22. package/cjs/createVovkApp.js +146 -0
  23. package/cjs/index.d.ts +69 -0
  24. package/cjs/index.js +42 -0
  25. package/cjs/openapi/error.d.ts +2 -0
  26. package/cjs/openapi/error.js +100 -0
  27. package/cjs/openapi/index.d.ts +8 -0
  28. package/cjs/openapi/index.js +21 -0
  29. package/cjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.d.ts +3 -0
  30. package/cjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.js +67 -0
  31. package/cjs/openapi/openAPIToVovkSchema/index.d.ts +4 -0
  32. package/cjs/openapi/openAPIToVovkSchema/index.js +141 -0
  33. package/cjs/openapi/openAPIToVovkSchema/inlineRefs.d.ts +10 -0
  34. package/cjs/openapi/openAPIToVovkSchema/inlineRefs.js +102 -0
  35. package/cjs/openapi/vovkSchemaToOpenAPI.d.ts +8 -0
  36. package/cjs/openapi/vovkSchemaToOpenAPI.js +238 -0
  37. package/cjs/types.d.ts +466 -0
  38. package/{types.js → cjs/types.js} +14 -2
  39. package/cjs/utils/camelCase.d.ts +6 -0
  40. package/cjs/utils/camelCase.js +37 -0
  41. package/cjs/utils/createCodeSamples.d.ts +20 -0
  42. package/cjs/utils/createCodeSamples.js +279 -0
  43. package/cjs/utils/createDecorator.d.ts +6 -0
  44. package/{createDecorator.js → cjs/utils/createDecorator.js} +24 -14
  45. package/cjs/utils/createLLMTools.d.ts +50 -0
  46. package/cjs/utils/createLLMTools.js +168 -0
  47. package/cjs/utils/createStandardValidation.d.ts +82 -0
  48. package/cjs/utils/createStandardValidation.js +34 -0
  49. package/cjs/utils/createValidateOnClient.d.ts +7 -0
  50. package/cjs/utils/createValidateOnClient.js +19 -0
  51. package/cjs/utils/deepExtend.d.ts +54 -0
  52. package/cjs/utils/deepExtend.js +134 -0
  53. package/{utils → cjs/utils}/generateStaticAPI.d.ts +2 -2
  54. package/cjs/utils/generateStaticAPI.js +30 -0
  55. package/cjs/utils/getJSONSchemaExample.d.ts +11 -0
  56. package/cjs/utils/getJSONSchemaExample.js +264 -0
  57. package/cjs/utils/getJSONSchemaSample.d.ts +2 -0
  58. package/cjs/utils/getJSONSchemaSample.js +167 -0
  59. package/cjs/utils/getSampleFromObject.d.ts +9 -0
  60. package/cjs/utils/getSampleFromObject.js +41 -0
  61. package/cjs/utils/getSchema.d.ts +21 -0
  62. package/cjs/utils/getSchema.js +38 -0
  63. package/cjs/utils/multitenant.d.ts +24 -0
  64. package/cjs/utils/multitenant.js +131 -0
  65. package/cjs/utils/parseQuery.d.ts +25 -0
  66. package/cjs/utils/parseQuery.js +156 -0
  67. package/cjs/utils/reqForm.d.ts +2 -0
  68. package/cjs/utils/reqForm.js +33 -0
  69. package/cjs/utils/reqMeta.d.ts +2 -0
  70. package/cjs/utils/reqQuery.d.ts +2 -0
  71. package/cjs/utils/reqQuery.js +10 -0
  72. package/cjs/utils/resolveGeneratorConfigValues.d.ts +18 -0
  73. package/cjs/utils/resolveGeneratorConfigValues.js +82 -0
  74. package/cjs/utils/serializeQuery.d.ts +13 -0
  75. package/cjs/utils/serializeQuery.js +65 -0
  76. package/cjs/utils/setHandlerSchema.d.ts +4 -0
  77. package/cjs/utils/setHandlerSchema.js +15 -0
  78. package/cjs/utils/upperFirst.d.ts +1 -0
  79. package/cjs/utils/upperFirst.js +6 -0
  80. package/cjs/utils/withValidationLibrary.d.ts +77 -0
  81. package/cjs/utils/withValidationLibrary.js +124 -0
  82. package/mjs/HttpException.d.ts +7 -0
  83. package/mjs/HttpException.js +15 -0
  84. package/mjs/JSONLinesResponse.d.ts +19 -0
  85. package/mjs/JSONLinesResponse.js +95 -0
  86. package/mjs/VovkApp.d.ts +34 -0
  87. package/mjs/VovkApp.js +304 -0
  88. package/mjs/client/createRPC.d.ts +5 -0
  89. package/mjs/client/createRPC.js +116 -0
  90. package/mjs/client/defaultHandler.d.ts +6 -0
  91. package/mjs/client/defaultHandler.js +29 -0
  92. package/mjs/client/defaultStreamHandler.d.ts +9 -0
  93. package/mjs/client/defaultStreamHandler.js +105 -0
  94. package/mjs/client/fetcher.d.ts +18 -0
  95. package/mjs/client/fetcher.js +97 -0
  96. package/mjs/client/index.d.ts +4 -0
  97. package/mjs/client/index.js +10 -0
  98. package/mjs/client/progressive.d.ts +9 -0
  99. package/mjs/client/progressive.js +54 -0
  100. package/mjs/client/types.d.ts +120 -0
  101. package/mjs/createVovkApp.d.ts +65 -0
  102. package/mjs/createVovkApp.js +146 -0
  103. package/mjs/index.d.ts +69 -0
  104. package/mjs/index.js +42 -0
  105. package/mjs/openapi/error.d.ts +2 -0
  106. package/mjs/openapi/error.js +100 -0
  107. package/mjs/openapi/index.d.ts +8 -0
  108. package/mjs/openapi/index.js +21 -0
  109. package/mjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.d.ts +3 -0
  110. package/mjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.js +67 -0
  111. package/mjs/openapi/openAPIToVovkSchema/index.d.ts +4 -0
  112. package/mjs/openapi/openAPIToVovkSchema/index.js +141 -0
  113. package/mjs/openapi/openAPIToVovkSchema/inlineRefs.d.ts +10 -0
  114. package/mjs/openapi/openAPIToVovkSchema/inlineRefs.js +102 -0
  115. package/mjs/openapi/vovkSchemaToOpenAPI.d.ts +8 -0
  116. package/mjs/openapi/vovkSchemaToOpenAPI.js +238 -0
  117. package/mjs/types.d.ts +466 -0
  118. package/mjs/types.js +77 -0
  119. package/mjs/utils/camelCase.d.ts +6 -0
  120. package/mjs/utils/camelCase.js +37 -0
  121. package/mjs/utils/createCodeSamples.d.ts +20 -0
  122. package/mjs/utils/createCodeSamples.js +279 -0
  123. package/mjs/utils/createDecorator.d.ts +6 -0
  124. package/mjs/utils/createDecorator.js +48 -0
  125. package/mjs/utils/createLLMTools.d.ts +50 -0
  126. package/mjs/utils/createLLMTools.js +168 -0
  127. package/mjs/utils/createStandardValidation.d.ts +82 -0
  128. package/mjs/utils/createStandardValidation.js +34 -0
  129. package/mjs/utils/createValidateOnClient.d.ts +7 -0
  130. package/mjs/utils/createValidateOnClient.js +19 -0
  131. package/mjs/utils/deepExtend.d.ts +54 -0
  132. package/mjs/utils/deepExtend.js +134 -0
  133. package/mjs/utils/generateStaticAPI.d.ts +4 -0
  134. package/mjs/utils/generateStaticAPI.js +30 -0
  135. package/mjs/utils/getJSONSchemaExample.d.ts +11 -0
  136. package/mjs/utils/getJSONSchemaExample.js +264 -0
  137. package/mjs/utils/getJSONSchemaSample.d.ts +2 -0
  138. package/mjs/utils/getJSONSchemaSample.js +167 -0
  139. package/mjs/utils/getSampleFromObject.d.ts +9 -0
  140. package/mjs/utils/getSampleFromObject.js +41 -0
  141. package/mjs/utils/getSchema.d.ts +21 -0
  142. package/mjs/utils/getSchema.js +38 -0
  143. package/mjs/utils/multitenant.d.ts +24 -0
  144. package/mjs/utils/multitenant.js +131 -0
  145. package/mjs/utils/parseQuery.d.ts +25 -0
  146. package/mjs/utils/parseQuery.js +156 -0
  147. package/mjs/utils/reqForm.d.ts +2 -0
  148. package/mjs/utils/reqForm.js +33 -0
  149. package/mjs/utils/reqMeta.d.ts +2 -0
  150. package/mjs/utils/reqMeta.js +13 -0
  151. package/mjs/utils/reqQuery.d.ts +2 -0
  152. package/mjs/utils/reqQuery.js +10 -0
  153. package/mjs/utils/resolveGeneratorConfigValues.d.ts +18 -0
  154. package/mjs/utils/resolveGeneratorConfigValues.js +82 -0
  155. package/mjs/utils/serializeQuery.d.ts +13 -0
  156. package/mjs/utils/serializeQuery.js +65 -0
  157. package/mjs/utils/setHandlerSchema.d.ts +4 -0
  158. package/mjs/utils/setHandlerSchema.js +15 -0
  159. package/mjs/utils/shim.d.ts +1 -0
  160. package/mjs/utils/shim.js +18 -0
  161. package/mjs/utils/upperFirst.d.ts +1 -0
  162. package/mjs/utils/upperFirst.js +6 -0
  163. package/mjs/utils/withValidationLibrary.d.ts +77 -0
  164. package/mjs/utils/withValidationLibrary.js +124 -0
  165. package/package.json +28 -6
  166. package/.npmignore +0 -2
  167. package/StreamJSONResponse.d.ts +0 -17
  168. package/StreamJSONResponse.js +0 -54
  169. package/VovkApp.js +0 -185
  170. package/client/clientizeController.d.ts +0 -4
  171. package/client/clientizeController.js +0 -93
  172. package/client/defaultFetcher.d.ts +0 -4
  173. package/client/defaultFetcher.js +0 -49
  174. package/client/defaultHandler.d.ts +0 -2
  175. package/client/defaultStreamHandler.d.ts +0 -4
  176. package/client/index.d.ts +0 -4
  177. package/client/index.js +0 -5
  178. package/client/types.d.ts +0 -100
  179. package/createDecorator.d.ts +0 -4
  180. package/createVovkApp.js +0 -118
  181. package/index.d.ts +0 -60
  182. package/index.js +0 -20
  183. package/types.d.ts +0 -157
  184. package/utils/generateStaticAPI.js +0 -18
  185. package/utils/getSchema.d.ts +0 -8
  186. package/utils/getSchema.js +0 -38
  187. package/utils/reqForm.d.ts +0 -3
  188. package/utils/reqForm.js +0 -13
  189. package/utils/reqMeta.d.ts +0 -3
  190. package/utils/reqQuery.d.ts +0 -3
  191. package/utils/reqQuery.js +0 -25
  192. package/utils/setClientValidatorsForHandler.d.ts +0 -5
  193. package/utils/setClientValidatorsForHandler.js +0 -25
  194. package/worker/index.d.ts +0 -3
  195. package/worker/index.js +0 -7
  196. package/worker/promisifyWorker.d.ts +0 -2
  197. package/worker/promisifyWorker.js +0 -141
  198. package/worker/types.d.ts +0 -31
  199. package/worker/worker.d.ts +0 -1
  200. package/worker/worker.js +0 -43
  201. /package/{HttpException.d.ts → cjs/HttpException.d.ts} +0 -0
  202. /package/{HttpException.js → cjs/HttpException.js} +0 -0
  203. /package/{client → cjs/client}/types.js +0 -0
  204. /package/{utils → cjs/utils}/reqMeta.js +0 -0
  205. /package/{utils → cjs/utils}/shim.d.ts +0 -0
  206. /package/{utils → cjs/utils}/shim.js +0 -0
  207. /package/{worker → mjs/client}/types.js +0 -0
@@ -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,18 @@
1
+ import type { PackageJson } from 'type-fest';
2
+ import type { VovkGeneratorConfig, VovkReadmeConfig, VovkSamplesConfig, VovkSchema } from '../types';
3
+ import type { OpenAPIObject } from 'openapi3-ts/oas31';
4
+ export declare function resolveGeneratorConfigValues({ schema, configs, segmentName, isBundle, projectPackageJson, }: {
5
+ schema: VovkSchema;
6
+ configs?: VovkGeneratorConfig[];
7
+ segmentName: string | null;
8
+ isBundle?: boolean;
9
+ projectPackageJson?: PackageJson;
10
+ }): {
11
+ readme: VovkReadmeConfig;
12
+ openAPIObject: OpenAPIObject;
13
+ samples: VovkSamplesConfig;
14
+ origin: string;
15
+ package: PackageJson;
16
+ imports: VovkGeneratorConfig['imports'];
17
+ reExports: VovkGeneratorConfig['reExports'];
18
+ };
@@ -0,0 +1,82 @@
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.resolveGeneratorConfigValues = resolveGeneratorConfigValues;
7
+ const deepExtend_1 = __importDefault(require("./deepExtend"));
8
+ function resolveGeneratorConfigValues({ schema, configs, segmentName, isBundle, projectPackageJson, }) {
9
+ const packageJson = (0, deepExtend_1.default)({}, {
10
+ main: './index.cjs',
11
+ module: './index.mjs',
12
+ types: './index.d.mts',
13
+ exports: {
14
+ '.': {
15
+ import: './index.mjs',
16
+ require: './index.cjs',
17
+ types: './index.d.mts',
18
+ },
19
+ './schema': {
20
+ import: './schema.cjs',
21
+ require: './schema.cjs',
22
+ types: './schema.d.cts',
23
+ },
24
+ './openapi': {
25
+ import: './openapi.cjs',
26
+ require: './openapi.cjs',
27
+ types: './openapi.d.cts',
28
+ },
29
+ },
30
+ }, projectPackageJson, schema.meta?.config?.generatorConfig?.package, isBundle ? schema.meta?.config?.bundle?.generatorConfig?.package : undefined, typeof segmentName === 'string' ? schema.segments?.[segmentName]?.meta?.package : undefined, typeof segmentName === 'string'
31
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.package
32
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.package), {}));
33
+ return {
34
+ package: Object.fromEntries(Object.entries(packageJson).filter(([key]) => ['name', 'version', 'description', 'license', 'authors', 'repository', 'homepage', 'bugs', 'keywords'].includes(key))),
35
+ openAPIObject: (0, deepExtend_1.default)({}, {
36
+ openapi: '3.1.0',
37
+ info: {
38
+ title: packageJson.name,
39
+ version: packageJson.version,
40
+ description: packageJson.description,
41
+ },
42
+ }, schema.meta?.config?.generatorConfig?.openAPIObject, isBundle ? schema.meta?.config?.bundle?.generatorConfig?.openAPIObject : undefined, typeof segmentName === 'string' ? schema?.segments?.[segmentName]?.meta?.openAPIObject : undefined, typeof segmentName === 'string'
43
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.openAPIObject
44
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.openAPIObject), {})),
45
+ samples: (0, deepExtend_1.default)({}, schema.meta?.config?.generatorConfig?.samples, isBundle ? schema.meta?.config?.bundle?.generatorConfig?.samples : undefined, typeof segmentName === 'string'
46
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.samples
47
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.samples), {})),
48
+ readme: (0, deepExtend_1.default)({}, schema.meta?.config?.generatorConfig?.readme, isBundle ? schema.meta?.config?.bundle?.generatorConfig?.readme : undefined, typeof segmentName === 'string'
49
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.readme
50
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.readme), {})),
51
+ origin: [
52
+ isBundle ? schema.meta?.config?.bundle?.generatorConfig?.origin : undefined,
53
+ typeof segmentName === 'string'
54
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.origin
55
+ : undefined,
56
+ schema.meta?.config?.generatorConfig?.origin,
57
+ ...(configs?.map((config) => config.origin) ?? []),
58
+ ]
59
+ .filter(Boolean)
60
+ .at(-1)
61
+ // remove trailing slash if any
62
+ ?.replace(/\/$/, '') ?? '',
63
+ imports: (0, deepExtend_1.default)({
64
+ fetcher: ['vovk'],
65
+ validateOnClient: null,
66
+ createRPC: ['vovk'],
67
+ }, schema.meta?.config?.generatorConfig?.imports, isBundle ? schema.meta?.config?.bundle?.generatorConfig?.imports : undefined, typeof segmentName === 'string'
68
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.imports
69
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.imports), {})),
70
+ reExports: (0, deepExtend_1.default)(
71
+ // segmentName can be an empty string (for the root segment) and null (for composed clients)
72
+ // therefore, !segmentName indicates that this either a composed client or a root segment of a segmented client
73
+ {}, !segmentName && schema.meta?.config?.generatorConfig?.reExports, !segmentName && isBundle ? schema.meta?.config?.bundle?.generatorConfig?.reExports : undefined,
74
+ // for segmented client, apply all reExports from all segments
75
+ typeof segmentName !== 'string' &&
76
+ Object.values(schema.meta?.config?.generatorConfig?.segments ?? {}).reduce((acc, segmentConfig) => (0, deepExtend_1.default)(acc, segmentConfig.reExports ?? {}), {}),
77
+ // for a specific segment, apply reExports from that segment
78
+ typeof segmentName === 'string'
79
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.reExports
80
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.reExports), {})),
81
+ };
82
+ }
@@ -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 setHandlerSchema(h: ((...args: KnownAny[]) => KnownAny) & {
3
+ _getSchema?: (controller: VovkController) => Omit<VovkHandlerSchema, 'httpMethod' | 'path'>;
4
+ }, schema: Omit<VovkHandlerSchema, 'httpMethod' | 'path'>): Promise<void>;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setHandlerSchema = setHandlerSchema;
4
+ async function setHandlerSchema(h, schema) {
5
+ h._getSchema = (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 schema;
14
+ };
15
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ if (typeof Symbol.dispose !== 'symbol') {
4
+ Object.defineProperty(Symbol, 'dispose', {
5
+ configurable: false,
6
+ enumerable: false,
7
+ writable: false,
8
+ value: Symbol.for('dispose'),
9
+ });
10
+ }
11
+ if (typeof Symbol.asyncDispose !== 'symbol') {
12
+ Object.defineProperty(Symbol, 'asyncDispose', {
13
+ configurable: false,
14
+ enumerable: false,
15
+ writable: false,
16
+ value: Symbol.for('asyncDispose'),
17
+ });
18
+ }
@@ -0,0 +1 @@
1
+ export declare function upperFirst(str: string): string;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.upperFirst = upperFirst;
4
+ function upperFirst(str) {
5
+ return str.charAt(0).toUpperCase() + str.slice(1);
6
+ }
@@ -0,0 +1,77 @@
1
+ import { VovkHandlerSchema, VovkTypedMethod, VovkValidationType, type KnownAny, type VovkRequest, type VovkOperationObject } from '../types';
2
+ type VovkRequestAny = VovkRequest<KnownAny, KnownAny, KnownAny>;
3
+ type Meta = {
4
+ __disableClientValidation?: boolean;
5
+ [key: string]: KnownAny;
6
+ };
7
+ export declare function withValidationLibrary<T extends VovkTypedMethod<(req: KnownAny, params: KnownAny) => KnownAny, KnownAny, KnownAny, KnownAny, KnownAny, KnownAny, boolean>, TBody_MODEL, TQuery_MODEL, TParams_MODEL, OUTPUT_MODEL, ITERATION_MODEL, IS_FORM extends boolean = false>({ isForm, disableServerSideValidation, skipSchemaEmission, validateEachIteration, body, query, params, output, iteration, handle, toJSONSchema, validate, operationObject, }: {
8
+ isForm?: IS_FORM;
9
+ disableServerSideValidation?: boolean | VovkValidationType[];
10
+ skipSchemaEmission?: boolean | VovkValidationType[];
11
+ validateEachIteration?: boolean;
12
+ body?: TBody_MODEL;
13
+ query?: TQuery_MODEL;
14
+ params?: TParams_MODEL;
15
+ output?: OUTPUT_MODEL;
16
+ iteration?: ITERATION_MODEL;
17
+ handle: T;
18
+ toJSONSchema?: (model: KnownAny, // performance concern
19
+ meta: {
20
+ type: VovkValidationType;
21
+ }) => KnownAny;
22
+ validate: (data: KnownAny, model: NonNullable<TBody_MODEL | TQuery_MODEL | TParams_MODEL | OUTPUT_MODEL | ITERATION_MODEL>, meta: {
23
+ type: VovkValidationType | 'form';
24
+ req: VovkRequestAny;
25
+ status?: number;
26
+ i?: number;
27
+ }) => KnownAny;
28
+ operationObject?: VovkOperationObject;
29
+ }): T & {
30
+ schema: Omit<VovkHandlerSchema, "httpMethod" | "path"> & Partial<VovkHandlerSchema>;
31
+ wrapper?: (req: VovkRequestAny, params: Parameters<T>[1]) => ReturnType<T>;
32
+ } & {
33
+ fn: {
34
+ <RETURN_TYPE = ReturnType<T>>(input?: (undefined extends TBody_MODEL | undefined ? undefined extends TQuery_MODEL | undefined ? undefined extends TParams_MODEL | undefined ? true : false : false : false) extends true ? {
35
+ disableClientValidation?: boolean;
36
+ } & (undefined extends TBody_MODEL | undefined ? {
37
+ body?: T["__types"]["body"];
38
+ } : {
39
+ body: T["__types"]["body"];
40
+ }) & (undefined extends TQuery_MODEL | undefined ? {
41
+ query?: T["__types"]["query"];
42
+ } : {
43
+ query: T["__types"]["query"];
44
+ }) & (undefined extends TParams_MODEL | undefined ? {
45
+ params?: T["__types"]["params"];
46
+ } : {
47
+ params: T["__types"]["params"];
48
+ }) & {
49
+ meta?: Meta;
50
+ } : never): (undefined extends TBody_MODEL | undefined ? undefined extends TQuery_MODEL | undefined ? undefined extends TParams_MODEL | undefined ? true : false : false : false) extends true ? RETURN_TYPE : never;
51
+ <RETURN_TYPE = ReturnType<T>>(input: {
52
+ disableClientValidation?: boolean;
53
+ } & (undefined extends TBody_MODEL | undefined ? {
54
+ body?: T["__types"]["body"];
55
+ } : {
56
+ body: T["__types"]["body"];
57
+ }) & (undefined extends TQuery_MODEL | undefined ? {
58
+ query?: T["__types"]["query"];
59
+ } : {
60
+ query: T["__types"]["query"];
61
+ }) & (undefined extends TParams_MODEL | undefined ? {
62
+ params?: T["__types"]["params"];
63
+ } : {
64
+ params: T["__types"]["params"];
65
+ }) & {
66
+ meta?: Meta;
67
+ }): RETURN_TYPE;
68
+ };
69
+ models: {
70
+ iteration?: (ITERATION_MODEL & ({} | null)) | undefined;
71
+ output?: (OUTPUT_MODEL & ({} | null)) | undefined;
72
+ params?: (TParams_MODEL & ({} | null)) | undefined;
73
+ query?: (TQuery_MODEL & ({} | null)) | undefined;
74
+ body?: (TBody_MODEL & ({} | null)) | undefined;
75
+ };
76
+ };
77
+ export {};
@@ -0,0 +1,124 @@
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.withValidationLibrary = withValidationLibrary;
7
+ const HttpException_1 = require("../HttpException");
8
+ const types_1 = require("../types");
9
+ const reqMeta_1 = __importDefault(require("./reqMeta"));
10
+ const setHandlerSchema_1 = require("./setHandlerSchema");
11
+ const validationTypes = ['body', 'query', 'params', 'output', 'iteration'];
12
+ function withValidationLibrary({ isForm, disableServerSideValidation, skipSchemaEmission, validateEachIteration, body, query, params, output, iteration, handle, toJSONSchema, validate, operationObject, }) {
13
+ const disableServerSideValidationKeys = disableServerSideValidation === false
14
+ ? []
15
+ : disableServerSideValidation === true
16
+ ? validationTypes
17
+ : (disableServerSideValidation ?? []);
18
+ const skipSchemaEmissionKeys = skipSchemaEmission === false ? [] : skipSchemaEmission === true ? validationTypes : (skipSchemaEmission ?? []);
19
+ const outputHandler = async (req, handlerParams) => {
20
+ const { __disableClientValidation } = req.vovk.meta();
21
+ let data = await handle(req, handlerParams);
22
+ if (__disableClientValidation) {
23
+ return data;
24
+ }
25
+ if (output && iteration) {
26
+ throw new HttpException_1.HttpException(types_1.HttpStatus.INTERNAL_SERVER_ERROR, "Output and iteration are mutually exclusive. You can't use them together.");
27
+ }
28
+ if (output && !disableServerSideValidationKeys.includes('output')) {
29
+ if (!data) {
30
+ throw new HttpException_1.HttpException(types_1.HttpStatus.INTERNAL_SERVER_ERROR, 'Output is required. You probably forgot to return something from your handler.');
31
+ }
32
+ data = (await validate(data, output, { type: 'output', req })) ?? data;
33
+ }
34
+ if (iteration && !disableServerSideValidationKeys.includes('iteration')) {
35
+ // We assume `data` is an async iterable here; you might want to check that:
36
+ if (!data || typeof data[Symbol.asyncIterator] !== 'function') {
37
+ throw new HttpException_1.HttpException(types_1.HttpStatus.INTERNAL_SERVER_ERROR, 'Data is not an async iterable but iteration validation is defined.');
38
+ }
39
+ // Return a brand-new async generator that yields validated items
40
+ return (async function* () {
41
+ let i = 0;
42
+ for await (const item of data) {
43
+ if (validateEachIteration || i === 0) {
44
+ await validate(item, iteration, { type: 'iteration', req, status: 200, i });
45
+ }
46
+ i++;
47
+ yield item;
48
+ }
49
+ })();
50
+ }
51
+ else if (validateEachIteration) {
52
+ throw new HttpException_1.HttpException(types_1.HttpStatus.INTERNAL_SERVER_ERROR, 'validateEachIteration is set but iteration is not defined.');
53
+ }
54
+ return data;
55
+ };
56
+ const resultHandler = (async (req, handlerParams) => {
57
+ const { __disableClientValidation } = req.vovk.meta();
58
+ if (!__disableClientValidation) {
59
+ if (body && !disableServerSideValidationKeys.includes('body')) {
60
+ const data = await req.vovk[isForm ? 'form' : 'body']();
61
+ const instance = (await validate(data, body, { type: isForm ? 'form' : 'body', req })) ?? data;
62
+ // redeclare to add ability to call req.json() and req.vovk.body() again
63
+ req.json = () => Promise.resolve(data);
64
+ req.vovk[isForm ? 'form' : 'body'] = () => Promise.resolve(instance);
65
+ }
66
+ if (query && !disableServerSideValidationKeys.includes('query')) {
67
+ const data = req.vovk.query();
68
+ const instance = (await validate(data, query, { type: 'query', req })) ?? data;
69
+ req.vovk.query = () => instance;
70
+ }
71
+ if (params && !disableServerSideValidationKeys.includes('params')) {
72
+ const data = req.vovk.params();
73
+ const instance = (await validate(data, params, { type: 'params', req })) ?? data;
74
+ req.vovk.params = () => instance;
75
+ }
76
+ }
77
+ return outputHandler(req, handlerParams);
78
+ });
79
+ function fn(input) {
80
+ const fakeReq = {
81
+ vovk: {
82
+ body: () => Promise.resolve((input?.body ?? {})),
83
+ query: () => (input?.query ?? {}),
84
+ params: () => (input?.params ?? {}),
85
+ meta: (meta) => (0, reqMeta_1.default)(fakeReq, meta),
86
+ form: () => {
87
+ throw new Error('Form data is not supported in this context.');
88
+ },
89
+ },
90
+ };
91
+ fakeReq.vovk.meta({ __disableClientValidation: input?.disableClientValidation, ...input?.meta });
92
+ return (resultHandler.wrapper ?? resultHandler)(fakeReq, (input?.params ?? {}));
93
+ }
94
+ const models = {
95
+ ...(body !== undefined ? { body } : {}),
96
+ ...(query !== undefined ? { query } : {}),
97
+ ...(params !== undefined ? { params } : {}),
98
+ ...(output !== undefined ? { output } : {}),
99
+ ...(iteration !== undefined ? { iteration } : {}),
100
+ };
101
+ const resultHandlerEnhanced = Object.assign(resultHandler, { fn, models });
102
+ if (toJSONSchema) {
103
+ const getJSONSchema = (model, type) => Object.assign(toJSONSchema(model, { type }), type === 'body' && isForm ? { 'x-isForm': isForm } : {});
104
+ const validation = {};
105
+ if (body && !skipSchemaEmissionKeys.includes('body')) {
106
+ validation.body = getJSONSchema(body, 'body');
107
+ }
108
+ if (query && !skipSchemaEmissionKeys.includes('query')) {
109
+ validation.query = getJSONSchema(query, 'query');
110
+ }
111
+ if (params && !skipSchemaEmissionKeys.includes('params')) {
112
+ validation.params = getJSONSchema(params, 'params');
113
+ }
114
+ if (output && !skipSchemaEmissionKeys.includes('output')) {
115
+ validation.output = getJSONSchema(output, 'output');
116
+ }
117
+ if (iteration && !skipSchemaEmissionKeys.includes('iteration')) {
118
+ validation.iteration = getJSONSchema(iteration, 'iteration');
119
+ }
120
+ resultHandlerEnhanced.schema = { validation, operationObject };
121
+ (0, setHandlerSchema_1.setHandlerSchema)(resultHandlerEnhanced, { validation, operationObject });
122
+ }
123
+ return resultHandlerEnhanced;
124
+ }
package/package.json CHANGED
@@ -1,29 +1,51 @@
1
1
  {
2
2
  "name": "vovk",
3
- "version": "3.0.0-draft.46",
4
- "description": "RESTful RPC for Next.js - Transforms Next.js into a powerful REST API platform with RPC capabilities.",
3
+ "version": "3.0.0-draft.460",
4
+ "main": "./cjs/index.js",
5
+ "module": "./mjs/index.js",
6
+ "types": "./mjs/index.d.ts",
7
+ "bin": {
8
+ "vovk-cli-npx": "./bin/index.mjs"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "import": "./mjs/index.js",
13
+ "require": "./cjs/index.js",
14
+ "types": "./mjs/index.d.ts"
15
+ }
16
+ },
17
+ "description": "RESTful RPC for Next.js",
5
18
  "repository": {
6
19
  "type": "git",
7
20
  "url": "git+https://github.com/finom/vovk.git"
8
21
  },
9
22
  "scripts": {
10
- "build": "shx rm -rf dist && tsc && shx cp package.json LICENSE .npmignore dist && shx cp ../../README.md dist",
23
+ "postbuild": "shx chmod +x ./bin/index.mjs",
24
+ "build": "shx rm -f *.tsbuildinfo && npm run build:cjs && npm run build:esm",
25
+ "build:esm": "tsc --module NodeNext --outDir mjs --moduleResolution nodenext",
26
+ "build:cjs": "tsc --module commonjs --outDir cjs",
27
+ "rm-dist": "shx rm -rf mjs cjs",
11
28
  "lint": "eslint . --fix",
12
29
  "tsc": "tsc --noEmit",
13
- "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 ..",
30
+ "npm-publish": "if [ -z \"$NPM_TAG\" ]; then echo 'Error: NPM_TAG is not set'; exit 1; fi; npm publish --tag=$NPM_TAG",
14
31
  "ncu": "npm-check-updates -u"
15
32
  },
16
33
  "keywords": [
17
34
  "nextjs",
18
35
  "router"
19
36
  ],
20
- "author": "Andrii Gubanov",
37
+ "author": "Andrey Gubanov",
21
38
  "license": "MIT",
22
39
  "bugs": {
23
40
  "url": "https://github.com/finom/vovk/issues"
24
41
  },
25
42
  "homepage": "https://vovk.dev",
26
43
  "peerDependencies": {
27
- "next": "*"
44
+ "next": "*",
45
+ "openapi3-ts": "^4"
46
+ },
47
+ "dependencies": {
48
+ "@standard-schema/spec": "^1.0.0",
49
+ "type-fest": "*"
28
50
  }
29
51
  }
package/.npmignore DELETED
@@ -1,2 +0,0 @@
1
- !*
2
- tsconfig.*
@@ -1,17 +0,0 @@
1
- import { KnownAny, StreamAbortMessage } from './types';
2
- import './utils/shim';
3
- export declare class StreamJSONResponse<T> extends Response {
4
- static defaultHeaders: {
5
- 'content-type': string;
6
- 'x-vovk-stream': string;
7
- };
8
- isClosed: boolean;
9
- controller?: ReadableStreamDefaultController;
10
- readonly encoder: TextEncoder;
11
- readonly readableStream: ReadableStream;
12
- constructor(init?: ResponseInit);
13
- send(data: T | StreamAbortMessage): void;
14
- close(): void;
15
- throw(e: KnownAny): void;
16
- [Symbol.dispose](): void;
17
- }
@@ -1,54 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StreamJSONResponse = void 0;
4
- require("./utils/shim");
5
- class StreamJSONResponse extends Response {
6
- static defaultHeaders = {
7
- 'content-type': 'text/plain; charset=utf-8',
8
- 'x-vovk-stream': 'true',
9
- };
10
- isClosed = false;
11
- controller;
12
- encoder;
13
- readableStream;
14
- constructor(init) {
15
- const encoder = new TextEncoder();
16
- let readableController;
17
- const readableStream = new ReadableStream({
18
- cancel: () => {
19
- this.isClosed = true;
20
- },
21
- start: (controller) => {
22
- readableController = controller;
23
- },
24
- });
25
- super(readableStream, {
26
- ...init,
27
- headers: init?.headers ?? StreamJSONResponse.defaultHeaders,
28
- });
29
- this.readableStream = readableStream;
30
- this.encoder = encoder;
31
- this.controller = readableController;
32
- }
33
- send(data) {
34
- const { controller, encoder } = this;
35
- if (this.isClosed)
36
- return;
37
- return controller?.enqueue(encoder.encode(JSON.stringify(data) + '\n'));
38
- }
39
- close() {
40
- const { controller } = this;
41
- if (this.isClosed)
42
- return;
43
- this.isClosed = true;
44
- controller?.close();
45
- }
46
- throw(e) {
47
- this.send({ isError: true, reason: e instanceof Error ? e.message : e });
48
- return this.close();
49
- }
50
- [Symbol.dispose]() {
51
- this.close();
52
- }
53
- }
54
- exports.StreamJSONResponse = StreamJSONResponse;