@orpc/standard-server 0.0.0-next.d0e429d → 0.0.0-next.d177d36

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,5 +1,5 @@
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.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
3
3
  </div>
4
4
 
5
5
  <h1></h1>
@@ -21,28 +21,24 @@
21
21
 
22
22
  <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
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.
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
25
25
 
26
26
  ---
27
27
 
28
28
  ## Highlights
29
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), 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.
30
+ - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
31
+ - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
32
+ - **📝 Contract-First Development**: Optionally define your API contract before implementation.
33
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte), Pinia Colada, and more.
34
+ - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
35
+ - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
36
+ - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
37
+ - **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature.
38
+ - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
39
+ - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
40
+ - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
41
+ - **🛡️ Reliability**: Well-tested, TypeScript-based, production-ready, and MIT licensed.
46
42
 
47
43
  ## Documentation
48
44
 
@@ -53,16 +49,30 @@ You can find the full documentation [here](https://orpc.unnoq.com).
53
49
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
50
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
51
  - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
52
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with NestJS.
53
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
56
54
  - [@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
55
  - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
56
+ - [@orpc/solid-query](https://www.npmjs.com/package/@orpc/solid-query): Integration with [Solid Query](https://tanstack.com/query/latest/docs/framework/solid/overview).
57
+ - [@orpc/svelte-query](https://www.npmjs.com/package/@orpc/svelte-query): Integration with [Svelte Query](https://tanstack.com/query/latest/docs/framework/svelte/overview).
58
58
  - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
59
59
  - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
60
60
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
61
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
62
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
61
63
 
62
64
  ## `@orpc/standard-server`
63
65
 
64
66
  This package is designed to be used as a base for other server implementations.
65
67
 
68
+ ## Sponsors
69
+
70
+ <p align="center">
71
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
72
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
73
+ </a>
74
+ </p>
75
+
66
76
  ## License
67
77
 
68
78
  Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,30 @@
1
+ import { S as StandardHeaders, c as StandardRequest, e as StandardResponse } from '../shared/standard-server.BD8Sg1A5.mjs';
2
+ import { Promisable } from '@orpc/shared';
3
+
4
+ interface ToBatchRequestOptions {
5
+ url: URL;
6
+ method: 'GET' | 'POST';
7
+ headers: StandardHeaders;
8
+ requests: readonly StandardRequest[];
9
+ }
10
+ declare function toBatchRequest(options: ToBatchRequestOptions): StandardRequest;
11
+ declare function parseBatchRequest(request: StandardRequest): StandardRequest[];
12
+
13
+ type BatchResponseMode = 'streaming' | 'buffered';
14
+ interface BatchResponseBodyItem extends StandardResponse {
15
+ index: number;
16
+ }
17
+ interface ToBatchResponseOptions extends StandardResponse {
18
+ body: AsyncIteratorObject<BatchResponseBodyItem>;
19
+ /**
20
+ * @default 'streaming'
21
+ */
22
+ mode?: BatchResponseMode;
23
+ }
24
+ declare function toBatchResponse(options: ToBatchResponseOptions): Promisable<StandardResponse>;
25
+ declare function parseBatchResponse(response: StandardResponse): AsyncGenerator<BatchResponseBodyItem>;
26
+
27
+ declare function toBatchAbortSignal(signals: readonly (AbortSignal | undefined)[]): AbortSignal | undefined;
28
+
29
+ export { parseBatchRequest, parseBatchResponse, toBatchAbortSignal, toBatchRequest, toBatchResponse };
30
+ export type { BatchResponseBodyItem, BatchResponseMode, ToBatchRequestOptions, ToBatchResponseOptions };
@@ -0,0 +1,30 @@
1
+ import { S as StandardHeaders, c as StandardRequest, e as StandardResponse } from '../shared/standard-server.BD8Sg1A5.js';
2
+ import { Promisable } from '@orpc/shared';
3
+
4
+ interface ToBatchRequestOptions {
5
+ url: URL;
6
+ method: 'GET' | 'POST';
7
+ headers: StandardHeaders;
8
+ requests: readonly StandardRequest[];
9
+ }
10
+ declare function toBatchRequest(options: ToBatchRequestOptions): StandardRequest;
11
+ declare function parseBatchRequest(request: StandardRequest): StandardRequest[];
12
+
13
+ type BatchResponseMode = 'streaming' | 'buffered';
14
+ interface BatchResponseBodyItem extends StandardResponse {
15
+ index: number;
16
+ }
17
+ interface ToBatchResponseOptions extends StandardResponse {
18
+ body: AsyncIteratorObject<BatchResponseBodyItem>;
19
+ /**
20
+ * @default 'streaming'
21
+ */
22
+ mode?: BatchResponseMode;
23
+ }
24
+ declare function toBatchResponse(options: ToBatchResponseOptions): Promisable<StandardResponse>;
25
+ declare function parseBatchResponse(response: StandardResponse): AsyncGenerator<BatchResponseBodyItem>;
26
+
27
+ declare function toBatchAbortSignal(signals: readonly (AbortSignal | undefined)[]): AbortSignal | undefined;
28
+
29
+ export { parseBatchRequest, parseBatchResponse, toBatchAbortSignal, toBatchRequest, toBatchResponse };
30
+ export type { BatchResponseBodyItem, BatchResponseMode, ToBatchRequestOptions, ToBatchResponseOptions };
@@ -0,0 +1,140 @@
1
+ import { stringifyJSON, parseEmptyableJSON, isAsyncIteratorObject, isObject } from '@orpc/shared';
2
+
3
+ function toBatchAbortSignal(signals) {
4
+ const realSignals = signals.filter((signal) => signal !== void 0);
5
+ if (realSignals.length === 0 || realSignals.length !== signals.length) {
6
+ return void 0;
7
+ }
8
+ const controller = new AbortController();
9
+ const abortIfAllInputsAborted = () => {
10
+ if (realSignals.every((signal) => signal.aborted)) {
11
+ controller.abort();
12
+ }
13
+ };
14
+ abortIfAllInputsAborted();
15
+ for (const signal of realSignals) {
16
+ signal.addEventListener("abort", () => {
17
+ abortIfAllInputsAborted();
18
+ }, {
19
+ once: true,
20
+ signal: controller.signal
21
+ });
22
+ }
23
+ return controller.signal;
24
+ }
25
+
26
+ function toBatchRequest(options) {
27
+ const url = new URL(options.url);
28
+ let body;
29
+ const batchRequestItems = options.requests.map((request) => ({
30
+ body: request.body,
31
+ headers: Object.keys(request.headers).length ? request.headers : void 0,
32
+ method: request.method === options.method ? void 0 : request.method,
33
+ url: request.url
34
+ }));
35
+ if (options.method === "GET") {
36
+ url.searchParams.append("batch", stringifyJSON(batchRequestItems));
37
+ } else if (options.method === "POST") {
38
+ body = batchRequestItems;
39
+ }
40
+ return {
41
+ method: options.method,
42
+ url,
43
+ headers: options.headers,
44
+ body,
45
+ signal: toBatchAbortSignal(options.requests.map((request) => request.signal))
46
+ };
47
+ }
48
+ function parseBatchRequest(request) {
49
+ const items = request.method === "GET" ? parseEmptyableJSON(request.url.searchParams.getAll("batch").at(-1)) : request.body;
50
+ if (!Array.isArray(items)) {
51
+ throw new TypeError("Invalid batch request");
52
+ }
53
+ return items.map((item) => {
54
+ return {
55
+ method: item.method ?? request.method,
56
+ url: new URL(item.url),
57
+ headers: item.headers ?? {},
58
+ body: item.body,
59
+ signal: request.signal
60
+ };
61
+ });
62
+ }
63
+
64
+ function toBatchResponse(options) {
65
+ const mode = options.mode ?? "streaming";
66
+ const minifyResponseItem = (item) => {
67
+ return {
68
+ index: item.index,
69
+ status: item.status === options.status ? void 0 : item.status,
70
+ headers: Object.keys(item.headers).length ? item.headers : void 0,
71
+ body: item.body
72
+ };
73
+ };
74
+ if (mode === "buffered") {
75
+ return (async () => {
76
+ try {
77
+ const body = [];
78
+ for await (const item of options.body) {
79
+ body.push(minifyResponseItem(item));
80
+ }
81
+ return {
82
+ headers: options.headers,
83
+ status: options.status,
84
+ body
85
+ };
86
+ } finally {
87
+ await options.body.return?.();
88
+ }
89
+ })();
90
+ }
91
+ return {
92
+ headers: options.headers,
93
+ status: options.status,
94
+ body: async function* () {
95
+ try {
96
+ for await (const item of options.body) {
97
+ yield {
98
+ index: item.index,
99
+ status: item.status === options.status ? void 0 : item.status,
100
+ headers: Object.keys(item.headers).length ? item.headers : void 0,
101
+ body: item.body
102
+ };
103
+ }
104
+ } finally {
105
+ await options.body.return?.();
106
+ }
107
+ }()
108
+ };
109
+ }
110
+ function parseBatchResponse(response) {
111
+ const body = response.body;
112
+ if (isAsyncIteratorObject(body) || Array.isArray(body)) {
113
+ return async function* () {
114
+ try {
115
+ for await (const item of body) {
116
+ if (!isObject(item) || !("index" in item) || typeof item.index !== "number") {
117
+ throw new TypeError("Invalid batch response", {
118
+ cause: item
119
+ });
120
+ }
121
+ yield {
122
+ index: item.index,
123
+ status: item.status ?? response.status,
124
+ headers: item.headers ?? {},
125
+ body: item.body
126
+ };
127
+ }
128
+ } finally {
129
+ if (isAsyncIteratorObject(body)) {
130
+ await body.return?.();
131
+ }
132
+ }
133
+ }();
134
+ }
135
+ throw new TypeError("Invalid batch response", {
136
+ cause: response
137
+ });
138
+ }
139
+
140
+ export { parseBatchRequest, parseBatchResponse, toBatchAbortSignal, toBatchRequest, toBatchResponse };
@@ -0,0 +1,62 @@
1
+ import { S as StandardHeaders, a as StandardLazyResponse } from './shared/standard-server.BD8Sg1A5.mjs';
2
+ export { b as StandardBody, d as StandardLazyRequest, c as StandardRequest, e as StandardResponse } from './shared/standard-server.BD8Sg1A5.mjs';
3
+
4
+ interface EventMessage {
5
+ event: string | undefined;
6
+ id: string | undefined;
7
+ data: string | undefined;
8
+ /**
9
+ * The number of milliseconds to wait before retrying the event iterator if error occurs.
10
+ */
11
+ retry: number | undefined;
12
+ comments: string[];
13
+ }
14
+
15
+ declare function decodeEventMessage(encoded: string): EventMessage;
16
+ interface EventDecoderOptions {
17
+ onEvent?: (event: EventMessage) => void;
18
+ }
19
+ declare class EventDecoder {
20
+ private options;
21
+ private incomplete;
22
+ constructor(options?: EventDecoderOptions);
23
+ feed(chunk: string): void;
24
+ end(): void;
25
+ }
26
+ declare class EventDecoderStream extends TransformStream<string, EventMessage> {
27
+ constructor();
28
+ }
29
+
30
+ declare function assertEventId(id: string): void;
31
+ declare function assertEventName(event: string): void;
32
+ declare function assertEventRetry(retry: number): void;
33
+ declare function assertEventComment(comment: string): void;
34
+ declare function encodeEventData(data: string | undefined): string;
35
+ declare function encodeEventComments(comments: string[] | undefined): string;
36
+ declare function encodeEventMessage(message: Partial<EventMessage>): string;
37
+
38
+ declare class EventEncoderError extends TypeError {
39
+ }
40
+ declare class EventDecoderError extends TypeError {
41
+ }
42
+ interface ErrorEventOptions extends ErrorOptions {
43
+ message?: string;
44
+ data?: unknown;
45
+ }
46
+ declare class ErrorEvent extends Error {
47
+ data: unknown;
48
+ constructor(options?: ErrorEventOptions);
49
+ }
50
+
51
+ type EventMeta = Partial<Pick<EventMessage, 'retry' | 'id' | 'comments'>>;
52
+ declare function withEventMeta<T extends object>(container: T, meta: EventMeta): T;
53
+ declare function getEventMeta(container: unknown): EventMeta | undefined;
54
+
55
+ declare function generateContentDisposition(filename: string): string;
56
+ declare function getFilenameFromContentDisposition(contentDisposition: string): string | undefined;
57
+ declare function mergeStandardHeaders(a: StandardHeaders, b: StandardHeaders): StandardHeaders;
58
+ declare function flattenHeader(header: string | readonly string[] | undefined): string | undefined;
59
+ declare function replicateStandardLazyResponse(response: StandardLazyResponse, count: number): StandardLazyResponse[];
60
+
61
+ export { ErrorEvent, EventDecoder, EventDecoderError, EventDecoderStream, EventEncoderError, StandardHeaders, StandardLazyResponse, assertEventComment, assertEventId, assertEventName, assertEventRetry, decodeEventMessage, encodeEventComments, encodeEventData, encodeEventMessage, flattenHeader, generateContentDisposition, getEventMeta, getFilenameFromContentDisposition, mergeStandardHeaders, replicateStandardLazyResponse, withEventMeta };
62
+ export type { ErrorEventOptions, EventDecoderOptions, EventMessage, EventMeta };
@@ -0,0 +1,62 @@
1
+ import { S as StandardHeaders, a as StandardLazyResponse } from './shared/standard-server.BD8Sg1A5.js';
2
+ export { b as StandardBody, d as StandardLazyRequest, c as StandardRequest, e as StandardResponse } from './shared/standard-server.BD8Sg1A5.js';
3
+
4
+ interface EventMessage {
5
+ event: string | undefined;
6
+ id: string | undefined;
7
+ data: string | undefined;
8
+ /**
9
+ * The number of milliseconds to wait before retrying the event iterator if error occurs.
10
+ */
11
+ retry: number | undefined;
12
+ comments: string[];
13
+ }
14
+
15
+ declare function decodeEventMessage(encoded: string): EventMessage;
16
+ interface EventDecoderOptions {
17
+ onEvent?: (event: EventMessage) => void;
18
+ }
19
+ declare class EventDecoder {
20
+ private options;
21
+ private incomplete;
22
+ constructor(options?: EventDecoderOptions);
23
+ feed(chunk: string): void;
24
+ end(): void;
25
+ }
26
+ declare class EventDecoderStream extends TransformStream<string, EventMessage> {
27
+ constructor();
28
+ }
29
+
30
+ declare function assertEventId(id: string): void;
31
+ declare function assertEventName(event: string): void;
32
+ declare function assertEventRetry(retry: number): void;
33
+ declare function assertEventComment(comment: string): void;
34
+ declare function encodeEventData(data: string | undefined): string;
35
+ declare function encodeEventComments(comments: string[] | undefined): string;
36
+ declare function encodeEventMessage(message: Partial<EventMessage>): string;
37
+
38
+ declare class EventEncoderError extends TypeError {
39
+ }
40
+ declare class EventDecoderError extends TypeError {
41
+ }
42
+ interface ErrorEventOptions extends ErrorOptions {
43
+ message?: string;
44
+ data?: unknown;
45
+ }
46
+ declare class ErrorEvent extends Error {
47
+ data: unknown;
48
+ constructor(options?: ErrorEventOptions);
49
+ }
50
+
51
+ type EventMeta = Partial<Pick<EventMessage, 'retry' | 'id' | 'comments'>>;
52
+ declare function withEventMeta<T extends object>(container: T, meta: EventMeta): T;
53
+ declare function getEventMeta(container: unknown): EventMeta | undefined;
54
+
55
+ declare function generateContentDisposition(filename: string): string;
56
+ declare function getFilenameFromContentDisposition(contentDisposition: string): string | undefined;
57
+ declare function mergeStandardHeaders(a: StandardHeaders, b: StandardHeaders): StandardHeaders;
58
+ declare function flattenHeader(header: string | readonly string[] | undefined): string | undefined;
59
+ declare function replicateStandardLazyResponse(response: StandardLazyResponse, count: number): StandardLazyResponse[];
60
+
61
+ export { ErrorEvent, EventDecoder, EventDecoderError, EventDecoderStream, EventEncoderError, StandardHeaders, StandardLazyResponse, assertEventComment, assertEventId, assertEventName, assertEventRetry, decodeEventMessage, encodeEventComments, encodeEventData, encodeEventMessage, flattenHeader, generateContentDisposition, getEventMeta, getFilenameFromContentDisposition, mergeStandardHeaders, replicateStandardLazyResponse, withEventMeta };
62
+ export type { ErrorEventOptions, EventDecoderOptions, EventMessage, EventMeta };
@@ -1,17 +1,17 @@
1
- // src/event-source/errors.ts
2
- var EventEncoderError = class extends TypeError {
3
- };
4
- var EventDecoderError = class extends TypeError {
5
- };
6
- var ErrorEvent = class extends Error {
1
+ import { isTypescriptObject, toArray, once, isAsyncIteratorObject, replicateAsyncIterator } from '@orpc/shared';
2
+
3
+ class EventEncoderError extends TypeError {
4
+ }
5
+ class EventDecoderError extends TypeError {
6
+ }
7
+ class ErrorEvent extends Error {
7
8
  data;
8
9
  constructor(options) {
9
10
  super(options?.message ?? "An error event was received", options);
10
11
  this.data = options?.data;
11
12
  }
12
- };
13
+ }
13
14
 
14
- // src/event-source/decoder.ts
15
15
  function decodeEventMessage(encoded) {
16
16
  const lines = encoded.replace(/\n+$/, "").split(/\n/);
17
17
  const message = {
@@ -45,7 +45,7 @@ function decodeEventMessage(encoded) {
45
45
  message.data = message.data?.replace(/\n$/, "");
46
46
  return message;
47
47
  }
48
- var EventDecoder = class {
48
+ class EventDecoder {
49
49
  constructor(options = {}) {
50
50
  this.options = options;
51
51
  }
@@ -70,11 +70,11 @@ var EventDecoder = class {
70
70
  }
71
71
  end() {
72
72
  if (this.incomplete) {
73
- throw new EventDecoderError("EventSource ended before complete");
73
+ throw new EventDecoderError("Event Iterator ended before complete");
74
74
  }
75
75
  }
76
- };
77
- var EventDecoderStream = class extends TransformStream {
76
+ }
77
+ class EventDecoderStream extends TransformStream {
78
78
  constructor() {
79
79
  let decoder;
80
80
  super({
@@ -93,27 +93,26 @@ var EventDecoderStream = class extends TransformStream {
93
93
  }
94
94
  });
95
95
  }
96
- };
96
+ }
97
97
 
98
- // src/event-source/encoder.ts
99
98
  function assertEventId(id) {
100
99
  if (id.includes("\n")) {
101
- throw new EventEncoderError("Event-source id must not contain a newline character");
100
+ throw new EventEncoderError("Event's id must not contain a newline character");
102
101
  }
103
102
  }
104
103
  function assertEventName(event) {
105
104
  if (event.includes("\n")) {
106
- throw new EventEncoderError("Event-source event must not contain a newline character");
105
+ throw new EventEncoderError("Event's event must not contain a newline character");
107
106
  }
108
107
  }
109
108
  function assertEventRetry(retry) {
110
109
  if (!Number.isInteger(retry) || retry < 0) {
111
- throw new EventEncoderError("Event-source retry must be a integer and >= 0");
110
+ throw new EventEncoderError("Event's retry must be a integer and >= 0");
112
111
  }
113
112
  }
114
113
  function assertEventComment(comment) {
115
114
  if (comment.includes("\n")) {
116
- throw new EventEncoderError("Event-source comment must not contain a newline character");
115
+ throw new EventEncoderError("Event's comment must not contain a newline character");
117
116
  }
118
117
  }
119
118
  function encodeEventData(data) {
@@ -157,9 +156,7 @@ function encodeEventMessage(message) {
157
156
  return output;
158
157
  }
159
158
 
160
- // src/event-source/meta.ts
161
- import { isTypescriptObject } from "@orpc/shared";
162
- var EVENT_SOURCE_META_SYMBOL = Symbol("ORPC_EVENT_SOURCE_META");
159
+ const EVENT_SOURCE_META_SYMBOL = Symbol("ORPC_EVENT_SOURCE_META");
163
160
  function withEventMeta(container, meta) {
164
161
  if (meta.id !== void 0) {
165
162
  assertEventId(meta.id);
@@ -185,25 +182,68 @@ function getEventMeta(container) {
185
182
  return isTypescriptObject(container) ? Reflect.get(container, EVENT_SOURCE_META_SYMBOL) : void 0;
186
183
  }
187
184
 
188
- // src/utils.ts
189
- import { contentDisposition, parse } from "@tinyhttp/content-disposition";
190
- export {
191
- ErrorEvent,
192
- EventDecoder,
193
- EventDecoderError,
194
- EventDecoderStream,
195
- EventEncoderError,
196
- assertEventComment,
197
- assertEventId,
198
- assertEventName,
199
- assertEventRetry,
200
- contentDisposition,
201
- decodeEventMessage,
202
- encodeEventComments,
203
- encodeEventData,
204
- encodeEventMessage,
205
- getEventMeta,
206
- parse as parseContentDisposition,
207
- withEventMeta
208
- };
209
- //# sourceMappingURL=index.js.map
185
+ function generateContentDisposition(filename) {
186
+ const escapedFileName = filename.replace(/"/g, '\\"');
187
+ const encodedFilenameStar = encodeURIComponent(filename).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
188
+ return `inline; filename="${escapedFileName}"; filename*=utf-8''${encodedFilenameStar}`;
189
+ }
190
+ function getFilenameFromContentDisposition(contentDisposition) {
191
+ const encodedFilenameStarMatch = contentDisposition.match(/filename\*=(UTF-8'')?([^;]*)/i);
192
+ if (encodedFilenameStarMatch && typeof encodedFilenameStarMatch[2] === "string") {
193
+ return decodeURIComponent(encodedFilenameStarMatch[2]);
194
+ }
195
+ const encodedFilenameMatch = contentDisposition.match(/filename="((?:\\"|[^"])*)"/i);
196
+ if (encodedFilenameMatch && typeof encodedFilenameMatch[1] === "string") {
197
+ return encodedFilenameMatch[1].replace(/\\"/g, '"');
198
+ }
199
+ }
200
+ function mergeStandardHeaders(a, b) {
201
+ const merged = { ...a };
202
+ for (const key in b) {
203
+ if (Array.isArray(b[key])) {
204
+ merged[key] = [...toArray(merged[key]), ...b[key]];
205
+ } else if (b[key] !== void 0) {
206
+ if (Array.isArray(merged[key])) {
207
+ merged[key] = [...merged[key], b[key]];
208
+ } else if (merged[key] !== void 0) {
209
+ merged[key] = [merged[key], b[key]];
210
+ } else {
211
+ merged[key] = b[key];
212
+ }
213
+ }
214
+ }
215
+ return merged;
216
+ }
217
+ function flattenHeader(header) {
218
+ if (typeof header === "string" || header === void 0) {
219
+ return header;
220
+ }
221
+ if (header.length === 0) {
222
+ return void 0;
223
+ }
224
+ return header.join(", ");
225
+ }
226
+ function replicateStandardLazyResponse(response, count) {
227
+ const replicated = [];
228
+ let bodyPromise;
229
+ let replicatedAsyncIteratorObjects;
230
+ for (let i = 0; i < count; i++) {
231
+ replicated.push({
232
+ ...response,
233
+ body: once(async () => {
234
+ if (replicatedAsyncIteratorObjects) {
235
+ return replicatedAsyncIteratorObjects.shift();
236
+ }
237
+ const body = await (bodyPromise ??= response.body());
238
+ if (!isAsyncIteratorObject(body)) {
239
+ return body;
240
+ }
241
+ replicatedAsyncIteratorObjects = replicateAsyncIterator(body, count);
242
+ return replicatedAsyncIteratorObjects.shift();
243
+ })
244
+ });
245
+ }
246
+ return replicated;
247
+ }
248
+
249
+ export { ErrorEvent, EventDecoder, EventDecoderError, EventDecoderStream, EventEncoderError, assertEventComment, assertEventId, assertEventName, assertEventRetry, decodeEventMessage, encodeEventComments, encodeEventData, encodeEventMessage, flattenHeader, generateContentDisposition, getEventMeta, getFilenameFromContentDisposition, mergeStandardHeaders, replicateStandardLazyResponse, withEventMeta };
@@ -0,0 +1,38 @@
1
+ interface StandardHeaders {
2
+ [key: string]: string | string[] | undefined;
3
+ }
4
+ type StandardBody = undefined | unknown | Blob | URLSearchParams | FormData | AsyncIterator<unknown | void, unknown | void, undefined>;
5
+ interface StandardRequest {
6
+ method: string;
7
+ url: URL;
8
+ headers: StandardHeaders;
9
+ /**
10
+ * The body has been parsed based on the content-type header.
11
+ */
12
+ body: StandardBody;
13
+ signal: AbortSignal | undefined;
14
+ }
15
+ interface StandardLazyRequest extends Omit<StandardRequest, 'body'> {
16
+ /**
17
+ * The body has been parsed based on the content-type header.
18
+ * This method can safely call multiple times (cached).
19
+ */
20
+ body: () => Promise<StandardBody>;
21
+ }
22
+ interface StandardResponse {
23
+ status: number;
24
+ headers: StandardHeaders;
25
+ /**
26
+ * The body has been parsed based on the content-type header.
27
+ */
28
+ body: StandardBody;
29
+ }
30
+ interface StandardLazyResponse extends Omit<StandardResponse, 'body'> {
31
+ /**
32
+ * The body has been parsed based on the content-type header.
33
+ * This method can safely call multiple times (cached).
34
+ */
35
+ body: () => Promise<StandardBody>;
36
+ }
37
+
38
+ export type { StandardHeaders as S, StandardLazyResponse as a, StandardBody as b, StandardRequest as c, StandardLazyRequest as d, StandardResponse as e };
@@ -0,0 +1,38 @@
1
+ interface StandardHeaders {
2
+ [key: string]: string | string[] | undefined;
3
+ }
4
+ type StandardBody = undefined | unknown | Blob | URLSearchParams | FormData | AsyncIterator<unknown | void, unknown | void, undefined>;
5
+ interface StandardRequest {
6
+ method: string;
7
+ url: URL;
8
+ headers: StandardHeaders;
9
+ /**
10
+ * The body has been parsed based on the content-type header.
11
+ */
12
+ body: StandardBody;
13
+ signal: AbortSignal | undefined;
14
+ }
15
+ interface StandardLazyRequest extends Omit<StandardRequest, 'body'> {
16
+ /**
17
+ * The body has been parsed based on the content-type header.
18
+ * This method can safely call multiple times (cached).
19
+ */
20
+ body: () => Promise<StandardBody>;
21
+ }
22
+ interface StandardResponse {
23
+ status: number;
24
+ headers: StandardHeaders;
25
+ /**
26
+ * The body has been parsed based on the content-type header.
27
+ */
28
+ body: StandardBody;
29
+ }
30
+ interface StandardLazyResponse extends Omit<StandardResponse, 'body'> {
31
+ /**
32
+ * The body has been parsed based on the content-type header.
33
+ * This method can safely call multiple times (cached).
34
+ */
35
+ body: () => Promise<StandardBody>;
36
+ }
37
+
38
+ export type { StandardHeaders as S, StandardLazyResponse as a, StandardBody as b, StandardRequest as c, StandardLazyRequest as d, StandardResponse as e };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/standard-server",
3
3
  "type": "module",
4
- "version": "0.0.0-next.d0e429d",
4
+ "version": "0.0.0-next.d177d36",
5
5
  "license": "MIT",
6
6
  "homepage": "https://unnoq.com",
7
7
  "repository": {
@@ -14,25 +14,24 @@
14
14
  ],
15
15
  "exports": {
16
16
  ".": {
17
- "types": "./dist/src/index.d.ts",
18
- "import": "./dist/index.js",
19
- "default": "./dist/index.js"
17
+ "types": "./dist/index.d.mts",
18
+ "import": "./dist/index.mjs",
19
+ "default": "./dist/index.mjs"
20
20
  },
21
- "./🔒/*": {
22
- "types": "./dist/src/*.d.ts"
21
+ "./batch": {
22
+ "types": "./dist/batch/index.d.mts",
23
+ "import": "./dist/batch/index.mjs",
24
+ "default": "./dist/batch/index.mjs"
23
25
  }
24
26
  },
25
27
  "files": [
26
- "!**/*.map",
27
- "!**/*.tsbuildinfo",
28
28
  "dist"
29
29
  ],
30
30
  "dependencies": {
31
- "@tinyhttp/content-disposition": "^2.2.2",
32
- "@orpc/shared": "0.0.0-next.d0e429d"
31
+ "@orpc/shared": "0.0.0-next.d177d36"
33
32
  },
34
33
  "scripts": {
35
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
34
+ "build": "unbuild",
36
35
  "build:watch": "pnpm run build --watch",
37
36
  "type:check": "tsc -b"
38
37
  }
@@ -1,16 +0,0 @@
1
- import type { EventMessage } from './types';
2
- export declare function decodeEventMessage(encoded: string): EventMessage;
3
- export interface EventDecoderOptions {
4
- onEvent?: (event: EventMessage) => void;
5
- }
6
- export declare class EventDecoder {
7
- private options;
8
- private incomplete;
9
- constructor(options?: EventDecoderOptions);
10
- feed(chunk: string): void;
11
- end(): void;
12
- }
13
- export declare class EventDecoderStream extends TransformStream<string, EventMessage> {
14
- constructor();
15
- }
16
- //# sourceMappingURL=decoder.d.ts.map
@@ -1,9 +0,0 @@
1
- import type { EventMessage } from './types';
2
- export declare function assertEventId(id: string): void;
3
- export declare function assertEventName(event: string): void;
4
- export declare function assertEventRetry(retry: number): void;
5
- export declare function assertEventComment(comment: string): void;
6
- export declare function encodeEventData(data: string | undefined): string;
7
- export declare function encodeEventComments(comments: string[] | undefined): string;
8
- export declare function encodeEventMessage(message: Partial<EventMessage>): string;
9
- //# sourceMappingURL=encoder.d.ts.map
@@ -1,13 +0,0 @@
1
- export declare class EventEncoderError extends TypeError {
2
- }
3
- export declare class EventDecoderError extends TypeError {
4
- }
5
- export interface ErrorEventOptions extends ErrorOptions {
6
- message?: string;
7
- data?: unknown;
8
- }
9
- export declare class ErrorEvent extends Error {
10
- data: unknown;
11
- constructor(options?: ErrorEventOptions);
12
- }
13
- //# sourceMappingURL=errors.d.ts.map
@@ -1,6 +0,0 @@
1
- export * from './decoder';
2
- export * from './encoder';
3
- export * from './errors';
4
- export * from './meta';
5
- export * from './types';
6
- //# sourceMappingURL=index.d.ts.map
@@ -1,5 +0,0 @@
1
- import type { EventMessage } from './types';
2
- export type EventMeta = Partial<Pick<EventMessage, 'retry' | 'id' | 'comments'>>;
3
- export declare function withEventMeta<T extends object>(container: T, meta: EventMeta): T;
4
- export declare function getEventMeta(container: unknown): EventMeta | undefined;
5
- //# sourceMappingURL=meta.d.ts.map
@@ -1,11 +0,0 @@
1
- export interface EventMessage {
2
- event: string | undefined;
3
- id: string | undefined;
4
- data: string | undefined;
5
- /**
6
- * The number of milliseconds to wait before retrying the event source if error occurs.
7
- */
8
- retry: number | undefined;
9
- comments: string[];
10
- }
11
- //# sourceMappingURL=types.d.ts.map
@@ -1,4 +0,0 @@
1
- export * from './event-source';
2
- export * from './types';
3
- export * from './utils';
4
- //# sourceMappingURL=index.d.ts.map
@@ -1,25 +0,0 @@
1
- export interface StandardHeaders {
2
- [key: string]: string | string[] | undefined;
3
- }
4
- export type StandardBody = undefined | unknown | Blob | URLSearchParams | FormData | AsyncIterator<unknown | void, unknown | void, undefined>;
5
- export interface StandardRequest {
6
- /**
7
- * Can be { request: Request } or { request: IncomingMessage, response: ServerResponse } based on the adapter.
8
- */
9
- raw: Record<string, unknown>;
10
- method: string;
11
- url: URL;
12
- headers: StandardHeaders;
13
- /**
14
- * The body has been parsed base on the content-type header.
15
- * This method can safely call multiple times (cached).
16
- */
17
- body: () => Promise<StandardBody>;
18
- signal: AbortSignal | undefined;
19
- }
20
- export interface StandardResponse {
21
- status: number;
22
- headers: StandardHeaders;
23
- body: StandardBody;
24
- }
25
- //# sourceMappingURL=types.d.ts.map
@@ -1,2 +0,0 @@
1
- export { contentDisposition, parse as parseContentDisposition } from '@tinyhttp/content-disposition';
2
- //# sourceMappingURL=utils.d.ts.map