@orpc/shared 2.0.0-beta.47 → 2.0.0-beta.48

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/README.md +2 -3
  2. package/dist/args.d.mts +2 -0
  3. package/dist/args.mjs +3 -0
  4. package/dist/array.d.mts +2 -0
  5. package/dist/array.mjs +7 -0
  6. package/dist/bigint.d.mts +9 -0
  7. package/dist/bigint.mjs +12 -0
  8. package/dist/buffer.d.mts +18 -0
  9. package/dist/buffer.mjs +66 -0
  10. package/dist/compare.d.mts +1 -0
  11. package/dist/compare.mjs +43 -0
  12. package/dist/consts.d.mts +1 -0
  13. package/dist/consts.mjs +1 -0
  14. package/dist/error.d.mts +1 -0
  15. package/dist/error.mjs +3 -0
  16. package/dist/function.d.mts +12 -0
  17. package/dist/function.mjs +31 -0
  18. package/dist/http.d.mts +29 -0
  19. package/dist/http.mjs +83 -0
  20. package/dist/id.d.mts +8 -0
  21. package/dist/id.mjs +7 -0
  22. package/dist/index.d.mts +25 -492
  23. package/dist/index.mjs +23 -1117
  24. package/dist/interceptor.d.mts +96 -0
  25. package/dist/interceptor.mjs +102 -0
  26. package/dist/iterator.d.mts +82 -0
  27. package/dist/iterator.mjs +151 -0
  28. package/dist/object.d.mts +64 -0
  29. package/dist/object.mjs +221 -0
  30. package/dist/plugin.d.mts +12 -0
  31. package/dist/plugin.mjs +58 -0
  32. package/dist/promise.d.mts +17 -0
  33. package/dist/promise.mjs +23 -0
  34. package/dist/proxy.d.mts +15 -0
  35. package/dist/proxy.mjs +15 -0
  36. package/dist/queue.d.mts +16 -0
  37. package/dist/queue.mjs +74 -0
  38. package/dist/signal.d.mts +13 -0
  39. package/dist/signal.mjs +74 -0
  40. package/dist/stream.d.mts +54 -0
  41. package/dist/stream.mjs +138 -0
  42. package/dist/tracing.d.mts +73 -0
  43. package/dist/tracing.mjs +89 -0
  44. package/dist/types.d.mts +32 -0
  45. package/dist/types.mjs +1 -0
  46. package/dist/value.d.mts +8 -0
  47. package/dist/value.mjs +6 -0
  48. package/package.json +3 -4
  49. package/dist/index.d.ts +0 -492
@@ -0,0 +1,96 @@
1
+ import type { Promisable } from "type-fest";
2
+ import type { PromiseWithError, ThrowableError } from "./types.mjs";
3
+ export type InterceptableOptions = Record<string, any>;
4
+ export type InterceptorOptions<
5
+ TOptions extends InterceptableOptions,
6
+ TResult
7
+ > = Omit<TOptions, "next"> & {
8
+ next(options?: TOptions): TResult;
9
+ };
10
+ export type Interceptor<
11
+ TOptions extends InterceptableOptions,
12
+ TResult
13
+ > = (options: InterceptorOptions<TOptions, TResult>) => TResult;
14
+ /**
15
+ * Can used for interceptors or middlewares
16
+ */
17
+ export declare function onStart<
18
+ T,
19
+ TOptions extends {
20
+ next: () => any;
21
+ },
22
+ TRest extends any[]
23
+ >(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions["next"]>>>;
24
+ /**
25
+ * Can used for interceptors or middlewares
26
+ */
27
+ export declare function onSuccess<
28
+ T,
29
+ TOptions extends {
30
+ next: () => any;
31
+ },
32
+ TRest extends any[]
33
+ >(callback: NoInfer<(result: Awaited<ReturnType<TOptions["next"]>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions["next"]>>>;
34
+ /**
35
+ * Creates an interceptor or middleware that invokes a callback whenever an error
36
+ * is thrown. The error is rethrown after the callback completes.
37
+ *
38
+ * @see {@link https://orpc.dev/docs/adapters/fetch-api | Fetch API Adapter}
39
+ */
40
+ export declare function onError<
41
+ T,
42
+ TOptions extends {
43
+ next: () => any;
44
+ },
45
+ TRest extends any[]
46
+ >(callback: NoInfer<(error: 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"]>>>;
47
+ export type OnFinishState<
48
+ TResult,
49
+ TError
50
+ > = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
51
+ /**
52
+ * Can used for interceptors or middlewares
53
+ */
54
+ export declare function onFinish<
55
+ T,
56
+ TOptions extends {
57
+ next: () => any;
58
+ },
59
+ TRest extends any[]
60
+ >(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"]>>>;
61
+ /**
62
+ * Creates a middleware or interceptor that invokes a callback when the returned async
63
+ * iterator object throws an error while being consumed.
64
+ *
65
+ * This does not replace the `onError`. `onError` only fires on the
66
+ * initial call (before the interceptor returns the iterator), whereas this
67
+ * callback only fires while consuming the iterator. Use both together to
68
+ * catch all possible errors.
69
+ */
70
+ export declare function onAsyncIteratorObjectError<
71
+ T,
72
+ TOptions extends {
73
+ next: () => any;
74
+ },
75
+ TRest extends any[]
76
+ >(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"]>>>;
77
+ /**
78
+ * Creates an interceptor that invokes a callback when the returned readable
79
+ * stream errors while being consumed.
80
+ *
81
+ * This does not replace the `onError`. `onError` only fires on the
82
+ * initial call (before the interceptor returns the stream), whereas this
83
+ * callback only fires while consuming the stream. Use both together to catch
84
+ * all possible errors.
85
+ */
86
+ export declare function onReadableStreamError<
87
+ T,
88
+ TOptions extends {
89
+ next: () => any;
90
+ },
91
+ TRest extends any[]
92
+ >(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"]>>>;
93
+ export declare function intercept<
94
+ TOptions extends InterceptableOptions,
95
+ TResult
96
+ >(interceptors: undefined | Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
@@ -0,0 +1,102 @@
1
+ import { isAsyncIteratorObject } from "@standard-server/shared";
2
+ import { wrapAsyncIterator } from "./iterator.mjs";
3
+ import { override } from "./proxy.mjs";
4
+ import { wrapReadableStream } from "./stream.mjs";
5
+
6
+ export function onStart(callback) {
7
+ return async (options, ...rest) => {
8
+ await callback(options, ...rest);
9
+ return await options.next();
10
+ };
11
+ }
12
+
13
+ export function onSuccess(callback) {
14
+ return async (options, ...rest) => {
15
+ const result = await options.next();
16
+ await callback(result, options, ...rest);
17
+ return result;
18
+ };
19
+ }
20
+
21
+ export function onError(callback) {
22
+ return async (options, ...rest) => {
23
+ try {
24
+ return await options.next();
25
+ } catch (error) {
26
+ await callback(error, options, ...rest);
27
+ throw error;
28
+ }
29
+ };
30
+ }
31
+
32
+ export function onFinish(callback) {
33
+ return async (options, ...rest) => {
34
+ let state;
35
+ try {
36
+ const result = await options.next();
37
+ state = [
38
+ null,
39
+ result,
40
+ true
41
+ ];
42
+ return result;
43
+ } catch (error) {
44
+ state = [
45
+ error,
46
+ undefined,
47
+ false
48
+ ];
49
+ throw error;
50
+ } finally {
51
+ await callback(state, options, ...rest);
52
+ }
53
+ };
54
+ }
55
+
56
+ export function onAsyncIteratorObjectError(callback) {
57
+
58
+
59
+
60
+
61
+
62
+ return async (options, ...rest) => {
63
+ const output = await options.next();
64
+ if (!isAsyncIteratorObject(output)) {
65
+ return output;
66
+ }
67
+
68
+ return override(output, wrapAsyncIterator(output, { onError: (error) => callback(error, options, ...rest) }));
69
+ };
70
+ }
71
+
72
+ export function onReadableStreamError(callback) {
73
+
74
+
75
+
76
+
77
+
78
+ return async (options, ...rest) => {
79
+ const output = await options.next();
80
+ if (!(output instanceof ReadableStream)) {
81
+ return output;
82
+ }
83
+
84
+ return override(output, wrapReadableStream(output, { onError: (error) => callback(error, options, ...rest) }));
85
+ };
86
+ }
87
+ export function intercept(interceptors, options, main) {
88
+ if (!interceptors?.length) {
89
+ return main(options);
90
+ }
91
+ const next = (options, index) => {
92
+ const interceptor = interceptors[index];
93
+ if (!interceptor) {
94
+ return main(options);
95
+ }
96
+ return interceptor({
97
+ ...options,
98
+ next: (newOptions = options) => next(newOptions, index + 1)
99
+ });
100
+ };
101
+ return next(options, 0);
102
+ }
@@ -0,0 +1,82 @@
1
+ import type { Promisable } from "type-fest";
2
+ import type { StartSpanOptions } from "./tracing.mjs";
3
+ import type { PromiseWithError, ThrowableError } from "./types.mjs";
4
+ import { AsyncIteratorClass } from "@standard-server/shared";
5
+ export interface WrapAsyncIteratorOptions<
6
+ TYield,
7
+ TReturn,
8
+ TMappedYield,
9
+ TMappedReturn
10
+ > {
11
+ /**
12
+ * Any call to the original iterator will be executed inside this function.
13
+ * Useful when you want execution to happen within a specific context,
14
+ * such as AsyncLocalStorage.
15
+ */
16
+ runWith?: (<T>(run: () => Promise<T>) => Promisable<T>) | undefined;
17
+ mapResult?: ((result: IteratorResult<TYield, TReturn>) => Promisable<IteratorResult<TMappedYield, TMappedReturn>>) | undefined;
18
+ mapError?: ((error: ThrowableError) => Promisable<ThrowableError>) | undefined;
19
+ onError?: ((error: ThrowableError) => Promisable<void>) | undefined;
20
+ /**
21
+ * Execute after the stream finishes or is cancelled.
22
+ */
23
+ onFinish?: (() => Promisable<void>) | undefined;
24
+ }
25
+ export declare function wrapAsyncIterator<
26
+ TYield,
27
+ TReturn,
28
+ TMappedYield = TYield,
29
+ TMappedReturn = TReturn
30
+ >(iterator: AsyncIterator<TYield, TReturn>, { runWith, mapResult, mapError, onError, onFinish }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): NoInfer<AsyncIteratorClass<TMappedYield, TMappedReturn>>;
31
+ export declare function traceAsyncIterator<
32
+ T,
33
+ TReturn,
34
+ TNext
35
+ >(options: StartSpanOptions | string, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
36
+ export declare function replicateAsyncIterator<
37
+ T,
38
+ TReturn,
39
+ TNext
40
+ >(source: AsyncIterator<T, TReturn, TNext>, count: number): AsyncIteratorClass<T, TReturn, TNext>[];
41
+ export interface ConsumeAsyncIteratorOptions<
42
+ T,
43
+ TReturn,
44
+ TError
45
+ > {
46
+ /**
47
+ * Called on each event
48
+ */
49
+ onEvent: (event: T) => void;
50
+ /**
51
+ * Called once error happens
52
+ */
53
+ onError?: ((error: TError) => void) | undefined;
54
+ /**
55
+ * Called once AsyncIteratorObject is done
56
+ *
57
+ * @remarks
58
+ * **Note**: If iterator is canceled, `undefined` can be passed on success
59
+ */
60
+ onSuccess?: ((value: TReturn | undefined) => void) | undefined;
61
+ /**
62
+ * Called once after onError or onSuccess
63
+ *
64
+ * @remarks
65
+ * **Note**: If iterator is canceled, `undefined` can be passed on success
66
+ */
67
+ onFinish?: ((state: [error: TError, data: undefined, isSuccess: false] | [error: null, data: TReturn | undefined, isSuccess: true]) => void) | undefined;
68
+ }
69
+ /**
70
+ * Consumes an AsyncIteratorObject with lifecycle callbacks.
71
+ *
72
+ * @remarks
73
+ * **Warning**: If no `onError` or `onFinish` is provided, errors are thrown into the unhandled rejection channel.
74
+ *
75
+ * @returns An unsubscribe callback that stops consuming and cleans up the iterator.
76
+ * @see {@link https://orpc.dev/docs/client/async-iterator-object#using-consumeasynciterator | AsyncIteratorObject in Client - Using consumeAsyncIterator}
77
+ */
78
+ export declare function consumeAsyncIterator<
79
+ T,
80
+ TReturn,
81
+ TError = ThrowableError
82
+ >(iterator: AsyncIterator<T, TReturn> | PromiseWithError<AsyncIterator<T, TReturn>, TError>, options: ConsumeAsyncIteratorOptions<T, TReturn, TError | ThrowableError>): () => Promise<void>;
@@ -0,0 +1,151 @@
1
+ import { AsyncIteratorClass } from "@standard-server/shared";
2
+ import { once } from "./function.mjs";
3
+ import { AsyncIdQueue } from "./queue.mjs";
4
+ import { recordSpanError, runInSpanContext, startSpan } from "./tracing.mjs";
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
+ } catch (error) {
15
+ isDone = true;
16
+ throw error;
17
+ }
18
+ return mapResult ? await mapResult(result) : result;
19
+ } catch (error) {
20
+ await onError?.(error);
21
+ throw mapError ? await mapError(error) : error;
22
+ }
23
+ }, async (_state) => {
24
+ try {
25
+
26
+
27
+ if (!isDone) {
28
+ try {
29
+ await runWith(async () => iterator.return?.());
30
+ } catch (error) {
31
+ await onError?.(error);
32
+ throw error;
33
+ }
34
+ }
35
+ } finally {
36
+ await onFinish?.();
37
+ }
38
+ });
39
+ }
40
+ export function traceAsyncIterator(options, iterator) {
41
+ const getSpan = once(() => startSpan(options));
42
+ return wrapAsyncIterator(iterator, {
43
+ runWith: (run) => runInSpanContext(getSpan(), run),
44
+ mapResult(result) {
45
+ getSpan()?.addEvent(result.done ? "completed" : "yielded");
46
+ return result;
47
+ },
48
+ onError(error) {
49
+ recordSpanError(getSpan(), error);
50
+ },
51
+ onFinish() {
52
+ getSpan()?.end();
53
+ }
54
+ });
55
+ }
56
+ export function replicateAsyncIterator(source, count) {
57
+ const queue = new AsyncIdQueue();
58
+ const ids = Array.from({ length: count }, (_, i) => i.toString());
59
+ let isSourceFinished = false;
60
+ const start = once(async () => {
61
+ try {
62
+ while (true) {
63
+ const item = await source.next();
64
+ ids.forEach((id) => {
65
+ if (queue.isOpen(id)) {
66
+ queue.push(id, { next: item });
67
+ }
68
+ });
69
+ if (item.done) {
70
+ break;
71
+ }
72
+ }
73
+ } catch (error) {
74
+ ids.forEach((id) => {
75
+ if (queue.isOpen(id)) {
76
+ queue.push(id, { error });
77
+ }
78
+ });
79
+ } finally {
80
+ isSourceFinished = true;
81
+ }
82
+ });
83
+ const replicated = ids.map((id) => {
84
+ queue.open(id);
85
+ return new AsyncIteratorClass(async () => {
86
+ start();
87
+ const item = await queue.pull(id);
88
+ if (item.next) {
89
+ return item.next;
90
+ }
91
+ throw item.error;
92
+ }, async ({ kind, error }) => {
93
+ queue.close({
94
+ id,
95
+ reason: error
96
+ });
97
+ if (kind === "cancelled" && !queue.size && !isSourceFinished) {
98
+ isSourceFinished = true;
99
+ await source?.return?.();
100
+ }
101
+ });
102
+ });
103
+ return replicated;
104
+ }
105
+
106
+ export function consumeAsyncIterator(iterator, options) {
107
+
108
+
109
+
110
+
111
+
112
+ void (async () => {
113
+ let onFinishState;
114
+ try {
115
+ const resolvedIterator = await iterator;
116
+ while (true) {
117
+ const { done, value } = await resolvedIterator.next();
118
+ if (done) {
119
+
120
+ const realValue = value;
121
+ onFinishState = [
122
+ null,
123
+ realValue,
124
+ true
125
+ ];
126
+ options.onSuccess?.(realValue);
127
+ break;
128
+ }
129
+ try {
130
+ options.onEvent(value);
131
+ } catch (error) {
132
+
133
+ await resolvedIterator.return?.();
134
+ throw error;
135
+ }
136
+ }
137
+ } catch (error) {
138
+ onFinishState = [
139
+ error,
140
+ undefined,
141
+ false
142
+ ];
143
+ options.onError?.(error);
144
+ } finally {
145
+ options.onFinish?.(onFinishState);
146
+ }
147
+ })();
148
+ return async () => {
149
+ await (await iterator)?.return?.();
150
+ };
151
+ }
@@ -0,0 +1,64 @@
1
+ import type { AnyFunction } from "./function.mjs";
2
+ export type Segment = string | number;
3
+ export declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
4
+ maps: Segment[][];
5
+ values: unknown[];
6
+ };
7
+ /**
8
+ * Get constructor of the value
9
+ *
10
+ */
11
+ export declare function getConstructor(value: unknown): Function | null | undefined;
12
+ export declare function getConstructors(value: unknown): Generator<Function>;
13
+ /**
14
+ * Checks whether a value is a plain object, including objects created with
15
+ * `Object.create(null)`.
16
+ */
17
+ export declare function isPlainObject(value: unknown): value is Record<PropertyKey, unknown>;
18
+ /**
19
+ * Returns `object[key]` only when it is an own property, so keys like
20
+ * `toString` do not resolve through the prototype chain.
21
+ */
22
+ export declare function getOwn<T extends object>(object: T, key: PropertyKey): T[keyof T] | undefined;
23
+ export declare function get(object: unknown, path: readonly PropertyKey[]): unknown;
24
+ /**
25
+ * Sets a value at the given path, creating plain objects for intermediate keys as needed.
26
+ */
27
+ export declare function set(root: object, path: [PropertyKey, ...PropertyKey[]] | [...PropertyKey[], PropertyKey], value: unknown): void;
28
+ /**
29
+ * Sets `object[key]`, defining `__proto__` as an own property instead of re-parenting the object.
30
+ */
31
+ export declare function setOwn(object: object, key: PropertyKey, value: unknown): void;
32
+ /**
33
+ * Merges two values by copying the second over the first, repeating the merge one level deeper for
34
+ * nested plain objects. Anything that is not a pair of plain objects is replaced by the second one.
35
+ */
36
+ export declare function mergeTwoLevels(first: unknown, second: unknown): unknown;
37
+ export declare function omit<
38
+ T extends object,
39
+ K extends keyof T
40
+ >(obj: T, keys: readonly K[]): Omit<T, K>;
41
+ export declare function pick<
42
+ T extends object,
43
+ K extends keyof T
44
+ >(obj: T, keys: readonly K[]): Pick<T, K>;
45
+ /**
46
+ * Deep clones arrays and plain objects, leaving every other value as is.
47
+ * Circular and shared references are preserved in the copy.
48
+ */
49
+ export declare function clone<T>(value: T): T;
50
+ export declare function copyOnWrite(parent: object, key: PropertyKey, original: unknown): unknown;
51
+ export declare function isPropertyKey(value: unknown): value is PropertyKey;
52
+ export declare const NullProtoObj: {
53
+ new <T extends Record<PropertyKey, unknown>>(): T;
54
+ };
55
+ /**
56
+ * Returns an object containing all methods of the given object, with each
57
+ * method bound to the original object instance.
58
+ *
59
+ * Methods are collected from both the object itself and its prototype chain
60
+ * (excluding `Object.prototype` and the `constructor` property).
61
+ */
62
+ export declare function bindMethods<T extends object>(obj: T, options?: {
63
+ unbound?: (keyof T)[];
64
+ }): Pick<T, { [K in keyof T]: T[K] extends AnyFunction ? K : never }[keyof T]>;