@orpc/standard-server-fetch 0.0.0-next.fea68c1 → 0.0.0-next.ff2168f

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/README.md CHANGED
@@ -1,68 +1,81 @@
1
1
  <div align="center">
2
- <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 />
2
+ <image align="center" src="https://orpc.dev/logo.webp" width=280 alt="oRPC logo" />
3
3
  </div>
4
4
 
5
5
  <h1></h1>
6
6
 
7
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">
8
+ <a href="https://codecov.io/gh/middleapi/orpc">
9
+ <img alt="codecov" src="https://codecov.io/gh/middleapi/orpc/branch/main/graph/badge.svg">
10
10
  </a>
11
11
  <a href="https://www.npmjs.com/package/@orpc/standard-server-fetch">
12
12
  <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fstandard-server-fetch?logo=npm" />
13
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" />
14
+ <a href="https://github.com/middleapi/orpc/blob/main/LICENSE">
15
+ <img alt="MIT License" src="https://img.shields.io/github/license/middleapi/orpc?logo=open-source-initiative" />
16
16
  </a>
17
17
  <a href="https://discord.gg/TXEbwRBvQn">
18
18
  <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
19
19
  </a>
20
+ <a href="https://deepwiki.com/middleapi/orpc">
21
+ <img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki">
22
+ </a>
20
23
  </div>
21
24
 
22
25
  <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
26
 
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.
27
+ **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
25
28
 
26
29
  ---
27
30
 
28
31
  ## Highlights
29
32
 
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), 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.
33
+ - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
34
+ - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
35
+ - **📝 Contract-First Development**: Optionally define your API contract before implementation.
36
+ - **🔍 First-Class OpenTelemetry**: Seamlessly integrate with OpenTelemetry for observability.
37
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), SWR, Pinia Colada, and more.
38
+ - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
39
+ - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
40
+ - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
41
+ - **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature.
42
+ - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
43
+ - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
44
+ - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
46
45
 
47
46
  ## Documentation
48
47
 
49
- You can find the full documentation [here](https://orpc.unnoq.com).
48
+ You can find the full documentation [here](https://orpc.dev).
50
49
 
51
50
  ## Packages
52
51
 
53
52
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
53
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
54
  - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
56
- - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
57
- - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
58
- - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
59
55
  - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
56
+ - [@orpc/otel](https://www.npmjs.com/package/@orpc/otel): [OpenTelemetry](https://opentelemetry.io/) integration for observability.
57
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
58
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
59
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
60
+ - [@orpc/experimental-react-swr](https://www.npmjs.com/package/@orpc/experimental-react-swr): [SWR](https://swr.vercel.app/) integration.
61
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
62
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
60
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/).
61
66
 
62
67
  ## `@orpc/standard-server-fetch`
63
68
 
64
69
  [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) server adapter for oRPC.
65
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
+
66
79
  ## License
67
80
 
68
- Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
81
+ Distributed under the MIT License. See [LICENSE](https://github.com/middleapi/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,77 @@
1
+ import { StandardBody, StandardHeaders, StandardLazyRequest, StandardRequest, StandardResponse, StandardLazyResponse } from '@orpc/standard-server';
2
+ import { SetSpanErrorOptions, AsyncIteratorClass } from '@orpc/shared';
3
+
4
+ interface ToEventIteratorOptions extends SetSpanErrorOptions {
5
+ }
6
+ declare function toEventIterator(stream: ReadableStream<Uint8Array> | null, options?: ToEventIteratorOptions): AsyncIteratorClass<unknown>;
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
+ * If true, an initial comment is sent immediately upon stream start to flush headers.
28
+ * This allows the receiving side to establish the connection without waiting for the first event.
29
+ *
30
+ * @default true
31
+ */
32
+ eventIteratorInitialCommentEnabled?: boolean;
33
+ /**
34
+ * The content of the initial comment sent upon stream start. Must not include newline characters.
35
+ *
36
+ * @default ''
37
+ */
38
+ eventIteratorInitialComment?: string;
39
+ }
40
+ declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): ReadableStream<Uint8Array>;
41
+
42
+ interface ToStandardBodyOptions extends ToEventIteratorOptions {
43
+ }
44
+ declare function toStandardBody(re: Request | Response, options?: ToStandardBodyOptions): Promise<StandardBody>;
45
+ interface ToFetchBodyOptions extends ToEventStreamOptions {
46
+ }
47
+ /**
48
+ * @param body
49
+ * @param headers - The headers can be changed by the function and effects on the original headers.
50
+ */
51
+ declare function toFetchBody(body: StandardBody, headers: Headers, options?: ToFetchBodyOptions): string | Blob | FormData | URLSearchParams | undefined | ReadableStream<Uint8Array>;
52
+
53
+ /**
54
+ * @param headers
55
+ * @param standardHeaders - The base headers can be changed by the function and effects on the original headers.
56
+ */
57
+ declare function toStandardHeaders(headers: Headers, standardHeaders?: StandardHeaders): StandardHeaders;
58
+ /**
59
+ * @param headers
60
+ * @param fetchHeaders - The base headers can be changed by the function and effects on the original headers.
61
+ */
62
+ declare function toFetchHeaders(headers: StandardHeaders, fetchHeaders?: Headers): Headers;
63
+
64
+ declare function toStandardLazyRequest(request: Request): StandardLazyRequest;
65
+ interface ToFetchRequestOptions extends ToFetchBodyOptions {
66
+ }
67
+ declare function toFetchRequest(request: StandardRequest, options?: ToFetchRequestOptions): Request;
68
+
69
+ interface ToFetchResponseOptions extends ToFetchBodyOptions {
70
+ }
71
+ declare function toFetchResponse(response: StandardResponse, options?: ToFetchResponseOptions): Response;
72
+ interface ToStandardLazyResponseOptions extends ToStandardBodyOptions {
73
+ }
74
+ declare function toStandardLazyResponse(response: Response, options?: ToStandardLazyResponseOptions): StandardLazyResponse;
75
+
76
+ export { toEventIterator, toEventStream, toFetchBody, toFetchHeaders, toFetchRequest, toFetchResponse, toStandardBody, toStandardHeaders, toStandardLazyRequest, toStandardLazyResponse };
77
+ export type { ToEventIteratorOptions, ToEventStreamOptions, ToFetchBodyOptions, ToFetchRequestOptions, ToFetchResponseOptions, ToStandardBodyOptions, ToStandardLazyResponseOptions };
@@ -0,0 +1,77 @@
1
+ import { StandardBody, StandardHeaders, StandardLazyRequest, StandardRequest, StandardResponse, StandardLazyResponse } from '@orpc/standard-server';
2
+ import { SetSpanErrorOptions, AsyncIteratorClass } from '@orpc/shared';
3
+
4
+ interface ToEventIteratorOptions extends SetSpanErrorOptions {
5
+ }
6
+ declare function toEventIterator(stream: ReadableStream<Uint8Array> | null, options?: ToEventIteratorOptions): AsyncIteratorClass<unknown>;
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
+ * If true, an initial comment is sent immediately upon stream start to flush headers.
28
+ * This allows the receiving side to establish the connection without waiting for the first event.
29
+ *
30
+ * @default true
31
+ */
32
+ eventIteratorInitialCommentEnabled?: boolean;
33
+ /**
34
+ * The content of the initial comment sent upon stream start. Must not include newline characters.
35
+ *
36
+ * @default ''
37
+ */
38
+ eventIteratorInitialComment?: string;
39
+ }
40
+ declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): ReadableStream<Uint8Array>;
41
+
42
+ interface ToStandardBodyOptions extends ToEventIteratorOptions {
43
+ }
44
+ declare function toStandardBody(re: Request | Response, options?: ToStandardBodyOptions): Promise<StandardBody>;
45
+ interface ToFetchBodyOptions extends ToEventStreamOptions {
46
+ }
47
+ /**
48
+ * @param body
49
+ * @param headers - The headers can be changed by the function and effects on the original headers.
50
+ */
51
+ declare function toFetchBody(body: StandardBody, headers: Headers, options?: ToFetchBodyOptions): string | Blob | FormData | URLSearchParams | undefined | ReadableStream<Uint8Array>;
52
+
53
+ /**
54
+ * @param headers
55
+ * @param standardHeaders - The base headers can be changed by the function and effects on the original headers.
56
+ */
57
+ declare function toStandardHeaders(headers: Headers, standardHeaders?: StandardHeaders): StandardHeaders;
58
+ /**
59
+ * @param headers
60
+ * @param fetchHeaders - The base headers can be changed by the function and effects on the original headers.
61
+ */
62
+ declare function toFetchHeaders(headers: StandardHeaders, fetchHeaders?: Headers): Headers;
63
+
64
+ declare function toStandardLazyRequest(request: Request): StandardLazyRequest;
65
+ interface ToFetchRequestOptions extends ToFetchBodyOptions {
66
+ }
67
+ declare function toFetchRequest(request: StandardRequest, options?: ToFetchRequestOptions): Request;
68
+
69
+ interface ToFetchResponseOptions extends ToFetchBodyOptions {
70
+ }
71
+ declare function toFetchResponse(response: StandardResponse, options?: ToFetchResponseOptions): Response;
72
+ interface ToStandardLazyResponseOptions extends ToStandardBodyOptions {
73
+ }
74
+ declare function toStandardLazyResponse(response: Response, options?: ToStandardLazyResponseOptions): StandardLazyResponse;
75
+
76
+ export { toEventIterator, toEventStream, toFetchBody, toFetchHeaders, toFetchRequest, toFetchResponse, toStandardBody, toStandardHeaders, toStandardLazyRequest, toStandardLazyResponse };
77
+ export type { ToEventIteratorOptions, ToEventStreamOptions, ToFetchBodyOptions, ToFetchRequestOptions, ToFetchResponseOptions, ToStandardBodyOptions, ToStandardLazyResponseOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,297 @@
1
+ import { AsyncIteratorClass, startSpan, runInSpanContext, AbortError, parseEmptyableJSON, isTypescriptObject, setSpanError, stringifyJSON, runWithSpan, isAsyncIteratorObject, once } from '@orpc/shared';
2
+ import { EventDecoderStream, withEventMeta, ErrorEvent, encodeEventMessage, getEventMeta, getFilenameFromContentDisposition, generateContentDisposition } from '@orpc/standard-server';
3
+
4
+ function toEventIterator(stream, options = {}) {
5
+ const eventStream = stream?.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());
6
+ const reader = eventStream?.getReader();
7
+ let span;
8
+ let isCancelled = false;
9
+ return new AsyncIteratorClass(async () => {
10
+ span ??= startSpan("consume_event_iterator_stream");
11
+ try {
12
+ while (true) {
13
+ if (reader === void 0) {
14
+ return { done: true, value: void 0 };
15
+ }
16
+ const { done, value } = await runInSpanContext(span, () => reader.read());
17
+ if (done) {
18
+ if (isCancelled) {
19
+ throw new AbortError("Stream was cancelled");
20
+ }
21
+ return { done: true, value: void 0 };
22
+ }
23
+ switch (value.event) {
24
+ case "message": {
25
+ let message = parseEmptyableJSON(value.data);
26
+ if (isTypescriptObject(message)) {
27
+ message = withEventMeta(message, value);
28
+ }
29
+ span?.addEvent("message");
30
+ return { done: false, value: message };
31
+ }
32
+ case "error": {
33
+ let error = new ErrorEvent({
34
+ data: parseEmptyableJSON(value.data)
35
+ });
36
+ error = withEventMeta(error, value);
37
+ span?.addEvent("error");
38
+ throw error;
39
+ }
40
+ case "done": {
41
+ let done2 = parseEmptyableJSON(value.data);
42
+ if (isTypescriptObject(done2)) {
43
+ done2 = withEventMeta(done2, value);
44
+ }
45
+ span?.addEvent("done");
46
+ return { done: true, value: done2 };
47
+ }
48
+ default: {
49
+ span?.addEvent("maybe_keepalive");
50
+ }
51
+ }
52
+ }
53
+ } catch (e) {
54
+ if (!(e instanceof ErrorEvent)) {
55
+ setSpanError(span, e, options);
56
+ }
57
+ throw e;
58
+ }
59
+ }, async (reason) => {
60
+ try {
61
+ if (reason !== "next") {
62
+ isCancelled = true;
63
+ span?.addEvent("cancelled");
64
+ }
65
+ await runInSpanContext(span, () => reader?.cancel());
66
+ } catch (e) {
67
+ setSpanError(span, e, options);
68
+ throw e;
69
+ } finally {
70
+ span?.end();
71
+ }
72
+ });
73
+ }
74
+ function toEventStream(iterator, options = {}) {
75
+ const keepAliveEnabled = options.eventIteratorKeepAliveEnabled ?? true;
76
+ const keepAliveInterval = options.eventIteratorKeepAliveInterval ?? 5e3;
77
+ const keepAliveComment = options.eventIteratorKeepAliveComment ?? "";
78
+ const initialCommentEnabled = options.eventIteratorInitialCommentEnabled ?? true;
79
+ const initialComment = options.eventIteratorInitialComment ?? "";
80
+ let cancelled = false;
81
+ let timeout;
82
+ let span;
83
+ const stream = new ReadableStream({
84
+ start(controller) {
85
+ span = startSpan("stream_event_iterator");
86
+ if (initialCommentEnabled) {
87
+ controller.enqueue(encodeEventMessage({
88
+ comments: [initialComment]
89
+ }));
90
+ }
91
+ },
92
+ async pull(controller) {
93
+ try {
94
+ if (keepAliveEnabled) {
95
+ timeout = setInterval(() => {
96
+ controller.enqueue(encodeEventMessage({
97
+ comments: [keepAliveComment]
98
+ }));
99
+ span?.addEvent("keepalive");
100
+ }, keepAliveInterval);
101
+ }
102
+ const value = await runInSpanContext(span, () => iterator.next());
103
+ clearInterval(timeout);
104
+ if (cancelled) {
105
+ return;
106
+ }
107
+ const meta = getEventMeta(value.value);
108
+ if (!value.done || value.value !== void 0 || meta !== void 0) {
109
+ const event = value.done ? "done" : "message";
110
+ controller.enqueue(encodeEventMessage({
111
+ ...meta,
112
+ event,
113
+ data: stringifyJSON(value.value)
114
+ }));
115
+ span?.addEvent(event);
116
+ }
117
+ if (value.done) {
118
+ controller.close();
119
+ span?.end();
120
+ }
121
+ } catch (err) {
122
+ clearInterval(timeout);
123
+ if (cancelled) {
124
+ return;
125
+ }
126
+ if (err instanceof ErrorEvent) {
127
+ controller.enqueue(encodeEventMessage({
128
+ ...getEventMeta(err),
129
+ event: "error",
130
+ data: stringifyJSON(err.data)
131
+ }));
132
+ span?.addEvent("error");
133
+ controller.close();
134
+ } else {
135
+ setSpanError(span, err);
136
+ controller.error(err);
137
+ }
138
+ span?.end();
139
+ }
140
+ },
141
+ async cancel() {
142
+ try {
143
+ cancelled = true;
144
+ clearInterval(timeout);
145
+ span?.addEvent("cancelled");
146
+ await runInSpanContext(span, () => iterator.return?.());
147
+ } catch (e) {
148
+ setSpanError(span, e);
149
+ throw e;
150
+ } finally {
151
+ span?.end();
152
+ }
153
+ }
154
+ }).pipeThrough(new TextEncoderStream());
155
+ return stream;
156
+ }
157
+
158
+ function toStandardBody(re, options = {}) {
159
+ return runWithSpan(
160
+ { name: "parse_standard_body", signal: options.signal },
161
+ async () => {
162
+ const contentDisposition = re.headers.get("content-disposition");
163
+ if (typeof contentDisposition === "string") {
164
+ const fileName = getFilenameFromContentDisposition(contentDisposition) ?? "blob";
165
+ const blob2 = await re.blob();
166
+ return new File([blob2], fileName, {
167
+ type: blob2.type
168
+ });
169
+ }
170
+ const contentType = re.headers.get("content-type");
171
+ if (!contentType || contentType.startsWith("application/json")) {
172
+ const text = await re.text();
173
+ return parseEmptyableJSON(text);
174
+ }
175
+ if (contentType.startsWith("multipart/form-data")) {
176
+ return await re.formData();
177
+ }
178
+ if (contentType.startsWith("application/x-www-form-urlencoded")) {
179
+ const text = await re.text();
180
+ return new URLSearchParams(text);
181
+ }
182
+ if (contentType.startsWith("text/event-stream")) {
183
+ return toEventIterator(re.body, options);
184
+ }
185
+ if (contentType.startsWith("text/plain")) {
186
+ return await re.text();
187
+ }
188
+ const blob = await re.blob();
189
+ return new File([blob], "blob", {
190
+ type: blob.type
191
+ });
192
+ }
193
+ );
194
+ }
195
+ function toFetchBody(body, headers, options = {}) {
196
+ const currentContentDisposition = headers.get("content-disposition");
197
+ headers.delete("content-type");
198
+ headers.delete("content-disposition");
199
+ if (body === void 0) {
200
+ return void 0;
201
+ }
202
+ if (body instanceof Blob) {
203
+ headers.set("content-type", body.type);
204
+ headers.set("content-length", body.size.toString());
205
+ headers.set(
206
+ "content-disposition",
207
+ currentContentDisposition ?? generateContentDisposition(body instanceof File ? body.name : "blob")
208
+ );
209
+ return body;
210
+ }
211
+ if (body instanceof FormData) {
212
+ return body;
213
+ }
214
+ if (body instanceof URLSearchParams) {
215
+ return body;
216
+ }
217
+ if (isAsyncIteratorObject(body)) {
218
+ headers.set("content-type", "text/event-stream");
219
+ return toEventStream(body, options);
220
+ }
221
+ headers.set("content-type", "application/json");
222
+ return stringifyJSON(body);
223
+ }
224
+
225
+ function toStandardHeaders(headers, standardHeaders = {}) {
226
+ headers.forEach((value, key) => {
227
+ if (Array.isArray(standardHeaders[key])) {
228
+ standardHeaders[key].push(value);
229
+ } else if (standardHeaders[key] !== void 0) {
230
+ standardHeaders[key] = [standardHeaders[key], value];
231
+ } else {
232
+ standardHeaders[key] = value;
233
+ }
234
+ });
235
+ return standardHeaders;
236
+ }
237
+ function toFetchHeaders(headers, fetchHeaders = new Headers()) {
238
+ for (const [key, value] of Object.entries(headers)) {
239
+ if (Array.isArray(value)) {
240
+ for (const v of value) {
241
+ fetchHeaders.append(key, v);
242
+ }
243
+ } else if (value !== void 0) {
244
+ fetchHeaders.append(key, value);
245
+ }
246
+ }
247
+ return fetchHeaders;
248
+ }
249
+
250
+ function toStandardLazyRequest(request) {
251
+ return {
252
+ url: new URL(request.url),
253
+ signal: request.signal,
254
+ method: request.method,
255
+ body: once(() => toStandardBody(request, { signal: request.signal })),
256
+ get headers() {
257
+ const headers = toStandardHeaders(request.headers);
258
+ Object.defineProperty(this, "headers", { value: headers, writable: true });
259
+ return headers;
260
+ },
261
+ set headers(value) {
262
+ Object.defineProperty(this, "headers", { value, writable: true });
263
+ }
264
+ };
265
+ }
266
+ function toFetchRequest(request, options = {}) {
267
+ const headers = toFetchHeaders(request.headers);
268
+ const body = toFetchBody(request.body, headers, options);
269
+ return new Request(request.url, {
270
+ signal: request.signal,
271
+ method: request.method,
272
+ headers,
273
+ body
274
+ });
275
+ }
276
+
277
+ function toFetchResponse(response, options = {}) {
278
+ const headers = toFetchHeaders(response.headers);
279
+ const body = toFetchBody(response.body, headers, options);
280
+ return new Response(body, { headers, status: response.status });
281
+ }
282
+ function toStandardLazyResponse(response, options = {}) {
283
+ return {
284
+ body: once(() => toStandardBody(response, options)),
285
+ status: response.status,
286
+ get headers() {
287
+ const headers = toStandardHeaders(response.headers);
288
+ Object.defineProperty(this, "headers", { value: headers, writable: true });
289
+ return headers;
290
+ },
291
+ set headers(value) {
292
+ Object.defineProperty(this, "headers", { value, writable: true });
293
+ }
294
+ };
295
+ }
296
+
297
+ export { toEventIterator, toEventStream, toFetchBody, toFetchHeaders, toFetchRequest, toFetchResponse, toStandardBody, toStandardHeaders, toStandardLazyRequest, toStandardLazyResponse };
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@orpc/standard-server-fetch",
3
3
  "type": "module",
4
- "version": "0.0.0-next.fea68c1",
4
+ "version": "0.0.0-next.ff2168f",
5
5
  "license": "MIT",
6
- "homepage": "https://unnoq.com",
6
+ "homepage": "https://orpc.dev",
7
7
  "repository": {
8
8
  "type": "git",
9
- "url": "git+https://github.com/unnoq/orpc.git",
9
+ "url": "git+https://github.com/middleapi/orpc.git",
10
10
  "directory": "packages/standard-server-fetch"
11
11
  },
12
12
  "keywords": [
@@ -14,28 +14,23 @@
14
14
  ],
15
15
  "exports": {
16
16
  ".": {
17
- "types": "./dist/src/index.d.ts",
18
- "import": "./dist/index.js",
19
- "default": "./dist/index.js"
20
- },
21
- "./🔒/*": {
22
- "types": "./dist/src/*.d.ts"
17
+ "types": "./dist/index.d.mts",
18
+ "import": "./dist/index.mjs",
19
+ "default": "./dist/index.mjs"
23
20
  }
24
21
  },
25
22
  "files": [
26
- "!**/*.map",
27
- "!**/*.tsbuildinfo",
28
23
  "dist"
29
24
  ],
30
25
  "dependencies": {
31
- "@orpc/shared": "0.0.0-next.fea68c1",
32
- "@orpc/standard-server": "0.0.0-next.fea68c1"
26
+ "@orpc/shared": "0.0.0-next.ff2168f",
27
+ "@orpc/standard-server": "0.0.0-next.ff2168f"
33
28
  },
34
29
  "devDependencies": {
35
- "@hono/node-server": "^1.13.8"
30
+ "@hono/node-server": "^1.19.9"
36
31
  },
37
32
  "scripts": {
38
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
33
+ "build": "unbuild",
39
34
  "build:watch": "pnpm run build --watch",
40
35
  "type:check": "tsc -b"
41
36
  }
package/dist/index.js DELETED
@@ -1,228 +0,0 @@
1
- // src/body.ts
2
- import { isAsyncIteratorObject, parseEmptyableJSON as parseEmptyableJSON2, stringifyJSON as stringifyJSON2 } from "@orpc/shared";
3
- import { contentDisposition, parseContentDisposition } from "@orpc/standard-server";
4
-
5
- // src/event-source.ts
6
- import { isTypescriptObject, parseEmptyableJSON, stringifyJSON } from "@orpc/shared";
7
- import {
8
- encodeEventMessage,
9
- ErrorEvent,
10
- EventDecoderStream,
11
- getEventMeta,
12
- UnknownEvent,
13
- withEventMeta
14
- } from "@orpc/standard-server";
15
- function toEventIterator(stream) {
16
- const eventStream = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());
17
- const reader = eventStream.getReader();
18
- async function* gen() {
19
- try {
20
- while (true) {
21
- const { done, value } = await reader.read();
22
- if (done) {
23
- return;
24
- }
25
- switch (value.event) {
26
- case "message": {
27
- let message = parseEmptyableJSON(value.data);
28
- if (isTypescriptObject(message)) {
29
- message = withEventMeta(message, value);
30
- }
31
- yield message;
32
- break;
33
- }
34
- case "error": {
35
- let error = new ErrorEvent({
36
- data: parseEmptyableJSON(value.data)
37
- });
38
- error = withEventMeta(error, value);
39
- throw error;
40
- }
41
- case "done": {
42
- let done2 = parseEmptyableJSON(value.data);
43
- if (isTypescriptObject(done2)) {
44
- done2 = withEventMeta(done2, value);
45
- }
46
- return done2;
47
- }
48
- default: {
49
- let error = new UnknownEvent({
50
- message: `Unknown event: ${value.event}`,
51
- data: parseEmptyableJSON(value.data)
52
- });
53
- error = withEventMeta(error, value);
54
- throw error;
55
- }
56
- }
57
- }
58
- } finally {
59
- await reader.cancel();
60
- }
61
- }
62
- return gen();
63
- }
64
- function toEventStream(iterator) {
65
- const stream = new ReadableStream({
66
- async pull(controller) {
67
- try {
68
- const value = await iterator.next();
69
- controller.enqueue(encodeEventMessage({
70
- ...getEventMeta(value.value),
71
- event: value.done ? "done" : "message",
72
- data: stringifyJSON(value.value)
73
- }));
74
- if (value.done) {
75
- controller.close();
76
- }
77
- } catch (err) {
78
- controller.enqueue(encodeEventMessage({
79
- ...getEventMeta(err),
80
- event: "error",
81
- data: err instanceof ErrorEvent ? stringifyJSON(err.data) : void 0
82
- }));
83
- controller.close();
84
- }
85
- },
86
- async cancel(reason) {
87
- if (reason) {
88
- await iterator.throw?.(reason);
89
- } else {
90
- await iterator.return?.();
91
- }
92
- }
93
- }).pipeThrough(new TextEncoderStream());
94
- return stream;
95
- }
96
-
97
- // src/body.ts
98
- async function toStandardBody(re) {
99
- if (!re.body) {
100
- return void 0;
101
- }
102
- const contentDisposition2 = re.headers.get("content-disposition");
103
- if (contentDisposition2) {
104
- const fileName = parseContentDisposition(contentDisposition2).parameters.filename;
105
- if (typeof fileName === "string") {
106
- const blob2 = await re.blob();
107
- return new File([blob2], fileName, {
108
- type: blob2.type
109
- });
110
- }
111
- }
112
- const contentType = re.headers.get("content-type");
113
- if (!contentType || contentType.startsWith("application/json")) {
114
- const text = await re.text();
115
- return parseEmptyableJSON2(text);
116
- }
117
- if (contentType.startsWith("multipart/form-data")) {
118
- return await re.formData();
119
- }
120
- if (contentType.startsWith("application/x-www-form-urlencoded")) {
121
- const text = await re.text();
122
- return new URLSearchParams(text);
123
- }
124
- if (contentType.startsWith("text/event-stream")) {
125
- return toEventIterator(re.body);
126
- }
127
- if (contentType.startsWith("text/plain")) {
128
- return await re.text();
129
- }
130
- const blob = await re.blob();
131
- return new File([blob], "blob", {
132
- type: blob.type
133
- });
134
- }
135
- function toFetchBody(body, headers) {
136
- headers.delete("content-type");
137
- headers.delete("content-disposition");
138
- if (body === void 0) {
139
- return void 0;
140
- }
141
- if (body instanceof Blob) {
142
- headers.set("content-type", body.type);
143
- headers.set("content-length", body.size.toString());
144
- headers.set(
145
- "content-disposition",
146
- contentDisposition(body instanceof File ? body.name : "blob", { type: "inline" })
147
- );
148
- return body;
149
- }
150
- if (body instanceof FormData) {
151
- return body;
152
- }
153
- if (body instanceof URLSearchParams) {
154
- return body;
155
- }
156
- if (isAsyncIteratorObject(body)) {
157
- headers.set("content-type", "text/event-stream");
158
- headers.set("cache-control", "no-cache");
159
- headers.set("connection", "keep-alive");
160
- return toEventStream(body);
161
- }
162
- headers.set("content-type", "application/json");
163
- return stringifyJSON2(body);
164
- }
165
-
166
- // src/headers.ts
167
- function toStandardHeaders(headers, standardHeaders = {}) {
168
- for (const [key, value] of headers) {
169
- if (Array.isArray(standardHeaders[key])) {
170
- standardHeaders[key].push(value);
171
- } else if (standardHeaders[key] !== void 0) {
172
- standardHeaders[key] = [standardHeaders[key], value];
173
- } else {
174
- standardHeaders[key] = value;
175
- }
176
- }
177
- return standardHeaders;
178
- }
179
- function toFetchHeaders(headers, fetchHeaders = new Headers()) {
180
- for (const [key, value] of Object.entries(headers)) {
181
- if (Array.isArray(value)) {
182
- for (const v of value) {
183
- fetchHeaders.append(key, v);
184
- }
185
- } else if (value !== void 0) {
186
- fetchHeaders.append(key, value);
187
- }
188
- }
189
- return fetchHeaders;
190
- }
191
-
192
- // src/request.ts
193
- import { once } from "@orpc/shared";
194
- function toStandardRequest(request) {
195
- return {
196
- raw: { request },
197
- url: new URL(request.url),
198
- signal: request.signal,
199
- method: request.method,
200
- body: once(() => toStandardBody(request)),
201
- get headers() {
202
- const headers = toStandardHeaders(request.headers);
203
- Object.defineProperty(this, "headers", { value: headers, writable: true });
204
- return headers;
205
- },
206
- set headers(value) {
207
- Object.defineProperty(this, "headers", { value, writable: true });
208
- }
209
- };
210
- }
211
-
212
- // src/response.ts
213
- function toFetchResponse(response) {
214
- const headers = toFetchHeaders(response.headers);
215
- const body = toFetchBody(response.body, headers);
216
- return new Response(body, { headers, status: response.status });
217
- }
218
- export {
219
- toEventIterator,
220
- toEventStream,
221
- toFetchBody,
222
- toFetchHeaders,
223
- toFetchResponse,
224
- toStandardBody,
225
- toStandardHeaders,
226
- toStandardRequest
227
- };
228
- //# sourceMappingURL=index.js.map
@@ -1,8 +0,0 @@
1
- import type { StandardBody } from '@orpc/standard-server';
2
- export declare function toStandardBody(re: Request | Response): Promise<StandardBody>;
3
- /**
4
- * @param body
5
- * @param headers - The headers can be changed by the function and effects on the original headers.
6
- */
7
- export declare function toFetchBody(body: StandardBody, headers: Headers): string | Blob | FormData | URLSearchParams | undefined | ReadableStream<Uint8Array>;
8
- //# sourceMappingURL=body.d.ts.map
@@ -1,3 +0,0 @@
1
- export declare function toEventIterator(stream: ReadableStream<Uint8Array>): AsyncGenerator<unknown | void, unknown | void, void>;
2
- export declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>): ReadableStream<Uint8Array>;
3
- //# sourceMappingURL=event-source.d.ts.map
@@ -1,12 +0,0 @@
1
- import type { StandardHeaders } from '@orpc/standard-server';
2
- /**
3
- * @param headers
4
- * @param standardHeaders - The base headers can be changed by the function and effects on the original headers.
5
- */
6
- export declare function toStandardHeaders(headers: Headers, standardHeaders?: StandardHeaders): StandardHeaders;
7
- /**
8
- * @param headers
9
- * @param fetchHeaders - The base headers can be changed by the function and effects on the original headers.
10
- */
11
- export declare function toFetchHeaders(headers: StandardHeaders, fetchHeaders?: Headers): Headers;
12
- //# sourceMappingURL=headers.d.ts.map
@@ -1,6 +0,0 @@
1
- export * from './body';
2
- export * from './event-source';
3
- export * from './headers';
4
- export * from './request';
5
- export * from './response';
6
- //# sourceMappingURL=index.d.ts.map
@@ -1,3 +0,0 @@
1
- import type { StandardRequest } from '@orpc/standard-server';
2
- export declare function toStandardRequest(request: Request): StandardRequest;
3
- //# sourceMappingURL=request.d.ts.map
@@ -1,3 +0,0 @@
1
- import type { StandardResponse } from '@orpc/standard-server';
2
- export declare function toFetchResponse(response: StandardResponse): Response;
3
- //# sourceMappingURL=response.d.ts.map