@orpc/shared 2.0.0-beta.5 → 2.0.0-beta.51

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 (51) hide show
  1. package/README.md +139 -102
  2. package/dist/args.d.ts +2 -0
  3. package/dist/args.js +5 -0
  4. package/dist/array.d.ts +5 -0
  5. package/dist/array.js +13 -0
  6. package/dist/bigint.d.ts +9 -0
  7. package/dist/bigint.js +15 -0
  8. package/dist/buffer.d.ts +18 -0
  9. package/dist/buffer.js +54 -0
  10. package/dist/compare.d.ts +1 -0
  11. package/dist/compare.js +26 -0
  12. package/dist/consts.d.ts +1 -0
  13. package/dist/consts.js +3 -0
  14. package/dist/error.d.ts +1 -0
  15. package/dist/error.js +5 -0
  16. package/dist/function.d.ts +12 -0
  17. package/dist/function.js +33 -0
  18. package/dist/http.d.ts +58 -0
  19. package/dist/http.js +147 -0
  20. package/dist/id.d.ts +8 -0
  21. package/dist/id.js +13 -0
  22. package/dist/index.d.ts +26 -306
  23. package/dist/index.js +23 -0
  24. package/dist/interceptor.d.ts +66 -0
  25. package/dist/interceptor.js +119 -0
  26. package/dist/iterator.d.ts +55 -0
  27. package/dist/iterator.js +141 -0
  28. package/dist/object.d.ts +62 -0
  29. package/dist/object.js +194 -0
  30. package/dist/plugin.d.ts +12 -0
  31. package/dist/plugin.js +45 -0
  32. package/dist/promise.d.ts +17 -0
  33. package/dist/promise.js +32 -0
  34. package/dist/proxy.d.ts +12 -0
  35. package/dist/proxy.js +25 -0
  36. package/dist/queue.d.ts +16 -0
  37. package/dist/queue.js +64 -0
  38. package/dist/regex.d.ts +9 -0
  39. package/dist/regex.js +11 -0
  40. package/dist/signal.d.ts +23 -0
  41. package/dist/signal.js +88 -0
  42. package/dist/stream.d.ts +47 -0
  43. package/dist/stream.js +129 -0
  44. package/dist/tracing.d.ts +73 -0
  45. package/dist/tracing.js +76 -0
  46. package/dist/types.d.ts +27 -0
  47. package/dist/value.d.ts +2 -0
  48. package/dist/value.js +6 -0
  49. package/package.json +22 -30
  50. package/dist/index.d.mts +0 -306
  51. package/dist/index.mjs +0 -892
package/dist/plugin.js ADDED
@@ -0,0 +1,45 @@
1
+ // src/plugin.ts
2
+ /**
3
+ * Sorts plugins based on their `before` and `after` dependencies.
4
+ */
5
+ function sortPlugins(plugins) {
6
+ const pluginCount = plugins.length;
7
+ const pluginIdToIndices = /* @__PURE__ */ new Map();
8
+ for (let i = 0; i < pluginCount; i++) {
9
+ const plugin = plugins[i];
10
+ const indices = pluginIdToIndices.get(plugin.name);
11
+ if (indices === void 0) pluginIdToIndices.set(plugin.name, [i]);
12
+ else indices.push(i);
13
+ }
14
+ const dependencies = Array.from({ length: pluginCount }, () => []);
15
+ for (let i = 0; i < pluginCount; i++) {
16
+ const plugin = plugins[i];
17
+ if (plugin.before !== void 0) for (const beforeId of plugin.before) {
18
+ const beforeIndices = pluginIdToIndices.get(beforeId);
19
+ if (beforeIndices !== void 0) for (const beforeIndex of beforeIndices) dependencies[beforeIndex].push(i);
20
+ }
21
+ if (plugin.after !== void 0) for (const afterId of plugin.after) {
22
+ const afterIndices = pluginIdToIndices.get(afterId);
23
+ if (afterIndices !== void 0) for (const afterIndex of afterIndices) dependencies[i].push(afterIndex);
24
+ }
25
+ }
26
+ const sorted = [];
27
+ const placed = /* @__PURE__ */ new Set();
28
+ while (sorted.length < pluginCount) {
29
+ const next = plugins.findIndex((_, i) => !placed.has(i) && dependencies[i].every((dependency) => placed.has(dependency)));
30
+ if (next === -1) throw new Error(`Circular dependency detected involving plugin "${findCyclicPlugin(plugins, dependencies, placed).name}"`);
31
+ placed.add(next);
32
+ sorted.push(plugins[next]);
33
+ }
34
+ return sorted;
35
+ }
36
+ function findCyclicPlugin(plugins, dependencies, placed) {
37
+ const seen = /* @__PURE__ */ new Set();
38
+ let current = plugins.findIndex((_, i) => !placed.has(i));
39
+ while (!seen.has(current)) {
40
+ seen.add(current);
41
+ current = dependencies[current].find((dependency) => !placed.has(dependency));
42
+ }
43
+ return plugins[current];
44
+ }
45
+ export { sortPlugins };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Creates a promise together with its associated `resolve` and `reject`
3
+ * functions.
4
+ *
5
+ * Equivalent to `Promise.withResolvers()`, but works in environments
6
+ * where that API is not yet available.
7
+ */
8
+ export declare function promiseWithResolvers<T>(): {
9
+ promise: Promise<T>;
10
+ resolve: (v: T) => void;
11
+ reject: (reason: unknown) => void;
12
+ };
13
+ /**
14
+ * Captures the current async context (such as AsyncLocalStorage) through a promise reaction, so no runtime API is needed.
15
+ * The returned function runs a callback inside it once; later calls reject.
16
+ */
17
+ export declare function captureAsyncContext(): <T>(callback: () => Promise<T>) => Promise<T>;
@@ -0,0 +1,32 @@
1
+ // src/promise.ts
2
+ /**
3
+ * Creates a promise together with its associated `resolve` and `reject`
4
+ * functions.
5
+ *
6
+ * Equivalent to `Promise.withResolvers()`, but works in environments
7
+ * where that API is not yet available.
8
+ */
9
+ function promiseWithResolvers() {
10
+ const result = {};
11
+ result.promise = new Promise((resolve, reject) => {
12
+ result.resolve = resolve;
13
+ result.reject = reject;
14
+ });
15
+ return result;
16
+ }
17
+ /**
18
+ * Captures the current async context (such as AsyncLocalStorage) through a promise reaction, so no runtime API is needed.
19
+ * The returned function runs a callback inside it once; later calls reject.
20
+ */
21
+ function captureAsyncContext() {
22
+ const { promise, resolve } = promiseWithResolvers();
23
+ const result = promise.then((callback) => callback());
24
+ let called = false;
25
+ return (callback) => {
26
+ if (called) return Promise.reject(/* @__PURE__ */ new Error("A captured async context can be run only once."));
27
+ called = true;
28
+ resolve(callback);
29
+ return result;
30
+ };
31
+ }
32
+ export { captureAsyncContext, promiseWithResolvers };
@@ -0,0 +1,12 @@
1
+ import { Value } from "./value.js";
2
+ /**
3
+ * Creates a proxy that overlays a `partial` object on top of a `target`.
4
+ *
5
+ * - Properties from `partial` take precedence.
6
+ * - Properties not present in `partial` fall back to the resolved `target`.
7
+ * - Methods are bound to the proxy to ensure a consistent `this` context.
8
+ *
9
+ * Useful for overriding specific properties of an object while delegating
10
+ * all other access to the original target without needing to know its full structure.
11
+ */
12
+ export declare function override<T extends object, U extends object>(target: Value<T>, partial: U): U & Omit<T, keyof U>;
package/dist/proxy.js ADDED
@@ -0,0 +1,25 @@
1
+ import { value } from "./value.js";
2
+ import { getOrBind } from "@standard-server/shared";
3
+ // src/proxy.ts
4
+ /**
5
+ * Creates a proxy that overlays a `partial` object on top of a `target`.
6
+ *
7
+ * - Properties from `partial` take precedence.
8
+ * - Properties not present in `partial` fall back to the resolved `target`.
9
+ * - Methods are bound to the proxy to ensure a consistent `this` context.
10
+ *
11
+ * Useful for overriding specific properties of an object while delegating
12
+ * all other access to the original target without needing to know its full structure.
13
+ */
14
+ function override(target, partial) {
15
+ return new Proxy(typeof target === "function" ? partial : target, {
16
+ get(_, prop) {
17
+ const targetValue = prop in partial ? partial : value(target);
18
+ return getOrBind(targetValue, prop);
19
+ },
20
+ has(_, prop) {
21
+ return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
22
+ }
23
+ });
24
+ }
25
+ export { override };
@@ -0,0 +1,16 @@
1
+ export interface AsyncIdQueueCloseOptions {
2
+ id?: string | undefined;
3
+ reason?: unknown;
4
+ }
5
+ export declare class AsyncIdQueue<T> {
6
+ private readonly openIds;
7
+ private readonly queues;
8
+ private readonly waiters;
9
+ get size(): number;
10
+ open(id: string): void;
11
+ isOpen(id: string): boolean;
12
+ push(id: string, item: T): void;
13
+ pull(id: string): Promise<T>;
14
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
15
+ private assertOpen;
16
+ }
package/dist/queue.js ADDED
@@ -0,0 +1,64 @@
1
+ import { AbortError } from "@standard-server/shared";
2
+ // src/queue.ts
3
+ var AsyncIdQueue = class {
4
+ openIds = /* @__PURE__ */ new Set();
5
+ queues = /* @__PURE__ */ new Map();
6
+ waiters = /* @__PURE__ */ new Map();
7
+ get size() {
8
+ return this.openIds.size;
9
+ }
10
+ open(id) {
11
+ this.openIds.add(id);
12
+ }
13
+ isOpen(id) {
14
+ return this.openIds.has(id);
15
+ }
16
+ push(id, item) {
17
+ this.assertOpen(id);
18
+ const pending = this.waiters.get(id);
19
+ if (pending?.length) {
20
+ pending.shift()[0](item);
21
+ if (pending.length === 0) this.waiters.delete(id);
22
+ } else {
23
+ const items = this.queues.get(id);
24
+ if (items) items.push(item);
25
+ else this.queues.set(id, [item]);
26
+ }
27
+ }
28
+ async pull(id) {
29
+ this.assertOpen(id);
30
+ const items = this.queues.get(id);
31
+ if (items?.length) {
32
+ const item = items.shift();
33
+ if (items.length === 0) this.queues.delete(id);
34
+ return item;
35
+ }
36
+ return new Promise((resolve, reject) => {
37
+ const waitingPulls = this.waiters.get(id);
38
+ const pending = [resolve, reject];
39
+ if (waitingPulls) waitingPulls.push(pending);
40
+ else this.waiters.set(id, [pending]);
41
+ });
42
+ }
43
+ close({ id, reason } = {}) {
44
+ if (id === void 0) {
45
+ this.waiters.forEach((pendingPulls, id) => {
46
+ const error = reason ?? new AbortError(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`);
47
+ pendingPulls.forEach(([, reject]) => reject(error));
48
+ });
49
+ this.waiters.clear();
50
+ this.openIds.clear();
51
+ this.queues.clear();
52
+ return;
53
+ }
54
+ const error = reason ?? new AbortError(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`);
55
+ this.waiters.get(id)?.forEach(([, reject]) => reject(error));
56
+ this.waiters.delete(id);
57
+ this.openIds.delete(id);
58
+ this.queues.delete(id);
59
+ }
60
+ assertOpen(id) {
61
+ if (!this.isOpen(id)) throw new Error(`[AsyncIdQueue] Cannot access queue[${id}] because it is not open or aborted.`);
62
+ }
63
+ };
64
+ export { AsyncIdQueue };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Matches an integer string: an optional `-`, then digits without leading zeros (`007` is rejected).
3
+ * Note that `-0` is accepted.
4
+ */
5
+ export declare const INTEGER_REGEX: RegExp;
6
+ /**
7
+ * Matches a non-negative integer string without leading zeros, such as an array index.
8
+ */
9
+ export declare const NON_NEGATIVE_INTEGER_REGEX: RegExp;
package/dist/regex.js ADDED
@@ -0,0 +1,11 @@
1
+ // src/regex.ts
2
+ /**
3
+ * Matches an integer string: an optional `-`, then digits without leading zeros (`007` is rejected).
4
+ * Note that `-0` is accepted.
5
+ */
6
+ const INTEGER_REGEX = /^-?(?:0|[1-9]\d*)$/;
7
+ /**
8
+ * Matches a non-negative integer string without leading zeros, such as an array index.
9
+ */
10
+ const NON_NEGATIVE_INTEGER_REGEX = /^(?:0|[1-9]\d*)$/;
11
+ export { INTEGER_REGEX, NON_NEGATIVE_INTEGER_REGEX };
@@ -0,0 +1,23 @@
1
+ export interface DisposableAllAbortSignal {
2
+ signal: AbortSignal | undefined;
3
+ dispose: () => void;
4
+ }
5
+ /**
6
+ * Returns a signal that aborts only after all provided signals are aborted,
7
+ * and a `dispose` function that removes the listeners added to the input signals.
8
+ */
9
+ export declare function disposableAllAbortSignal(signals: readonly (AbortSignal | undefined)[]): DisposableAllAbortSignal;
10
+ /**
11
+ * Returns a signal that aborts as soon as any of the provided signals aborts,
12
+ * with the same abort reason.
13
+ *
14
+ * Prefers the native `AbortSignal.any` when available, and falls back to a manual
15
+ * implementation otherwise, including in runtimes without the `AbortSignal` global.
16
+ */
17
+ export declare function anyAbortSignal(signals: readonly (AbortSignal | undefined)[]): AbortSignal | undefined;
18
+ export declare function runWithSignal<T>(signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T>;
19
+ /**
20
+ * Calls `onAbort` with the abort reason once the signal aborts, or synchronously, before returning,
21
+ * if it is already aborted. Does nothing without a signal. Returns a function that removes the listener.
22
+ */
23
+ export declare function listenAbort(signal: AbortSignal | undefined, onAbort: (reason: unknown) => void): () => void;
package/dist/signal.js ADDED
@@ -0,0 +1,88 @@
1
+ import { promiseWithResolvers } from "./promise.js";
2
+ import { throwIfAborted } from "@standard-server/shared";
3
+ // src/signal.ts
4
+ /**
5
+ * Returns a signal that aborts only after all provided signals are aborted,
6
+ * and a `dispose` function that removes the listeners added to the input signals.
7
+ */
8
+ function disposableAllAbortSignal(signals) {
9
+ const realSignals = signals.filter((signal) => signal !== void 0);
10
+ if (realSignals.length === 0 || realSignals.length !== signals.length) return {
11
+ signal: void 0,
12
+ dispose: () => {}
13
+ };
14
+ const controller = new AbortController();
15
+ const listenersController = new AbortController();
16
+ const dispose = () => listenersController.abort();
17
+ const abortIfAllAborted = () => {
18
+ if (realSignals.every((signal) => signal.aborted)) {
19
+ controller.abort();
20
+ dispose();
21
+ }
22
+ };
23
+ abortIfAllAborted();
24
+ for (const signal of realSignals) signal.addEventListener("abort", abortIfAllAborted, {
25
+ once: true,
26
+ signal: listenersController.signal
27
+ });
28
+ return {
29
+ signal: controller.signal,
30
+ dispose
31
+ };
32
+ }
33
+ /**
34
+ * Returns a signal that aborts as soon as any of the provided signals aborts,
35
+ * with the same abort reason.
36
+ *
37
+ * Prefers the native `AbortSignal.any` when available, and falls back to a manual
38
+ * implementation otherwise, including in runtimes without the `AbortSignal` global.
39
+ */
40
+ function anyAbortSignal(signals) {
41
+ const realSignals = signals.filter((signal) => signal !== void 0);
42
+ if (realSignals.length === 0) return;
43
+ if (realSignals.length === 1) return realSignals[0];
44
+ if (typeof AbortSignal !== "undefined" && typeof AbortSignal.any === "function") return AbortSignal.any(realSignals);
45
+ const controller = new AbortController();
46
+ for (const signal of realSignals) {
47
+ if (signal.aborted) {
48
+ controller.abort(signal.reason);
49
+ break;
50
+ }
51
+ signal.addEventListener("abort", () => {
52
+ controller.abort(signal.reason);
53
+ }, {
54
+ once: true,
55
+ signal: controller.signal
56
+ });
57
+ }
58
+ return controller.signal;
59
+ }
60
+ async function runWithSignal(signal, fn) {
61
+ if (!signal) return fn();
62
+ throwIfAborted(signal);
63
+ const { promise, reject, resolve } = promiseWithResolvers();
64
+ let abortListener;
65
+ signal.addEventListener("abort", abortListener = () => {
66
+ reject(signal.reason);
67
+ abortListener = void 0;
68
+ });
69
+ try {
70
+ fn().then(resolve, reject);
71
+ return await promise;
72
+ } finally {
73
+ if (abortListener) signal.removeEventListener("abort", abortListener);
74
+ }
75
+ }
76
+ const noop = () => {};
77
+ /**
78
+ * Calls `onAbort` with the abort reason once the signal aborts, or synchronously, before returning,
79
+ * if it is already aborted. Does nothing without a signal. Returns a function that removes the listener.
80
+ */
81
+ function listenAbort(signal, onAbort) {
82
+ if (!signal) return noop;
83
+ const listener = () => onAbort(signal.reason);
84
+ if (signal.aborted) listener();
85
+ else signal.addEventListener("abort", listener, { once: true });
86
+ return () => signal.removeEventListener("abort", listener);
87
+ }
88
+ export { anyAbortSignal, disposableAllAbortSignal, listenAbort, runWithSignal };
@@ -0,0 +1,47 @@
1
+ import { StartSpanOptions } from "./tracing.js";
2
+ import { Promisable, ThrowableError } from "./types.js";
3
+ import { AsyncIteratorClass } from "@standard-server/shared";
4
+ export declare function replicateReadableStream<T>(stream: ReadableStream<T>, count: number): ReadableStream<T>[];
5
+ export type ReadableStreamReadResult<T> = {
6
+ done: false;
7
+ value: T;
8
+ } | {
9
+ done: true;
10
+ value?: T | undefined;
11
+ };
12
+ export interface WrapReadableStreamOptions<T, TMapped> {
13
+ /**
14
+ * Any call to the original stream reader will be executed inside this function.
15
+ * Useful when you want execution to happen within a specific context,
16
+ * such as AsyncLocalStorage.
17
+ */
18
+ runWith?: (<T>(run: () => Promise<T>) => Promisable<T>) | undefined;
19
+ mapResult?: ((result: ReadableStreamReadResult<T>) => Promisable<ReadableStreamReadResult<TMapped>>) | undefined;
20
+ mapError?: ((error: ThrowableError) => Promisable<ThrowableError>) | undefined;
21
+ onError?: ((error: ThrowableError) => Promisable<void>) | undefined;
22
+ /**
23
+ * Guaranteed to execute exactly once after the stream finishes or is cancelled.
24
+ */
25
+ onFinish?: (() => Promisable<void>) | undefined;
26
+ }
27
+ export declare function wrapReadableStream<T, TMapped = T>(stream: ReadableStream<T>, { runWith, mapResult, mapError, onError, onFinish }: WrapReadableStreamOptions<T, TMapped>): NoInfer<ReadableStream<TMapped>>;
28
+ export declare function traceReadableStream<T>(options: StartSpanOptions | string, stream: ReadableStream<T>): ReadableStream<T>;
29
+ /**
30
+ * Converts a {@link ReadableStream} into an {@link AsyncIteratorClass}.
31
+ *
32
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration}
33
+ */
34
+ export declare function streamToAsyncIteratorObject<T>(stream: ReadableStream<T>, { signal }?: {
35
+ signal?: AbortSignal | undefined;
36
+ }): AsyncIteratorClass<T>;
37
+ /**
38
+ * Converts an `AsyncIterator` into a `ReadableStream`.
39
+ */
40
+ export declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
41
+ /**
42
+ * Converts an `AsyncIterator` into a `ReadableStream`, ensuring that
43
+ * all emitted object values are *unproxied* before enqueuing.
44
+ *
45
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration}
46
+ */
47
+ export declare function asyncIteratorToUnproxiedDataStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
package/dist/stream.js ADDED
@@ -0,0 +1,129 @@
1
+ import { once } from "./function.js";
2
+ import { isPlainObject } from "./object.js";
3
+ import { promiseWithResolvers } from "./promise.js";
4
+ import { recordSpanError, runInSpanContext, startSpan } from "./tracing.js";
5
+ import { AsyncIteratorClass } from "@standard-server/shared";
6
+ // src/stream.ts
7
+ function replicateReadableStream(stream, count) {
8
+ if (count <= 0) return [];
9
+ const replicated = [];
10
+ let pending = stream;
11
+ for (let index = 0; index < count - 1; index++) {
12
+ const [replica, remainder] = pending.tee();
13
+ replicated.push(replica);
14
+ pending = remainder;
15
+ }
16
+ replicated.push(pending);
17
+ return replicated;
18
+ }
19
+ function wrapReadableStream(stream, { runWith, mapResult, mapError, onError, onFinish }) {
20
+ runWith ??= (run) => run();
21
+ const reader = once(() => stream.getReader());
22
+ const finish = once(async () => onFinish?.());
23
+ return new ReadableStream({
24
+ async pull(controller) {
25
+ let result;
26
+ try {
27
+ const readResult = await runWith(() => reader().read());
28
+ result = mapResult ? await mapResult(readResult) : readResult;
29
+ } catch (error) {
30
+ try {
31
+ await onError?.(error);
32
+ controller.error(mapError ? await mapError(error) : error);
33
+ } finally {
34
+ await finish();
35
+ }
36
+ return;
37
+ }
38
+ if (result.done) {
39
+ controller.close();
40
+ await finish();
41
+ } else controller.enqueue(result.value);
42
+ },
43
+ async cancel(reason) {
44
+ try {
45
+ try {
46
+ await runWith(() => reader().cancel(reason));
47
+ } catch (error) {
48
+ await onError?.(error);
49
+ throw error;
50
+ }
51
+ } finally {
52
+ await finish();
53
+ }
54
+ }
55
+ }, { highWaterMark: 0 });
56
+ }
57
+ function traceReadableStream(options, stream) {
58
+ const getSpan = once(() => startSpan(options));
59
+ return wrapReadableStream(stream, {
60
+ runWith: (run) => runInSpanContext(getSpan(), run),
61
+ mapResult(result) {
62
+ getSpan()?.addEvent(result.done ? "closed" : "enqueued");
63
+ return result;
64
+ },
65
+ onError(error) {
66
+ recordSpanError(getSpan(), error);
67
+ },
68
+ onFinish() {
69
+ getSpan()?.end();
70
+ }
71
+ });
72
+ }
73
+ /**
74
+ * Converts a {@link ReadableStream} into an {@link AsyncIteratorClass}.
75
+ *
76
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration}
77
+ */
78
+ function streamToAsyncIteratorObject(stream, { signal } = {}) {
79
+ const reader = stream.getReader();
80
+ let cancelledBySignal = false;
81
+ return new AsyncIteratorClass(async () => {
82
+ if (signal?.aborted) {
83
+ cancelledBySignal = true;
84
+ throw signal.reason;
85
+ }
86
+ if (!signal) return reader.read();
87
+ const { promise, reject } = promiseWithResolvers();
88
+ const onAbort = () => reject(signal.reason);
89
+ signal.addEventListener("abort", onAbort, { once: true });
90
+ try {
91
+ return await Promise.race([reader.read(), promise.catch(async (reason) => {
92
+ cancelledBySignal = true;
93
+ throw reason;
94
+ })]);
95
+ } finally {
96
+ signal.removeEventListener("abort", onAbort);
97
+ }
98
+ }, async ({ kind, error }) => {
99
+ if (kind === "cancelled" || kind === "error" && cancelledBySignal) await reader.cancel(error);
100
+ });
101
+ }
102
+ /**
103
+ * Converts an `AsyncIterator` into a `ReadableStream`.
104
+ */
105
+ function asyncIteratorToStream(iterator) {
106
+ return createIteratorStream(iterator, (value) => value);
107
+ }
108
+ /**
109
+ * Converts an `AsyncIterator` into a `ReadableStream`, ensuring that
110
+ * all emitted object values are *unproxied* before enqueuing.
111
+ *
112
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk | AI SDK Integration}
113
+ */
114
+ function asyncIteratorToUnproxiedDataStream(iterator) {
115
+ return createIteratorStream(iterator, (value) => isPlainObject(value) ? { ...value } : Array.isArray(value) ? value.map((i) => i) : value);
116
+ }
117
+ function createIteratorStream(iterator, map) {
118
+ return new ReadableStream({
119
+ async pull(controller) {
120
+ const { done, value } = await iterator.next();
121
+ if (done) controller.close();
122
+ else controller.enqueue(map(value));
123
+ },
124
+ async cancel() {
125
+ await iterator.return?.();
126
+ }
127
+ }, { highWaterMark: 0 });
128
+ }
129
+ export { asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, replicateReadableStream, streamToAsyncIteratorObject, traceReadableStream, wrapReadableStream };
@@ -0,0 +1,73 @@
1
+ import { Promisable } from "./types.js";
2
+ export type TracingAttributeValue = string | number | boolean | string[] | number[] | boolean[];
3
+ export interface TracingException {
4
+ name?: string;
5
+ message: string;
6
+ stack?: string;
7
+ code?: string | number;
8
+ }
9
+ export type TracingHeaders = Record<string, string | string[] | undefined>;
10
+ export type TracingExceptionLevel = "error" | "info";
11
+ export interface TracingSpan {
12
+ setAttribute(key: string, value: TracingAttributeValue): void;
13
+ /**
14
+ * Renames the span. Backends that cannot rename spans ignore it.
15
+ */
16
+ updateName(name: string): void;
17
+ /**
18
+ * Adds an event to the span. Backends without span events ignore it.
19
+ */
20
+ addEvent(name: string): void;
21
+ /**
22
+ * Records an exception on the span. The `error` level also marks the span as failed.
23
+ */
24
+ recordException(level: TracingExceptionLevel, exception: TracingException): void;
25
+ end(): void;
26
+ }
27
+ /**
28
+ * The tracing backend oRPC records spans with, see `@orpc/opentelemetry` and `@orpc/cloudflare`.
29
+ *
30
+ * A `parent` defaults to the active span of the backend when omitted.
31
+ */
32
+ export interface Tracer {
33
+ /**
34
+ * Starts a span without making it active. The caller must end it.
35
+ */
36
+ startSpan(name: string, parent?: TracingSpan): TracingSpan;
37
+ /**
38
+ * Starts a span, makes it active while `fn` runs, and passes it to `fn`. The caller must end it.
39
+ */
40
+ startActiveSpan<T>(name: string, parent: TracingSpan | undefined, fn: (span: TracingSpan) => Promise<T>): Promise<T>;
41
+ getActiveSpan(): TracingSpan | undefined;
42
+ /**
43
+ * Runs `fn` with `span` as the active span. Backends that cannot activate a span run `fn` directly.
44
+ */
45
+ withActiveSpan<T>(span: TracingSpan, fn: () => Promisable<T>): Promisable<T>;
46
+ /**
47
+ * Writes the trace context of `span` into `headers`. Absent when the backend does not propagate context.
48
+ */
49
+ inject?(span: TracingSpan, headers: TracingHeaders): void;
50
+ /**
51
+ * Reads the remote parent from `headers`. Absent when the backend does not propagate context.
52
+ */
53
+ extract?(headers: TracingHeaders): TracingSpan | undefined;
54
+ }
55
+ export declare function setTracer(tracer: Tracer | undefined): void;
56
+ export declare function getTracer(): Tracer | undefined;
57
+ export interface StartSpanOptions {
58
+ /**
59
+ * The name of the span to create.
60
+ */
61
+ name: string;
62
+ /**
63
+ * The span to use as parent. Defaults to the active span of the backend.
64
+ */
65
+ parent?: TracingSpan | undefined;
66
+ }
67
+ export declare function startSpan(options: StartSpanOptions | string): TracingSpan | undefined;
68
+ export declare function recordSpanError(span: TracingSpan | undefined, error: unknown): void;
69
+ export declare function setSpanAttributeIfDefined(span: TracingSpan | undefined, key: string, value: TracingAttributeValue | undefined): void;
70
+ export declare function toTracingException(error: unknown): TracingException;
71
+ export declare function toSpanAttributeValue(data: unknown): string;
72
+ export declare function runWithSpan<T>(options: string | StartSpanOptions, fn: (span?: TracingSpan) => Promisable<T>): Promise<T>;
73
+ export declare function runInSpanContext<T>(span: TracingSpan | undefined, fn: () => Promisable<T>): Promisable<T>;
@@ -0,0 +1,76 @@
1
+ import { isAbortError } from "./error.js";
2
+ // src/tracing.ts
3
+ const TRACER_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_TRACER");
4
+ function setTracer(tracer) {
5
+ globalThis[TRACER_SYMBOL] = tracer;
6
+ }
7
+ function getTracer() {
8
+ return globalThis[TRACER_SYMBOL];
9
+ }
10
+ function startSpan(options) {
11
+ const tracer = getTracer();
12
+ if (!tracer) return;
13
+ if (typeof options === "string") return tracer.startSpan(options);
14
+ return tracer.startSpan(options.name, options.parent);
15
+ }
16
+ function recordSpanError(span, error) {
17
+ if (!span) return;
18
+ span.recordException(isAbortError(error) ? "info" : "error", toTracingException(error));
19
+ }
20
+ function setSpanAttributeIfDefined(span, key, value) {
21
+ if (!span || value === void 0) return;
22
+ span.setAttribute(key, value);
23
+ }
24
+ function toTracingException(error) {
25
+ if (error instanceof Error) {
26
+ const exception = {
27
+ message: error.message,
28
+ name: error.name,
29
+ stack: error.stack
30
+ };
31
+ if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) exception.code = error.code;
32
+ return exception;
33
+ }
34
+ return { message: String(error) };
35
+ }
36
+ function toSpanAttributeValue(data) {
37
+ if (data === void 0) return "undefined";
38
+ try {
39
+ return JSON.stringify(data, (_, value) => {
40
+ if (typeof value === "bigint") return value.toString();
41
+ if (value instanceof Map || value instanceof Set) return Array.from(value);
42
+ return value;
43
+ });
44
+ } catch {
45
+ return String(data);
46
+ }
47
+ }
48
+ function runWithSpan(options, fn) {
49
+ const tracer = getTracer();
50
+ if (!tracer) try {
51
+ return Promise.resolve(fn());
52
+ } catch (e) {
53
+ return Promise.reject(e);
54
+ }
55
+ return runWithTracerSpan(tracer, options, fn);
56
+ }
57
+ async function runWithTracerSpan(tracer, options, fn) {
58
+ const name = typeof options === "string" ? options : options.name;
59
+ const parent = typeof options === "string" ? void 0 : options.parent;
60
+ return tracer.startActiveSpan(name, parent, async (span) => {
61
+ try {
62
+ return await fn(span);
63
+ } catch (e) {
64
+ recordSpanError(span, e);
65
+ throw e;
66
+ } finally {
67
+ span.end();
68
+ }
69
+ });
70
+ }
71
+ function runInSpanContext(span, fn) {
72
+ const tracer = getTracer();
73
+ if (!span || !tracer) return fn();
74
+ return tracer.withActiveSpan(span, fn);
75
+ }
76
+ export { getTracer, recordSpanError, runInSpanContext, runWithSpan, setSpanAttributeIfDefined, setTracer, startSpan, toSpanAttributeValue, toTracingException };