@orpc/standard-server-node 0.0.0-next.00fb0f4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 oRPC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ <div align="center">
2
+ <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
3
+ </div>
4
+
5
+ <h1></h1>
6
+
7
+ <div align="center">
8
+ <a href="https://codecov.io/gh/unnoq/orpc">
9
+ <img alt="codecov" src="https://codecov.io/gh/unnoq/orpc/branch/main/graph/badge.svg">
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@orpc/standard-server-node">
12
+ <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fstandard-server-node?logo=npm" />
13
+ </a>
14
+ <a href="https://github.com/unnoq/orpc/blob/main/LICENSE">
15
+ <img alt="MIT License" src="https://img.shields.io/github/license/unnoq/orpc?logo=open-source-initiative" />
16
+ </a>
17
+ <a href="https://discord.gg/TXEbwRBvQn">
18
+ <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
19
+ </a>
20
+ </div>
21
+
22
+ <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
+
24
+ **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards, ensuring a smooth and enjoyable developer experience.
25
+
26
+ ---
27
+
28
+ ## Highlights
29
+
30
+ - **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly.
31
+ - **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation.
32
+ - **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence.
33
+ - **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation.
34
+ - **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more.
35
+ - **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue, Solid, Svelte), Pinia Colada, and more.
36
+ - **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more.
37
+ - **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box.
38
+ - **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency.
39
+ - **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup.
40
+ - **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature.
41
+ - **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses.
42
+ - **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly.
43
+ - **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors.
44
+ - **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind.
45
+ - **Simplicity 💡**: Enjoy straightforward, clean code with no hidden magic.
46
+
47
+ ## Documentation
48
+
49
+ You can find the full documentation [here](https://orpc.unnoq.com).
50
+
51
+ ## Packages
52
+
53
+ - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
+ - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
+ - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
56
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
57
+ - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
58
+ - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
59
+ - [@orpc/solid-query](https://www.npmjs.com/package/@orpc/solid-query): Integration with [Solid Query](https://tanstack.com/query/latest/docs/framework/solid/overview).
60
+ - [@orpc/svelte-query](https://www.npmjs.com/package/@orpc/svelte-query): Integration with [Svelte Query](https://tanstack.com/query/latest/docs/framework/svelte/overview).
61
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
62
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
63
+ - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
64
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
65
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
66
+
67
+ ## `@orpc/standard-server-node`
68
+
69
+ [Node.js](https://nodejs.org) server adapter for oRPC.
70
+
71
+ ## Sponsors
72
+
73
+ <p align="center">
74
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
75
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
76
+ </a>
77
+ </p>
78
+
79
+ ## License
80
+
81
+ Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,56 @@
1
+ import { StandardBody, StandardHeaders, StandardLazyRequest, StandardResponse } from '@orpc/standard-server';
2
+ import { Readable } from 'node:stream';
3
+ import { IncomingMessage, ServerResponse } from 'node:http';
4
+ import { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
5
+
6
+ declare function toEventIterator(stream: Readable): AsyncGenerator<unknown | void, unknown | void, void>;
7
+ interface ToEventStreamOptions {
8
+ /**
9
+ * If true, a ping comment is sent periodically to keep the connection alive.
10
+ *
11
+ * @default true
12
+ */
13
+ eventIteratorKeepAliveEnabled?: boolean;
14
+ /**
15
+ * Interval (in milliseconds) between ping comments sent after the last event.
16
+ *
17
+ * @default 5000
18
+ */
19
+ eventIteratorKeepAliveInterval?: number;
20
+ /**
21
+ * The content of the ping comment. Must not include newline characters.
22
+ *
23
+ * @default ''
24
+ */
25
+ eventIteratorKeepAliveComment?: string;
26
+ }
27
+ declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): Readable;
28
+
29
+ type NodeHttpRequest = (IncomingMessage | Http2ServerRequest) & {
30
+ /**
31
+ * Replace `req.url` with `req.originalUrl` when `req.originalUrl` is available.
32
+ * This is useful for `express.js` middleware.
33
+ */
34
+ originalUrl?: string;
35
+ };
36
+ type NodeHttpResponse = ServerResponse | Http2ServerResponse;
37
+
38
+ declare function toStandardBody(req: NodeHttpRequest): Promise<StandardBody>;
39
+ interface ToNodeHttpBodyOptions extends ToEventStreamOptions {
40
+ }
41
+ /**
42
+ * @param body
43
+ * @param headers - WARNING: The headers can be changed by the function and effects on the original headers.
44
+ * @param options
45
+ */
46
+ declare function toNodeHttpBody(body: StandardBody, headers: StandardHeaders, options?: ToNodeHttpBodyOptions): Readable | undefined | string;
47
+
48
+ declare function toStandardLazyRequest(req: NodeHttpRequest, res: NodeHttpResponse): StandardLazyRequest;
49
+
50
+ interface SendStandardResponseOptions extends ToNodeHttpBodyOptions {
51
+ }
52
+ declare function sendStandardResponse(res: NodeHttpResponse, standardResponse: StandardResponse, options?: SendStandardResponseOptions): Promise<void>;
53
+
54
+ declare function toAbortSignal(res: NodeHttpResponse): AbortSignal;
55
+
56
+ export { type NodeHttpRequest, type NodeHttpResponse, type SendStandardResponseOptions, type ToEventStreamOptions, type ToNodeHttpBodyOptions, sendStandardResponse, toAbortSignal, toEventIterator, toEventStream, toNodeHttpBody, toStandardBody, toStandardLazyRequest };
@@ -0,0 +1,56 @@
1
+ import { StandardBody, StandardHeaders, StandardLazyRequest, StandardResponse } from '@orpc/standard-server';
2
+ import { Readable } from 'node:stream';
3
+ import { IncomingMessage, ServerResponse } from 'node:http';
4
+ import { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
5
+
6
+ declare function toEventIterator(stream: Readable): AsyncGenerator<unknown | void, unknown | void, void>;
7
+ interface ToEventStreamOptions {
8
+ /**
9
+ * If true, a ping comment is sent periodically to keep the connection alive.
10
+ *
11
+ * @default true
12
+ */
13
+ eventIteratorKeepAliveEnabled?: boolean;
14
+ /**
15
+ * Interval (in milliseconds) between ping comments sent after the last event.
16
+ *
17
+ * @default 5000
18
+ */
19
+ eventIteratorKeepAliveInterval?: number;
20
+ /**
21
+ * The content of the ping comment. Must not include newline characters.
22
+ *
23
+ * @default ''
24
+ */
25
+ eventIteratorKeepAliveComment?: string;
26
+ }
27
+ declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): Readable;
28
+
29
+ type NodeHttpRequest = (IncomingMessage | Http2ServerRequest) & {
30
+ /**
31
+ * Replace `req.url` with `req.originalUrl` when `req.originalUrl` is available.
32
+ * This is useful for `express.js` middleware.
33
+ */
34
+ originalUrl?: string;
35
+ };
36
+ type NodeHttpResponse = ServerResponse | Http2ServerResponse;
37
+
38
+ declare function toStandardBody(req: NodeHttpRequest): Promise<StandardBody>;
39
+ interface ToNodeHttpBodyOptions extends ToEventStreamOptions {
40
+ }
41
+ /**
42
+ * @param body
43
+ * @param headers - WARNING: The headers can be changed by the function and effects on the original headers.
44
+ * @param options
45
+ */
46
+ declare function toNodeHttpBody(body: StandardBody, headers: StandardHeaders, options?: ToNodeHttpBodyOptions): Readable | undefined | string;
47
+
48
+ declare function toStandardLazyRequest(req: NodeHttpRequest, res: NodeHttpResponse): StandardLazyRequest;
49
+
50
+ interface SendStandardResponseOptions extends ToNodeHttpBodyOptions {
51
+ }
52
+ declare function sendStandardResponse(res: NodeHttpResponse, standardResponse: StandardResponse, options?: SendStandardResponseOptions): Promise<void>;
53
+
54
+ declare function toAbortSignal(res: NodeHttpResponse): AbortSignal;
55
+
56
+ export { type NodeHttpRequest, type NodeHttpResponse, type SendStandardResponseOptions, type ToEventStreamOptions, type ToNodeHttpBodyOptions, sendStandardResponse, toAbortSignal, toEventIterator, toEventStream, toNodeHttpBody, toStandardBody, toStandardLazyRequest };
package/dist/index.mjs ADDED
@@ -0,0 +1,230 @@
1
+ import { Readable } from 'node:stream';
2
+ import { stringifyJSON, parseEmptyableJSON, isTypescriptObject, isAsyncIteratorObject, once } from '@orpc/shared';
3
+ import { EventDecoderStream, encodeEventMessage, getEventMeta, ErrorEvent, withEventMeta, parseContentDisposition, contentDisposition } from '@orpc/standard-server';
4
+
5
+ function toEventIterator(stream) {
6
+ const eventStream = Readable.toWeb(stream).pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());
7
+ const reader = eventStream.getReader();
8
+ async function* gen() {
9
+ try {
10
+ while (true) {
11
+ const { done, value } = await reader.read();
12
+ if (done) {
13
+ return;
14
+ }
15
+ switch (value.event) {
16
+ case "message": {
17
+ let message = parseEmptyableJSON(value.data);
18
+ if (isTypescriptObject(message)) {
19
+ message = withEventMeta(message, value);
20
+ }
21
+ yield message;
22
+ break;
23
+ }
24
+ case "error": {
25
+ let error = new ErrorEvent({
26
+ data: parseEmptyableJSON(value.data)
27
+ });
28
+ error = withEventMeta(error, value);
29
+ throw error;
30
+ }
31
+ case "done": {
32
+ let done2 = parseEmptyableJSON(value.data);
33
+ if (isTypescriptObject(done2)) {
34
+ done2 = withEventMeta(done2, value);
35
+ }
36
+ return done2;
37
+ }
38
+ }
39
+ }
40
+ } finally {
41
+ await reader.cancel();
42
+ }
43
+ }
44
+ return gen();
45
+ }
46
+ function toEventStream(iterator, options = {}) {
47
+ const keepAliveEnabled = options.eventIteratorKeepAliveEnabled ?? true;
48
+ const keepAliveInterval = options.eventIteratorKeepAliveInterval ?? 5e3;
49
+ const keepAliveComment = options.eventIteratorKeepAliveComment ?? "";
50
+ let timeout;
51
+ const stream = new ReadableStream({
52
+ async pull(controller) {
53
+ try {
54
+ if (keepAliveEnabled) {
55
+ timeout = setInterval(() => {
56
+ controller.enqueue(encodeEventMessage({
57
+ comments: [keepAliveComment]
58
+ }));
59
+ }, keepAliveInterval);
60
+ }
61
+ const value = await iterator.next();
62
+ clearInterval(timeout);
63
+ controller.enqueue(encodeEventMessage({
64
+ ...getEventMeta(value.value),
65
+ event: value.done ? "done" : "message",
66
+ data: stringifyJSON(value.value)
67
+ }));
68
+ if (value.done) {
69
+ controller.close();
70
+ }
71
+ } catch (err) {
72
+ clearInterval(timeout);
73
+ controller.enqueue(encodeEventMessage({
74
+ ...getEventMeta(err),
75
+ event: "error",
76
+ data: err instanceof ErrorEvent ? stringifyJSON(err.data) : void 0
77
+ }));
78
+ controller.close();
79
+ }
80
+ },
81
+ async cancel(reason) {
82
+ if (reason) {
83
+ await iterator.throw?.(reason);
84
+ } else {
85
+ await iterator.return?.();
86
+ }
87
+ }
88
+ });
89
+ return Readable.fromWeb(stream);
90
+ }
91
+
92
+ async function toStandardBody(req) {
93
+ const method = req.method ?? "GET";
94
+ if (method === "GET" || method === "HEAD") {
95
+ return void 0;
96
+ }
97
+ const contentDisposition2 = req.headers["content-disposition"];
98
+ const contentType = req.headers["content-type"];
99
+ if (contentDisposition2) {
100
+ const fileName = parseContentDisposition(contentDisposition2).parameters.filename;
101
+ if (typeof fileName === "string") {
102
+ return _streamToFile(req, fileName, contentType ?? "");
103
+ }
104
+ }
105
+ if (!contentType || contentType.startsWith("application/json")) {
106
+ const text = await _streamToString(req);
107
+ return parseEmptyableJSON(text);
108
+ }
109
+ if (contentType.startsWith("multipart/form-data")) {
110
+ return _streamToFormData(req, contentType);
111
+ }
112
+ if (contentType.startsWith("application/x-www-form-urlencoded")) {
113
+ const text = await _streamToString(req);
114
+ return new URLSearchParams(text);
115
+ }
116
+ if (contentType.startsWith("text/event-stream")) {
117
+ return toEventIterator(req);
118
+ }
119
+ if (contentType.startsWith("text/plain")) {
120
+ return _streamToString(req);
121
+ }
122
+ return _streamToFile(req, "blob", contentType);
123
+ }
124
+ function toNodeHttpBody(body, headers, options = {}) {
125
+ delete headers["content-type"];
126
+ delete headers["content-disposition"];
127
+ if (body === void 0) {
128
+ return;
129
+ }
130
+ if (body instanceof Blob) {
131
+ headers["content-type"] = body.type;
132
+ headers["content-length"] = body.size.toString();
133
+ headers["content-disposition"] = contentDisposition(
134
+ body instanceof File ? body.name : "blob",
135
+ { type: "inline" }
136
+ );
137
+ return Readable.fromWeb(body.stream());
138
+ }
139
+ if (body instanceof FormData) {
140
+ const response = new Response(body);
141
+ headers["content-type"] = response.headers.get("content-type");
142
+ return Readable.fromWeb(response.body);
143
+ }
144
+ if (body instanceof URLSearchParams) {
145
+ headers["content-type"] = "application/x-www-form-urlencoded";
146
+ return body.toString();
147
+ }
148
+ if (isAsyncIteratorObject(body)) {
149
+ headers["content-type"] = "text/event-stream";
150
+ headers["cache-control"] = "no-cache";
151
+ headers.connection = "keep-alive";
152
+ return toEventStream(body, options);
153
+ }
154
+ headers["content-type"] = "application/json";
155
+ return stringifyJSON(body);
156
+ }
157
+ function _streamToFormData(stream, contentType) {
158
+ const response = new Response(stream, {
159
+ headers: {
160
+ "content-type": contentType
161
+ }
162
+ });
163
+ return response.formData();
164
+ }
165
+ async function _streamToString(stream) {
166
+ let string = "";
167
+ for await (const chunk of stream) {
168
+ string += chunk.toString();
169
+ }
170
+ return string;
171
+ }
172
+ async function _streamToFile(stream, fileName, contentType) {
173
+ const chunks = [];
174
+ for await (const chunk of stream) {
175
+ chunks.push(chunk);
176
+ }
177
+ return new File(chunks, fileName, { type: contentType });
178
+ }
179
+
180
+ function toAbortSignal(res) {
181
+ const controller = new AbortController();
182
+ res.on("close", () => {
183
+ if (res.errored) {
184
+ controller.abort(res.errored.toString());
185
+ } else if (!res.writableFinished) {
186
+ controller.abort("Client connection prematurely closed.");
187
+ } else {
188
+ controller.abort("Server closed the connection.");
189
+ }
190
+ });
191
+ return controller.signal;
192
+ }
193
+
194
+ function toStandardLazyRequest(req, res) {
195
+ const method = req.method ?? "GET";
196
+ const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https:" : "http:";
197
+ const host = req.headers.host ?? "localhost";
198
+ const url = new URL(req.originalUrl ?? req.url ?? "/", `${protocol}//${host}`);
199
+ return {
200
+ method,
201
+ url,
202
+ headers: req.headers,
203
+ body: once(() => toStandardBody(req)),
204
+ signal: toAbortSignal(res)
205
+ };
206
+ }
207
+
208
+ function sendStandardResponse(res, standardResponse, options = {}) {
209
+ return new Promise((resolve, reject) => {
210
+ res.on("error", reject);
211
+ res.on("finish", resolve);
212
+ const resHeaders = standardResponse.headers;
213
+ const resBody = toNodeHttpBody(standardResponse.body, resHeaders, options);
214
+ res.writeHead(standardResponse.status, resHeaders);
215
+ if (resBody === void 0) {
216
+ res.end(resBody);
217
+ } else if (typeof resBody === "string") {
218
+ res.end(resBody);
219
+ } else {
220
+ res.on("close", () => {
221
+ if (!resBody.closed) {
222
+ resBody.destroy(res.errored ?? void 0);
223
+ }
224
+ });
225
+ resBody.pipe(res);
226
+ }
227
+ });
228
+ }
229
+
230
+ export { sendStandardResponse, toAbortSignal, toEventIterator, toEventStream, toNodeHttpBody, toStandardBody, toStandardLazyRequest };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@orpc/standard-server-node",
3
+ "type": "module",
4
+ "version": "0.0.0-next.00fb0f4",
5
+ "license": "MIT",
6
+ "homepage": "https://orpc.unnoq.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/unnoq/orpc.git",
10
+ "directory": "packages/standard-server-node"
11
+ },
12
+ "keywords": [
13
+ "orpc"
14
+ ],
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.mts",
18
+ "import": "./dist/index.mjs",
19
+ "default": "./dist/index.mjs"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "dependencies": {
26
+ "@orpc/shared": "0.0.0-next.00fb0f4",
27
+ "@orpc/standard-server": "0.0.0-next.00fb0f4"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^22.13.1",
31
+ "@types/supertest": "^6.0.2",
32
+ "supertest": "^7.0.0"
33
+ },
34
+ "scripts": {
35
+ "build": "unbuild",
36
+ "build:watch": "pnpm run build --watch",
37
+ "type:check": "tsc -b"
38
+ }
39
+ }