@orpc/shared 0.0.0-next.ee46dab → 0.0.0-next.ee5598c

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
@@ -26,28 +26,24 @@
26
26
 
27
27
  <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
28
28
 
29
- **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards, ensuring a smooth and enjoyable developer experience.
29
+ **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards
30
30
 
31
31
  ---
32
32
 
33
33
  ## Highlights
34
34
 
35
- - **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly.
36
- - **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation.
37
- - **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence.
38
- - **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation.
39
- - **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more.
40
- - **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue, Solid, Svelte), Pinia Colada, and more.
41
- - **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more.
42
- - **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box.
43
- - **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency.
44
- - **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup.
45
- - **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature.
46
- - **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses.
47
- - **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly.
48
- - **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors.
49
- - **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind.
50
- - **Simplicity 💡**: Enjoy straightforward, clean code with no hidden magic.
35
+ - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
36
+ - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
37
+ - **📝 Contract-First Development**: Optionally define your API contract before implementation.
38
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), Pinia Colada, and more.
39
+ - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
40
+ - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
41
+ - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
42
+ - **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature.
43
+ - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
44
+ - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
45
+ - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
46
+ - **🛡️ Reliability**: Well-tested, TypeScript-based, production-ready, and MIT licensed.
51
47
 
52
48
  ## Documentation
53
49
 
@@ -58,13 +54,12 @@ You can find the full documentation [here](https://orpc.unnoq.com).
58
54
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
59
55
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
60
56
  - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
57
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
58
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
61
59
  - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
62
- - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
63
- - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
64
- - [@orpc/solid-query](https://www.npmjs.com/package/@orpc/solid-query): Integration with [Solid Query](https://tanstack.com/query/latest/docs/framework/solid/overview).
65
- - [@orpc/svelte-query](https://www.npmjs.com/package/@orpc/svelte-query): Integration with [Svelte Query](https://tanstack.com/query/latest/docs/framework/svelte/overview).
60
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
66
61
  - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
67
- - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
62
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
68
63
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
69
64
  - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
70
65
  - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
package/dist/index.d.mts CHANGED
@@ -1,19 +1,96 @@
1
1
  import { Promisable } from 'type-fest';
2
- export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
3
3
  export { group, guard, mapEntries, mapValues, omit } from 'radash';
4
4
 
5
5
  type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
6
6
  declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
7
7
 
8
- declare function toArray<T>(value: T | T[] | null | undefined): T[];
8
+ declare function toArray<T>(value: T): T extends readonly any[] ? T : Exclude<T, undefined | null>[];
9
+ declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
10
+
11
+ /**
12
+ * Converts Request/Response/Blob/File/.. to a buffer (ArrayBuffer or Uint8Array).
13
+ *
14
+ * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
15
+ */
16
+ declare function readAsBuffer(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): Promise<ArrayBuffer | Uint8Array>;
9
17
 
10
18
  type AnyFunction = (...args: any[]) => any;
11
19
  declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
20
+ declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
21
+ /**
22
+ * Executes the callback function after the current call stack has been cleared.
23
+ */
24
+ declare function defer(callback: () => void): void;
12
25
 
13
26
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
14
27
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
15
28
  };
16
29
 
30
+ interface EventPublisherOptions {
31
+ /**
32
+ * Maximum number of events to buffer for async iterator subscribers.
33
+ *
34
+ * If the buffer exceeds this limit, the oldest event is dropped.
35
+ * This prevents unbounded memory growth if consumers process events slowly.
36
+ *
37
+ * Set to:
38
+ * - `0`: Disable buffering. Events must be consumed before the next one arrives.
39
+ * - `1`: Only keep the latest event. Useful for real-time updates where only the most recent value matters.
40
+ * - `Infinity`: Keep all events. Ensures no data loss, but may lead to high memory usage.
41
+ *
42
+ * @default 100
43
+ */
44
+ maxBufferedEvents?: number;
45
+ }
46
+ interface EventPublisherSubscribeIteratorOptions extends EventPublisherOptions {
47
+ /**
48
+ * Aborts the async iterator. Throws if aborted before or during pulling.
49
+ */
50
+ signal?: AbortSignal;
51
+ }
52
+ declare class EventPublisher<T extends Record<PropertyKey, any>> {
53
+ #private;
54
+ constructor(options?: EventPublisherOptions);
55
+ get size(): number;
56
+ /**
57
+ * Emits an event and delivers the payload to all subscribed listeners.
58
+ */
59
+ publish<K extends keyof T>(event: K, payload: T[K]): void;
60
+ /**
61
+ * Subscribes to a specific event using a callback function.
62
+ * Returns an unsubscribe function to remove the listener.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * const unsubscribe = publisher.subscribe('event', (payload) => {
67
+ * console.log(payload)
68
+ * })
69
+ *
70
+ * // Later
71
+ * unsubscribe()
72
+ * ```
73
+ */
74
+ subscribe<K extends keyof T>(event: K, listener: (payload: T[K]) => void): () => void;
75
+ /**
76
+ * Subscribes to a specific event using an async iterator.
77
+ * Useful for `for await...of` loops with optional buffering and abort support.
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * for await (const payload of publisher.subscribe('event', { signal })) {
82
+ * console.log(payload)
83
+ * }
84
+ * ```
85
+ */
86
+ subscribe<K extends keyof T>(event: K, options?: EventPublisherSubscribeIteratorOptions): AsyncGenerator<T[K]> & AsyncIteratorObject<T[K]>;
87
+ }
88
+
89
+ declare class SequentialIdGenerator {
90
+ private index;
91
+ generate(): string;
92
+ }
93
+
17
94
  type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
18
95
  type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
19
96
  type PromiseWithError<T, TError> = Promise<T> & {
@@ -33,41 +110,66 @@ type ThrowableError = Registry extends {
33
110
  } ? T : Error;
34
111
 
35
112
  type InterceptableOptions = Record<string, any>;
36
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult, TError> = Omit<TOptions, 'next'> & {
37
- next(options?: TOptions): PromiseWithError<TResult, TError>;
113
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
114
+ next(options?: TOptions): TResult;
38
115
  };
39
- type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult, TError>) => PromiseWithError<TResult, TError>;
116
+ type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
40
117
  /**
41
118
  * Can used for interceptors or middlewares
42
119
  */
43
- declare function onStart<TOptions extends {
120
+ declare function onStart<T, TOptions extends {
44
121
  next(): any;
45
- }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
122
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
46
123
  /**
47
124
  * Can used for interceptors or middlewares
48
125
  */
49
- declare function onSuccess<TOptions extends {
126
+ declare function onSuccess<T, TOptions extends {
50
127
  next(): any;
51
- }, TRest extends any[]>(callback: NoInfer<(result: Awaited<ReturnType<TOptions['next']>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
128
+ }, TRest extends any[]>(callback: NoInfer<(result: Awaited<ReturnType<TOptions['next']>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
52
129
  /**
53
130
  * Can used for interceptors or middlewares
54
131
  */
55
- declare function onError<TOptions extends {
132
+ declare function onError<T, TOptions extends {
56
133
  next(): any;
57
- }, TRest extends any[]>(callback: NoInfer<(error: ReturnType<TOptions['next']> extends PromiseWithError<any, infer E> ? E : ThrowableError, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
58
- type OnFinishState<TResult, TError> = [TResult, null, 'success'] | [undefined, TError, 'error'];
134
+ }, TRest extends any[]>(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']>>>;
135
+ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
59
136
  /**
60
137
  * Can used for interceptors or middlewares
61
138
  */
62
- declare function onFinish<TOptions extends {
139
+ declare function onFinish<T, TOptions extends {
63
140
  next(): any;
64
- }, 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) => Promise<Awaited<ReturnType<TOptions['next']>>>;
65
- declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
141
+ }, 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']>>>;
142
+ declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
66
143
 
67
144
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
145
+ interface AsyncIteratorClassNextFn<T, TReturn> {
146
+ (): Promise<IteratorResult<T, TReturn>>;
147
+ }
148
+ interface AsyncIteratorClassCleanupFn {
149
+ (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
150
+ }
151
+ declare const fallbackAsyncDisposeSymbol: unique symbol;
152
+ declare const asyncDisposeSymbol: typeof Symbol extends {
153
+ asyncDispose: infer T;
154
+ } ? T : typeof fallbackAsyncDisposeSymbol;
155
+ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implements AsyncIteratorObject<T, TReturn, TNext>, AsyncGenerator<T, TReturn, TNext> {
156
+ #private;
157
+ constructor(next: AsyncIteratorClassNextFn<T, TReturn>, cleanup: AsyncIteratorClassCleanupFn);
158
+ next(): Promise<IteratorResult<T, TReturn>>;
159
+ return(value?: any): Promise<IteratorResult<T, TReturn>>;
160
+ throw(err: any): Promise<IteratorResult<T, TReturn>>;
161
+ /**
162
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
163
+ */
164
+ [asyncDisposeSymbol](): Promise<void>;
165
+ [Symbol.asyncIterator](): this;
166
+ }
167
+ declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
68
168
 
69
169
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
70
- declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
170
+ declare function stringifyJSON<T>(value: T | {
171
+ toJSON(): T;
172
+ }): undefined extends T ? undefined | string : string;
71
173
 
72
174
  type Segment = string | number;
73
175
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
@@ -84,8 +186,30 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
84
186
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
85
187
  declare function clone<T>(value: T): T;
86
188
  declare function get(object: object, path: readonly string[]): unknown;
189
+ declare function isPropertyKey(value: unknown): value is PropertyKey;
190
+ declare const NullProtoObj: ({
191
+ new <T extends Record<PropertyKey, unknown>>(): T;
192
+ });
193
+
194
+ interface AsyncIdQueueCloseOptions {
195
+ id?: string;
196
+ reason?: unknown;
197
+ }
198
+ declare class AsyncIdQueue<T> {
199
+ private readonly openIds;
200
+ private readonly items;
201
+ private readonly pendingPulls;
202
+ get length(): number;
203
+ open(id: string): void;
204
+ isOpen(id: string): boolean;
205
+ push(id: string, item: T): void;
206
+ pull(id: string): Promise<T>;
207
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
208
+ assertOpen(id: string): void;
209
+ }
87
210
 
88
- type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
89
- declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
211
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
212
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
90
213
 
91
- export { type AnyFunction, type InterceptableOptions, type Interceptor, type InterceptorOptions, type IntersectPick, type MaybeOptionalOptions, type OmitChainMethodDeep, type OnFinishState, type PromiseWithError, type Registry, type Segment, type SetOptional, type ThrowableError, type Value, clone, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, stringifyJSON, toArray, value };
214
+ export { AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
215
+ export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
package/dist/index.d.ts CHANGED
@@ -1,19 +1,96 @@
1
1
  import { Promisable } from 'type-fest';
2
- export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
3
3
  export { group, guard, mapEntries, mapValues, omit } from 'radash';
4
4
 
5
5
  type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
6
6
  declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
7
7
 
8
- declare function toArray<T>(value: T | T[] | null | undefined): T[];
8
+ declare function toArray<T>(value: T): T extends readonly any[] ? T : Exclude<T, undefined | null>[];
9
+ declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
10
+
11
+ /**
12
+ * Converts Request/Response/Blob/File/.. to a buffer (ArrayBuffer or Uint8Array).
13
+ *
14
+ * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
15
+ */
16
+ declare function readAsBuffer(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): Promise<ArrayBuffer | Uint8Array>;
9
17
 
10
18
  type AnyFunction = (...args: any[]) => any;
11
19
  declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
20
+ declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
21
+ /**
22
+ * Executes the callback function after the current call stack has been cleared.
23
+ */
24
+ declare function defer(callback: () => void): void;
12
25
 
13
26
  type OmitChainMethodDeep<T extends object, K extends keyof any> = {
14
27
  [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
15
28
  };
16
29
 
30
+ interface EventPublisherOptions {
31
+ /**
32
+ * Maximum number of events to buffer for async iterator subscribers.
33
+ *
34
+ * If the buffer exceeds this limit, the oldest event is dropped.
35
+ * This prevents unbounded memory growth if consumers process events slowly.
36
+ *
37
+ * Set to:
38
+ * - `0`: Disable buffering. Events must be consumed before the next one arrives.
39
+ * - `1`: Only keep the latest event. Useful for real-time updates where only the most recent value matters.
40
+ * - `Infinity`: Keep all events. Ensures no data loss, but may lead to high memory usage.
41
+ *
42
+ * @default 100
43
+ */
44
+ maxBufferedEvents?: number;
45
+ }
46
+ interface EventPublisherSubscribeIteratorOptions extends EventPublisherOptions {
47
+ /**
48
+ * Aborts the async iterator. Throws if aborted before or during pulling.
49
+ */
50
+ signal?: AbortSignal;
51
+ }
52
+ declare class EventPublisher<T extends Record<PropertyKey, any>> {
53
+ #private;
54
+ constructor(options?: EventPublisherOptions);
55
+ get size(): number;
56
+ /**
57
+ * Emits an event and delivers the payload to all subscribed listeners.
58
+ */
59
+ publish<K extends keyof T>(event: K, payload: T[K]): void;
60
+ /**
61
+ * Subscribes to a specific event using a callback function.
62
+ * Returns an unsubscribe function to remove the listener.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * const unsubscribe = publisher.subscribe('event', (payload) => {
67
+ * console.log(payload)
68
+ * })
69
+ *
70
+ * // Later
71
+ * unsubscribe()
72
+ * ```
73
+ */
74
+ subscribe<K extends keyof T>(event: K, listener: (payload: T[K]) => void): () => void;
75
+ /**
76
+ * Subscribes to a specific event using an async iterator.
77
+ * Useful for `for await...of` loops with optional buffering and abort support.
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * for await (const payload of publisher.subscribe('event', { signal })) {
82
+ * console.log(payload)
83
+ * }
84
+ * ```
85
+ */
86
+ subscribe<K extends keyof T>(event: K, options?: EventPublisherSubscribeIteratorOptions): AsyncGenerator<T[K]> & AsyncIteratorObject<T[K]>;
87
+ }
88
+
89
+ declare class SequentialIdGenerator {
90
+ private index;
91
+ generate(): string;
92
+ }
93
+
17
94
  type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
18
95
  type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
19
96
  type PromiseWithError<T, TError> = Promise<T> & {
@@ -33,41 +110,66 @@ type ThrowableError = Registry extends {
33
110
  } ? T : Error;
34
111
 
35
112
  type InterceptableOptions = Record<string, any>;
36
- type InterceptorOptions<TOptions extends InterceptableOptions, TResult, TError> = Omit<TOptions, 'next'> & {
37
- next(options?: TOptions): PromiseWithError<TResult, TError>;
113
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
114
+ next(options?: TOptions): TResult;
38
115
  };
39
- type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult, TError>) => PromiseWithError<TResult, TError>;
116
+ type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
40
117
  /**
41
118
  * Can used for interceptors or middlewares
42
119
  */
43
- declare function onStart<TOptions extends {
120
+ declare function onStart<T, TOptions extends {
44
121
  next(): any;
45
- }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
122
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
46
123
  /**
47
124
  * Can used for interceptors or middlewares
48
125
  */
49
- declare function onSuccess<TOptions extends {
126
+ declare function onSuccess<T, TOptions extends {
50
127
  next(): any;
51
- }, TRest extends any[]>(callback: NoInfer<(result: Awaited<ReturnType<TOptions['next']>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
128
+ }, TRest extends any[]>(callback: NoInfer<(result: Awaited<ReturnType<TOptions['next']>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
52
129
  /**
53
130
  * Can used for interceptors or middlewares
54
131
  */
55
- declare function onError<TOptions extends {
132
+ declare function onError<T, TOptions extends {
56
133
  next(): any;
57
- }, TRest extends any[]>(callback: NoInfer<(error: ReturnType<TOptions['next']> extends PromiseWithError<any, infer E> ? E : ThrowableError, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
58
- type OnFinishState<TResult, TError> = [TResult, null, 'success'] | [undefined, TError, 'error'];
134
+ }, TRest extends any[]>(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']>>>;
135
+ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
59
136
  /**
60
137
  * Can used for interceptors or middlewares
61
138
  */
62
- declare function onFinish<TOptions extends {
139
+ declare function onFinish<T, TOptions extends {
63
140
  next(): any;
64
- }, 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) => Promise<Awaited<ReturnType<TOptions['next']>>>;
65
- declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
141
+ }, 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']>>>;
142
+ declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
66
143
 
67
144
  declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
145
+ interface AsyncIteratorClassNextFn<T, TReturn> {
146
+ (): Promise<IteratorResult<T, TReturn>>;
147
+ }
148
+ interface AsyncIteratorClassCleanupFn {
149
+ (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
150
+ }
151
+ declare const fallbackAsyncDisposeSymbol: unique symbol;
152
+ declare const asyncDisposeSymbol: typeof Symbol extends {
153
+ asyncDispose: infer T;
154
+ } ? T : typeof fallbackAsyncDisposeSymbol;
155
+ declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implements AsyncIteratorObject<T, TReturn, TNext>, AsyncGenerator<T, TReturn, TNext> {
156
+ #private;
157
+ constructor(next: AsyncIteratorClassNextFn<T, TReturn>, cleanup: AsyncIteratorClassCleanupFn);
158
+ next(): Promise<IteratorResult<T, TReturn>>;
159
+ return(value?: any): Promise<IteratorResult<T, TReturn>>;
160
+ throw(err: any): Promise<IteratorResult<T, TReturn>>;
161
+ /**
162
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
163
+ */
164
+ [asyncDisposeSymbol](): Promise<void>;
165
+ [Symbol.asyncIterator](): this;
166
+ }
167
+ declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[];
68
168
 
69
169
  declare function parseEmptyableJSON(text: string | null | undefined): unknown;
70
- declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
170
+ declare function stringifyJSON<T>(value: T | {
171
+ toJSON(): T;
172
+ }): undefined extends T ? undefined | string : string;
71
173
 
72
174
  type Segment = string | number;
73
175
  declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
@@ -84,8 +186,30 @@ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>
84
186
  declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
85
187
  declare function clone<T>(value: T): T;
86
188
  declare function get(object: object, path: readonly string[]): unknown;
189
+ declare function isPropertyKey(value: unknown): value is PropertyKey;
190
+ declare const NullProtoObj: ({
191
+ new <T extends Record<PropertyKey, unknown>>(): T;
192
+ });
193
+
194
+ interface AsyncIdQueueCloseOptions {
195
+ id?: string;
196
+ reason?: unknown;
197
+ }
198
+ declare class AsyncIdQueue<T> {
199
+ private readonly openIds;
200
+ private readonly items;
201
+ private readonly pendingPulls;
202
+ get length(): number;
203
+ open(id: string): void;
204
+ isOpen(id: string): boolean;
205
+ push(id: string, item: T): void;
206
+ pull(id: string): Promise<T>;
207
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
208
+ assertOpen(id: string): void;
209
+ }
87
210
 
88
- type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
89
- declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
211
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T);
212
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never;
90
213
 
91
- export { type AnyFunction, type InterceptableOptions, type Interceptor, type InterceptorOptions, type IntersectPick, type MaybeOptionalOptions, type OmitChainMethodDeep, type OnFinishState, type PromiseWithError, type Registry, type Segment, type SetOptional, type ThrowableError, type Value, clone, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, stringifyJSON, toArray, value };
214
+ export { AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
215
+ export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
package/dist/index.mjs CHANGED
@@ -7,6 +7,17 @@ function resolveMaybeOptionalOptions(rest) {
7
7
  function toArray(value) {
8
8
  return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
9
9
  }
10
+ function splitInHalf(arr) {
11
+ const half = Math.ceil(arr.length / 2);
12
+ return [arr.slice(0, half), arr.slice(half)];
13
+ }
14
+
15
+ function readAsBuffer(source) {
16
+ if (typeof source.bytes === "function") {
17
+ return source.bytes();
18
+ }
19
+ return source.arrayBuffer();
20
+ }
10
21
 
11
22
  function once(fn) {
12
23
  let cached;
@@ -19,6 +30,302 @@ function once(fn) {
19
30
  return result;
20
31
  };
21
32
  }
33
+ function sequential(fn) {
34
+ let lastOperationPromise = Promise.resolve();
35
+ return (...args) => {
36
+ return lastOperationPromise = lastOperationPromise.catch(() => {
37
+ }).then(() => {
38
+ return fn(...args);
39
+ });
40
+ };
41
+ }
42
+ function defer(callback) {
43
+ if (typeof setTimeout === "function") {
44
+ setTimeout(callback, 0);
45
+ } else {
46
+ Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(callback)));
47
+ }
48
+ }
49
+
50
+ class AsyncIdQueue {
51
+ openIds = /* @__PURE__ */ new Set();
52
+ items = /* @__PURE__ */ new Map();
53
+ pendingPulls = /* @__PURE__ */ new Map();
54
+ get length() {
55
+ return this.openIds.size;
56
+ }
57
+ open(id) {
58
+ this.openIds.add(id);
59
+ }
60
+ isOpen(id) {
61
+ return this.openIds.has(id);
62
+ }
63
+ push(id, item) {
64
+ this.assertOpen(id);
65
+ const pending = this.pendingPulls.get(id);
66
+ if (pending?.length) {
67
+ pending.shift()[0](item);
68
+ if (pending.length === 0) {
69
+ this.pendingPulls.delete(id);
70
+ }
71
+ } else {
72
+ const items = this.items.get(id);
73
+ if (items) {
74
+ items.push(item);
75
+ } else {
76
+ this.items.set(id, [item]);
77
+ }
78
+ }
79
+ }
80
+ async pull(id) {
81
+ this.assertOpen(id);
82
+ const items = this.items.get(id);
83
+ if (items?.length) {
84
+ const item = items.shift();
85
+ if (items.length === 0) {
86
+ this.items.delete(id);
87
+ }
88
+ return item;
89
+ }
90
+ return new Promise((resolve, reject) => {
91
+ const waitingPulls = this.pendingPulls.get(id);
92
+ const pending = [resolve, reject];
93
+ if (waitingPulls) {
94
+ waitingPulls.push(pending);
95
+ } else {
96
+ this.pendingPulls.set(id, [pending]);
97
+ }
98
+ });
99
+ }
100
+ close({ id, reason } = {}) {
101
+ if (id === void 0) {
102
+ this.pendingPulls.forEach((pendingPulls, id2) => {
103
+ pendingPulls.forEach(([, reject]) => {
104
+ reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id2}] was closed or aborted while waiting for pulling.`));
105
+ });
106
+ });
107
+ this.pendingPulls.clear();
108
+ this.openIds.clear();
109
+ this.items.clear();
110
+ return;
111
+ }
112
+ this.pendingPulls.get(id)?.forEach(([, reject]) => {
113
+ reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`));
114
+ });
115
+ this.pendingPulls.delete(id);
116
+ this.openIds.delete(id);
117
+ this.items.delete(id);
118
+ }
119
+ assertOpen(id) {
120
+ if (!this.isOpen(id)) {
121
+ throw new Error(`[AsyncIdQueue] Cannot access queue[${id}] because it is not open or aborted.`);
122
+ }
123
+ }
124
+ }
125
+
126
+ function isAsyncIteratorObject(maybe) {
127
+ if (!maybe || typeof maybe !== "object") {
128
+ return false;
129
+ }
130
+ return "next" in maybe && typeof maybe.next === "function" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
131
+ }
132
+ const fallbackAsyncDisposeSymbol = Symbol.for("asyncDispose");
133
+ const asyncDisposeSymbol = Symbol.asyncDispose ?? fallbackAsyncDisposeSymbol;
134
+ class AsyncIteratorClass {
135
+ #isDone = false;
136
+ #isExecuteComplete = false;
137
+ #cleanup;
138
+ #next;
139
+ constructor(next, cleanup) {
140
+ this.#cleanup = cleanup;
141
+ this.#next = sequential(async () => {
142
+ if (this.#isDone) {
143
+ return { done: true, value: void 0 };
144
+ }
145
+ try {
146
+ const result = await next();
147
+ if (result.done) {
148
+ this.#isDone = true;
149
+ }
150
+ return result;
151
+ } catch (err) {
152
+ this.#isDone = true;
153
+ throw err;
154
+ } finally {
155
+ if (this.#isDone && !this.#isExecuteComplete) {
156
+ this.#isExecuteComplete = true;
157
+ await this.#cleanup("next");
158
+ }
159
+ }
160
+ });
161
+ }
162
+ next() {
163
+ return this.#next();
164
+ }
165
+ async return(value) {
166
+ this.#isDone = true;
167
+ if (!this.#isExecuteComplete) {
168
+ this.#isExecuteComplete = true;
169
+ await this.#cleanup("return");
170
+ }
171
+ return { done: true, value };
172
+ }
173
+ async throw(err) {
174
+ this.#isDone = true;
175
+ if (!this.#isExecuteComplete) {
176
+ this.#isExecuteComplete = true;
177
+ await this.#cleanup("throw");
178
+ }
179
+ throw err;
180
+ }
181
+ /**
182
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
183
+ */
184
+ async [asyncDisposeSymbol]() {
185
+ this.#isDone = true;
186
+ if (!this.#isExecuteComplete) {
187
+ this.#isExecuteComplete = true;
188
+ await this.#cleanup("dispose");
189
+ }
190
+ }
191
+ [Symbol.asyncIterator]() {
192
+ return this;
193
+ }
194
+ }
195
+ function replicateAsyncIterator(source, count) {
196
+ const queue = new AsyncIdQueue();
197
+ const replicated = [];
198
+ let error;
199
+ const start = once(async () => {
200
+ try {
201
+ while (true) {
202
+ const item = await source.next();
203
+ for (let id = 0; id < count; id++) {
204
+ if (queue.isOpen(id.toString())) {
205
+ queue.push(id.toString(), item);
206
+ }
207
+ }
208
+ if (item.done) {
209
+ break;
210
+ }
211
+ }
212
+ } catch (e) {
213
+ error = { value: e };
214
+ }
215
+ });
216
+ for (let id = 0; id < count; id++) {
217
+ queue.open(id.toString());
218
+ replicated.push(new AsyncIteratorClass(
219
+ () => {
220
+ start();
221
+ return new Promise((resolve, reject) => {
222
+ queue.pull(id.toString()).then(resolve).catch(reject);
223
+ defer(() => {
224
+ if (error) {
225
+ reject(error.value);
226
+ }
227
+ });
228
+ });
229
+ },
230
+ async (reason) => {
231
+ queue.close({ id: id.toString() });
232
+ if (reason !== "next") {
233
+ if (replicated.every((_, id2) => !queue.isOpen(id2.toString()))) {
234
+ await source?.return?.();
235
+ }
236
+ }
237
+ }
238
+ ));
239
+ }
240
+ return replicated;
241
+ }
242
+
243
+ class EventPublisher {
244
+ #listenersMap = /* @__PURE__ */ new Map();
245
+ #maxBufferedEvents;
246
+ constructor(options = {}) {
247
+ this.#maxBufferedEvents = options.maxBufferedEvents ?? 100;
248
+ }
249
+ get size() {
250
+ return this.#listenersMap.size;
251
+ }
252
+ /**
253
+ * Emits an event and delivers the payload to all subscribed listeners.
254
+ */
255
+ publish(event, payload) {
256
+ const listeners = this.#listenersMap.get(event);
257
+ if (!listeners) {
258
+ return;
259
+ }
260
+ for (const listener of listeners) {
261
+ listener(payload);
262
+ }
263
+ }
264
+ subscribe(event, listenerOrOptions) {
265
+ if (typeof listenerOrOptions === "function") {
266
+ let listeners = this.#listenersMap.get(event);
267
+ if (!listeners) {
268
+ this.#listenersMap.set(event, listeners = /* @__PURE__ */ new Set());
269
+ }
270
+ listeners.add(listenerOrOptions);
271
+ return () => {
272
+ listeners.delete(listenerOrOptions);
273
+ if (listeners.size === 0) {
274
+ this.#listenersMap.delete(event);
275
+ }
276
+ };
277
+ }
278
+ const signal = listenerOrOptions?.signal;
279
+ const maxBufferedEvents = listenerOrOptions?.maxBufferedEvents ?? this.#maxBufferedEvents;
280
+ signal?.throwIfAborted();
281
+ const bufferedEvents = [];
282
+ const pullResolvers = [];
283
+ const unsubscribe = this.subscribe(event, (payload) => {
284
+ const resolver = pullResolvers.shift();
285
+ if (resolver) {
286
+ resolver[0]({ done: false, value: payload });
287
+ } else {
288
+ bufferedEvents.push(payload);
289
+ if (bufferedEvents.length > maxBufferedEvents) {
290
+ bufferedEvents.shift();
291
+ }
292
+ }
293
+ });
294
+ const abortListener = (event2) => {
295
+ unsubscribe();
296
+ pullResolvers.forEach((resolver) => resolver[1](event2.target.reason));
297
+ pullResolvers.length = 0;
298
+ bufferedEvents.length = 0;
299
+ };
300
+ signal?.addEventListener("abort", abortListener, { once: true });
301
+ return new AsyncIteratorClass(async () => {
302
+ if (signal?.aborted) {
303
+ throw signal.reason;
304
+ }
305
+ if (bufferedEvents.length > 0) {
306
+ return { done: false, value: bufferedEvents.shift() };
307
+ }
308
+ return new Promise((resolve, reject) => {
309
+ pullResolvers.push([resolve, reject]);
310
+ });
311
+ }, async () => {
312
+ unsubscribe();
313
+ signal?.removeEventListener("abort", abortListener);
314
+ pullResolvers.forEach((resolver) => resolver[0]({ done: true, value: void 0 }));
315
+ pullResolvers.length = 0;
316
+ bufferedEvents.length = 0;
317
+ });
318
+ }
319
+ }
320
+
321
+ class SequentialIdGenerator {
322
+ index = BigInt(0);
323
+ generate() {
324
+ const id = this.index.toString(32);
325
+ this.index++;
326
+ return id;
327
+ }
328
+ }
22
329
 
23
330
  function onStart(callback) {
24
331
  return async (options, ...rest) => {
@@ -48,36 +355,28 @@ function onFinish(callback) {
48
355
  return async (options, ...rest) => {
49
356
  try {
50
357
  const result = await options.next();
51
- state = [result, null, "success"];
358
+ state = [null, result, true];
52
359
  return result;
53
360
  } catch (error) {
54
- state = [void 0, error, "error"];
361
+ state = [error, void 0, false];
55
362
  throw error;
56
363
  } finally {
57
364
  await callback(state, options, ...rest);
58
365
  }
59
366
  };
60
367
  }
61
- async function intercept(interceptors, options, main) {
62
- let index = 0;
63
- const next = async (options2) => {
64
- const interceptor = interceptors[index++];
368
+ function intercept(interceptors, options, main) {
369
+ const next = (options2, index) => {
370
+ const interceptor = interceptors[index];
65
371
  if (!interceptor) {
66
- return await main(options2);
372
+ return main(options2);
67
373
  }
68
- return await interceptor({
374
+ return interceptor({
69
375
  ...options2,
70
- next: (newOptions = options2) => next(newOptions)
376
+ next: (newOptions = options2) => next(newOptions, index + 1)
71
377
  });
72
378
  };
73
- return await next(options);
74
- }
75
-
76
- function isAsyncIteratorObject(maybe) {
77
- if (!maybe || typeof maybe !== "object") {
78
- return false;
79
- }
80
- return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
379
+ return next(options, 0);
81
380
  }
82
381
 
83
382
  function parseEmptyableJSON(text) {
@@ -138,6 +437,17 @@ function get(object, path) {
138
437
  }
139
438
  return current;
140
439
  }
440
+ function isPropertyKey(value) {
441
+ const type = typeof value;
442
+ return type === "string" || type === "number" || type === "symbol";
443
+ }
444
+ const NullProtoObj = /* @__PURE__ */ (() => {
445
+ const e = function() {
446
+ };
447
+ e.prototype = /* @__PURE__ */ Object.create(null);
448
+ Object.freeze(e.prototype);
449
+ return e;
450
+ })();
141
451
 
142
452
  function value(value2, ...args) {
143
453
  if (typeof value2 === "function") {
@@ -146,4 +456,4 @@ function value(value2, ...args) {
146
456
  return value2;
147
457
  }
148
458
 
149
- export { clone, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, stringifyJSON, toArray, value };
459
+ export { AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, SequentialIdGenerator, clone, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/shared",
3
3
  "type": "module",
4
- "version": "0.0.0-next.ee46dab",
4
+ "version": "0.0.0-next.ee5598c",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -24,8 +24,13 @@
24
24
  "dist"
25
25
  ],
26
26
  "dependencies": {
27
- "radash": "^12.1.0",
28
- "type-fest": "^4.26.1"
27
+ "radash": "^12.1.1",
28
+ "type-fest": "^4.39.1"
29
+ },
30
+ "devDependencies": {
31
+ "arktype": "2.1.20",
32
+ "valibot": "^1.1.0",
33
+ "zod": "^3.25.76"
29
34
  },
30
35
  "scripts": {
31
36
  "build": "unbuild",