@orpc/shared 0.0.0-next.fd6982a → 0.0.0-next.fdd2389

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/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Promisable } from 'type-fest';
2
- export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
3
- export { group, guard, mapEntries, mapValues, omit } from 'radash';
2
+ export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
3
+ import { Tracer, TraceAPI, ContextAPI, PropagationAPI, SpanOptions, Context, Span, AttributeValue, Exception } from '@opentelemetry/api';
4
+ export { group, guard, mapEntries, mapValues, omit, retry, sleep } from 'radash';
4
5
 
5
6
  type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
6
7
  declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
@@ -8,17 +9,99 @@ 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>;
22
+ /**
23
+ * Executes the callback function after the current call stack has been cleared.
24
+ */
25
+ declare function defer(callback: () => void): void;
14
26
 
15
27
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
16
28
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
17
29
  };
18
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.fdd2389";
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
+
19
102
  declare class SequentialIdGenerator {
20
- private nextId;
21
- generate(): number;
103
+ private index;
104
+ generate(): string;
22
105
  }
23
106
 
24
107
  type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
@@ -38,6 +121,7 @@ interface Registry {
38
121
  type ThrowableError = Registry extends {
39
122
  throwableError: infer T;
40
123
  } ? T : Error;
124
+ type InferAsyncIterableYield<T> = T extends AsyncIterable<infer U> ? U : never;
41
125
 
42
126
  type InterceptableOptions = Record<string, any>;
43
127
  type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
@@ -71,20 +155,119 @@ declare function onFinish<T, TOptions extends {
71
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']>>>;
72
156
  declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
73
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
+
74
224
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
75
- interface CreateAsyncIteratorObjectCleanupFn {
225
+ interface AsyncIteratorClassNextFn<T, TReturn> {
226
+ (): Promise<IteratorResult<T, TReturn>>;
227
+ }
228
+ interface AsyncIteratorClassCleanupFn {
76
229
  (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
77
230
  }
78
- declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): 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>;
79
255
 
80
256
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
81
- 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;
82
260
 
83
261
  type Segment = string | number;
84
262
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
85
263
  maps: Segment[][];
86
264
  values: unknown[];
87
265
  };
266
+ /**
267
+ * Get constructor of the value
268
+ *
269
+ */
270
+ declare function getConstructor(value: unknown): Function | null | undefined;
88
271
  /**
89
272
  * Check if the value is an object even it created by `Object.create(null)` or more tricky way.
90
273
  */
@@ -94,28 +277,59 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
94
277
  */
95
278
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
96
279
  declare function clone<T>(value: T): T;
97
- declare function get(object: object, path: readonly string[]): unknown;
280
+ declare function get(object: unknown, path: readonly string[]): unknown;
98
281
  declare function isPropertyKey(value: unknown): value is PropertyKey;
282
+ declare const NullProtoObj: ({
283
+ new <T extends Record<PropertyKey, unknown>>(): T;
284
+ });
285
+
286
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
287
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
288
+ /**
289
+ * Returns the value if it is defined, otherwise returns the fallback
290
+ */
291
+ declare function fallback<T>(value: T | undefined, fallback: T): T;
292
+
293
+ /**
294
+ * Prevents objects from being awaitable by intercepting the `then` method
295
+ * when called by the native await mechanism. This is useful for preventing
296
+ * accidental awaiting of objects that aren't meant to be promises.
297
+ */
298
+ declare function preventNativeAwait<T extends object>(target: T): T;
299
+ /**
300
+ * Create a proxy that overlays one object (`overlay`) on top of another (`target`).
301
+ *
302
+ * - Properties from `overlay` take precedence.
303
+ * - Properties not in `overlay` fall back to `target`.
304
+ * - Methods from either object are bound to `overlay` so `this` is consistent.
305
+ *
306
+ * Useful when you want to override or extend behavior without fully copying/merging objects.
307
+ */
308
+ declare function overlayProxy<T extends object, U extends object>(target: Value<T>, partial: U): U & Omit<T, keyof U>;
99
309
 
100
310
  interface AsyncIdQueueCloseOptions {
101
- id?: number;
102
- reason?: Error;
311
+ id?: string;
312
+ reason?: unknown;
103
313
  }
104
314
  declare class AsyncIdQueue<T> {
105
315
  private readonly openIds;
106
- private readonly items;
107
- private readonly pendingPulls;
316
+ private readonly queues;
317
+ private readonly waiters;
108
318
  get length(): number;
109
- open(id: number): void;
110
- isOpen(id: number): boolean;
111
- push(id: number, item: T): void;
112
- pull(id: number): Promise<T>;
319
+ get waiterIds(): string[];
320
+ hasBufferedItems(id: string): boolean;
321
+ open(id: string): void;
322
+ isOpen(id: string): boolean;
323
+ push(id: string, item: T): void;
324
+ pull(id: string): Promise<T>;
113
325
  close({ id, reason }?: AsyncIdQueueCloseOptions): void;
114
- assertOpen(id: number): void;
326
+ assertOpen(id: string): void;
115
327
  }
116
328
 
117
- type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
118
- declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
329
+ declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>): AsyncIteratorClass<T>;
330
+ declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
331
+
332
+ declare function tryDecodeURIComponent(value: string): string;
119
333
 
120
- export { AsyncIdQueue, SequentialIdGenerator, clone, createAsyncIteratorObject, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
121
- export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
334
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, defer, fallback, findDeepMatches, get, getConstructor, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
335
+ 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 };