vovk 3.0.0-draft.21 → 3.0.0-draft.210

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 (169) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +8 -96
  3. package/bin/index.mjs +8 -0
  4. package/{HttpException.d.ts → cjs/HttpException.d.ts} +2 -2
  5. package/{HttpException.js → cjs/HttpException.js} +3 -3
  6. package/cjs/JSONLinesResponse.d.ts +14 -0
  7. package/{StreamJSONResponse.js → cjs/JSONLinesResponse.js} +15 -10
  8. package/{Segment.d.ts → cjs/VovkApp.d.ts} +11 -10
  9. package/cjs/VovkApp.js +189 -0
  10. package/cjs/client/createRPC.d.ts +3 -0
  11. package/cjs/client/createRPC.js +87 -0
  12. package/{client → cjs/client}/defaultHandler.d.ts +1 -1
  13. package/cjs/client/defaultHandler.js +22 -0
  14. package/cjs/client/defaultStreamHandler.d.ts +4 -0
  15. package/{client → cjs/client}/defaultStreamHandler.js +11 -12
  16. package/cjs/client/fetcher.d.ts +13 -0
  17. package/cjs/client/fetcher.js +90 -0
  18. package/cjs/client/index.d.ts +3 -0
  19. package/cjs/client/index.js +8 -0
  20. package/cjs/client/types.d.ts +111 -0
  21. package/{createSegment.d.ts → cjs/createVovkApp.d.ts} +11 -10
  22. package/cjs/createVovkApp.js +132 -0
  23. package/cjs/index.d.ts +65 -0
  24. package/cjs/index.js +37 -0
  25. package/cjs/openapi/error.d.ts +2 -0
  26. package/cjs/openapi/error.js +100 -0
  27. package/cjs/openapi/generateFnName.d.ts +23 -0
  28. package/cjs/openapi/generateFnName.js +81 -0
  29. package/cjs/openapi/index.d.ts +12 -0
  30. package/cjs/openapi/index.js +21 -0
  31. package/cjs/openapi/openAPIToVovkSchema.d.ts +2 -0
  32. package/cjs/openapi/openAPIToVovkSchema.js +197 -0
  33. package/cjs/openapi/vovkSchemaToOpenAPI.d.ts +9 -0
  34. package/cjs/openapi/vovkSchemaToOpenAPI.js +237 -0
  35. package/cjs/types.d.ts +364 -0
  36. package/cjs/types.js +74 -0
  37. package/cjs/utils/camelCase.d.ts +6 -0
  38. package/cjs/utils/camelCase.js +37 -0
  39. package/cjs/utils/createCodeExamples.d.ts +19 -0
  40. package/cjs/utils/createCodeExamples.js +114 -0
  41. package/cjs/utils/createDecorator.d.ts +6 -0
  42. package/{createDecorator.js → cjs/utils/createDecorator.js} +22 -15
  43. package/cjs/utils/createLLMFunctions.d.ts +20 -0
  44. package/cjs/utils/createLLMFunctions.js +100 -0
  45. package/cjs/utils/generateStaticAPI.d.ts +4 -0
  46. package/cjs/utils/generateStaticAPI.js +30 -0
  47. package/cjs/utils/getSchema.d.ts +21 -0
  48. package/cjs/utils/getSchema.js +43 -0
  49. package/cjs/utils/multitenant.d.ts +24 -0
  50. package/cjs/utils/multitenant.js +170 -0
  51. package/cjs/utils/parseQuery.d.ts +25 -0
  52. package/cjs/utils/parseQuery.js +156 -0
  53. package/cjs/utils/reqForm.d.ts +2 -0
  54. package/cjs/utils/reqForm.js +33 -0
  55. package/{utils → cjs/utils}/reqMeta.d.ts +1 -2
  56. package/cjs/utils/reqQuery.d.ts +2 -0
  57. package/cjs/utils/reqQuery.js +10 -0
  58. package/cjs/utils/serializeQuery.d.ts +13 -0
  59. package/cjs/utils/serializeQuery.js +65 -0
  60. package/cjs/utils/setHandlerSchema.d.ts +4 -0
  61. package/cjs/utils/setHandlerSchema.js +15 -0
  62. package/cjs/utils/withStandard.d.ts +51 -0
  63. package/cjs/utils/withStandard.js +30 -0
  64. package/cjs/utils/withValidationLibrary.d.ts +49 -0
  65. package/cjs/utils/withValidationLibrary.js +123 -0
  66. package/mjs/HttpException.d.ts +7 -0
  67. package/mjs/HttpException.js +15 -0
  68. package/mjs/JSONLinesResponse.d.ts +14 -0
  69. package/mjs/JSONLinesResponse.js +59 -0
  70. package/mjs/VovkApp.d.ts +29 -0
  71. package/mjs/VovkApp.js +189 -0
  72. package/mjs/client/createRPC.d.ts +3 -0
  73. package/mjs/client/createRPC.js +87 -0
  74. package/mjs/client/defaultHandler.d.ts +2 -0
  75. package/mjs/client/defaultHandler.js +22 -0
  76. package/mjs/client/defaultStreamHandler.d.ts +4 -0
  77. package/mjs/client/defaultStreamHandler.js +81 -0
  78. package/mjs/client/fetcher.d.ts +13 -0
  79. package/mjs/client/fetcher.js +90 -0
  80. package/mjs/client/index.d.ts +3 -0
  81. package/mjs/client/index.js +8 -0
  82. package/mjs/client/types.d.ts +111 -0
  83. package/mjs/createVovkApp.d.ts +63 -0
  84. package/mjs/createVovkApp.js +132 -0
  85. package/mjs/index.d.ts +65 -0
  86. package/mjs/index.js +37 -0
  87. package/mjs/openapi/error.d.ts +2 -0
  88. package/mjs/openapi/error.js +100 -0
  89. package/mjs/openapi/generateFnName.d.ts +23 -0
  90. package/mjs/openapi/generateFnName.js +81 -0
  91. package/mjs/openapi/index.d.ts +12 -0
  92. package/mjs/openapi/index.js +21 -0
  93. package/mjs/openapi/openAPIToVovkSchema.d.ts +2 -0
  94. package/mjs/openapi/openAPIToVovkSchema.js +197 -0
  95. package/mjs/openapi/vovkSchemaToOpenAPI.d.ts +9 -0
  96. package/mjs/openapi/vovkSchemaToOpenAPI.js +237 -0
  97. package/mjs/types.d.ts +364 -0
  98. package/mjs/types.js +74 -0
  99. package/mjs/utils/camelCase.d.ts +6 -0
  100. package/mjs/utils/camelCase.js +37 -0
  101. package/mjs/utils/createCodeExamples.d.ts +19 -0
  102. package/mjs/utils/createCodeExamples.js +114 -0
  103. package/mjs/utils/createDecorator.d.ts +6 -0
  104. package/mjs/utils/createDecorator.js +45 -0
  105. package/mjs/utils/createLLMFunctions.d.ts +20 -0
  106. package/mjs/utils/createLLMFunctions.js +100 -0
  107. package/mjs/utils/generateStaticAPI.d.ts +4 -0
  108. package/mjs/utils/generateStaticAPI.js +30 -0
  109. package/mjs/utils/getSchema.d.ts +21 -0
  110. package/mjs/utils/getSchema.js +43 -0
  111. package/mjs/utils/multitenant.d.ts +24 -0
  112. package/mjs/utils/multitenant.js +170 -0
  113. package/mjs/utils/parseQuery.d.ts +25 -0
  114. package/mjs/utils/parseQuery.js +156 -0
  115. package/mjs/utils/reqForm.d.ts +2 -0
  116. package/mjs/utils/reqForm.js +33 -0
  117. package/mjs/utils/reqMeta.d.ts +2 -0
  118. package/mjs/utils/reqMeta.js +13 -0
  119. package/mjs/utils/reqQuery.d.ts +2 -0
  120. package/mjs/utils/reqQuery.js +10 -0
  121. package/mjs/utils/serializeQuery.d.ts +13 -0
  122. package/mjs/utils/serializeQuery.js +65 -0
  123. package/mjs/utils/setHandlerSchema.d.ts +4 -0
  124. package/mjs/utils/setHandlerSchema.js +15 -0
  125. package/mjs/utils/shim.d.ts +1 -0
  126. package/mjs/utils/shim.js +18 -0
  127. package/mjs/utils/withStandard.d.ts +51 -0
  128. package/mjs/utils/withStandard.js +30 -0
  129. package/mjs/utils/withValidationLibrary.d.ts +49 -0
  130. package/mjs/utils/withValidationLibrary.js +123 -0
  131. package/package.json +30 -5
  132. package/.npmignore +0 -2
  133. package/Segment.js +0 -182
  134. package/StreamJSONResponse.d.ts +0 -17
  135. package/client/clientizeController.d.ts +0 -4
  136. package/client/clientizeController.js +0 -92
  137. package/client/defaultFetcher.d.ts +0 -4
  138. package/client/defaultFetcher.js +0 -49
  139. package/client/defaultHandler.js +0 -21
  140. package/client/defaultStreamHandler.d.ts +0 -4
  141. package/client/index.d.ts +0 -4
  142. package/client/index.js +0 -5
  143. package/client/types.d.ts +0 -100
  144. package/createDecorator.d.ts +0 -4
  145. package/createSegment.js +0 -118
  146. package/generateStaticAPI.d.ts +0 -4
  147. package/generateStaticAPI.js +0 -18
  148. package/index.d.ts +0 -60
  149. package/index.js +0 -20
  150. package/types.d.ts +0 -155
  151. package/types.js +0 -65
  152. package/utils/getSchema.d.ts +0 -8
  153. package/utils/getSchema.js +0 -38
  154. package/utils/reqQuery.d.ts +0 -3
  155. package/utils/reqQuery.js +0 -25
  156. package/utils/setClientValidatorsForHandler.d.ts +0 -5
  157. package/utils/setClientValidatorsForHandler.js +0 -28
  158. package/worker/index.d.ts +0 -3
  159. package/worker/index.js +0 -7
  160. package/worker/promisifyWorker.d.ts +0 -2
  161. package/worker/promisifyWorker.js +0 -141
  162. package/worker/types.d.ts +0 -31
  163. package/worker/worker.d.ts +0 -1
  164. package/worker/worker.js +0 -43
  165. /package/{client → cjs/client}/types.js +0 -0
  166. /package/{utils → cjs/utils}/reqMeta.js +0 -0
  167. /package/{utils → cjs/utils}/shim.d.ts +0 -0
  168. /package/{utils → cjs/utils}/shim.js +0 -0
  169. /package/{worker → mjs/client}/types.js +0 -0
package/LICENSE CHANGED
@@ -16,7 +16,7 @@
16
16
  "nextjs",
17
17
  "router"
18
18
  ],
19
- "author": "Andrii Gubanov",
19
+ "author": "Andrey Gubanov",
20
20
  "license": "MIT",
21
21
  "bugs": {
22
22
  "url": "https://github.com/finom/vovk/issues"
package/README.md CHANGED
@@ -4,109 +4,21 @@
4
4
  <source width="300" media="(prefers-color-scheme: light)" srcset="https://vovk.dev/vovk-logo.svg">
5
5
  <img width="300" alt="vovk" src="https://vovk.dev/vovk-logo.svg">
6
6
  </picture><br>
7
- <strong>RESTful RPC for Next.js</strong>
8
-
7
+ <strong>RESTful + RPC = ♥️</strong>
9
8
  </p>
10
9
 
11
10
  <p align="center">
12
- Transforms <a href="https://nextjs.org/docs/app">Next.js</a> into a powerful REST API platform with RPC capabilities.
13
- <br><br>
14
- ℹ️ Improved syntax for Zod and DTO validation is coming soon. Stay tuned!
11
+ Back-end meta-framework for <a href="https://nextjs.org/docs/app">Next.js</a>
15
12
  </p>
16
13
 
17
- <p align="center">
18
- <a href="https://vovk.dev/">Documentation</a>&nbsp;&nbsp;&nbsp;&nbsp;
19
- <a href="https://discord.gg/qdT8WEHUuP">Discord</a>&nbsp;&nbsp;&nbsp;&nbsp;
20
- <a href="https://github.com/finom/vovk-examples">Code Examples</a>&nbsp;&nbsp;&nbsp;&nbsp;
21
- <a href="https://github.com/finom/vovk-zod">vovk-zod</a>&nbsp;&nbsp;&nbsp;&nbsp;
22
- <a href="https://github.com/finom/vovk-hello-world">vovk-hello-world</a>&nbsp;&nbsp;&nbsp;&nbsp;
23
- <a href="https://github.com/finom/vovk-react-native-example">vovk-react-native-example</a>
24
- </p>
25
- <p align="center">
26
- <a href="https://www.npmjs.com/package/vovk"><img src="https://badge.fury.io/js/vovk.svg" alt="npm version" /></a>&nbsp;
27
- <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg" alt="TypeScript" /></a>&nbsp;
28
- <a href="https://github.com/finom/vovk/actions/workflows/main.yml"><img src="https://github.com/finom/vovk/actions/workflows/main.yml/badge.svg" alt="Build status" /></a>
29
- </p>
14
+ ---
30
15
 
31
- <br />
16
+ ## vovk [![npm version](https://badge.fury.io/js/vovk.svg)](https://www.npmjs.com/package/vovk)
32
17
 
33
- Example back-end Controller Class:
18
+ The main library with [zero dependencies](https://bundlephobia.com/result?p=vovk) that's going to be used in production. It provides a wrapper for Next.js API routes, internal RPC API, utilities and types.
34
19
 
35
- ```ts
36
- // /src/modules/post/PostController.ts
37
- import { get, prefix, type VovkRequest } from 'vovk';
38
- import PostService from './PostService';
39
-
40
- @prefix('posts')
41
- export default class PostController {
42
- /**
43
- * Create a comment on a post
44
- * POST /api/posts/:postId/comments
45
- */
46
- @post(':postId/comments')
47
- static async createComment(
48
- // decorate NextRequest type with body and query types
49
- req: VovkRequest<{ content: string; userId: string }, { notificationType: 'push' | 'email' }>,
50
- { postId }: { postId: string } // params
51
- ) {
52
- // use standard Next.js API to get body and query
53
- const { content, userId } = await req.json();
54
- const notificationType = req.nextUrl.searchParams.get('notificationType');
55
-
56
- // perform the request to the database in a custom service
57
- return PostService.createComment({
58
- postId,
59
- content,
60
- userId,
61
- notificationType,
62
- });
63
- }
64
- }
20
+ ```sh
21
+ npm install vovk
65
22
  ```
66
23
 
67
- Example component that uses the auto-generated client library:
68
-
69
- ```tsx
70
- 'use client';
71
- import { useState } from 'react';
72
- import { PostController } from 'vovk-client';
73
- import type { VovkReturnType } from 'vovk';
74
-
75
- export default function Example() {
76
- const [response, setResponse] = useState<VovkReturnType<typeof PostController.createComment>>();
77
-
78
- return (
79
- <>
80
- <button
81
- onClick={async () =>
82
- setResponse(
83
- await PostController.createComment({
84
- body: {
85
- content: 'Hello, World!',
86
- userId: '1',
87
- },
88
- params: { postId: '69' },
89
- query: { notificationType: 'push' },
90
- })
91
- )
92
- }
93
- >
94
- Post a comment
95
- </button>
96
- <div>{JSON.stringify(response)}</div>
97
- </>
98
- );
99
- }
100
- ```
101
-
102
- Alternatively, the resource can be fetched wit the regular `fetch` function:
103
-
104
- ```ts
105
- fetch('/api/posts/69?notificationType=push', {
106
- method: 'POST',
107
- body: JSON.stringify({
108
- content: 'Hello, World!',
109
- userId: '1',
110
- }),
111
- });
112
- ```
24
+ For more information, please visit the [getting started guide](https://vovk.dev/getting-started) or check out the [Vovk.ts examples](https://vovk-examples.vercel.app/).
package/bin/index.mjs ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'child_process';
3
+
4
+ console.warn(`Vovk CLI requires vovk-cli package. Running "npx vovk-cli ${process.argv.slice(2).join(' ')}" instead.`);
5
+
6
+ spawn('npx', ['vovk-cli', ...process.argv.slice(2)], { stdio: 'inherit' }).on('exit', (code) => {
7
+ process.exit(code);
8
+ });
@@ -1,5 +1,5 @@
1
- import type { _HttpStatus as HttpStatus } from './types';
2
- export declare class _HttpException extends Error {
1
+ import type { HttpStatus } from './types.js';
2
+ export declare class HttpException extends Error {
3
3
  statusCode: HttpStatus;
4
4
  message: string;
5
5
  cause?: unknown;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._HttpException = void 0;
4
- class _HttpException extends Error {
3
+ exports.HttpException = void 0;
4
+ class HttpException extends Error {
5
5
  statusCode;
6
6
  message;
7
7
  cause;
@@ -12,4 +12,4 @@ class _HttpException extends Error {
12
12
  this.cause = cause;
13
13
  }
14
14
  }
15
- exports._HttpException = _HttpException;
15
+ exports.HttpException = HttpException;
@@ -0,0 +1,14 @@
1
+ import { headers } from 'next/headers';
2
+ import type { KnownAny, StreamAbortMessage } from './types.js';
3
+ import './utils/shim.js';
4
+ export declare class JSONLinesResponse<T> extends Response {
5
+ isClosed: boolean;
6
+ controller?: ReadableStreamDefaultController;
7
+ readonly encoder: TextEncoder;
8
+ readonly readableStream: ReadableStream;
9
+ constructor(requestHeaders: Awaited<ReturnType<typeof headers>>, init?: ResponseInit);
10
+ send(data: T | StreamAbortMessage): void;
11
+ close(): void;
12
+ throw(e: KnownAny): void;
13
+ [Symbol.dispose](): void;
14
+ }
@@ -1,17 +1,13 @@
1
1
  "use strict";
2
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
- };
3
+ exports.JSONLinesResponse = void 0;
4
+ require("./utils/shim.js");
5
+ class JSONLinesResponse extends Response {
10
6
  isClosed = false;
11
7
  controller;
12
8
  encoder;
13
9
  readableStream;
14
- constructor(init) {
10
+ constructor(requestHeaders, init) {
15
11
  const encoder = new TextEncoder();
16
12
  let readableController;
17
13
  const readableStream = new ReadableStream({
@@ -22,9 +18,18 @@ class _StreamJSONResponse extends Response {
22
18
  readableController = controller;
23
19
  },
24
20
  });
21
+ if (!requestHeaders) {
22
+ throw new Error('Request headers are required');
23
+ }
24
+ const accept = requestHeaders.get('accept');
25
25
  super(readableStream, {
26
26
  ...init,
27
- headers: init?.headers ?? _StreamJSONResponse.defaultHeaders,
27
+ headers: {
28
+ ...init?.headers,
29
+ 'Content-Type': accept?.includes('application/jsonl')
30
+ ? 'application/jsonl; charset=utf-8'
31
+ : 'text/plain; charset=utf-8',
32
+ },
28
33
  });
29
34
  this.readableStream = readableStream;
30
35
  this.encoder = encoder;
@@ -51,4 +56,4 @@ class _StreamJSONResponse extends Response {
51
56
  this.close();
52
57
  }
53
58
  }
54
- exports._StreamJSONResponse = _StreamJSONResponse;
59
+ exports.JSONLinesResponse = JSONLinesResponse;
@@ -1,27 +1,28 @@
1
- import { _HttpMethod as HttpMethod, _HttpStatus as HttpStatus, type _RouteHandler as RouteHandler, type _VovkController as VovkController, type _DecoratorOptions as DecoratorOptions, type _VovkRequest as VovkRequest } from './types';
2
- export declare class _Segment {
1
+ import type { NextRequest } from 'next/server';
2
+ import { HttpMethod, HttpStatus, type RouteHandler, type VovkController, type DecoratorOptions } from './types.js';
3
+ export declare class VovkApp {
3
4
  #private;
4
5
  private static getHeadersFromOptions;
5
- _routes: Record<HttpMethod, Map<VovkController, Record<string, RouteHandler>>>;
6
- GET: (req: VovkRequest, data: {
6
+ routes: Record<HttpMethod, Map<VovkController, Record<string, RouteHandler>>>;
7
+ GET: (req: NextRequest, data: {
7
8
  params: Promise<Record<string, string[]>>;
8
9
  }) => Promise<Response>;
9
- POST: (req: VovkRequest, data: {
10
+ POST: (req: NextRequest, data: {
10
11
  params: Promise<Record<string, string[]>>;
11
12
  }) => Promise<Response>;
12
- PUT: (req: VovkRequest, data: {
13
+ PUT: (req: NextRequest, data: {
13
14
  params: Promise<Record<string, string[]>>;
14
15
  }) => Promise<Response>;
15
- PATCH: (req: VovkRequest, data: {
16
+ PATCH: (req: NextRequest, data: {
16
17
  params: Promise<Record<string, string[]>>;
17
18
  }) => Promise<Response>;
18
- DELETE: (req: VovkRequest, data: {
19
+ DELETE: (req: NextRequest, data: {
19
20
  params: Promise<Record<string, string[]>>;
20
21
  }) => Promise<Response>;
21
- HEAD: (req: VovkRequest, data: {
22
+ HEAD: (req: NextRequest, data: {
22
23
  params: Promise<Record<string, string[]>>;
23
24
  }) => Promise<Response>;
24
- OPTIONS: (req: VovkRequest, data: {
25
+ OPTIONS: (req: NextRequest, data: {
25
26
  params: Promise<Record<string, string[]>>;
26
27
  }) => Promise<Response>;
27
28
  respond: (status: HttpStatus, body: unknown, options?: DecoratorOptions) => Response;
package/cjs/VovkApp.js ADDED
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ var _a;
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.VovkApp = void 0;
8
+ const types_js_1 = require("./types.js");
9
+ const HttpException_js_1 = require("./HttpException.js");
10
+ const JSONLinesResponse_js_1 = require("./JSONLinesResponse.js");
11
+ const reqQuery_js_1 = __importDefault(require("./utils/reqQuery.js"));
12
+ const reqMeta_js_1 = __importDefault(require("./utils/reqMeta.js"));
13
+ const reqForm_js_1 = __importDefault(require("./utils/reqForm.js"));
14
+ const headers_1 = require("next/headers");
15
+ class VovkApp {
16
+ static getHeadersFromOptions(options) {
17
+ if (!options)
18
+ return {};
19
+ const corsHeaders = {
20
+ 'access-control-allow-origin': '*',
21
+ 'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
22
+ 'access-control-allow-headers': 'content-type, authorization',
23
+ };
24
+ const headers = {
25
+ ...(options.cors ? corsHeaders : {}),
26
+ ...(options.headers ?? {}),
27
+ };
28
+ return headers;
29
+ }
30
+ routes = {
31
+ GET: new Map(),
32
+ POST: new Map(),
33
+ PUT: new Map(),
34
+ PATCH: new Map(),
35
+ DELETE: new Map(),
36
+ HEAD: new Map(),
37
+ OPTIONS: new Map(),
38
+ };
39
+ GET = async (req, data) => this.#callMethod(types_js_1.HttpMethod.GET, req, await data.params);
40
+ POST = async (req, data) => this.#callMethod(types_js_1.HttpMethod.POST, req, await data.params);
41
+ PUT = async (req, data) => this.#callMethod(types_js_1.HttpMethod.PUT, req, await data.params);
42
+ PATCH = async (req, data) => this.#callMethod(types_js_1.HttpMethod.PATCH, req, await data.params);
43
+ DELETE = async (req, data) => this.#callMethod(types_js_1.HttpMethod.DELETE, req, await data.params);
44
+ HEAD = async (req, data) => this.#callMethod(types_js_1.HttpMethod.HEAD, req, await data.params);
45
+ OPTIONS = async (req, data) => this.#callMethod(types_js_1.HttpMethod.OPTIONS, req, await data.params);
46
+ respond = (status, body, options) => {
47
+ return new Response(JSON.stringify(body), {
48
+ status,
49
+ headers: {
50
+ 'content-type': 'application/json',
51
+ ..._a.getHeadersFromOptions(options),
52
+ },
53
+ });
54
+ };
55
+ #respondWithError = (statusCode, message, options, cause) => {
56
+ return this.respond(statusCode, {
57
+ cause,
58
+ statusCode,
59
+ message,
60
+ isError: true,
61
+ }, options);
62
+ };
63
+ #getHandler = ({ handlers, path, params, }) => {
64
+ const methodParams = {};
65
+ if (Object.keys(params).length === 0) {
66
+ return { handler: handlers[''], methodParams };
67
+ }
68
+ const allMethodKeys = Object.keys(handlers);
69
+ let methodKeys = [];
70
+ const pathStr = path.join('/');
71
+ methodKeys = allMethodKeys
72
+ // First, try to match literal routes exactly.
73
+ .filter((p) => {
74
+ if (p.includes(':'))
75
+ return false; // Skip parameterized paths
76
+ return p === pathStr;
77
+ });
78
+ if (!methodKeys.length) {
79
+ methodKeys = allMethodKeys.filter((p) => {
80
+ const routeSegments = p.split('/');
81
+ if (routeSegments.length !== path.length)
82
+ return false;
83
+ for (let i = 0; i < routeSegments.length; i++) {
84
+ const routeSegment = routeSegments[i];
85
+ const pathSegment = path[i];
86
+ if (routeSegment.startsWith(':')) {
87
+ const parameter = routeSegment.slice(1);
88
+ if (parameter in methodParams) {
89
+ throw new HttpException_js_1.HttpException(types_js_1.HttpStatus.INTERNAL_SERVER_ERROR, `Duplicate parameter "${parameter}" at ${p}`);
90
+ }
91
+ // If it's a parameterized segment, capture the parameter value.
92
+ methodParams[parameter] = pathSegment;
93
+ }
94
+ else if (routeSegment !== pathSegment) {
95
+ // If it's a literal segment and it does not match the corresponding path segment, return false.
96
+ return false;
97
+ }
98
+ }
99
+ return true;
100
+ });
101
+ }
102
+ if (methodKeys.length > 1) {
103
+ throw new HttpException_js_1.HttpException(types_js_1.HttpStatus.INTERNAL_SERVER_ERROR, `Conflicting routes found: ${methodKeys.join(', ')}`);
104
+ }
105
+ const [methodKey] = methodKeys;
106
+ if (methodKey) {
107
+ return { handler: handlers[methodKey], methodParams };
108
+ }
109
+ return { handler: null, methodParams };
110
+ };
111
+ #callMethod = async (httpMethod, nextReq, params) => {
112
+ const req = nextReq;
113
+ const controllers = this.routes[httpMethod];
114
+ const path = params[Object.keys(params)[0]];
115
+ const handlers = {};
116
+ controllers.forEach((staticMethods, controller) => {
117
+ const prefix = controller._prefix ?? '';
118
+ if (!controller._activated) {
119
+ throw new HttpException_js_1.HttpException(types_js_1.HttpStatus.INTERNAL_SERVER_ERROR, `Controller "${controller.name}" found but not activated`);
120
+ }
121
+ Object.entries(staticMethods ?? {}).forEach(([path, staticMethod]) => {
122
+ const fullPath = [prefix, path].filter(Boolean).join('/');
123
+ handlers[fullPath] = { staticMethod, controller };
124
+ });
125
+ });
126
+ const { handler, methodParams } = this.#getHandler({ handlers, path, params });
127
+ if (!handler) {
128
+ return this.#respondWithError(types_js_1.HttpStatus.NOT_FOUND, `${Object.keys(handlers)} - Route ${path.join('/')} is not found`);
129
+ }
130
+ const { staticMethod, controller } = handler;
131
+ req.vovk = {
132
+ body: () => req.json(),
133
+ query: () => (0, reqQuery_js_1.default)(req),
134
+ meta: (meta) => (0, reqMeta_js_1.default)(req, meta),
135
+ form: () => (0, reqForm_js_1.default)(req),
136
+ params: () => methodParams,
137
+ };
138
+ try {
139
+ await staticMethod._options?.before?.call(controller, req);
140
+ const result = await staticMethod.call(controller, req, methodParams);
141
+ const isIterator = typeof result === 'object' &&
142
+ !!result &&
143
+ ((Reflect.has(result, Symbol.iterator) &&
144
+ typeof result[Symbol.iterator] === 'function') ||
145
+ (Reflect.has(result, Symbol.asyncIterator) &&
146
+ typeof result[Symbol.asyncIterator] === 'function'));
147
+ if (isIterator && !(result instanceof Array)) {
148
+ const streamResponse = new JSONLinesResponse_js_1.JSONLinesResponse(await (0, headers_1.headers)(), {
149
+ headers: {
150
+ ..._a.getHeadersFromOptions(staticMethod._options),
151
+ },
152
+ });
153
+ void (async () => {
154
+ try {
155
+ for await (const chunk of result) {
156
+ streamResponse.send(chunk);
157
+ }
158
+ }
159
+ catch (e) {
160
+ return streamResponse.throw(e);
161
+ }
162
+ return streamResponse.close();
163
+ })();
164
+ return streamResponse;
165
+ }
166
+ if (result instanceof Response) {
167
+ return result;
168
+ }
169
+ return this.respond(200, result ?? null, staticMethod._options);
170
+ }
171
+ catch (e) {
172
+ const err = e;
173
+ try {
174
+ await controller._onError?.(err, req);
175
+ }
176
+ catch (onErrorError) {
177
+ // eslint-disable-next-line no-console
178
+ console.error(onErrorError);
179
+ }
180
+ if (err.message !== 'NEXT_REDIRECT' && err.message !== 'NEXT_NOT_FOUND') {
181
+ const statusCode = err.statusCode || types_js_1.HttpStatus.INTERNAL_SERVER_ERROR;
182
+ return this.#respondWithError(statusCode, err.message, staticMethod._options, err.cause);
183
+ }
184
+ throw e; // if NEXT_REDIRECT or NEXT_NOT_FOUND, rethrow it
185
+ }
186
+ };
187
+ }
188
+ exports.VovkApp = VovkApp;
189
+ _a = VovkApp;
@@ -0,0 +1,3 @@
1
+ import type { KnownAny, VovkSchema } from '../types.js';
2
+ import type { VovkClient, VovkClientFetcher, VovkDefaultFetcherOptions } from './types.js';
3
+ export declare const createRPC: <T, OPTS extends Record<string, KnownAny> = Record<string, never>>(schema: VovkSchema, segmentName: string, rpcModuleName: string, fetcher?: VovkClientFetcher<OPTS>, options?: VovkDefaultFetcherOptions<OPTS>) => VovkClient<T, OPTS>;
@@ -0,0 +1,87 @@
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.createRPC = void 0;
7
+ const fetcher_js_1 = require("./fetcher.js");
8
+ const defaultHandler_js_1 = require("./defaultHandler.js");
9
+ const defaultStreamHandler_js_1 = require("./defaultStreamHandler.js");
10
+ const serializeQuery_js_1 = __importDefault(require("../utils/serializeQuery.js"));
11
+ const trimPath = (path) => path.trim().replace(/^\/|\/$/g, '');
12
+ const getHandlerPath = (endpoint, params, query) => {
13
+ let result = endpoint;
14
+ const queryStr = query ? (0, serializeQuery_js_1.default)(query) : null;
15
+ for (const [key, value] of Object.entries(params ?? {})) {
16
+ result = result.replace(`:${key}`, value);
17
+ }
18
+ return `${result}${queryStr ? '?' : ''}${queryStr}`;
19
+ };
20
+ const createRPC = (schema, segmentName, rpcModuleName, fetcher = fetcher_js_1.fetcher, options) => {
21
+ const segmentNamePath = options?.segmentNameOverride ?? segmentName;
22
+ const segmentSchema = schema.segments[segmentName];
23
+ if (!segmentSchema)
24
+ throw new Error(`Unable to create RPC module. Segment schema is missing. Check client template.`);
25
+ const controllerSchema = schema.segments[segmentName]?.controllers[rpcModuleName];
26
+ const client = {};
27
+ if (!controllerSchema)
28
+ throw new Error(`Unable to create RPC module. Controller schema is missing. Check client template.`);
29
+ const controllerPrefix = trimPath(controllerSchema.prefix ?? '');
30
+ for (const [staticMethodName, handlerSchema] of Object.entries(controllerSchema.handlers ?? {})) {
31
+ const { path, httpMethod, validation } = handlerSchema;
32
+ const getEndpoint = ({ apiRoot, params, query, }) => {
33
+ apiRoot ??= options?.apiRoot ?? '/api';
34
+ const endpoint = [
35
+ apiRoot.startsWith('http://') || apiRoot.startsWith('https://') || apiRoot.startsWith('/') ? '' : '/',
36
+ apiRoot,
37
+ segmentNamePath,
38
+ getHandlerPath([controllerPrefix, path].filter(Boolean).join('/'), params, query),
39
+ ]
40
+ .filter(Boolean)
41
+ .join('/');
42
+ return endpoint;
43
+ };
44
+ const handler = (input = {}) => {
45
+ const validate = async ({ body, query, params, endpoint, }) => {
46
+ const validateOnClient = input.validateOnClient ?? options?.validateOnClient;
47
+ if (validateOnClient && validation) {
48
+ if (typeof validateOnClient !== 'function') {
49
+ throw new Error('validateOnClient must be a function');
50
+ }
51
+ await validateOnClient({ body, query, params, endpoint }, validation, schema);
52
+ }
53
+ };
54
+ const internalOptions = {
55
+ name: staticMethodName,
56
+ httpMethod: httpMethod,
57
+ getEndpoint,
58
+ validate,
59
+ defaultHandler: defaultHandler_js_1.defaultHandler,
60
+ defaultStreamHandler: defaultStreamHandler_js_1.defaultStreamHandler,
61
+ };
62
+ const internalInput = {
63
+ ...options,
64
+ ...input,
65
+ body: input.body ?? null,
66
+ query: input.query ?? {},
67
+ params: input.params ?? {},
68
+ };
69
+ if (!fetcher)
70
+ throw new Error('Fetcher is not provided');
71
+ const fetcherPromise = fetcher(internalOptions, internalInput);
72
+ if (!(fetcherPromise instanceof Promise))
73
+ return Promise.resolve(fetcherPromise);
74
+ return input.transform ? fetcherPromise.then(input.transform) : fetcherPromise;
75
+ };
76
+ handler.schema = handlerSchema;
77
+ handler.controllerSchema = controllerSchema;
78
+ handler.segmentSchema = segmentSchema;
79
+ handler.fullSchema = schema;
80
+ handler.isRPC = true;
81
+ handler.path = [segmentNamePath, controllerPrefix, path].filter(Boolean).join('/');
82
+ // @ts-expect-error TODO
83
+ client[staticMethodName] = handler;
84
+ }
85
+ return client;
86
+ };
87
+ exports.createRPC = createRPC;
@@ -1,2 +1,2 @@
1
1
  export declare const DEFAULT_ERROR_MESSAGE = "Unknown error at defaultHandler";
2
- export declare const _defaultHandler: (response: Response) => Promise<unknown>;
2
+ export declare const defaultHandler: (response: Response) => Promise<unknown>;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultHandler = exports.DEFAULT_ERROR_MESSAGE = void 0;
4
+ const HttpException_js_1 = require("../HttpException.js");
5
+ exports.DEFAULT_ERROR_MESSAGE = 'Unknown error at defaultHandler';
6
+ const defaultHandler = async (response) => {
7
+ let result;
8
+ try {
9
+ result = await response.json();
10
+ }
11
+ catch (e) {
12
+ // handle parsing errors
13
+ throw new HttpException_js_1.HttpException(response.status, e?.message ?? exports.DEFAULT_ERROR_MESSAGE);
14
+ }
15
+ if (!response.ok) {
16
+ // handle server errors
17
+ const errorResponse = result;
18
+ throw new HttpException_js_1.HttpException(response.status, errorResponse?.message ?? exports.DEFAULT_ERROR_MESSAGE, errorResponse?.cause);
19
+ }
20
+ return result;
21
+ };
22
+ exports.defaultHandler = defaultHandler;
@@ -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>>;
@@ -1,11 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._defaultStreamHandler = exports.DEFAULT_ERROR_MESSAGE = void 0;
4
- const types_1 = require("../types");
5
- const HttpException_1 = require("../HttpException");
6
- require("../utils/shim");
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
7
  exports.DEFAULT_ERROR_MESSAGE = 'Unknown error at defaultStreamHandler';
8
- const _defaultStreamHandler = async (response) => {
8
+ const defaultStreamHandler = async (response) => {
9
9
  if (!response.ok) {
10
10
  let result;
11
11
  try {
@@ -15,10 +15,10 @@ const _defaultStreamHandler = async (response) => {
15
15
  // ignore parsing errors
16
16
  }
17
17
  // handle server errors
18
- throw new HttpException_1._HttpException(response.status, result.message ?? exports.DEFAULT_ERROR_MESSAGE);
18
+ throw new HttpException_js_1.HttpException(response.status, result.message ?? exports.DEFAULT_ERROR_MESSAGE);
19
19
  }
20
20
  if (!response.body)
21
- throw new HttpException_1._HttpException(types_1._HttpStatus.NULL, 'Stream body is falsy. Check your controller code.');
21
+ throw new HttpException_js_1.HttpException(types_js_1.HttpStatus.NULL, 'Stream body is falsy. Check your controller code.');
22
22
  const reader = response.body.getReader();
23
23
  // if streaming is too rapid, we need to make sure that the loop is stopped
24
24
  let canceled = false;
@@ -26,9 +26,11 @@ const _defaultStreamHandler = async (response) => {
26
26
  let prepend = '';
27
27
  while (true) {
28
28
  let value;
29
- let done = false;
30
29
  try {
30
+ let done;
31
31
  ({ value, done } = await reader.read());
32
+ if (done)
33
+ break;
32
34
  }
33
35
  catch (error) {
34
36
  await reader.cancel();
@@ -36,9 +38,6 @@ const _defaultStreamHandler = async (response) => {
36
38
  err.cause = error;
37
39
  throw err;
38
40
  }
39
- if (done) {
40
- return;
41
- }
42
41
  // typeof value === 'number' is a workaround for React Native
43
42
  const string = typeof value === 'number' ? String.fromCharCode(value) : new TextDecoder().decode(value);
44
43
  prepend += string;
@@ -79,4 +78,4 @@ const _defaultStreamHandler = async (response) => {
79
78
  },
80
79
  };
81
80
  };
82
- exports._defaultStreamHandler = _defaultStreamHandler;
81
+ exports.defaultStreamHandler = defaultStreamHandler;
@@ -0,0 +1,13 @@
1
+ import type { VovkDefaultFetcherOptions, VovkClientFetcher } from './types.js';
2
+ export declare const DEFAULT_ERROR_MESSAGE = "Unknown error at default fetcher";
3
+ export declare function createFetcher<T>({ prepareRequestInit, transformResponse, }?: {
4
+ prepareRequestInit?: (init: RequestInit, options: VovkDefaultFetcherOptions<T>) => RequestInit | Promise<RequestInit> | void | Promise<void>;
5
+ transformResponse?: (resp: unknown, options: VovkDefaultFetcherOptions<T>, init: RequestInit) => unknown;
6
+ }): VovkClientFetcher<VovkDefaultFetcherOptions<T>>;
7
+ export declare const fetcher: VovkClientFetcher<{
8
+ apiRoot?: string;
9
+ disableClientValidation?: boolean;
10
+ validateOnClient?: import("./types.js").VovkValidateOnClient;
11
+ interpretAs?: string;
12
+ init?: RequestInit;
13
+ }>;