@orpc/shared 0.0.0-next.343cede → 0.0.0-next.347f023

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
 
@@ -55,9 +50,11 @@ You can find the full documentation [here](https://orpc.unnoq.com).
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
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.
58
54
  - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
59
55
  - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
60
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.
61
58
  - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
62
59
  - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
63
60
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
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,6 +28,18 @@ 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.347f023";
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
+
23
43
  interface EventPublisherOptions {
24
44
  /**
25
45
  * Maximum number of events to buffer for async iterator subscribers.
@@ -80,8 +100,8 @@ declare class EventPublisher<T extends Record<PropertyKey, any>> {
80
100
  }
81
101
 
82
102
  declare class SequentialIdGenerator {
83
- private nextId;
84
- generate(): number;
103
+ private index;
104
+ generate(): string;
85
105
  }
86
106
 
87
107
  type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
@@ -101,6 +121,7 @@ interface Registry {
101
121
  type ThrowableError = Registry extends {
102
122
  throwableError: infer T;
103
123
  } ? T : Error;
124
+ type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
104
125
 
105
126
  type InterceptableOptions = Record<string, any>;
106
127
  type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
@@ -134,6 +155,72 @@ declare function onFinish<T, TOptions extends {
134
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']>>>;
135
156
  declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
136
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
+
137
224
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
138
225
  interface AsyncIteratorClassNextFn<T, TReturn> {
139
226
  (): Promise<IteratorResult<T, TReturn>>;
@@ -158,9 +245,18 @@ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implemen
158
245
  [Symbol.asyncIterator](): this;
159
246
  }
160
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>;
161
255
 
162
256
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
163
- 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;
164
260
 
165
261
  type Segment = string | number;
166
262
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
@@ -176,31 +272,45 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
176
272
  */
177
273
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
178
274
  declare function clone<T>(value: T): T;
179
- declare function get(object: object, path: readonly string[]): unknown;
275
+ declare function get(object: unknown, path: readonly string[]): unknown;
180
276
  declare function isPropertyKey(value: unknown): value is PropertyKey;
181
277
  declare const NullProtoObj: ({
182
278
  new <T extends Record<PropertyKey, unknown>>(): T;
183
279
  });
184
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
+
185
288
  interface AsyncIdQueueCloseOptions {
186
- id?: number;
289
+ id?: string;
187
290
  reason?: unknown;
188
291
  }
189
292
  declare class AsyncIdQueue<T> {
190
293
  private readonly openIds;
191
- private readonly items;
192
- private readonly pendingPulls;
294
+ private readonly queues;
295
+ private readonly waiters;
193
296
  get length(): number;
194
- open(id: number): void;
195
- isOpen(id: number): boolean;
196
- push(id: number, item: T): void;
197
- 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>;
198
303
  close({ id, reason }?: AsyncIdQueueCloseOptions): void;
199
- assertOpen(id: number): void;
304
+ assertOpen(id: string): void;
200
305
  }
201
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
+
202
312
  type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
203
313
  declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
204
314
 
205
- export { AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
206
- export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, 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,6 +28,18 @@ 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.347f023";
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
+
23
43
  interface EventPublisherOptions {
24
44
  /**
25
45
  * Maximum number of events to buffer for async iterator subscribers.
@@ -80,8 +100,8 @@ declare class EventPublisher<T extends Record<PropertyKey, any>> {
80
100
  }
81
101
 
82
102
  declare class SequentialIdGenerator {
83
- private nextId;
84
- generate(): number;
103
+ private index;
104
+ generate(): string;
85
105
  }
86
106
 
87
107
  type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
@@ -101,6 +121,7 @@ interface Registry {
101
121
  type ThrowableError = Registry extends {
102
122
  throwableError: infer T;
103
123
  } ? T : Error;
124
+ type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
104
125
 
105
126
  type InterceptableOptions = Record<string, any>;
106
127
  type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
@@ -134,6 +155,72 @@ declare function onFinish<T, TOptions extends {
134
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']>>>;
135
156
  declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
136
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
+
137
224
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
138
225
  interface AsyncIteratorClassNextFn<T, TReturn> {
139
226
  (): Promise<IteratorResult<T, TReturn>>;
@@ -158,9 +245,18 @@ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implemen
158
245
  [Symbol.asyncIterator](): this;
159
246
  }
160
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>;
161
255
 
162
256
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
163
- 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;
164
260
 
165
261
  type Segment = string | number;
166
262
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
@@ -176,31 +272,45 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
176
272
  */
177
273
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
178
274
  declare function clone<T>(value: T): T;
179
- declare function get(object: object, path: readonly string[]): unknown;
275
+ declare function get(object: unknown, path: readonly string[]): unknown;
180
276
  declare function isPropertyKey(value: unknown): value is PropertyKey;
181
277
  declare const NullProtoObj: ({
182
278
  new <T extends Record<PropertyKey, unknown>>(): T;
183
279
  });
184
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
+
185
288
  interface AsyncIdQueueCloseOptions {
186
- id?: number;
289
+ id?: string;
187
290
  reason?: unknown;
188
291
  }
189
292
  declare class AsyncIdQueue<T> {
190
293
  private readonly openIds;
191
- private readonly items;
192
- private readonly pendingPulls;
294
+ private readonly queues;
295
+ private readonly waiters;
193
296
  get length(): number;
194
- open(id: number): void;
195
- isOpen(id: number): boolean;
196
- push(id: number, item: T): void;
197
- 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>;
198
303
  close({ id, reason }?: AsyncIdQueueCloseOptions): void;
199
- assertOpen(id: number): void;
304
+ assertOpen(id: string): void;
200
305
  }
201
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
+
202
312
  type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
203
313
  declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
204
314
 
205
- export { AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
206
- export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, 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.347f023";
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 () => {
@@ -40,13 +58,112 @@ function defer(callback) {
40
58
  }
41
59
  }
42
60
 
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;
65
+ }
66
+ function getGlobalOtelConfig() {
67
+ return globalThis[GLOBAL_OTEL_CONFIG_KEY];
68
+ }
69
+ function startSpan(name, options = {}, context) {
70
+ const tracer = getGlobalOtelConfig()?.tracer;
71
+ return tracer?.startSpan(name, options, context);
72
+ }
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;
101
+ }
102
+ return exception;
103
+ }
104
+ return { message: String(error) };
105
+ }
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) => {
130
+ try {
131
+ return await fn(span);
132
+ } catch (e) {
133
+ setSpanError(span, e, options);
134
+ throw e;
135
+ } finally {
136
+ span.end();
137
+ }
138
+ };
139
+ if (context) {
140
+ return tracer.startActiveSpan(name, options, context, callback);
141
+ } else {
142
+ return tracer.startActiveSpan(name, options, callback);
143
+ }
144
+ }
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);
152
+ }
153
+
43
154
  class AsyncIdQueue {
44
155
  openIds = /* @__PURE__ */ new Set();
45
- items = /* @__PURE__ */ new Map();
46
- pendingPulls = /* @__PURE__ */ new Map();
156
+ queues = /* @__PURE__ */ new Map();
157
+ waiters = /* @__PURE__ */ new Map();
47
158
  get length() {
48
159
  return this.openIds.size;
49
160
  }
161
+ get waiterIds() {
162
+ return Array.from(this.waiters.keys());
163
+ }
164
+ hasBufferedItems(id) {
165
+ return Boolean(this.queues.get(id)?.length);
166
+ }
50
167
  open(id) {
51
168
  this.openIds.add(id);
52
169
  }
@@ -55,59 +172,59 @@ class AsyncIdQueue {
55
172
  }
56
173
  push(id, item) {
57
174
  this.assertOpen(id);
58
- const pending = this.pendingPulls.get(id);
175
+ const pending = this.waiters.get(id);
59
176
  if (pending?.length) {
60
177
  pending.shift()[0](item);
61
178
  if (pending.length === 0) {
62
- this.pendingPulls.delete(id);
179
+ this.waiters.delete(id);
63
180
  }
64
181
  } else {
65
- const items = this.items.get(id);
182
+ const items = this.queues.get(id);
66
183
  if (items) {
67
184
  items.push(item);
68
185
  } else {
69
- this.items.set(id, [item]);
186
+ this.queues.set(id, [item]);
70
187
  }
71
188
  }
72
189
  }
73
190
  async pull(id) {
74
191
  this.assertOpen(id);
75
- const items = this.items.get(id);
192
+ const items = this.queues.get(id);
76
193
  if (items?.length) {
77
194
  const item = items.shift();
78
195
  if (items.length === 0) {
79
- this.items.delete(id);
196
+ this.queues.delete(id);
80
197
  }
81
198
  return item;
82
199
  }
83
200
  return new Promise((resolve, reject) => {
84
- const waitingPulls = this.pendingPulls.get(id);
201
+ const waitingPulls = this.waiters.get(id);
85
202
  const pending = [resolve, reject];
86
203
  if (waitingPulls) {
87
204
  waitingPulls.push(pending);
88
205
  } else {
89
- this.pendingPulls.set(id, [pending]);
206
+ this.waiters.set(id, [pending]);
90
207
  }
91
208
  });
92
209
  }
93
210
  close({ id, reason } = {}) {
94
211
  if (id === void 0) {
95
- this.pendingPulls.forEach((pendingPulls, id2) => {
212
+ this.waiters.forEach((pendingPulls, id2) => {
96
213
  pendingPulls.forEach(([, reject]) => {
97
214
  reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id2}] was closed or aborted while waiting for pulling.`));
98
215
  });
99
216
  });
100
- this.pendingPulls.clear();
217
+ this.waiters.clear();
101
218
  this.openIds.clear();
102
- this.items.clear();
219
+ this.queues.clear();
103
220
  return;
104
221
  }
105
- this.pendingPulls.get(id)?.forEach(([, reject]) => {
222
+ this.waiters.get(id)?.forEach(([, reject]) => {
106
223
  reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`));
107
224
  });
108
- this.pendingPulls.delete(id);
225
+ this.waiters.delete(id);
109
226
  this.openIds.delete(id);
110
- this.items.delete(id);
227
+ this.queues.delete(id);
111
228
  }
112
229
  assertOpen(id) {
113
230
  if (!this.isOpen(id)) {
@@ -120,7 +237,7 @@ function isAsyncIteratorObject(maybe) {
120
237
  if (!maybe || typeof maybe !== "object") {
121
238
  return false;
122
239
  }
123
- 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";
124
241
  }
125
242
  const fallbackAsyncDisposeSymbol = Symbol.for("asyncDispose");
126
243
  const asyncDisposeSymbol = Symbol.asyncDispose ?? fallbackAsyncDisposeSymbol;
@@ -193,7 +310,8 @@ function replicateAsyncIterator(source, count) {
193
310
  try {
194
311
  while (true) {
195
312
  const item = await source.next();
196
- for (let id = 0; id < count; id++) {
313
+ for (let i = 0; i < count; i++) {
314
+ const id = i.toString();
197
315
  if (queue.isOpen(id)) {
198
316
  queue.push(id, item);
199
317
  }
@@ -202,28 +320,31 @@ function replicateAsyncIterator(source, count) {
202
320
  break;
203
321
  }
204
322
  }
205
- } catch (e) {
206
- error = { value: e };
323
+ } catch (reason) {
324
+ error = { value: reason };
325
+ queue.waiterIds.forEach((id) => {
326
+ queue.close({ id, reason });
327
+ });
207
328
  }
208
329
  });
209
- for (let id = 0; id < count; id++) {
330
+ for (let i = 0; i < count; i++) {
331
+ const id = i.toString();
210
332
  queue.open(id);
211
333
  replicated.push(new AsyncIteratorClass(
212
334
  () => {
213
335
  start();
214
336
  return new Promise((resolve, reject) => {
215
- queue.pull(id).then(resolve).catch(reject);
216
- defer(() => {
217
- if (error) {
218
- reject(error.value);
219
- }
220
- });
337
+ if (!error || queue.hasBufferedItems(id)) {
338
+ queue.pull(id).then(resolve).catch(reject);
339
+ } else {
340
+ reject(error.value);
341
+ }
221
342
  });
222
343
  },
223
344
  async (reason) => {
224
345
  queue.close({ id });
225
346
  if (reason !== "next") {
226
- if (replicated.every((_, id2) => !queue.isOpen(id2))) {
347
+ if (!queue.length) {
227
348
  await source?.return?.();
228
349
  }
229
350
  }
@@ -232,6 +353,34 @@ function replicateAsyncIterator(source, count) {
232
353
  }
233
354
  return replicated;
234
355
  }
356
+ function asyncIteratorWithSpan({ name, ...options }, iterator) {
357
+ let span;
358
+ return new AsyncIteratorClass(
359
+ async () => {
360
+ span ??= startSpan(name);
361
+ try {
362
+ const result = await runInSpanContext(span, () => iterator.next());
363
+ span?.addEvent(result.done ? "completed" : "yielded");
364
+ return result;
365
+ } catch (err) {
366
+ setSpanError(span, err, options);
367
+ throw err;
368
+ }
369
+ },
370
+ async (reason) => {
371
+ try {
372
+ if (reason !== "next") {
373
+ await runInSpanContext(span, () => iterator.return?.());
374
+ }
375
+ } catch (err) {
376
+ setSpanError(span, err, options);
377
+ throw err;
378
+ } finally {
379
+ span?.end();
380
+ }
381
+ }
382
+ );
383
+ }
235
384
 
236
385
  class EventPublisher {
237
386
  #listenersMap = /* @__PURE__ */ new Map();
@@ -270,6 +419,7 @@ class EventPublisher {
270
419
  }
271
420
  const signal = listenerOrOptions?.signal;
272
421
  const maxBufferedEvents = listenerOrOptions?.maxBufferedEvents ?? this.#maxBufferedEvents;
422
+ signal?.throwIfAborted();
273
423
  const bufferedEvents = [];
274
424
  const pullResolvers = [];
275
425
  const unsubscribe = this.subscribe(event, (payload) => {
@@ -311,13 +461,11 @@ class EventPublisher {
311
461
  }
312
462
 
313
463
  class SequentialIdGenerator {
314
- nextId = 0;
464
+ index = BigInt(0);
315
465
  generate() {
316
- if (this.nextId === Number.MAX_SAFE_INTEGER) {
317
- this.nextId = 0;
318
- return Number.MAX_SAFE_INTEGER;
319
- }
320
- return this.nextId++;
466
+ const id = this.index.toString(32);
467
+ this.index++;
468
+ return id;
321
469
  }
322
470
  }
323
471
 
@@ -443,6 +591,73 @@ const NullProtoObj = /* @__PURE__ */ (() => {
443
591
  return e;
444
592
  })();
445
593
 
594
+ function preventNativeAwait(target) {
595
+ return new Proxy(target, {
596
+ get(target2, prop, receiver) {
597
+ const value = Reflect.get(target2, prop, receiver);
598
+ if (prop !== "then" || typeof value !== "function") {
599
+ return value;
600
+ }
601
+ return new Proxy(value, {
602
+ apply(targetFn, thisArg, args) {
603
+ if (args.length !== 2 || args.some((arg) => !isNativeFunction(arg))) {
604
+ return Reflect.apply(targetFn, thisArg, args);
605
+ }
606
+ let shouldOmit = true;
607
+ args[0].call(thisArg, preventNativeAwait(new Proxy(target2, {
608
+ get: (target3, prop2, receiver2) => {
609
+ if (shouldOmit && prop2 === "then") {
610
+ shouldOmit = false;
611
+ return void 0;
612
+ }
613
+ return Reflect.get(target3, prop2, receiver2);
614
+ }
615
+ })));
616
+ }
617
+ });
618
+ }
619
+ });
620
+ }
621
+ const NATIVE_FUNCTION_REGEX = /^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;
622
+ function isNativeFunction(fn) {
623
+ return typeof fn === "function" && NATIVE_FUNCTION_REGEX.test(fn.toString());
624
+ }
625
+
626
+ function streamToAsyncIteratorClass(stream) {
627
+ const reader = stream.getReader();
628
+ return new AsyncIteratorClass(
629
+ async () => {
630
+ return reader.read();
631
+ },
632
+ async () => {
633
+ await reader.cancel();
634
+ }
635
+ );
636
+ }
637
+ function asyncIteratorToStream(iterator) {
638
+ return new ReadableStream({
639
+ async pull(controller) {
640
+ const { done, value } = await iterator.next();
641
+ if (done) {
642
+ controller.close();
643
+ } else {
644
+ controller.enqueue(value);
645
+ }
646
+ },
647
+ async cancel() {
648
+ await iterator.return?.();
649
+ }
650
+ });
651
+ }
652
+
653
+ function tryDecodeURIComponent(value) {
654
+ try {
655
+ return decodeURIComponent(value);
656
+ } catch {
657
+ return value;
658
+ }
659
+ }
660
+
446
661
  function value(value2, ...args) {
447
662
  if (typeof value2 === "function") {
448
663
  return value2(...args);
@@ -450,4 +665,4 @@ function value(value2, ...args) {
450
665
  return value2;
451
666
  }
452
667
 
453
- export { AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
668
+ 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.343cede",
4
+ "version": "0.0.0-next.347f023",
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.1"
34
43
  },
35
44
  "scripts": {
36
45
  "build": "unbuild",