@orpc/shared 2.0.0-beta.14 → 2.0.0-beta.15

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
@@ -107,7 +107,6 @@ Like what we build over at [middleapi](https://github.com/middleapi)? You can he
107
107
  </tr>
108
108
  <tr>
109
109
  <td align="center"><a href="https://github.com/christ12938?ref=orpc" target="_blank" rel="noopener" title="christ12938"><img src="https://avatars.githubusercontent.com/u/25758598?v=4" width="139" alt="christ12938"/><br />christ12938</a></td>
110
- <td align="center"><a href="https://github.com/peter-adam-dy?ref=orpc" target="_blank" rel="noopener" title="Peter Adam"><img src="https://avatars.githubusercontent.com/u/132129459?u=4f3dbbb3b443990b56acb7d6a5d11ed2c555f6db&amp;v=4" width="139" alt="Peter Adam"/><br />Peter Adam</a></td>
111
110
  <td align="center"><a href="https://github.com/Ryanjso?ref=orpc" target="_blank" rel="noopener" title="Ryan Soderberg"><img src="https://avatars.githubusercontent.com/u/39172778?u=5ed913c31d57e7221b75784abcad48c7ebddde27&amp;v=4" width="139" alt="Ryan Soderberg"/><br />Ryan Soderberg</a></td>
112
111
  <td align="center"><a href="https://github.com/itigoore01?ref=orpc" target="_blank" rel="noopener" title="shota"><img src="https://avatars.githubusercontent.com/u/11831107?u=c976a6dc7e055eb026304c46c99100ed22b0c8e0&amp;v=4" width="139" alt="shota"/><br />shota</a></td>
113
112
  </tr>
@@ -168,6 +167,7 @@ Like what we build over at [middleapi](https://github.com/middleapi)? You can he
168
167
  <a href="https://github.com/nguyenlc1993?ref=orpc" target="_blank" rel="noopener" title="Lê Cao Nguyên"><img src="https://avatars.githubusercontent.com/u/13871971?u=83c8b69d9e35b589c4e1f066cc113b1d9461386f&amp;v=4" width="32" height="32" alt="Lê Cao Nguyên" /></a>
169
168
  <a href="https://github.com/wobsoriano?ref=orpc" target="_blank" rel="noopener" title="Robert Soriano"><img src="https://avatars.githubusercontent.com/u/13049130?u=6d72104182e7c9ed25934815313fb69107332111&amp;v=4" width="32" height="32" alt="Robert Soriano" /></a>
170
169
  <a href="https://github.com/SKostyukovich?ref=orpc" target="_blank" rel="noopener" title="SKostyukovich"><img src="https://avatars.githubusercontent.com/u/10700067?v=4" width="32" height="32" alt="SKostyukovich" /></a>
170
+ <a href="https://github.com/peter-adam-dy?ref=orpc" target="_blank" rel="noopener" title="Peter Adam"><img src="https://avatars.githubusercontent.com/u/132129459?u=4f3dbbb3b443990b56acb7d6a5d11ed2c555f6db&amp;v=4" width="32" height="32" alt="Peter Adam" /></a>
171
171
  <a href="https://github.com/FabworksHQ?ref=orpc" target="_blank" rel="noopener" title="Fabworks"><img src="https://avatars.githubusercontent.com/u/160179500?v=4" width="32" height="32" alt="Fabworks" /></a>
172
172
  <a href="https://github.com/NovakAnton?ref=orpc" target="_blank" rel="noopener" title="Novak Antonijevic"><img src="https://avatars.githubusercontent.com/u/157126729?u=ae49fa22292d55c0434ff0ca008206155b18663b&amp;v=4" width="32" height="32" alt="Novak Antonijevic" /></a>
173
173
  <a href="https://github.com/laduniestu?ref=orpc" target="_blank" rel="noopener" title="Laduni Estu Syalwa"><img src="https://avatars.githubusercontent.com/u/44757637?u=a2fc1ea8f7d827a96721176f79d30592d1c48059&amp;v=4" width="32" height="32" alt="Laduni Estu Syalwa" /></a>
package/dist/index.d.mts CHANGED
@@ -102,6 +102,30 @@ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess
102
102
  declare function onFinish<T, TOptions extends {
103
103
  next: () => any;
104
104
  }, 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']>>>;
105
+ /**
106
+ * Creates a middleware or interceptor that invokes a callback when the returned async
107
+ * iterator object throws an error while being consumed.
108
+ *
109
+ * This does not replace the `onError`. `onError` only fires on the
110
+ * initial call (before the interceptor returns the iterator), whereas this
111
+ * callback only fires while consuming the iterator. Use both together to
112
+ * catch all possible errors.
113
+ */
114
+ declare function onAsyncIteratorObjectError<T, TOptions extends {
115
+ next: () => any;
116
+ }, TRest extends any[]>(callback: NoInfer<(error: ThrowableError | (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']>>>;
117
+ /**
118
+ * Creates an interceptor that invokes a callback when the returned readable
119
+ * stream errors while being consumed.
120
+ *
121
+ * This does not replace the `onError`. `onError` only fires on the
122
+ * initial call (before the interceptor returns the stream), whereas this
123
+ * callback only fires while consuming the stream. Use both together to catch
124
+ * all possible errors.
125
+ */
126
+ declare function onReadableStreamError<T, TOptions extends {
127
+ next: () => any;
128
+ }, TRest extends any[]>(callback: NoInfer<(error: ThrowableError | (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']>>>;
105
129
  declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: undefined | Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
106
130
 
107
131
  /**
@@ -147,8 +171,8 @@ interface WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>
147
171
  */
148
172
  runWith?: <T>(run: () => Promise<T>) => Promise<T>;
149
173
  mapResult?: (result: IteratorResult<TYield, TReturn>) => Promisable<IteratorResult<TMappedYield, TMappedReturn>>;
150
- mapError?: (error: unknown) => Promisable<unknown>;
151
- onError?: (error: unknown) => Promisable<void>;
174
+ mapError?: (error: ThrowableError) => Promisable<ThrowableError>;
175
+ onError?: (error: ThrowableError) => Promisable<void>;
152
176
  /**
153
177
  * Execute after the stream finishes or is cancelled.
154
178
  */
@@ -157,6 +181,35 @@ interface WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>
157
181
  declare function wrapAsyncIterator<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { runWith, mapResult, mapError, onError, onFinish }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): NoInfer<AsyncIteratorClass<TMappedYield, TMappedReturn>>;
158
182
  declare function traceAsyncIterator<T, TReturn, TNext>(options: StartSpanOptions | string, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
159
183
  declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
184
+ interface ConsumeAsyncIteratorOptions<T, TReturn, TError> {
185
+ /**
186
+ * Called on each event
187
+ */
188
+ onEvent: (event: T) => void;
189
+ /**
190
+ * Called once error happens
191
+ */
192
+ onError?: (error: TError) => void;
193
+ /**
194
+ * Called once AsyncIteratorObject is done
195
+ *
196
+ * @info If iterator is canceled, `undefined` can be passed on success
197
+ */
198
+ onSuccess?: (value: TReturn | undefined) => void;
199
+ /**
200
+ * Called once after onError or onSuccess
201
+ *
202
+ * @info If iterator is canceled, `undefined` can be passed on success
203
+ */
204
+ onFinish?: (state: [error: TError, data: undefined, isSuccess: false] | [error: null, data: TReturn | undefined, isSuccess: true]) => void;
205
+ }
206
+ /**
207
+ * Consumes an AsyncIteratorObject with lifecycle callbacks
208
+ *
209
+ * @warning If no `onError` or `onFinish` is provided, error will be thrown into unhandled rejection channel.
210
+ * @return unsubscribe callback
211
+ */
212
+ declare function consumeAsyncIterator<T, TReturn, TError = ThrowableError>(iterator: AsyncIterator<T, TReturn> | PromiseWithError<AsyncIterator<T, TReturn>, TError>, options: ConsumeAsyncIteratorOptions<T, TReturn, TError | ThrowableError>): () => Promise<void>;
160
213
 
161
214
  type Segment = string | number;
162
215
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
@@ -275,8 +328,8 @@ interface WrapReadableStreamOptions<T, TMapped> {
275
328
  */
276
329
  runWith?: <T>(run: () => Promise<T>) => Promise<T>;
277
330
  mapResult?: (result: ReadableStreamReadResult<T>) => Promisable<ReadableStreamReadResult<TMapped>>;
278
- mapError?: (error: unknown) => Promisable<unknown>;
279
- onError?: (error: unknown) => Promisable<void>;
331
+ mapError?: (error: ThrowableError) => Promisable<ThrowableError>;
332
+ onError?: (error: ThrowableError) => Promisable<void>;
280
333
  /**
281
334
  * Guaranteed to execute exactly once after the stream finishes or is cancelled.
282
335
  */
@@ -285,9 +338,9 @@ interface WrapReadableStreamOptions<T, TMapped> {
285
338
  declare function wrapReadableStream<T, TMapped = T>(stream: ReadableStream<T>, { runWith, mapResult, mapError, onError, onFinish }: WrapReadableStreamOptions<T, TMapped>): NoInfer<ReadableStream<TMapped>>;
286
339
  declare function traceReadableStream<T>(options: StartSpanOptions | string, stream: ReadableStream<T>): ReadableStream<T>;
287
340
  /**
288
- * Converts a `ReadableStream` into an `AsyncIteratorClass`.
341
+ * Converts a {@link ReadableStream} into an {@link AsyncIteratorClass}.
289
342
  */
290
- declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>, { signal }?: {
343
+ declare function streamToAsyncIteratorObject<T>(stream: ReadableStream<T>, { signal }?: {
291
344
  signal?: undefined | AbortSignal;
292
345
  }): AsyncIteratorClass<T>;
293
346
  /**
@@ -302,5 +355,5 @@ declare function asyncIteratorToUnproxiedDataStream<T>(iterator: AsyncIterator<T
302
355
 
303
356
  declare function tryDecodeURIComponent(value: string): string;
304
357
 
305
- export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, defer, findDeepMatches, get, getConstructor, getOpenTelemetryConfig, intercept, isAbortError, isDeepEqual, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, omit, onError, onFinish, onStart, onSuccess, once, override, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorClass, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, wrapAsyncIterator, wrapReadableStream };
306
- export type { AnyFunction, AsyncIdQueueCloseOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OnFinishState, OpenTelemetryConfig, OrderablePlugin, PromiseWithError, Public, ReadableStreamReadResult, Registry, RunWithSpanOptions, Segment, StartSpanOptions, ThrowableError, Value, WrapAsyncIteratorOptions, WrapReadableStreamOptions };
358
+ export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, consumeAsyncIterator, defer, findDeepMatches, get, getConstructor, getOpenTelemetryConfig, intercept, isAbortError, isDeepEqual, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, omit, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, once, override, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorObject, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, wrapAsyncIterator, wrapReadableStream };
359
+ export type { AnyFunction, AsyncIdQueueCloseOptions, ConsumeAsyncIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OnFinishState, OpenTelemetryConfig, OrderablePlugin, PromiseWithError, Public, ReadableStreamReadResult, Registry, RunWithSpanOptions, Segment, StartSpanOptions, ThrowableError, Value, WrapAsyncIteratorOptions, WrapReadableStreamOptions };
package/dist/index.d.ts CHANGED
@@ -102,6 +102,30 @@ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess
102
102
  declare function onFinish<T, TOptions extends {
103
103
  next: () => any;
104
104
  }, 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']>>>;
105
+ /**
106
+ * Creates a middleware or interceptor that invokes a callback when the returned async
107
+ * iterator object throws an error while being consumed.
108
+ *
109
+ * This does not replace the `onError`. `onError` only fires on the
110
+ * initial call (before the interceptor returns the iterator), whereas this
111
+ * callback only fires while consuming the iterator. Use both together to
112
+ * catch all possible errors.
113
+ */
114
+ declare function onAsyncIteratorObjectError<T, TOptions extends {
115
+ next: () => any;
116
+ }, TRest extends any[]>(callback: NoInfer<(error: ThrowableError | (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']>>>;
117
+ /**
118
+ * Creates an interceptor that invokes a callback when the returned readable
119
+ * stream errors while being consumed.
120
+ *
121
+ * This does not replace the `onError`. `onError` only fires on the
122
+ * initial call (before the interceptor returns the stream), whereas this
123
+ * callback only fires while consuming the stream. Use both together to catch
124
+ * all possible errors.
125
+ */
126
+ declare function onReadableStreamError<T, TOptions extends {
127
+ next: () => any;
128
+ }, TRest extends any[]>(callback: NoInfer<(error: ThrowableError | (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']>>>;
105
129
  declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: undefined | Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
106
130
 
107
131
  /**
@@ -147,8 +171,8 @@ interface WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>
147
171
  */
148
172
  runWith?: <T>(run: () => Promise<T>) => Promise<T>;
149
173
  mapResult?: (result: IteratorResult<TYield, TReturn>) => Promisable<IteratorResult<TMappedYield, TMappedReturn>>;
150
- mapError?: (error: unknown) => Promisable<unknown>;
151
- onError?: (error: unknown) => Promisable<void>;
174
+ mapError?: (error: ThrowableError) => Promisable<ThrowableError>;
175
+ onError?: (error: ThrowableError) => Promisable<void>;
152
176
  /**
153
177
  * Execute after the stream finishes or is cancelled.
154
178
  */
@@ -157,6 +181,35 @@ interface WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>
157
181
  declare function wrapAsyncIterator<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { runWith, mapResult, mapError, onError, onFinish }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): NoInfer<AsyncIteratorClass<TMappedYield, TMappedReturn>>;
158
182
  declare function traceAsyncIterator<T, TReturn, TNext>(options: StartSpanOptions | string, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
159
183
  declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
184
+ interface ConsumeAsyncIteratorOptions<T, TReturn, TError> {
185
+ /**
186
+ * Called on each event
187
+ */
188
+ onEvent: (event: T) => void;
189
+ /**
190
+ * Called once error happens
191
+ */
192
+ onError?: (error: TError) => void;
193
+ /**
194
+ * Called once AsyncIteratorObject is done
195
+ *
196
+ * @info If iterator is canceled, `undefined` can be passed on success
197
+ */
198
+ onSuccess?: (value: TReturn | undefined) => void;
199
+ /**
200
+ * Called once after onError or onSuccess
201
+ *
202
+ * @info If iterator is canceled, `undefined` can be passed on success
203
+ */
204
+ onFinish?: (state: [error: TError, data: undefined, isSuccess: false] | [error: null, data: TReturn | undefined, isSuccess: true]) => void;
205
+ }
206
+ /**
207
+ * Consumes an AsyncIteratorObject with lifecycle callbacks
208
+ *
209
+ * @warning If no `onError` or `onFinish` is provided, error will be thrown into unhandled rejection channel.
210
+ * @return unsubscribe callback
211
+ */
212
+ declare function consumeAsyncIterator<T, TReturn, TError = ThrowableError>(iterator: AsyncIterator<T, TReturn> | PromiseWithError<AsyncIterator<T, TReturn>, TError>, options: ConsumeAsyncIteratorOptions<T, TReturn, TError | ThrowableError>): () => Promise<void>;
160
213
 
161
214
  type Segment = string | number;
162
215
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
@@ -275,8 +328,8 @@ interface WrapReadableStreamOptions<T, TMapped> {
275
328
  */
276
329
  runWith?: <T>(run: () => Promise<T>) => Promise<T>;
277
330
  mapResult?: (result: ReadableStreamReadResult<T>) => Promisable<ReadableStreamReadResult<TMapped>>;
278
- mapError?: (error: unknown) => Promisable<unknown>;
279
- onError?: (error: unknown) => Promisable<void>;
331
+ mapError?: (error: ThrowableError) => Promisable<ThrowableError>;
332
+ onError?: (error: ThrowableError) => Promisable<void>;
280
333
  /**
281
334
  * Guaranteed to execute exactly once after the stream finishes or is cancelled.
282
335
  */
@@ -285,9 +338,9 @@ interface WrapReadableStreamOptions<T, TMapped> {
285
338
  declare function wrapReadableStream<T, TMapped = T>(stream: ReadableStream<T>, { runWith, mapResult, mapError, onError, onFinish }: WrapReadableStreamOptions<T, TMapped>): NoInfer<ReadableStream<TMapped>>;
286
339
  declare function traceReadableStream<T>(options: StartSpanOptions | string, stream: ReadableStream<T>): ReadableStream<T>;
287
340
  /**
288
- * Converts a `ReadableStream` into an `AsyncIteratorClass`.
341
+ * Converts a {@link ReadableStream} into an {@link AsyncIteratorClass}.
289
342
  */
290
- declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>, { signal }?: {
343
+ declare function streamToAsyncIteratorObject<T>(stream: ReadableStream<T>, { signal }?: {
291
344
  signal?: undefined | AbortSignal;
292
345
  }): AsyncIteratorClass<T>;
293
346
  /**
@@ -302,5 +355,5 @@ declare function asyncIteratorToUnproxiedDataStream<T>(iterator: AsyncIterator<T
302
355
 
303
356
  declare function tryDecodeURIComponent(value: string): string;
304
357
 
305
- export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, defer, findDeepMatches, get, getConstructor, getOpenTelemetryConfig, intercept, isAbortError, isDeepEqual, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, omit, onError, onFinish, onStart, onSuccess, once, override, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorClass, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, wrapAsyncIterator, wrapReadableStream };
306
- export type { AnyFunction, AsyncIdQueueCloseOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OnFinishState, OpenTelemetryConfig, OrderablePlugin, PromiseWithError, Public, ReadableStreamReadResult, Registry, RunWithSpanOptions, Segment, StartSpanOptions, ThrowableError, Value, WrapAsyncIteratorOptions, WrapReadableStreamOptions };
358
+ export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, consumeAsyncIterator, defer, findDeepMatches, get, getConstructor, getOpenTelemetryConfig, intercept, isAbortError, isDeepEqual, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, omit, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, once, override, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorObject, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, wrapAsyncIterator, wrapReadableStream };
359
+ export type { AnyFunction, AsyncIdQueueCloseOptions, ConsumeAsyncIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OnFinishState, OpenTelemetryConfig, OrderablePlugin, PromiseWithError, Public, ReadableStreamReadResult, Registry, RunWithSpanOptions, Segment, StartSpanOptions, ThrowableError, Value, WrapAsyncIteratorOptions, WrapReadableStreamOptions };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { AbortError, AsyncIteratorClass, isTypescriptObject, getOrBind } from '@standardserver/shared';
1
+ import { AbortError, AsyncIteratorClass, getOrBind, isTypescriptObject, isAsyncIteratorObject } from '@standardserver/shared';
2
2
  export { AbortError, AsyncIteratorClass, SequentialIdGenerator, getOrBind, isAsyncIteratorObject, isTypescriptObject, parseEmptyableJSON, sequential, sleep, stringifyJSON, toArray } from '@standardserver/shared';
3
3
 
4
4
  function resolveMaybeOptionalOptions(rest) {
@@ -184,61 +184,6 @@ function compareSequentialIds(a, b) {
184
184
  return a < b ? -1 : a > b ? 1 : 0;
185
185
  }
186
186
 
187
- function onStart(callback) {
188
- return async (options, ...rest) => {
189
- await callback(options, ...rest);
190
- return await options.next();
191
- };
192
- }
193
- function onSuccess(callback) {
194
- return async (options, ...rest) => {
195
- const result = await options.next();
196
- await callback(result, options, ...rest);
197
- return result;
198
- };
199
- }
200
- function onError(callback) {
201
- return async (options, ...rest) => {
202
- try {
203
- return await options.next();
204
- } catch (error) {
205
- await callback(error, options, ...rest);
206
- throw error;
207
- }
208
- };
209
- }
210
- function onFinish(callback) {
211
- let state;
212
- return async (options, ...rest) => {
213
- try {
214
- const result = await options.next();
215
- state = [null, result, true];
216
- return result;
217
- } catch (error) {
218
- state = [error, void 0, false];
219
- throw error;
220
- } finally {
221
- await callback(state, options, ...rest);
222
- }
223
- };
224
- }
225
- function intercept(interceptors, options, main) {
226
- if (!interceptors?.length) {
227
- return main(options);
228
- }
229
- const next = (options2, index) => {
230
- const interceptor = interceptors[index];
231
- if (!interceptor) {
232
- return main(options2);
233
- }
234
- return interceptor({
235
- ...options2,
236
- next: (newOptions = options2) => next(newOptions, index + 1)
237
- });
238
- };
239
- return next(options, 0);
240
- }
241
-
242
187
  const SPAN_ERROR_STATUS = 2;
243
188
  const OPENTELEMETRY_CONFIG_SYMBOL = Symbol.for("ORPC_OPENTELEMETRY_CONFIG");
244
189
  function setOpenTelemetryConfig(config) {
@@ -511,6 +456,55 @@ function replicateAsyncIterator(source, count) {
511
456
  });
512
457
  return replicated;
513
458
  }
459
+ function consumeAsyncIterator(iterator, options) {
460
+ void (async () => {
461
+ let onFinishState;
462
+ try {
463
+ const resolvedIterator = await iterator;
464
+ while (true) {
465
+ const { done, value } = await resolvedIterator.next();
466
+ if (done) {
467
+ const realValue = value;
468
+ onFinishState = [null, realValue, true];
469
+ options.onSuccess?.(realValue);
470
+ break;
471
+ }
472
+ options.onEvent(value);
473
+ }
474
+ } catch (error) {
475
+ onFinishState = [error, void 0, false];
476
+ if (!options.onError && !options.onFinish) {
477
+ throw error;
478
+ }
479
+ options.onError?.(error);
480
+ } finally {
481
+ options.onFinish?.(onFinishState);
482
+ }
483
+ })();
484
+ return async () => {
485
+ await (await iterator)?.return?.();
486
+ };
487
+ }
488
+
489
+ function value(value2, ...args) {
490
+ if (typeof value2 === "function") {
491
+ return value2(...args);
492
+ }
493
+ return value2;
494
+ }
495
+
496
+ function override(target, partial) {
497
+ const proxy = new Proxy(typeof target === "function" ? partial : target, {
498
+ get(_, prop) {
499
+ const targetValue = prop in partial ? partial : value(target);
500
+ return getOrBind(targetValue, prop);
501
+ },
502
+ has(_, prop) {
503
+ return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
504
+ }
505
+ });
506
+ return proxy;
507
+ }
514
508
 
515
509
  function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
516
510
  if (check(payload)) {
@@ -623,84 +617,6 @@ function bindMethods(obj) {
623
617
  return methods;
624
618
  }
625
619
 
626
- function sortPlugins(plugins) {
627
- const pluginCount = plugins.length;
628
- const pluginIdToIndices = /* @__PURE__ */ new Map();
629
- for (let i = 0; i < pluginCount; i++) {
630
- const plugin = plugins[i];
631
- const indices = pluginIdToIndices.get(plugin.name);
632
- if (indices === void 0) {
633
- pluginIdToIndices.set(plugin.name, [i]);
634
- } else {
635
- indices.push(i);
636
- }
637
- }
638
- const graph = Array.from(
639
- { length: pluginCount },
640
- () => /* @__PURE__ */ new Set()
641
- );
642
- for (let i = 0; i < pluginCount; i++) {
643
- const plugin = plugins[i];
644
- const beforeList = plugin.before;
645
- if (beforeList !== void 0) {
646
- for (const beforeId of beforeList) {
647
- const beforeIndices = pluginIdToIndices.get(beforeId);
648
- if (beforeIndices === void 0)
649
- continue;
650
- for (const beforeIndex of beforeIndices) {
651
- const beforeGraph = graph[beforeIndex];
652
- if (beforeGraph !== void 0) {
653
- beforeGraph.add(i);
654
- }
655
- }
656
- }
657
- }
658
- const afterList = plugin.after;
659
- if (afterList !== void 0) {
660
- const currentGraph = graph[i];
661
- if (currentGraph !== void 0) {
662
- for (const afterId of afterList) {
663
- const afterIndices = pluginIdToIndices.get(afterId);
664
- if (afterIndices === void 0)
665
- continue;
666
- for (const afterIndex of afterIndices) {
667
- currentGraph.add(afterIndex);
668
- }
669
- }
670
- }
671
- }
672
- }
673
- const sorted = [];
674
- const visiting = /* @__PURE__ */ new Set();
675
- const visited = /* @__PURE__ */ new Set();
676
- function visit(index) {
677
- if (visited.has(index))
678
- return;
679
- if (visiting.has(index)) {
680
- const plugin2 = plugins[index];
681
- const pluginId = plugin2 !== void 0 ? plugin2.name : "unknown";
682
- throw new Error(`Circular dependency detected involving plugin "${pluginId}"`);
683
- }
684
- visiting.add(index);
685
- const deps = graph[index];
686
- if (deps !== void 0) {
687
- for (const depIndex of deps) {
688
- visit(depIndex);
689
- }
690
- }
691
- visiting.delete(index);
692
- visited.add(index);
693
- const plugin = plugins[index];
694
- if (plugin !== void 0) {
695
- sorted.push(plugin);
696
- }
697
- }
698
- for (let i = 0; i < pluginCount; i++) {
699
- visit(i);
700
- }
701
- return sorted;
702
- }
703
-
704
620
  function promiseWithResolvers() {
705
621
  const result = {};
706
622
  result.promise = new Promise((resolve, reject) => {
@@ -710,69 +626,6 @@ function promiseWithResolvers() {
710
626
  return result;
711
627
  }
712
628
 
713
- function value(value2, ...args) {
714
- if (typeof value2 === "function") {
715
- return value2(...args);
716
- }
717
- return value2;
718
- }
719
-
720
- function override(target, partial) {
721
- const proxy = new Proxy(typeof target === "function" ? partial : target, {
722
- get(_, prop) {
723
- const targetValue = prop in partial ? partial : value(target);
724
- return getOrBind(targetValue, prop);
725
- },
726
- has(_, prop) {
727
- return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
728
- }
729
- });
730
- return proxy;
731
- }
732
-
733
- function allAbortSignal(signals) {
734
- const realSignals = signals.filter((signal) => signal !== void 0);
735
- if (realSignals.length === 0 || realSignals.length !== signals.length) {
736
- return void 0;
737
- }
738
- const controller = new AbortController();
739
- const abortIfAllAborted = () => {
740
- if (realSignals.every((signal) => signal.aborted)) {
741
- controller.abort();
742
- }
743
- };
744
- abortIfAllAborted();
745
- for (const signal of realSignals) {
746
- signal.addEventListener("abort", () => {
747
- abortIfAllAborted();
748
- }, {
749
- once: true,
750
- signal: controller.signal
751
- });
752
- }
753
- return controller.signal;
754
- }
755
- async function runWithSignal(signal, fn) {
756
- if (!signal) {
757
- return fn();
758
- }
759
- signal.throwIfAborted();
760
- const { promise, reject, resolve } = promiseWithResolvers();
761
- let abortListener;
762
- signal.addEventListener("abort", abortListener = () => {
763
- reject(signal.reason);
764
- abortListener = void 0;
765
- });
766
- try {
767
- fn().then(resolve, reject);
768
- return await promise;
769
- } finally {
770
- if (abortListener) {
771
- signal.removeEventListener("abort", abortListener);
772
- }
773
- }
774
- }
775
-
776
629
  function replicateReadableStream(stream, count) {
777
630
  if (count <= 0) {
778
631
  return [];
@@ -843,7 +696,7 @@ function traceReadableStream(options, stream) {
843
696
  }
844
697
  });
845
698
  }
846
- function streamToAsyncIteratorClass(stream, { signal } = {}) {
699
+ function streamToAsyncIteratorObject(stream, { signal } = {}) {
847
700
  const reader = stream.getReader();
848
701
  let cancelledBySignal = false;
849
702
  return new AsyncIteratorClass(
@@ -909,4 +762,202 @@ function asyncIteratorToUnproxiedDataStream(iterator) {
909
762
  });
910
763
  }
911
764
 
912
- export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, defer, findDeepMatches, get, getConstructor, getOpenTelemetryConfig, intercept, isAbortError, isDeepEqual, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, omit, onError, onFinish, onStart, onSuccess, once, override, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorClass, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, wrapAsyncIterator, wrapReadableStream };
765
+ function onStart(callback) {
766
+ return async (options, ...rest) => {
767
+ await callback(options, ...rest);
768
+ return await options.next();
769
+ };
770
+ }
771
+ function onSuccess(callback) {
772
+ return async (options, ...rest) => {
773
+ const result = await options.next();
774
+ await callback(result, options, ...rest);
775
+ return result;
776
+ };
777
+ }
778
+ function onError(callback) {
779
+ return async (options, ...rest) => {
780
+ try {
781
+ return await options.next();
782
+ } catch (error) {
783
+ await callback(error, options, ...rest);
784
+ throw error;
785
+ }
786
+ };
787
+ }
788
+ function onFinish(callback) {
789
+ let state;
790
+ return async (options, ...rest) => {
791
+ try {
792
+ const result = await options.next();
793
+ state = [null, result, true];
794
+ return result;
795
+ } catch (error) {
796
+ state = [error, void 0, false];
797
+ throw error;
798
+ } finally {
799
+ await callback(state, options, ...rest);
800
+ }
801
+ };
802
+ }
803
+ function onAsyncIteratorObjectError(callback) {
804
+ return async (options, ...rest) => {
805
+ const output = await options.next();
806
+ if (!isAsyncIteratorObject(output)) {
807
+ return output;
808
+ }
809
+ return override(output, wrapAsyncIterator(output, {
810
+ onError: (error) => callback(error, options, ...rest)
811
+ }));
812
+ };
813
+ }
814
+ function onReadableStreamError(callback) {
815
+ return async (options, ...rest) => {
816
+ const output = await options.next();
817
+ if (!(output instanceof ReadableStream)) {
818
+ return output;
819
+ }
820
+ return override(output, wrapReadableStream(output, {
821
+ onError: (error) => callback(error, options, ...rest)
822
+ }));
823
+ };
824
+ }
825
+ function intercept(interceptors, options, main) {
826
+ if (!interceptors?.length) {
827
+ return main(options);
828
+ }
829
+ const next = (options2, index) => {
830
+ const interceptor = interceptors[index];
831
+ if (!interceptor) {
832
+ return main(options2);
833
+ }
834
+ return interceptor({
835
+ ...options2,
836
+ next: (newOptions = options2) => next(newOptions, index + 1)
837
+ });
838
+ };
839
+ return next(options, 0);
840
+ }
841
+
842
+ function sortPlugins(plugins) {
843
+ const pluginCount = plugins.length;
844
+ const pluginIdToIndices = /* @__PURE__ */ new Map();
845
+ for (let i = 0; i < pluginCount; i++) {
846
+ const plugin = plugins[i];
847
+ const indices = pluginIdToIndices.get(plugin.name);
848
+ if (indices === void 0) {
849
+ pluginIdToIndices.set(plugin.name, [i]);
850
+ } else {
851
+ indices.push(i);
852
+ }
853
+ }
854
+ const graph = Array.from(
855
+ { length: pluginCount },
856
+ () => /* @__PURE__ */ new Set()
857
+ );
858
+ for (let i = 0; i < pluginCount; i++) {
859
+ const plugin = plugins[i];
860
+ const beforeList = plugin.before;
861
+ if (beforeList !== void 0) {
862
+ for (const beforeId of beforeList) {
863
+ const beforeIndices = pluginIdToIndices.get(beforeId);
864
+ if (beforeIndices === void 0)
865
+ continue;
866
+ for (const beforeIndex of beforeIndices) {
867
+ const beforeGraph = graph[beforeIndex];
868
+ if (beforeGraph !== void 0) {
869
+ beforeGraph.add(i);
870
+ }
871
+ }
872
+ }
873
+ }
874
+ const afterList = plugin.after;
875
+ if (afterList !== void 0) {
876
+ const currentGraph = graph[i];
877
+ if (currentGraph !== void 0) {
878
+ for (const afterId of afterList) {
879
+ const afterIndices = pluginIdToIndices.get(afterId);
880
+ if (afterIndices === void 0)
881
+ continue;
882
+ for (const afterIndex of afterIndices) {
883
+ currentGraph.add(afterIndex);
884
+ }
885
+ }
886
+ }
887
+ }
888
+ }
889
+ const sorted = [];
890
+ const visiting = /* @__PURE__ */ new Set();
891
+ const visited = /* @__PURE__ */ new Set();
892
+ function visit(index) {
893
+ if (visited.has(index))
894
+ return;
895
+ if (visiting.has(index)) {
896
+ const plugin2 = plugins[index];
897
+ const pluginId = plugin2 !== void 0 ? plugin2.name : "unknown";
898
+ throw new Error(`Circular dependency detected involving plugin "${pluginId}"`);
899
+ }
900
+ visiting.add(index);
901
+ const deps = graph[index];
902
+ if (deps !== void 0) {
903
+ for (const depIndex of deps) {
904
+ visit(depIndex);
905
+ }
906
+ }
907
+ visiting.delete(index);
908
+ visited.add(index);
909
+ const plugin = plugins[index];
910
+ if (plugin !== void 0) {
911
+ sorted.push(plugin);
912
+ }
913
+ }
914
+ for (let i = 0; i < pluginCount; i++) {
915
+ visit(i);
916
+ }
917
+ return sorted;
918
+ }
919
+
920
+ function allAbortSignal(signals) {
921
+ const realSignals = signals.filter((signal) => signal !== void 0);
922
+ if (realSignals.length === 0 || realSignals.length !== signals.length) {
923
+ return void 0;
924
+ }
925
+ const controller = new AbortController();
926
+ const abortIfAllAborted = () => {
927
+ if (realSignals.every((signal) => signal.aborted)) {
928
+ controller.abort();
929
+ }
930
+ };
931
+ abortIfAllAborted();
932
+ for (const signal of realSignals) {
933
+ signal.addEventListener("abort", () => {
934
+ abortIfAllAborted();
935
+ }, {
936
+ once: true,
937
+ signal: controller.signal
938
+ });
939
+ }
940
+ return controller.signal;
941
+ }
942
+ async function runWithSignal(signal, fn) {
943
+ if (!signal) {
944
+ return fn();
945
+ }
946
+ signal.throwIfAborted();
947
+ const { promise, reject, resolve } = promiseWithResolvers();
948
+ let abortListener;
949
+ signal.addEventListener("abort", abortListener = () => {
950
+ reject(signal.reason);
951
+ abortListener = void 0;
952
+ });
953
+ try {
954
+ fn().then(resolve, reject);
955
+ return await promise;
956
+ } finally {
957
+ if (abortListener) {
958
+ signal.removeEventListener("abort", abortListener);
959
+ }
960
+ }
961
+ }
962
+
963
+ export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, consumeAsyncIterator, defer, findDeepMatches, get, getConstructor, getOpenTelemetryConfig, intercept, isAbortError, isDeepEqual, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, omit, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, once, override, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorObject, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, wrapAsyncIterator, wrapReadableStream };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/shared",
3
3
  "type": "module",
4
- "version": "2.0.0-beta.14",
4
+ "version": "2.0.0-beta.15",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.dev",
7
7
  "repository": {
@@ -33,7 +33,7 @@
33
33
  }
34
34
  },
35
35
  "dependencies": {
36
- "@standardserver/shared": "^0.0.25",
36
+ "@standardserver/shared": "^0.0.32",
37
37
  "radash": "^12.1.1",
38
38
  "type-fest": "^5.3.1"
39
39
  },