@orpc/shared 0.0.0-next.8c618ab → 0.0.0-next.8caa447

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,8 +1,3 @@
1
- > [!WARNING]
2
- >
3
- > `@orpc/shared` is an internal dependency of oRPC packages. It does not follow semver and may change at any time without notice.
4
- > Please do not use it in your project.
5
-
6
1
  <div align="center">
7
2
  <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
8
3
  </div>
@@ -35,7 +30,8 @@
35
30
  - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
36
31
  - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
37
32
  - **📝 Contract-First Development**: Optionally define your API contract before implementation.
38
- - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte), Pinia Colada, and more.
33
+ - **🔍 First-Class OpenTelemetry**: Seamlessly integrate with OpenTelemetry for observability.
34
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), SWR, Pinia Colada, and more.
39
35
  - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
40
36
  - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
41
37
  - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
@@ -43,7 +39,6 @@
43
39
  - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
44
40
  - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
45
41
  - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
46
- - **🛡️ Reliability**: Well-tested, TypeScript-based, production-ready, and MIT licensed.
47
42
 
48
43
  ## Documentation
49
44
 
@@ -54,14 +49,14 @@ You can find the full documentation [here](https://orpc.unnoq.com).
54
49
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
55
50
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
56
51
  - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
57
- - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with NestJS.
52
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
53
+ - [@orpc/otel](https://www.npmjs.com/package/@orpc/otel): [OpenTelemetry](https://opentelemetry.io/) integration for observability.
54
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
58
55
  - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
59
- - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
60
- - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
61
- - [@orpc/solid-query](https://www.npmjs.com/package/@orpc/solid-query): Integration with [Solid Query](https://tanstack.com/query/latest/docs/framework/solid/overview).
62
- - [@orpc/svelte-query](https://www.npmjs.com/package/@orpc/svelte-query): Integration with [Svelte Query](https://tanstack.com/query/latest/docs/framework/svelte/overview).
56
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
57
+ - [@orpc/experimental-react-swr](https://www.npmjs.com/package/@orpc/experimental-react-swr): [SWR](https://swr.vercel.app/) integration.
63
58
  - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
64
- - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
59
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
65
60
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
66
61
  - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
67
62
  - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
package/dist/index.d.mts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Promisable } from 'type-fest';
2
- export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
3
+ import { Tracer, TraceAPI, ContextAPI, PropagationAPI, SpanOptions, Context, Span, AttributeValue, Exception } from '@opentelemetry/api';
3
4
  export { group, guard, mapEntries, mapValues, omit } from 'radash';
4
5
 
5
6
  type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
@@ -8,6 +9,13 @@ declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>):
8
9
  declare function toArray<T>(value: T): T extends readonly any[] ? T : Exclude<T, undefined | null>[];
9
10
  declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
10
11
 
12
+ /**
13
+ * Converts Request/Response/Blob/File/.. to a buffer (ArrayBuffer or Uint8Array).
14
+ *
15
+ * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
16
+ */
17
+ declare function readAsBuffer(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): Promise<ArrayBuffer | Uint8Array>;
18
+
11
19
  type AnyFunction = (...args: any[]) => any;
12
20
  declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
13
21
  declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
@@ -20,9 +28,80 @@ type OmitChainMethodDeep<T extends object, K extends keyof any> = {
20
28
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
21
29
  };
22
30
 
31
+ declare const ORPC_NAME = "orpc";
32
+ declare const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
33
+ declare const ORPC_SHARED_PACKAGE_VERSION = "0.0.0-next.8caa447";
34
+
35
+ /**
36
+ * Error thrown when an operation is aborted.
37
+ * Uses the standardized 'AbortError' name for consistency with JavaScript APIs.
38
+ */
39
+ declare class AbortError extends Error {
40
+ constructor(...rest: ConstructorParameters<typeof Error>);
41
+ }
42
+
43
+ interface EventPublisherOptions {
44
+ /**
45
+ * Maximum number of events to buffer for async iterator subscribers.
46
+ *
47
+ * If the buffer exceeds this limit, the oldest event is dropped.
48
+ * This prevents unbounded memory growth if consumers process events slowly.
49
+ *
50
+ * Set to:
51
+ * - `0`: Disable buffering. Events must be consumed before the next one arrives.
52
+ * - `1`: Only keep the latest event. Useful for real-time updates where only the most recent value matters.
53
+ * - `Infinity`: Keep all events. Ensures no data loss, but may lead to high memory usage.
54
+ *
55
+ * @default 100
56
+ */
57
+ maxBufferedEvents?: number;
58
+ }
59
+ interface EventPublisherSubscribeIteratorOptions extends EventPublisherOptions {
60
+ /**
61
+ * Aborts the async iterator. Throws if aborted before or during pulling.
62
+ */
63
+ signal?: AbortSignal | undefined;
64
+ }
65
+ declare class EventPublisher<T extends Record<PropertyKey, any>> {
66
+ #private;
67
+ constructor(options?: EventPublisherOptions);
68
+ get size(): number;
69
+ /**
70
+ * Emits an event and delivers the payload to all subscribed listeners.
71
+ */
72
+ publish<K extends keyof T>(event: K, payload: T[K]): void;
73
+ /**
74
+ * Subscribes to a specific event using a callback function.
75
+ * Returns an unsubscribe function to remove the listener.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * const unsubscribe = publisher.subscribe('event', (payload) => {
80
+ * console.log(payload)
81
+ * })
82
+ *
83
+ * // Later
84
+ * unsubscribe()
85
+ * ```
86
+ */
87
+ subscribe<K extends keyof T>(event: K, listener: (payload: T[K]) => void): () => void;
88
+ /**
89
+ * Subscribes to a specific event using an async iterator.
90
+ * Useful for `for await...of` loops with optional buffering and abort support.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * for await (const payload of publisher.subscribe('event', { signal })) {
95
+ * console.log(payload)
96
+ * }
97
+ * ```
98
+ */
99
+ subscribe<K extends keyof T>(event: K, options?: EventPublisherSubscribeIteratorOptions): AsyncGenerator<T[K]> & AsyncIteratorObject<T[K]>;
100
+ }
101
+
23
102
  declare class SequentialIdGenerator {
24
- private nextId;
25
- generate(): number;
103
+ private index;
104
+ generate(): string;
26
105
  }
27
106
 
28
107
  type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
@@ -42,6 +121,7 @@ interface Registry {
42
121
  type ThrowableError = Registry extends {
43
122
  throwableError: infer T;
44
123
  } ? T : Error;
124
+ type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
45
125
 
46
126
  type InterceptableOptions = Record<string, any>;
47
127
  type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
@@ -75,15 +155,108 @@ declare function onFinish<T, TOptions extends {
75
155
  }, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>, ReturnType<TOptions['next']> extends PromiseWithError<any, infer E> ? E : ThrowableError>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
76
156
  declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
77
157
 
158
+ /**
159
+ * Only import types from @opentelemetry/api to avoid runtime dependencies.
160
+ */
161
+
162
+ interface OtelConfig {
163
+ tracer: Tracer;
164
+ trace: TraceAPI;
165
+ context: ContextAPI;
166
+ propagation: PropagationAPI;
167
+ }
168
+ /**
169
+ * Sets the global OpenTelemetry config.
170
+ * Call this once at app startup. Use `undefined` to disable tracing.
171
+ */
172
+ declare function setGlobalOtelConfig(config: OtelConfig | undefined): void;
173
+ /**
174
+ * Gets the global OpenTelemetry config.
175
+ * Returns `undefined` if OpenTelemetry is not configured, initialized, or enabled.
176
+ */
177
+ declare function getGlobalOtelConfig(): OtelConfig | undefined;
178
+ /**
179
+ * Starts a new OpenTelemetry span with the given name and options.
180
+ *
181
+ * @returns The new span, or `undefined` if no tracer is set.
182
+ */
183
+ declare function startSpan(name: string, options?: SpanOptions, context?: Context): Span | undefined;
184
+ interface SetSpanErrorOptions {
185
+ /**
186
+ * Span error status is not set if error is due to cancellation by the signal.
187
+ */
188
+ signal?: AbortSignal;
189
+ }
190
+ /**
191
+ * Records and sets the error status on the given span.
192
+ * If the span is `undefined`, it does nothing.
193
+ */
194
+ declare function setSpanError(span: Span | undefined, error: unknown, options?: SetSpanErrorOptions): void;
195
+ declare function setSpanAttribute(span: Span | undefined, key: string, value: AttributeValue | undefined): void;
196
+ /**
197
+ * Converts an error to an OpenTelemetry Exception.
198
+ */
199
+ declare function toOtelException(error: unknown): Exclude<Exception, string>;
200
+ /**
201
+ * Converts a value to a string suitable for OpenTelemetry span attributes.
202
+ */
203
+ declare function toSpanAttributeValue(data: unknown): string;
204
+ interface RunWithSpanOptions extends SpanOptions, SetSpanErrorOptions {
205
+ /**
206
+ * The name of the span to create.
207
+ */
208
+ name: string;
209
+ /**
210
+ * Context to use for the span.
211
+ */
212
+ context?: Context;
213
+ }
214
+ /**
215
+ * Runs a function within the context of a new OpenTelemetry span.
216
+ * The span is ended automatically, and errors are recorded to the span.
217
+ */
218
+ declare function runWithSpan<T>({ name, context, ...options }: RunWithSpanOptions, fn: (span?: Span) => Promisable<T>): Promise<T>;
219
+ /**
220
+ * Runs a function within the context of an existing OpenTelemetry span.
221
+ */
222
+ declare function runInSpanContext<T>(span: Span | undefined, fn: () => Promisable<T>): Promise<T>;
223
+
78
224
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
79
- interface CreateAsyncIteratorObjectCleanupFn {
225
+ interface AsyncIteratorClassNextFn<T, TReturn> {
226
+ (): Promise<IteratorResult<T, TReturn>>;
227
+ }
228
+ interface AsyncIteratorClassCleanupFn {
80
229
  (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
81
230
  }
82
- declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>;
83
- declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>)[];
231
+ declare const fallbackAsyncDisposeSymbol: unique symbol;
232
+ declare const asyncDisposeSymbol: typeof Symbol extends {
233
+ asyncDispose: infer T;
234
+ } ? T : typeof fallbackAsyncDisposeSymbol;
235
+ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implements AsyncIteratorObject<T, TReturn, TNext>, AsyncGenerator<T, TReturn, TNext> {
236
+ #private;
237
+ constructor(next: AsyncIteratorClassNextFn<T, TReturn>, cleanup: AsyncIteratorClassCleanupFn);
238
+ next(): Promise<IteratorResult<T, TReturn>>;
239
+ return(value?: any): Promise<IteratorResult<T, TReturn>>;
240
+ throw(err: any): Promise<IteratorResult<T, TReturn>>;
241
+ /**
242
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
243
+ */
244
+ [asyncDisposeSymbol](): Promise<void>;
245
+ [Symbol.asyncIterator](): this;
246
+ }
247
+ declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
248
+ interface AsyncIteratorWithSpanOptions extends SetSpanErrorOptions {
249
+ /**
250
+ * The name of the span to create.
251
+ */
252
+ name: string;
253
+ }
254
+ declare function asyncIteratorWithSpan<T, TReturn, TNext>({ name, ...options }: AsyncIteratorWithSpanOptions, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
84
255
 
85
256
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
86
- declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
257
+ declare function stringifyJSON<T>(value: T | {
258
+ toJSON(): T;
259
+ }): undefined extends T ? undefined | string : string;
87
260
 
88
261
  type Segment = string | number;
89
262
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
@@ -99,31 +272,45 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
99
272
  */
100
273
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
101
274
  declare function clone<T>(value: T): T;
102
- declare function get(object: object, path: readonly string[]): unknown;
275
+ declare function get(object: unknown, path: readonly string[]): unknown;
103
276
  declare function isPropertyKey(value: unknown): value is PropertyKey;
104
277
  declare const NullProtoObj: ({
105
278
  new <T extends Record<PropertyKey, unknown>>(): T;
106
279
  });
107
280
 
281
+ /**
282
+ * Prevents objects from being awaitable by intercepting the `then` method
283
+ * when called by the native await mechanism. This is useful for preventing
284
+ * accidental awaiting of objects that aren't meant to be promises.
285
+ */
286
+ declare function preventNativeAwait<T extends object>(target: T): T;
287
+
108
288
  interface AsyncIdQueueCloseOptions {
109
- id?: number;
289
+ id?: string;
110
290
  reason?: unknown;
111
291
  }
112
292
  declare class AsyncIdQueue<T> {
113
293
  private readonly openIds;
114
- private readonly items;
115
- private readonly pendingPulls;
294
+ private readonly queues;
295
+ private readonly waiters;
116
296
  get length(): number;
117
- open(id: number): void;
118
- isOpen(id: number): boolean;
119
- push(id: number, item: T): void;
120
- pull(id: number): Promise<T>;
297
+ get waiterIds(): string[];
298
+ hasBufferedItems(id: string): boolean;
299
+ open(id: string): void;
300
+ isOpen(id: string): boolean;
301
+ push(id: string, item: T): void;
302
+ pull(id: string): Promise<T>;
121
303
  close({ id, reason }?: AsyncIdQueueCloseOptions): void;
122
- assertOpen(id: number): void;
304
+ assertOpen(id: string): void;
123
305
  }
124
306
 
307
+ declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>): AsyncIteratorClass<T>;
308
+ declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
309
+
310
+ declare function tryDecodeURIComponent(value: string): string;
311
+
125
312
  type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
126
313
  declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
127
314
 
128
- export { AsyncIdQueue, NullProtoObj, SequentialIdGenerator, clone, createAsyncIteratorObject, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
129
- export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
315
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, defer, findDeepMatches, get, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
316
+ export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, AsyncIteratorWithSpanOptions, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InferAsyncIterableYield, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, OtelConfig, PromiseWithError, Registry, RunWithSpanOptions, Segment, SetOptional, SetSpanErrorOptions, ThrowableError, Value };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Promisable } from 'type-fest';
2
- export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
3
+ import { Tracer, TraceAPI, ContextAPI, PropagationAPI, SpanOptions, Context, Span, AttributeValue, Exception } from '@opentelemetry/api';
3
4
  export { group, guard, mapEntries, mapValues, omit } from 'radash';
4
5
 
5
6
  type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
@@ -8,6 +9,13 @@ declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>):
8
9
  declare function toArray<T>(value: T): T extends readonly any[] ? T : Exclude<T, undefined | null>[];
9
10
  declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
10
11
 
12
+ /**
13
+ * Converts Request/Response/Blob/File/.. to a buffer (ArrayBuffer or Uint8Array).
14
+ *
15
+ * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
16
+ */
17
+ declare function readAsBuffer(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): Promise<ArrayBuffer | Uint8Array>;
18
+
11
19
  type AnyFunction = (...args: any[]) => any;
12
20
  declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
13
21
  declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
@@ -20,9 +28,80 @@ type OmitChainMethodDeep<T extends object, K extends keyof any> = {
20
28
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
21
29
  };
22
30
 
31
+ declare const ORPC_NAME = "orpc";
32
+ declare const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
33
+ declare const ORPC_SHARED_PACKAGE_VERSION = "0.0.0-next.8caa447";
34
+
35
+ /**
36
+ * Error thrown when an operation is aborted.
37
+ * Uses the standardized 'AbortError' name for consistency with JavaScript APIs.
38
+ */
39
+ declare class AbortError extends Error {
40
+ constructor(...rest: ConstructorParameters<typeof Error>);
41
+ }
42
+
43
+ interface EventPublisherOptions {
44
+ /**
45
+ * Maximum number of events to buffer for async iterator subscribers.
46
+ *
47
+ * If the buffer exceeds this limit, the oldest event is dropped.
48
+ * This prevents unbounded memory growth if consumers process events slowly.
49
+ *
50
+ * Set to:
51
+ * - `0`: Disable buffering. Events must be consumed before the next one arrives.
52
+ * - `1`: Only keep the latest event. Useful for real-time updates where only the most recent value matters.
53
+ * - `Infinity`: Keep all events. Ensures no data loss, but may lead to high memory usage.
54
+ *
55
+ * @default 100
56
+ */
57
+ maxBufferedEvents?: number;
58
+ }
59
+ interface EventPublisherSubscribeIteratorOptions extends EventPublisherOptions {
60
+ /**
61
+ * Aborts the async iterator. Throws if aborted before or during pulling.
62
+ */
63
+ signal?: AbortSignal | undefined;
64
+ }
65
+ declare class EventPublisher<T extends Record<PropertyKey, any>> {
66
+ #private;
67
+ constructor(options?: EventPublisherOptions);
68
+ get size(): number;
69
+ /**
70
+ * Emits an event and delivers the payload to all subscribed listeners.
71
+ */
72
+ publish<K extends keyof T>(event: K, payload: T[K]): void;
73
+ /**
74
+ * Subscribes to a specific event using a callback function.
75
+ * Returns an unsubscribe function to remove the listener.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * const unsubscribe = publisher.subscribe('event', (payload) => {
80
+ * console.log(payload)
81
+ * })
82
+ *
83
+ * // Later
84
+ * unsubscribe()
85
+ * ```
86
+ */
87
+ subscribe<K extends keyof T>(event: K, listener: (payload: T[K]) => void): () => void;
88
+ /**
89
+ * Subscribes to a specific event using an async iterator.
90
+ * Useful for `for await...of` loops with optional buffering and abort support.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * for await (const payload of publisher.subscribe('event', { signal })) {
95
+ * console.log(payload)
96
+ * }
97
+ * ```
98
+ */
99
+ subscribe<K extends keyof T>(event: K, options?: EventPublisherSubscribeIteratorOptions): AsyncGenerator<T[K]> & AsyncIteratorObject<T[K]>;
100
+ }
101
+
23
102
  declare class SequentialIdGenerator {
24
- private nextId;
25
- generate(): number;
103
+ private index;
104
+ generate(): string;
26
105
  }
27
106
 
28
107
  type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
@@ -42,6 +121,7 @@ interface Registry {
42
121
  type ThrowableError = Registry extends {
43
122
  throwableError: infer T;
44
123
  } ? T : Error;
124
+ type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
45
125
 
46
126
  type InterceptableOptions = Record<string, any>;
47
127
  type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
@@ -75,15 +155,108 @@ declare function onFinish<T, TOptions extends {
75
155
  }, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>, ReturnType<TOptions['next']> extends PromiseWithError<any, infer E> ? E : ThrowableError>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
76
156
  declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
77
157
 
158
+ /**
159
+ * Only import types from @opentelemetry/api to avoid runtime dependencies.
160
+ */
161
+
162
+ interface OtelConfig {
163
+ tracer: Tracer;
164
+ trace: TraceAPI;
165
+ context: ContextAPI;
166
+ propagation: PropagationAPI;
167
+ }
168
+ /**
169
+ * Sets the global OpenTelemetry config.
170
+ * Call this once at app startup. Use `undefined` to disable tracing.
171
+ */
172
+ declare function setGlobalOtelConfig(config: OtelConfig | undefined): void;
173
+ /**
174
+ * Gets the global OpenTelemetry config.
175
+ * Returns `undefined` if OpenTelemetry is not configured, initialized, or enabled.
176
+ */
177
+ declare function getGlobalOtelConfig(): OtelConfig | undefined;
178
+ /**
179
+ * Starts a new OpenTelemetry span with the given name and options.
180
+ *
181
+ * @returns The new span, or `undefined` if no tracer is set.
182
+ */
183
+ declare function startSpan(name: string, options?: SpanOptions, context?: Context): Span | undefined;
184
+ interface SetSpanErrorOptions {
185
+ /**
186
+ * Span error status is not set if error is due to cancellation by the signal.
187
+ */
188
+ signal?: AbortSignal;
189
+ }
190
+ /**
191
+ * Records and sets the error status on the given span.
192
+ * If the span is `undefined`, it does nothing.
193
+ */
194
+ declare function setSpanError(span: Span | undefined, error: unknown, options?: SetSpanErrorOptions): void;
195
+ declare function setSpanAttribute(span: Span | undefined, key: string, value: AttributeValue | undefined): void;
196
+ /**
197
+ * Converts an error to an OpenTelemetry Exception.
198
+ */
199
+ declare function toOtelException(error: unknown): Exclude<Exception, string>;
200
+ /**
201
+ * Converts a value to a string suitable for OpenTelemetry span attributes.
202
+ */
203
+ declare function toSpanAttributeValue(data: unknown): string;
204
+ interface RunWithSpanOptions extends SpanOptions, SetSpanErrorOptions {
205
+ /**
206
+ * The name of the span to create.
207
+ */
208
+ name: string;
209
+ /**
210
+ * Context to use for the span.
211
+ */
212
+ context?: Context;
213
+ }
214
+ /**
215
+ * Runs a function within the context of a new OpenTelemetry span.
216
+ * The span is ended automatically, and errors are recorded to the span.
217
+ */
218
+ declare function runWithSpan<T>({ name, context, ...options }: RunWithSpanOptions, fn: (span?: Span) => Promisable<T>): Promise<T>;
219
+ /**
220
+ * Runs a function within the context of an existing OpenTelemetry span.
221
+ */
222
+ declare function runInSpanContext<T>(span: Span | undefined, fn: () => Promisable<T>): Promise<T>;
223
+
78
224
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
79
- interface CreateAsyncIteratorObjectCleanupFn {
225
+ interface AsyncIteratorClassNextFn<T, TReturn> {
226
+ (): Promise<IteratorResult<T, TReturn>>;
227
+ }
228
+ interface AsyncIteratorClassCleanupFn {
80
229
  (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
81
230
  }
82
- declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>;
83
- declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>)[];
231
+ declare const fallbackAsyncDisposeSymbol: unique symbol;
232
+ declare const asyncDisposeSymbol: typeof Symbol extends {
233
+ asyncDispose: infer T;
234
+ } ? T : typeof fallbackAsyncDisposeSymbol;
235
+ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implements AsyncIteratorObject<T, TReturn, TNext>, AsyncGenerator<T, TReturn, TNext> {
236
+ #private;
237
+ constructor(next: AsyncIteratorClassNextFn<T, TReturn>, cleanup: AsyncIteratorClassCleanupFn);
238
+ next(): Promise<IteratorResult<T, TReturn>>;
239
+ return(value?: any): Promise<IteratorResult<T, TReturn>>;
240
+ throw(err: any): Promise<IteratorResult<T, TReturn>>;
241
+ /**
242
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
243
+ */
244
+ [asyncDisposeSymbol](): Promise<void>;
245
+ [Symbol.asyncIterator](): this;
246
+ }
247
+ declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
248
+ interface AsyncIteratorWithSpanOptions extends SetSpanErrorOptions {
249
+ /**
250
+ * The name of the span to create.
251
+ */
252
+ name: string;
253
+ }
254
+ declare function asyncIteratorWithSpan<T, TReturn, TNext>({ name, ...options }: AsyncIteratorWithSpanOptions, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
84
255
 
85
256
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
86
- declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
257
+ declare function stringifyJSON<T>(value: T | {
258
+ toJSON(): T;
259
+ }): undefined extends T ? undefined | string : string;
87
260
 
88
261
  type Segment = string | number;
89
262
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
@@ -99,31 +272,45 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
99
272
  */
100
273
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
101
274
  declare function clone<T>(value: T): T;
102
- declare function get(object: object, path: readonly string[]): unknown;
275
+ declare function get(object: unknown, path: readonly string[]): unknown;
103
276
  declare function isPropertyKey(value: unknown): value is PropertyKey;
104
277
  declare const NullProtoObj: ({
105
278
  new <T extends Record<PropertyKey, unknown>>(): T;
106
279
  });
107
280
 
281
+ /**
282
+ * Prevents objects from being awaitable by intercepting the `then` method
283
+ * when called by the native await mechanism. This is useful for preventing
284
+ * accidental awaiting of objects that aren't meant to be promises.
285
+ */
286
+ declare function preventNativeAwait<T extends object>(target: T): T;
287
+
108
288
  interface AsyncIdQueueCloseOptions {
109
- id?: number;
289
+ id?: string;
110
290
  reason?: unknown;
111
291
  }
112
292
  declare class AsyncIdQueue<T> {
113
293
  private readonly openIds;
114
- private readonly items;
115
- private readonly pendingPulls;
294
+ private readonly queues;
295
+ private readonly waiters;
116
296
  get length(): number;
117
- open(id: number): void;
118
- isOpen(id: number): boolean;
119
- push(id: number, item: T): void;
120
- pull(id: number): Promise<T>;
297
+ get waiterIds(): string[];
298
+ hasBufferedItems(id: string): boolean;
299
+ open(id: string): void;
300
+ isOpen(id: string): boolean;
301
+ push(id: string, item: T): void;
302
+ pull(id: string): Promise<T>;
121
303
  close({ id, reason }?: AsyncIdQueueCloseOptions): void;
122
- assertOpen(id: number): void;
304
+ assertOpen(id: string): void;
123
305
  }
124
306
 
307
+ declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>): AsyncIteratorClass<T>;
308
+ declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
309
+
310
+ declare function tryDecodeURIComponent(value: string): string;
311
+
125
312
  type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
126
313
  declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
127
314
 
128
- export { AsyncIdQueue, NullProtoObj, SequentialIdGenerator, clone, createAsyncIteratorObject, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
129
- export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
315
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, defer, findDeepMatches, get, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
316
+ export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, AsyncIteratorWithSpanOptions, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InferAsyncIterableYield, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, OtelConfig, PromiseWithError, Registry, RunWithSpanOptions, Segment, SetOptional, SetSpanErrorOptions, ThrowableError, Value };
package/dist/index.mjs CHANGED
@@ -12,6 +12,24 @@ function splitInHalf(arr) {
12
12
  return [arr.slice(0, half), arr.slice(half)];
13
13
  }
14
14
 
15
+ function readAsBuffer(source) {
16
+ if (typeof source.bytes === "function") {
17
+ return source.bytes();
18
+ }
19
+ return source.arrayBuffer();
20
+ }
21
+
22
+ const ORPC_NAME = "orpc";
23
+ const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
24
+ const ORPC_SHARED_PACKAGE_VERSION = "0.0.0-next.8caa447";
25
+
26
+ class AbortError extends Error {
27
+ constructor(...rest) {
28
+ super(...rest);
29
+ this.name = "AbortError";
30
+ }
31
+ }
32
+
15
33
  function once(fn) {
16
34
  let cached;
17
35
  return () => {
@@ -33,83 +51,119 @@ function sequential(fn) {
33
51
  };
34
52
  }
35
53
  function defer(callback) {
36
- if ("setTimeout" in globalThis && typeof globalThis.setTimeout === "function") {
37
- globalThis.setTimeout(callback, 0);
54
+ if (typeof setTimeout === "function") {
55
+ setTimeout(callback, 0);
38
56
  } else {
39
57
  Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(callback)));
40
58
  }
41
59
  }
42
60
 
43
- class SequentialIdGenerator {
44
- nextId = 0;
45
- generate() {
46
- if (this.nextId === Number.MAX_SAFE_INTEGER) {
47
- this.nextId = 0;
48
- return Number.MAX_SAFE_INTEGER;
49
- }
50
- return this.nextId++;
51
- }
61
+ const SPAN_ERROR_STATUS = 2;
62
+ const GLOBAL_OTEL_CONFIG_KEY = `__${ORPC_SHARED_PACKAGE_NAME}@${ORPC_SHARED_PACKAGE_VERSION}/otel/config__`;
63
+ function setGlobalOtelConfig(config) {
64
+ globalThis[GLOBAL_OTEL_CONFIG_KEY] = config;
52
65
  }
53
-
54
- function onStart(callback) {
55
- return async (options, ...rest) => {
56
- await callback(options, ...rest);
57
- return await options.next();
58
- };
66
+ function getGlobalOtelConfig() {
67
+ return globalThis[GLOBAL_OTEL_CONFIG_KEY];
59
68
  }
60
- function onSuccess(callback) {
61
- return async (options, ...rest) => {
62
- const result = await options.next();
63
- await callback(result, options, ...rest);
64
- return result;
65
- };
69
+ function startSpan(name, options = {}, context) {
70
+ const tracer = getGlobalOtelConfig()?.tracer;
71
+ return tracer?.startSpan(name, options, context);
66
72
  }
67
- function onError(callback) {
68
- return async (options, ...rest) => {
69
- try {
70
- return await options.next();
71
- } catch (error) {
72
- await callback(error, options, ...rest);
73
- throw error;
73
+ function setSpanError(span, error, options = {}) {
74
+ if (!span) {
75
+ return;
76
+ }
77
+ const exception = toOtelException(error);
78
+ span.recordException(exception);
79
+ if (!options.signal?.aborted || options.signal.reason !== error) {
80
+ span.setStatus({
81
+ code: SPAN_ERROR_STATUS,
82
+ message: exception.message
83
+ });
84
+ }
85
+ }
86
+ function setSpanAttribute(span, key, value) {
87
+ if (!span || value === void 0) {
88
+ return;
89
+ }
90
+ span.setAttribute(key, value);
91
+ }
92
+ function toOtelException(error) {
93
+ if (error instanceof Error) {
94
+ const exception = {
95
+ message: error.message,
96
+ name: error.name,
97
+ stack: error.stack
98
+ };
99
+ if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) {
100
+ exception.code = error.code;
74
101
  }
75
- };
102
+ return exception;
103
+ }
104
+ return { message: String(error) };
76
105
  }
77
- function onFinish(callback) {
78
- let state;
79
- return async (options, ...rest) => {
106
+ function toSpanAttributeValue(data) {
107
+ if (data === void 0) {
108
+ return "undefined";
109
+ }
110
+ try {
111
+ return JSON.stringify(data, (_, value) => {
112
+ if (typeof value === "bigint") {
113
+ return value.toString();
114
+ }
115
+ if (value instanceof Map || value instanceof Set) {
116
+ return Array.from(value);
117
+ }
118
+ return value;
119
+ });
120
+ } catch {
121
+ return String(data);
122
+ }
123
+ }
124
+ async function runWithSpan({ name, context, ...options }, fn) {
125
+ const tracer = getGlobalOtelConfig()?.tracer;
126
+ if (!tracer) {
127
+ return fn();
128
+ }
129
+ const callback = async (span) => {
80
130
  try {
81
- const result = await options.next();
82
- state = [null, result, true];
83
- return result;
84
- } catch (error) {
85
- state = [error, void 0, false];
86
- throw error;
131
+ return await fn(span);
132
+ } catch (e) {
133
+ setSpanError(span, e, options);
134
+ throw e;
87
135
  } finally {
88
- await callback(state, options, ...rest);
136
+ span.end();
89
137
  }
90
138
  };
139
+ if (context) {
140
+ return tracer.startActiveSpan(name, options, context, callback);
141
+ } else {
142
+ return tracer.startActiveSpan(name, options, callback);
143
+ }
91
144
  }
92
- function intercept(interceptors, options, main) {
93
- const next = (options2, index) => {
94
- const interceptor = interceptors[index];
95
- if (!interceptor) {
96
- return main(options2);
97
- }
98
- return interceptor({
99
- ...options2,
100
- next: (newOptions = options2) => next(newOptions, index + 1)
101
- });
102
- };
103
- return next(options, 0);
145
+ async function runInSpanContext(span, fn) {
146
+ const otelConfig = getGlobalOtelConfig();
147
+ if (!span || !otelConfig) {
148
+ return fn();
149
+ }
150
+ const ctx = otelConfig.trace.setSpan(otelConfig.context.active(), span);
151
+ return otelConfig.context.with(ctx, fn);
104
152
  }
105
153
 
106
154
  class AsyncIdQueue {
107
155
  openIds = /* @__PURE__ */ new Set();
108
- items = /* @__PURE__ */ new Map();
109
- pendingPulls = /* @__PURE__ */ new Map();
156
+ queues = /* @__PURE__ */ new Map();
157
+ waiters = /* @__PURE__ */ new Map();
110
158
  get length() {
111
159
  return this.openIds.size;
112
160
  }
161
+ get waiterIds() {
162
+ return Array.from(this.waiters.keys());
163
+ }
164
+ hasBufferedItems(id) {
165
+ return Boolean(this.queues.get(id)?.length);
166
+ }
113
167
  open(id) {
114
168
  this.openIds.add(id);
115
169
  }
@@ -118,59 +172,59 @@ class AsyncIdQueue {
118
172
  }
119
173
  push(id, item) {
120
174
  this.assertOpen(id);
121
- const pending = this.pendingPulls.get(id);
175
+ const pending = this.waiters.get(id);
122
176
  if (pending?.length) {
123
177
  pending.shift()[0](item);
124
178
  if (pending.length === 0) {
125
- this.pendingPulls.delete(id);
179
+ this.waiters.delete(id);
126
180
  }
127
181
  } else {
128
- const items = this.items.get(id);
182
+ const items = this.queues.get(id);
129
183
  if (items) {
130
184
  items.push(item);
131
185
  } else {
132
- this.items.set(id, [item]);
186
+ this.queues.set(id, [item]);
133
187
  }
134
188
  }
135
189
  }
136
190
  async pull(id) {
137
191
  this.assertOpen(id);
138
- const items = this.items.get(id);
192
+ const items = this.queues.get(id);
139
193
  if (items?.length) {
140
194
  const item = items.shift();
141
195
  if (items.length === 0) {
142
- this.items.delete(id);
196
+ this.queues.delete(id);
143
197
  }
144
198
  return item;
145
199
  }
146
200
  return new Promise((resolve, reject) => {
147
- const waitingPulls = this.pendingPulls.get(id);
201
+ const waitingPulls = this.waiters.get(id);
148
202
  const pending = [resolve, reject];
149
203
  if (waitingPulls) {
150
204
  waitingPulls.push(pending);
151
205
  } else {
152
- this.pendingPulls.set(id, [pending]);
206
+ this.waiters.set(id, [pending]);
153
207
  }
154
208
  });
155
209
  }
156
210
  close({ id, reason } = {}) {
157
211
  if (id === void 0) {
158
- this.pendingPulls.forEach((pendingPulls, id2) => {
212
+ this.waiters.forEach((pendingPulls, id2) => {
159
213
  pendingPulls.forEach(([, reject]) => {
160
214
  reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id2}] was closed or aborted while waiting for pulling.`));
161
215
  });
162
216
  });
163
- this.pendingPulls.clear();
217
+ this.waiters.clear();
164
218
  this.openIds.clear();
165
- this.items.clear();
219
+ this.queues.clear();
166
220
  return;
167
221
  }
168
- this.pendingPulls.get(id)?.forEach(([, reject]) => {
222
+ this.waiters.get(id)?.forEach(([, reject]) => {
169
223
  reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`));
170
224
  });
171
- this.pendingPulls.delete(id);
225
+ this.waiters.delete(id);
172
226
  this.openIds.delete(id);
173
- this.items.delete(id);
227
+ this.queues.delete(id);
174
228
  }
175
229
  assertOpen(id) {
176
230
  if (!this.isOpen(id)) {
@@ -183,110 +237,286 @@ function isAsyncIteratorObject(maybe) {
183
237
  if (!maybe || typeof maybe !== "object") {
184
238
  return false;
185
239
  }
186
- return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
240
+ return "next" in maybe && typeof maybe.next === "function" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
187
241
  }
188
- function createAsyncIteratorObject(next, cleanup) {
189
- let isExecuteComplete = false;
190
- let isDone = false;
191
- const iterator = {
192
- next: sequential(async () => {
193
- if (isDone) {
242
+ const fallbackAsyncDisposeSymbol = Symbol.for("asyncDispose");
243
+ const asyncDisposeSymbol = Symbol.asyncDispose ?? fallbackAsyncDisposeSymbol;
244
+ class AsyncIteratorClass {
245
+ #isDone = false;
246
+ #isExecuteComplete = false;
247
+ #cleanup;
248
+ #next;
249
+ constructor(next, cleanup) {
250
+ this.#cleanup = cleanup;
251
+ this.#next = sequential(async () => {
252
+ if (this.#isDone) {
194
253
  return { done: true, value: void 0 };
195
254
  }
196
255
  try {
197
256
  const result = await next();
198
257
  if (result.done) {
199
- isDone = true;
258
+ this.#isDone = true;
200
259
  }
201
260
  return result;
202
261
  } catch (err) {
203
- isDone = true;
262
+ this.#isDone = true;
204
263
  throw err;
205
264
  } finally {
206
- if (isDone && !isExecuteComplete) {
207
- isExecuteComplete = true;
208
- await cleanup("next");
265
+ if (this.#isDone && !this.#isExecuteComplete) {
266
+ this.#isExecuteComplete = true;
267
+ await this.#cleanup("next");
209
268
  }
210
269
  }
211
- }),
212
- async return(value) {
213
- isDone = true;
214
- if (!isExecuteComplete) {
215
- isExecuteComplete = true;
216
- await cleanup("return");
217
- }
218
- return { done: true, value };
219
- },
220
- async throw(err) {
221
- isDone = true;
222
- if (!isExecuteComplete) {
223
- isExecuteComplete = true;
224
- await cleanup("throw");
225
- }
226
- throw err;
227
- },
228
- /**
229
- * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
230
- */
231
- async [Symbol.asyncDispose ?? Symbol.for("asyncDispose")]() {
232
- isDone = true;
233
- if (!isExecuteComplete) {
234
- isExecuteComplete = true;
235
- await cleanup("dispose");
236
- }
237
- },
238
- [Symbol.asyncIterator]() {
239
- return iterator;
270
+ });
271
+ }
272
+ next() {
273
+ return this.#next();
274
+ }
275
+ async return(value) {
276
+ this.#isDone = true;
277
+ if (!this.#isExecuteComplete) {
278
+ this.#isExecuteComplete = true;
279
+ await this.#cleanup("return");
240
280
  }
241
- };
242
- return iterator;
281
+ return { done: true, value };
282
+ }
283
+ async throw(err) {
284
+ this.#isDone = true;
285
+ if (!this.#isExecuteComplete) {
286
+ this.#isExecuteComplete = true;
287
+ await this.#cleanup("throw");
288
+ }
289
+ throw err;
290
+ }
291
+ /**
292
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
293
+ */
294
+ async [asyncDisposeSymbol]() {
295
+ this.#isDone = true;
296
+ if (!this.#isExecuteComplete) {
297
+ this.#isExecuteComplete = true;
298
+ await this.#cleanup("dispose");
299
+ }
300
+ }
301
+ [Symbol.asyncIterator]() {
302
+ return this;
303
+ }
243
304
  }
244
305
  function replicateAsyncIterator(source, count) {
245
306
  const queue = new AsyncIdQueue();
246
- const replicated = [];
247
- let error;
307
+ const ids = Array.from({ length: count }, (_, i) => i.toString());
308
+ let isSourceFinished = false;
248
309
  const start = once(async () => {
249
310
  try {
250
311
  while (true) {
251
312
  const item = await source.next();
252
- for (let id = 0; id < count; id++) {
313
+ ids.forEach((id) => {
253
314
  if (queue.isOpen(id)) {
254
- queue.push(id, item);
315
+ queue.push(id, { next: item });
255
316
  }
256
- }
317
+ });
257
318
  if (item.done) {
258
319
  break;
259
320
  }
260
321
  }
261
- } catch (e) {
262
- error = { value: e };
322
+ } catch (error) {
323
+ ids.forEach((id) => {
324
+ if (queue.isOpen(id)) {
325
+ queue.push(id, { error });
326
+ }
327
+ });
328
+ } finally {
329
+ isSourceFinished = true;
263
330
  }
264
331
  });
265
- for (let id = 0; id < count; id++) {
332
+ const replicated = ids.map((id) => {
266
333
  queue.open(id);
267
- replicated.push(createAsyncIteratorObject(
268
- () => {
334
+ return new AsyncIteratorClass(
335
+ async () => {
269
336
  start();
270
- return new Promise((resolve, reject) => {
271
- queue.pull(id).then(resolve).catch(reject);
272
- defer(() => {
273
- if (error) {
274
- reject(error.value);
275
- }
276
- });
277
- });
337
+ const item = await queue.pull(id);
338
+ if (item.next) {
339
+ return item.next;
340
+ }
341
+ throw item.error;
278
342
  },
279
343
  async (reason) => {
280
344
  queue.close({ id });
345
+ if (reason !== "next" && !queue.length && !isSourceFinished) {
346
+ isSourceFinished = true;
347
+ await source?.return?.();
348
+ }
349
+ }
350
+ );
351
+ });
352
+ return replicated;
353
+ }
354
+ function asyncIteratorWithSpan({ name, ...options }, iterator) {
355
+ let span;
356
+ return new AsyncIteratorClass(
357
+ async () => {
358
+ span ??= startSpan(name);
359
+ try {
360
+ const result = await runInSpanContext(span, () => iterator.next());
361
+ span?.addEvent(result.done ? "completed" : "yielded");
362
+ return result;
363
+ } catch (err) {
364
+ setSpanError(span, err, options);
365
+ throw err;
366
+ }
367
+ },
368
+ async (reason) => {
369
+ try {
281
370
  if (reason !== "next") {
282
- if (replicated.every((_, id2) => !queue.isOpen(id2))) {
283
- await source?.return?.();
284
- }
371
+ await runInSpanContext(span, () => iterator.return?.());
285
372
  }
373
+ } catch (err) {
374
+ setSpanError(span, err, options);
375
+ throw err;
376
+ } finally {
377
+ span?.end();
286
378
  }
287
- ));
379
+ }
380
+ );
381
+ }
382
+
383
+ class EventPublisher {
384
+ #listenersMap = /* @__PURE__ */ new Map();
385
+ #maxBufferedEvents;
386
+ constructor(options = {}) {
387
+ this.#maxBufferedEvents = options.maxBufferedEvents ?? 100;
288
388
  }
289
- return replicated;
389
+ get size() {
390
+ return this.#listenersMap.size;
391
+ }
392
+ /**
393
+ * Emits an event and delivers the payload to all subscribed listeners.
394
+ */
395
+ publish(event, payload) {
396
+ const listeners = this.#listenersMap.get(event);
397
+ if (!listeners) {
398
+ return;
399
+ }
400
+ for (const listener of listeners) {
401
+ listener(payload);
402
+ }
403
+ }
404
+ subscribe(event, listenerOrOptions) {
405
+ if (typeof listenerOrOptions === "function") {
406
+ let listeners = this.#listenersMap.get(event);
407
+ if (!listeners) {
408
+ this.#listenersMap.set(event, listeners = /* @__PURE__ */ new Set());
409
+ }
410
+ listeners.add(listenerOrOptions);
411
+ return () => {
412
+ listeners.delete(listenerOrOptions);
413
+ if (listeners.size === 0) {
414
+ this.#listenersMap.delete(event);
415
+ }
416
+ };
417
+ }
418
+ const signal = listenerOrOptions?.signal;
419
+ const maxBufferedEvents = listenerOrOptions?.maxBufferedEvents ?? this.#maxBufferedEvents;
420
+ signal?.throwIfAborted();
421
+ const bufferedEvents = [];
422
+ const pullResolvers = [];
423
+ const unsubscribe = this.subscribe(event, (payload) => {
424
+ const resolver = pullResolvers.shift();
425
+ if (resolver) {
426
+ resolver[0]({ done: false, value: payload });
427
+ } else {
428
+ bufferedEvents.push(payload);
429
+ if (bufferedEvents.length > maxBufferedEvents) {
430
+ bufferedEvents.shift();
431
+ }
432
+ }
433
+ });
434
+ const abortListener = (event2) => {
435
+ unsubscribe();
436
+ pullResolvers.forEach((resolver) => resolver[1](event2.target.reason));
437
+ pullResolvers.length = 0;
438
+ bufferedEvents.length = 0;
439
+ };
440
+ signal?.addEventListener("abort", abortListener, { once: true });
441
+ return new AsyncIteratorClass(async () => {
442
+ if (signal?.aborted) {
443
+ throw signal.reason;
444
+ }
445
+ if (bufferedEvents.length > 0) {
446
+ return { done: false, value: bufferedEvents.shift() };
447
+ }
448
+ return new Promise((resolve, reject) => {
449
+ pullResolvers.push([resolve, reject]);
450
+ });
451
+ }, async () => {
452
+ unsubscribe();
453
+ signal?.removeEventListener("abort", abortListener);
454
+ pullResolvers.forEach((resolver) => resolver[0]({ done: true, value: void 0 }));
455
+ pullResolvers.length = 0;
456
+ bufferedEvents.length = 0;
457
+ });
458
+ }
459
+ }
460
+
461
+ class SequentialIdGenerator {
462
+ index = BigInt(0);
463
+ generate() {
464
+ const id = this.index.toString(32);
465
+ this.index++;
466
+ return id;
467
+ }
468
+ }
469
+
470
+ function onStart(callback) {
471
+ return async (options, ...rest) => {
472
+ await callback(options, ...rest);
473
+ return await options.next();
474
+ };
475
+ }
476
+ function onSuccess(callback) {
477
+ return async (options, ...rest) => {
478
+ const result = await options.next();
479
+ await callback(result, options, ...rest);
480
+ return result;
481
+ };
482
+ }
483
+ function onError(callback) {
484
+ return async (options, ...rest) => {
485
+ try {
486
+ return await options.next();
487
+ } catch (error) {
488
+ await callback(error, options, ...rest);
489
+ throw error;
490
+ }
491
+ };
492
+ }
493
+ function onFinish(callback) {
494
+ let state;
495
+ return async (options, ...rest) => {
496
+ try {
497
+ const result = await options.next();
498
+ state = [null, result, true];
499
+ return result;
500
+ } catch (error) {
501
+ state = [error, void 0, false];
502
+ throw error;
503
+ } finally {
504
+ await callback(state, options, ...rest);
505
+ }
506
+ };
507
+ }
508
+ function intercept(interceptors, options, main) {
509
+ const next = (options2, index) => {
510
+ const interceptor = interceptors[index];
511
+ if (!interceptor) {
512
+ return main(options2);
513
+ }
514
+ return interceptor({
515
+ ...options2,
516
+ next: (newOptions = options2) => next(newOptions, index + 1)
517
+ });
518
+ };
519
+ return next(options, 0);
290
520
  }
291
521
 
292
522
  function parseEmptyableJSON(text) {
@@ -359,6 +589,73 @@ const NullProtoObj = /* @__PURE__ */ (() => {
359
589
  return e;
360
590
  })();
361
591
 
592
+ function preventNativeAwait(target) {
593
+ return new Proxy(target, {
594
+ get(target2, prop, receiver) {
595
+ const value = Reflect.get(target2, prop, receiver);
596
+ if (prop !== "then" || typeof value !== "function") {
597
+ return value;
598
+ }
599
+ return new Proxy(value, {
600
+ apply(targetFn, thisArg, args) {
601
+ if (args.length !== 2 || args.some((arg) => !isNativeFunction(arg))) {
602
+ return Reflect.apply(targetFn, thisArg, args);
603
+ }
604
+ let shouldOmit = true;
605
+ args[0].call(thisArg, preventNativeAwait(new Proxy(target2, {
606
+ get: (target3, prop2, receiver2) => {
607
+ if (shouldOmit && prop2 === "then") {
608
+ shouldOmit = false;
609
+ return void 0;
610
+ }
611
+ return Reflect.get(target3, prop2, receiver2);
612
+ }
613
+ })));
614
+ }
615
+ });
616
+ }
617
+ });
618
+ }
619
+ const NATIVE_FUNCTION_REGEX = /^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;
620
+ function isNativeFunction(fn) {
621
+ return typeof fn === "function" && NATIVE_FUNCTION_REGEX.test(fn.toString());
622
+ }
623
+
624
+ function streamToAsyncIteratorClass(stream) {
625
+ const reader = stream.getReader();
626
+ return new AsyncIteratorClass(
627
+ async () => {
628
+ return reader.read();
629
+ },
630
+ async () => {
631
+ await reader.cancel();
632
+ }
633
+ );
634
+ }
635
+ function asyncIteratorToStream(iterator) {
636
+ return new ReadableStream({
637
+ async pull(controller) {
638
+ const { done, value } = await iterator.next();
639
+ if (done) {
640
+ controller.close();
641
+ } else {
642
+ controller.enqueue(value);
643
+ }
644
+ },
645
+ async cancel() {
646
+ await iterator.return?.();
647
+ }
648
+ });
649
+ }
650
+
651
+ function tryDecodeURIComponent(value) {
652
+ try {
653
+ return decodeURIComponent(value);
654
+ } catch {
655
+ return value;
656
+ }
657
+ }
658
+
362
659
  function value(value2, ...args) {
363
660
  if (typeof value2 === "function") {
364
661
  return value2(...args);
@@ -366,4 +663,4 @@ function value(value2, ...args) {
366
663
  return value2;
367
664
  }
368
665
 
369
- export { AsyncIdQueue, NullProtoObj, SequentialIdGenerator, clone, createAsyncIteratorObject, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
666
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, defer, findDeepMatches, get, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/shared",
3
3
  "type": "module",
4
- "version": "0.0.0-next.8c618ab",
4
+ "version": "0.0.0-next.8caa447",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -23,14 +23,23 @@
23
23
  "files": [
24
24
  "dist"
25
25
  ],
26
+ "peerDependencies": {
27
+ "@opentelemetry/api": ">=1.9.0"
28
+ },
29
+ "peerDependenciesMeta": {
30
+ "@opentelemetry/api": {
31
+ "optional": true
32
+ }
33
+ },
26
34
  "dependencies": {
27
- "radash": "^12.1.0",
35
+ "radash": "^12.1.1",
28
36
  "type-fest": "^4.39.1"
29
37
  },
30
38
  "devDependencies": {
39
+ "@opentelemetry/api": "^1.9.0",
31
40
  "arktype": "2.1.20",
32
41
  "valibot": "^1.1.0",
33
- "zod": "^3.25.49"
42
+ "zod": "^4.1.5"
34
43
  },
35
44
  "scripts": {
36
45
  "build": "unbuild",