@orpc/shared 2.0.0-beta.49 → 2.0.0-beta.50

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.
Files changed (49) hide show
  1. package/dist/args.d.ts +1 -1
  2. package/dist/args.js +4 -2
  3. package/dist/array.d.ts +4 -1
  4. package/dist/array.js +11 -5
  5. package/dist/bigint.d.ts +1 -1
  6. package/dist/bigint.js +12 -16
  7. package/dist/buffer.d.ts +4 -4
  8. package/dist/buffer.js +44 -67
  9. package/dist/compare.d.ts +1 -1
  10. package/dist/compare.js +23 -42
  11. package/dist/consts.d.ts +1 -1
  12. package/dist/consts.js +3 -1
  13. package/dist/error.d.ts +1 -1
  14. package/dist/error.js +4 -2
  15. package/dist/function.d.ts +1 -1
  16. package/dist/function.js +27 -32
  17. package/dist/http.d.ts +29 -0
  18. package/dist/http.js +128 -94
  19. package/dist/id.d.ts +1 -1
  20. package/dist/id.js +11 -11
  21. package/dist/index.d.ts +26 -34
  22. package/dist/index.js +23 -32
  23. package/dist/interceptor.d.ts +17 -17
  24. package/dist/interceptor.js +106 -126
  25. package/dist/iterator.d.ts +41 -41
  26. package/dist/iterator.js +136 -152
  27. package/dist/object.d.ts +10 -8
  28. package/dist/object.js +176 -227
  29. package/dist/plugin.d.ts +7 -7
  30. package/dist/plugin.js +41 -57
  31. package/dist/promise.d.ts +4 -4
  32. package/dist/promise.js +28 -28
  33. package/dist/proxy.d.ts +2 -2
  34. package/dist/proxy.js +23 -22
  35. package/dist/queue.d.ts +13 -13
  36. package/dist/queue.js +64 -79
  37. package/dist/regex.d.ts +9 -0
  38. package/dist/regex.js +11 -0
  39. package/dist/signal.d.ts +7 -2
  40. package/dist/signal.js +83 -80
  41. package/dist/stream.d.ts +23 -23
  42. package/dist/stream.js +118 -144
  43. package/dist/tracing.d.ts +50 -50
  44. package/dist/tracing.js +60 -85
  45. package/dist/types.d.ts +7 -10
  46. package/dist/value.d.ts +1 -1
  47. package/dist/value.js +5 -5
  48. package/package.json +2 -2
  49. package/dist/types.js +0 -1
@@ -1,139 +1,119 @@
1
- import { isAsyncIteratorObject } from '@standard-server/shared';
2
- import { wrapAsyncIterator } from './iterator.js';
3
- import { override } from './proxy.js';
4
- import { wrapReadableStream } from './stream.js';
1
+ import { wrapAsyncIterator } from "./iterator.js";
2
+ import { override } from "./proxy.js";
3
+ import { wrapReadableStream } from "./stream.js";
4
+ import { isAsyncIteratorObject } from "@standard-server/shared";
5
+ // src/interceptor.ts
5
6
  /**
6
- * Can used for interceptors or middlewares
7
- */
8
- // oxlint-disable-next-line typescript/no-unnecessary-type-parameters
9
- export function onStart(callback) {
10
- return async (options, ...rest) => {
11
- await callback(options, ...rest);
12
- return await options.next();
13
- };
7
+ * Can used for interceptors or middlewares
8
+ */
9
+ function onStart(callback) {
10
+ return async (options, ...rest) => {
11
+ await callback(options, ...rest);
12
+ return await options.next();
13
+ };
14
14
  }
15
15
  /**
16
- * Can used for interceptors or middlewares
17
- */
18
- // oxlint-disable-next-line typescript/no-unnecessary-type-parameters
19
- export function onSuccess(callback) {
20
- return async (options, ...rest) => {
21
- const result = await options.next();
22
- await callback(result, options, ...rest);
23
- return result;
24
- };
16
+ * Can used for interceptors or middlewares
17
+ */
18
+ function onSuccess(callback) {
19
+ return async (options, ...rest) => {
20
+ const result = await options.next();
21
+ await callback(result, options, ...rest);
22
+ return result;
23
+ };
25
24
  }
26
25
  /**
27
- * Creates an interceptor or middleware that invokes a callback whenever an error
28
- * is thrown. The error is rethrown after the callback completes.
29
- *
30
- * @see {@link https://orpc.dev/docs/adapters/fetch-api | Fetch API Adapter}
31
- */
32
- // oxlint-disable-next-line typescript/no-unnecessary-type-parameters
33
- export function onError(callback) {
34
- return async (options, ...rest) => {
35
- try {
36
- return await options.next();
37
- }
38
- catch (error) {
39
- await callback(error, options, ...rest);
40
- throw error;
41
- }
42
- };
26
+ * Creates an interceptor or middleware that invokes a callback whenever an error
27
+ * is thrown. The error is rethrown after the callback completes.
28
+ *
29
+ * @see {@link https://orpc.dev/docs/adapters/fetch-api | Fetch API Adapter}
30
+ */
31
+ function onError(callback) {
32
+ return async (options, ...rest) => {
33
+ try {
34
+ return await options.next();
35
+ } catch (error) {
36
+ await callback(error, options, ...rest);
37
+ throw error;
38
+ }
39
+ };
43
40
  }
44
41
  /**
45
- * Can used for interceptors or middlewares
46
- */
47
- // oxlint-disable-next-line typescript/no-unnecessary-type-parameters
48
- export function onFinish(callback) {
49
- return async (options, ...rest) => {
50
- let state;
51
- try {
52
- const result = await options.next();
53
- state = [null, result, true];
54
- return result;
55
- }
56
- catch (error) {
57
- state = [error, undefined, false];
58
- throw error;
59
- }
60
- finally {
61
- await callback(state, options, ...rest);
62
- }
63
- };
42
+ * Can used for interceptors or middlewares
43
+ */
44
+ function onFinish(callback) {
45
+ return async (options, ...rest) => {
46
+ let state;
47
+ try {
48
+ const result = await options.next();
49
+ state = [
50
+ null,
51
+ result,
52
+ true
53
+ ];
54
+ return result;
55
+ } catch (error) {
56
+ state = [
57
+ error,
58
+ void 0,
59
+ false
60
+ ];
61
+ throw error;
62
+ } finally {
63
+ await callback(state, options, ...rest);
64
+ }
65
+ };
64
66
  }
65
67
  /**
66
- * Creates a middleware or interceptor that invokes a callback when the returned async
67
- * iterator object throws an error while being consumed.
68
- *
69
- * This does not replace the `onError`. `onError` only fires on the
70
- * initial call (before the interceptor returns the iterator), whereas this
71
- * callback only fires while consuming the iterator. Use both together to
72
- * catch all possible errors.
73
- */
74
- export function onAsyncIteratorObjectError(callback) {
75
- // The typed error should always be combined with `ThrowableError`
76
- // because an AsyncIterator can throw any error during iteration,
77
- // while TError only represents errors from the initial promise.
78
- // In oRPC client/server usage, initial and iteration errors are usually the same,
79
- // but this utility is shared, so it needs to support the general case.
80
- return async (options, ...rest) => {
81
- const output = await options.next();
82
- if (!isAsyncIteratorObject(output)) {
83
- return output;
84
- }
85
- /**
86
- * @warning
87
- * Remember use `override` for AsyncIteratorObject to remain other special properties
88
- */
89
- return override(output, wrapAsyncIterator(output, {
90
- onError: (error) => callback(error, options, ...rest),
91
- }));
92
- };
68
+ * Creates a middleware or interceptor that invokes a callback when the returned async
69
+ * iterator object throws an error while being consumed.
70
+ *
71
+ * This does not replace the `onError`. `onError` only fires on the
72
+ * initial call (before the interceptor returns the iterator), whereas this
73
+ * callback only fires while consuming the iterator. Use both together to
74
+ * catch all possible errors.
75
+ */
76
+ function onAsyncIteratorObjectError(callback) {
77
+ return async (options, ...rest) => {
78
+ const output = await options.next();
79
+ if (!isAsyncIteratorObject(output)) return output;
80
+ /**
81
+ * @warning
82
+ * Remember use `override` for AsyncIteratorObject to remain other special properties
83
+ */
84
+ return override(output, wrapAsyncIterator(output, { onError: (error) => callback(error, options, ...rest) }));
85
+ };
93
86
  }
94
87
  /**
95
- * Creates an interceptor that invokes a callback when the returned readable
96
- * stream errors while being consumed.
97
- *
98
- * This does not replace the `onError`. `onError` only fires on the
99
- * initial call (before the interceptor returns the stream), whereas this
100
- * callback only fires while consuming the stream. Use both together to catch
101
- * all possible errors.
102
- */
103
- // oxlint-disable-next-line typescript/no-unnecessary-type-parameters
104
- export function onReadableStreamError(callback) {
105
- // The typed error should always be combined with `ThrowableError`
106
- // because a ReadableStream can throw any error during iteration,
107
- // while TError only represents errors from the initial promise.
108
- // In oRPC client/server usage, initial and iteration errors are usually the same,
109
- // but this utility is shared, so it needs to support the general case.
110
- return async (options, ...rest) => {
111
- const output = await options.next();
112
- if (!(output instanceof ReadableStream)) {
113
- return output;
114
- }
115
- /**
116
- * @warning
117
- * Remember use `override` for ReadableStream to remain other special properties
118
- */
119
- return override(output, wrapReadableStream(output, {
120
- onError: (error) => callback(error, options, ...rest),
121
- }));
122
- };
88
+ * Creates an interceptor that invokes a callback when the returned readable
89
+ * stream errors while being consumed.
90
+ *
91
+ * This does not replace the `onError`. `onError` only fires on the
92
+ * initial call (before the interceptor returns the stream), whereas this
93
+ * callback only fires while consuming the stream. Use both together to catch
94
+ * all possible errors.
95
+ */
96
+ function onReadableStreamError(callback) {
97
+ return async (options, ...rest) => {
98
+ const output = await options.next();
99
+ if (!(output instanceof ReadableStream)) return output;
100
+ /**
101
+ * @warning
102
+ * Remember use `override` for ReadableStream to remain other special properties
103
+ */
104
+ return override(output, wrapReadableStream(output, { onError: (error) => callback(error, options, ...rest) }));
105
+ };
123
106
  }
124
- export function intercept(interceptors, options, main) {
125
- if (!interceptors?.length) {
126
- return main(options);
127
- }
128
- const next = (options, index) => {
129
- const interceptor = interceptors[index];
130
- if (!interceptor) {
131
- return main(options);
132
- }
133
- return interceptor({
134
- ...options,
135
- next: (newOptions = options) => next(newOptions, index + 1),
136
- });
137
- };
138
- return next(options, 0);
107
+ function intercept(interceptors, options, main) {
108
+ if (!interceptors?.length) return main(options);
109
+ const next = (options, index) => {
110
+ const interceptor = interceptors[index];
111
+ if (!interceptor) return main(options);
112
+ return interceptor({
113
+ ...options,
114
+ next: (newOptions = options) => next(newOptions, index + 1)
115
+ });
116
+ };
117
+ return next(options, 0);
139
118
  }
119
+ export { intercept, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess };
@@ -1,48 +1,48 @@
1
- import { AsyncIteratorClass } from '@standard-server/shared';
2
- import type { Promisable } from 'type-fest';
3
- import type { StartSpanOptions } from './tracing.ts';
4
- import type { PromiseWithError, ThrowableError } from './types.ts';
1
+ import { StartSpanOptions } from "./tracing.js";
2
+ import { PromiseWithError, ThrowableError } from "./types.js";
3
+ import { AsyncIteratorClass } from "@standard-server/shared";
4
+ import { Promisable } from "type-fest";
5
5
  export interface WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn> {
6
- /**
7
- * Any call to the original iterator will be executed inside this function.
8
- * Useful when you want execution to happen within a specific context,
9
- * such as AsyncLocalStorage.
10
- */
11
- runWith?: (<T>(run: () => Promise<T>) => Promisable<T>) | undefined;
12
- mapResult?: ((result: IteratorResult<TYield, TReturn>) => Promisable<IteratorResult<TMappedYield, TMappedReturn>>) | undefined;
13
- mapError?: ((error: ThrowableError) => Promisable<ThrowableError>) | undefined;
14
- onError?: ((error: ThrowableError) => Promisable<void>) | undefined;
15
- /**
16
- * Execute after the stream finishes or is cancelled.
17
- */
18
- onFinish?: (() => Promisable<void>) | undefined;
6
+ /**
7
+ * Any call to the original iterator will be executed inside this function.
8
+ * Useful when you want execution to happen within a specific context,
9
+ * such as AsyncLocalStorage.
10
+ */
11
+ runWith?: (<T>(run: () => Promise<T>) => Promisable<T>) | undefined;
12
+ mapResult?: ((result: IteratorResult<TYield, TReturn>) => Promisable<IteratorResult<TMappedYield, TMappedReturn>>) | undefined;
13
+ mapError?: ((error: ThrowableError) => Promisable<ThrowableError>) | undefined;
14
+ onError?: ((error: ThrowableError) => Promisable<void>) | undefined;
15
+ /**
16
+ * Execute after the stream finishes or is cancelled.
17
+ */
18
+ onFinish?: (() => Promisable<void>) | undefined;
19
19
  }
20
- export 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>>;
20
+ export 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>>;
21
21
  export declare function traceAsyncIterator<T, TReturn, TNext>(options: StartSpanOptions | string, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
22
22
  export declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): AsyncIteratorClass<T, TReturn, TNext>[];
23
23
  export interface ConsumeAsyncIteratorOptions<T, TReturn, TError> {
24
- /**
25
- * Called on each event
26
- */
27
- onEvent: (event: T) => void;
28
- /**
29
- * Called once error happens
30
- */
31
- onError?: ((error: TError) => void) | undefined;
32
- /**
33
- * Called once AsyncIteratorObject is done
34
- *
35
- * @remarks
36
- * **Note**: If iterator is canceled, `undefined` can be passed on success
37
- */
38
- onSuccess?: ((value: TReturn | undefined) => void) | undefined;
39
- /**
40
- * Called once after onError or onSuccess
41
- *
42
- * @remarks
43
- * **Note**: If iterator is canceled, `undefined` can be passed on success
44
- */
45
- onFinish?: ((state: [error: TError, data: undefined, isSuccess: false] | [error: null, data: TReturn | undefined, isSuccess: true]) => void) | undefined;
24
+ /**
25
+ * Called on each event
26
+ */
27
+ onEvent: (event: T) => void;
28
+ /**
29
+ * Called once error happens
30
+ */
31
+ onError?: ((error: TError) => void) | undefined;
32
+ /**
33
+ * Called once AsyncIteratorObject is done
34
+ *
35
+ * @remarks
36
+ * **Note**: If iterator is canceled, `undefined` can be passed on success
37
+ */
38
+ onSuccess?: ((value: TReturn | undefined) => void) | undefined;
39
+ /**
40
+ * Called once after onError or onSuccess
41
+ *
42
+ * @remarks
43
+ * **Note**: If iterator is canceled, `undefined` can be passed on success
44
+ */
45
+ onFinish?: ((state: [error: TError, data: undefined, isSuccess: false] | [error: null, data: TReturn | undefined, isSuccess: true]) => void) | undefined;
46
46
  }
47
47
  /**
48
48
  * Consumes an AsyncIteratorObject with lifecycle callbacks.
@@ -53,4 +53,4 @@ export interface ConsumeAsyncIteratorOptions<T, TReturn, TError> {
53
53
  * @returns An unsubscribe callback that stops consuming and cleans up the iterator.
54
54
  * @see {@link https://orpc.dev/docs/client/async-iterator-object#using-consumeasynciterator | AsyncIteratorObject in Client - Using consumeAsyncIterator}
55
55
  */
56
- export declare function consumeAsyncIterator<T, TReturn, TError = ThrowableError>(iterator: AsyncIterator<T, TReturn> | PromiseWithError<AsyncIterator<T, TReturn>, TError>, options: ConsumeAsyncIteratorOptions<T, TReturn, TError | ThrowableError>): () => Promise<void>;
56
+ export declare function consumeAsyncIterator<T, TReturn, TError = ThrowableError>(iterator: AsyncIterator<T, TReturn> | PromiseWithError<AsyncIterator<T, TReturn>, TError>, options: ConsumeAsyncIteratorOptions<T, TReturn, TError | ThrowableError>): () => Promise<void>;
package/dist/iterator.js CHANGED
@@ -1,157 +1,141 @@
1
- import { AsyncIteratorClass } from '@standard-server/shared';
2
- import { once } from './function.js';
3
- import { AsyncIdQueue } from './queue.js';
4
- import { recordSpanError, runInSpanContext, startSpan } from './tracing.js';
5
- export function wrapAsyncIterator(iterator, { runWith, mapResult, mapError, onError, onFinish, }) {
6
- runWith ??= (run) => run();
7
- let isDone;
8
- return new AsyncIteratorClass(async () => {
9
- try {
10
- let result;
11
- try {
12
- result = await runWith(() => iterator.next());
13
- isDone = result.done;
14
- }
15
- catch (error) {
16
- isDone = true;
17
- throw error;
18
- }
19
- return mapResult ? await mapResult(result) : result;
20
- }
21
- catch (error) {
22
- await onError?.(error);
23
- throw mapError ? await mapError(error) : error;
24
- }
25
- }, async (_state) => {
26
- try {
27
- // Only cancel the original iterator if it has not finished yet.
28
- // Do not rely on _state because the user's options may throw errors.
29
- if (!isDone) {
30
- try {
31
- await runWith(async () => iterator.return?.());
32
- }
33
- catch (error) {
34
- await onError?.(error);
35
- throw error;
36
- }
37
- }
38
- }
39
- finally {
40
- await onFinish?.();
41
- }
42
- });
1
+ import { once } from "./function.js";
2
+ import { AsyncIdQueue } from "./queue.js";
3
+ import { recordSpanError, runInSpanContext, startSpan } from "./tracing.js";
4
+ import { AsyncIteratorClass } from "@standard-server/shared";
5
+ // src/iterator.ts
6
+ function wrapAsyncIterator(iterator, { runWith, mapResult, mapError, onError, onFinish }) {
7
+ runWith ??= (run) => run();
8
+ let isDone;
9
+ return new AsyncIteratorClass(async () => {
10
+ try {
11
+ let result;
12
+ try {
13
+ result = await runWith(() => iterator.next());
14
+ isDone = result.done;
15
+ } catch (error) {
16
+ isDone = true;
17
+ throw error;
18
+ }
19
+ return mapResult ? await mapResult(result) : result;
20
+ } catch (error) {
21
+ await onError?.(error);
22
+ throw mapError ? await mapError(error) : error;
23
+ }
24
+ }, async (_state) => {
25
+ try {
26
+ if (!isDone) try {
27
+ await runWith(async () => iterator.return?.());
28
+ } catch (error) {
29
+ await onError?.(error);
30
+ throw error;
31
+ }
32
+ } finally {
33
+ await onFinish?.();
34
+ }
35
+ });
43
36
  }
44
- export function traceAsyncIterator(options, iterator) {
45
- const getSpan = once(() => startSpan(options));
46
- return wrapAsyncIterator(iterator, {
47
- runWith: (run) => runInSpanContext(getSpan(), run),
48
- mapResult(result) {
49
- getSpan()?.addEvent(result.done ? 'completed' : 'yielded');
50
- return result;
51
- },
52
- onError(error) {
53
- recordSpanError(getSpan(), error);
54
- },
55
- onFinish() {
56
- getSpan()?.end();
57
- },
58
- });
37
+ function traceAsyncIterator(options, iterator) {
38
+ const getSpan = once(() => startSpan(options));
39
+ return wrapAsyncIterator(iterator, {
40
+ runWith: (run) => runInSpanContext(getSpan(), run),
41
+ mapResult(result) {
42
+ getSpan()?.addEvent(result.done ? "completed" : "yielded");
43
+ return result;
44
+ },
45
+ onError(error) {
46
+ recordSpanError(getSpan(), error);
47
+ },
48
+ onFinish() {
49
+ getSpan()?.end();
50
+ }
51
+ });
59
52
  }
60
- export function replicateAsyncIterator(source, count) {
61
- const queue = new AsyncIdQueue();
62
- const ids = Array.from({ length: count }, (_, i) => i.toString());
63
- let isSourceFinished = false;
64
- const start = once(async () => {
65
- try {
66
- while (true) {
67
- const item = await source.next();
68
- ids.forEach((id) => {
69
- if (queue.isOpen(id)) {
70
- queue.push(id, { next: item });
71
- }
72
- });
73
- if (item.done) {
74
- break;
75
- }
76
- }
77
- }
78
- catch (error) {
79
- ids.forEach((id) => {
80
- if (queue.isOpen(id)) {
81
- queue.push(id, { error });
82
- }
83
- });
84
- }
85
- finally {
86
- isSourceFinished = true;
87
- }
88
- });
89
- const replicated = ids.map((id) => {
90
- queue.open(id);
91
- return new AsyncIteratorClass(async () => {
92
- void start();
93
- const item = await queue.pull(id);
94
- if (item.next) {
95
- return item.next;
96
- }
97
- throw item.error;
98
- }, async ({ kind, error }) => {
99
- queue.close({ id, reason: error });
100
- if (kind === 'cancelled' && !queue.size && !isSourceFinished) {
101
- isSourceFinished = true;
102
- await source?.return?.();
103
- }
104
- });
105
- });
106
- return replicated;
53
+ function replicateAsyncIterator(source, count) {
54
+ const queue = new AsyncIdQueue();
55
+ const ids = Array.from({ length: count }, (_, i) => i.toString());
56
+ let isSourceFinished = false;
57
+ const start = once(async () => {
58
+ try {
59
+ while (true) {
60
+ const item = await source.next();
61
+ ids.forEach((id) => {
62
+ if (queue.isOpen(id)) queue.push(id, { next: item });
63
+ });
64
+ if (item.done) break;
65
+ }
66
+ } catch (error) {
67
+ ids.forEach((id) => {
68
+ if (queue.isOpen(id)) queue.push(id, { error });
69
+ });
70
+ } finally {
71
+ isSourceFinished = true;
72
+ }
73
+ });
74
+ return ids.map((id) => {
75
+ queue.open(id);
76
+ return new AsyncIteratorClass(async () => {
77
+ start();
78
+ const item = await queue.pull(id);
79
+ if (item.next) return item.next;
80
+ throw item.error;
81
+ }, async ({ kind, error }) => {
82
+ queue.close({
83
+ id,
84
+ reason: error
85
+ });
86
+ if (kind === "cancelled" && !queue.size && !isSourceFinished) {
87
+ isSourceFinished = true;
88
+ await source?.return?.();
89
+ }
90
+ });
91
+ });
107
92
  }
108
93
  /**
109
- * Consumes an AsyncIteratorObject with lifecycle callbacks.
110
- *
111
- * @remarks
112
- * **Warning**: If no `onError` or `onFinish` is provided, errors are thrown into the unhandled rejection channel.
113
- *
114
- * @returns An unsubscribe callback that stops consuming and cleans up the iterator.
115
- * @see {@link https://orpc.dev/docs/client/async-iterator-object#using-consumeasynciterator | AsyncIteratorObject in Client - Using consumeAsyncIterator}
116
- */
117
- export function consumeAsyncIterator(iterator, options) {
118
- // The typed error should always be combined with `ThrowableError`
119
- // because an AsyncIterator can throw any error during iteration,
120
- // while TError only represents errors from the initial promise.
121
- // In oRPC client/server usage, initial and iteration errors are usually the same,
122
- // but this utility is shared, so it needs to support the general case.
123
- void (async () => {
124
- let onFinishState;
125
- try {
126
- const resolvedIterator = await iterator;
127
- while (true) {
128
- const { done, value } = await resolvedIterator.next();
129
- if (done) {
130
- // if iterator is canceled, value can be undefined
131
- const realValue = value;
132
- onFinishState = [null, realValue, true];
133
- options.onSuccess?.(realValue);
134
- break;
135
- }
136
- try {
137
- options.onEvent(value);
138
- }
139
- catch (error) {
140
- // Close the source before reporting the onEvent error
141
- await resolvedIterator.return?.();
142
- throw error;
143
- }
144
- }
145
- }
146
- catch (error) {
147
- onFinishState = [error, undefined, false];
148
- options.onError?.(error);
149
- }
150
- finally {
151
- options.onFinish?.(onFinishState);
152
- }
153
- })();
154
- return async () => {
155
- await (await iterator)?.return?.();
156
- };
94
+ * Consumes an AsyncIteratorObject with lifecycle callbacks.
95
+ *
96
+ * @remarks
97
+ * **Warning**: If no `onError` or `onFinish` is provided, errors are thrown into the unhandled rejection channel.
98
+ *
99
+ * @returns An unsubscribe callback that stops consuming and cleans up the iterator.
100
+ * @see {@link https://orpc.dev/docs/client/async-iterator-object#using-consumeasynciterator | AsyncIteratorObject in Client - Using consumeAsyncIterator}
101
+ */
102
+ function consumeAsyncIterator(iterator, options) {
103
+ (async () => {
104
+ let onFinishState;
105
+ try {
106
+ const resolvedIterator = await iterator;
107
+ while (true) {
108
+ const { done, value } = await resolvedIterator.next();
109
+ if (done) {
110
+ const realValue = value;
111
+ onFinishState = [
112
+ null,
113
+ realValue,
114
+ true
115
+ ];
116
+ options.onSuccess?.(realValue);
117
+ break;
118
+ }
119
+ try {
120
+ options.onEvent(value);
121
+ } catch (error) {
122
+ await resolvedIterator.return?.();
123
+ throw error;
124
+ }
125
+ }
126
+ } catch (error) {
127
+ onFinishState = [
128
+ error,
129
+ void 0,
130
+ false
131
+ ];
132
+ options.onError?.(error);
133
+ } finally {
134
+ options.onFinish?.(onFinishState);
135
+ }
136
+ })();
137
+ return async () => {
138
+ await (await iterator)?.return?.();
139
+ };
157
140
  }
141
+ export { consumeAsyncIterator, replicateAsyncIterator, traceAsyncIterator, wrapAsyncIterator };