@orpc/shared
Advanced tools
Comparing version
import { Promisable } from 'type-fest'; | ||
export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest'; | ||
export { group, guard, mapEntries, mapValues, omit, retry, trim } from 'radash'; | ||
export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest'; | ||
export { group, guard, mapEntries, mapValues, omit } from 'radash'; | ||
type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions]; | ||
declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T; | ||
declare function toArray<T>(value: T): T extends readonly any[] ? T : Exclude<T, undefined | null>[]; | ||
declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]]; | ||
/** | ||
* Converts Request/Response/Blob/File/.. to a buffer (ArrayBuffer or Uint8Array). | ||
* | ||
* Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet. | ||
*/ | ||
declare function readAsBuffer(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): Promise<ArrayBuffer | Uint8Array>; | ||
type AnyFunction = (...args: any[]) => any; | ||
declare function once<T extends () => any>(fn: T): () => ReturnType<T>; | ||
declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>; | ||
/** | ||
* Executes the callback function after the current call stack has been cleared. | ||
*/ | ||
declare function defer(callback: () => void): void; | ||
@@ -12,9 +30,69 @@ type OmitChainMethodDeep<T extends object, K extends keyof any> = { | ||
declare function toError(error: unknown): Error; | ||
interface EventPublisherOptions { | ||
/** | ||
* Maximum number of events to buffer for async iterator subscribers. | ||
* | ||
* If the buffer exceeds this limit, the oldest event is dropped. | ||
* This prevents unbounded memory growth if consumers process events slowly. | ||
* | ||
* Set to: | ||
* - `0`: Disable buffering. Events must be consumed before the next one arrives. | ||
* - `1`: Only keep the latest event. Useful for real-time updates where only the most recent value matters. | ||
* - `Infinity`: Keep all events. Ensures no data loss, but may lead to high memory usage. | ||
* | ||
* @default 100 | ||
*/ | ||
maxBufferedEvents?: number; | ||
} | ||
interface EventPublisherSubscribeIteratorOptions extends EventPublisherOptions { | ||
/** | ||
* Aborts the async iterator. Throws if aborted before or during pulling. | ||
*/ | ||
signal?: AbortSignal; | ||
} | ||
declare class EventPublisher<T extends Record<PropertyKey, any>> { | ||
#private; | ||
constructor(options?: EventPublisherOptions); | ||
get size(): number; | ||
/** | ||
* Emits an event and delivers the payload to all subscribed listeners. | ||
*/ | ||
publish<K extends keyof T>(event: K, payload: T[K]): void; | ||
/** | ||
* Subscribes to a specific event using a callback function. | ||
* Returns an unsubscribe function to remove the listener. | ||
* | ||
* @example | ||
* ```ts | ||
* const unsubscribe = publisher.subscribe('event', (payload) => { | ||
* console.log(payload) | ||
* }) | ||
* | ||
* // Later | ||
* unsubscribe() | ||
* ``` | ||
*/ | ||
subscribe<K extends keyof T>(event: K, listener: (payload: T[K]) => void): () => void; | ||
/** | ||
* Subscribes to a specific event using an async iterator. | ||
* Useful for `for await...of` loops with optional buffering and abort support. | ||
* | ||
* @example | ||
* ```ts | ||
* for await (const payload of publisher.subscribe('event', { signal })) { | ||
* console.log(payload) | ||
* } | ||
* ``` | ||
*/ | ||
subscribe<K extends keyof T>(event: K, options?: EventPublisherSubscribeIteratorOptions): AsyncGenerator<T[K]> & AsyncIteratorObject<T[K]>; | ||
} | ||
type InterceptableOptions = Record<string, any>; | ||
type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & { | ||
next(options?: TOptions): Promise<TResult>; | ||
}; | ||
type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult>) => Promise<TResult> & { | ||
declare class SequentialIdGenerator { | ||
private index; | ||
generate(): string; | ||
} | ||
type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>; | ||
type IntersectPick<T, U> = Pick<T, keyof T & keyof U>; | ||
type PromiseWithError<T, TError> = Promise<T> & { | ||
__error?: { | ||
@@ -25,44 +103,75 @@ type: TError; | ||
/** | ||
* The place where you can config the orpc types. | ||
* | ||
* - `throwableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict. | ||
*/ | ||
interface Registry { | ||
} | ||
type ThrowableError = Registry extends { | ||
throwableError: infer T; | ||
} ? T : Error; | ||
type InterceptableOptions = Record<string, any>; | ||
type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & { | ||
next(options?: TOptions): TResult; | ||
}; | ||
type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult; | ||
/** | ||
* Can used for interceptors or middlewares | ||
*/ | ||
declare function onStart<TOptions extends { | ||
declare function onStart<T, TOptions extends { | ||
next(): any; | ||
}, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>; | ||
}, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>; | ||
/** | ||
* Can used for interceptors or middlewares | ||
*/ | ||
declare function onSuccess<TOptions extends { | ||
declare function onSuccess<T, TOptions extends { | ||
next(): any; | ||
}, 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']>>>; | ||
}, 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']>>>; | ||
/** | ||
* Can used for interceptors or middlewares | ||
*/ | ||
declare function onError<TError, TOptions extends { | ||
declare function onError<T, TOptions extends { | ||
next(): any; | ||
}, TRest extends any[]>(callback: NoInfer<(error: TError, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>> & { | ||
__error?: { | ||
type: TError; | ||
}; | ||
}; | ||
type OnFinishState<TResult, TError> = [TResult, undefined, 'success'] | [undefined, TError, 'error']; | ||
}, 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']>>>; | ||
type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true]; | ||
/** | ||
* Can used for interceptors or middlewares | ||
*/ | ||
declare function onFinish<TError, TOptions extends { | ||
declare function onFinish<T, TOptions extends { | ||
next(): any; | ||
}, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>, TError>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>> & { | ||
__error?: { | ||
type: TError; | ||
}; | ||
}; | ||
declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>; | ||
}, 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']>>>; | ||
declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult; | ||
declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>; | ||
interface AsyncIteratorClassNextFn<T, TReturn> { | ||
(): Promise<IteratorResult<T, TReturn>>; | ||
} | ||
interface AsyncIteratorClassCleanupFn { | ||
(reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>; | ||
} | ||
declare const fallbackAsyncDisposeSymbol: unique symbol; | ||
declare const asyncDisposeSymbol: typeof Symbol extends { | ||
asyncDispose: infer T; | ||
} ? T : typeof fallbackAsyncDisposeSymbol; | ||
declare class AsyncIteratorClass<T, TReturn = unknown, TNext = unknown> implements AsyncIteratorObject<T, TReturn, TNext>, AsyncGenerator<T, TReturn, TNext> { | ||
#private; | ||
constructor(next: AsyncIteratorClassNextFn<T, TReturn>, cleanup: AsyncIteratorClassCleanupFn); | ||
next(): Promise<IteratorResult<T, TReturn>>; | ||
return(value?: any): Promise<IteratorResult<T, TReturn>>; | ||
throw(err: any): Promise<IteratorResult<T, TReturn>>; | ||
/** | ||
* asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose') | ||
*/ | ||
[asyncDisposeSymbol](): Promise<void>; | ||
[Symbol.asyncIterator](): this; | ||
} | ||
declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): (AsyncIteratorClass<T, TReturn, TNext>)[]; | ||
declare function parseEmptyableJSON(text: string | null | undefined): unknown; | ||
declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string; | ||
declare function stringifyJSON<T>(value: T | { | ||
toJSON(): T; | ||
}): undefined extends T ? undefined | string : string; | ||
type Segment = string | number; | ||
declare function set(root: unknown, segments: Readonly<Segment[]>, value: unknown): unknown; | ||
declare function get(root: Readonly<Record<string, unknown> | unknown[]>, segments: Readonly<Segment[]>): unknown; | ||
declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): { | ||
@@ -80,9 +189,33 @@ maps: Segment[][]; | ||
declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>; | ||
declare function clone<T>(value: T): T; | ||
declare function get(object: unknown, path: readonly string[]): unknown; | ||
declare function isPropertyKey(value: unknown): value is PropertyKey; | ||
declare const NullProtoObj: ({ | ||
new <T extends Record<PropertyKey, unknown>>(): T; | ||
}); | ||
type MaybeOptionalOptions<TOptions> = [options: TOptions] | (Record<never, never> extends TOptions ? [] : never); | ||
type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>; | ||
interface AsyncIdQueueCloseOptions { | ||
id?: string; | ||
reason?: unknown; | ||
} | ||
declare class AsyncIdQueue<T> { | ||
private readonly openIds; | ||
private readonly items; | ||
private readonly pendingPulls; | ||
get length(): number; | ||
open(id: string): void; | ||
isOpen(id: string): boolean; | ||
push(id: string, item: T): void; | ||
pull(id: string): Promise<T>; | ||
close({ id, reason }?: AsyncIdQueueCloseOptions): void; | ||
assertOpen(id: string): void; | ||
} | ||
type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>); | ||
declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>; | ||
declare function streamToAsyncIteratorClass<T>(stream: ReadableStream<T>): AsyncIteratorClass<T>; | ||
declare function asyncIteratorToStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>; | ||
export { type AnyFunction, type InterceptableOptions, type Interceptor, type InterceptorOptions, type MaybeOptionalOptions, type OmitChainMethodDeep, type OnFinishState, type Segment, type SetOptional, type Value, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, set, stringifyJSON, toError, value }; | ||
type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => T); | ||
declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): T extends Value<infer U, any> ? U : never; | ||
export { AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, SequentialIdGenerator, asyncIteratorToStream, clone, defer, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, sequential, splitInHalf, streamToAsyncIteratorClass, stringifyJSON, toArray, value }; | ||
export type { AnyFunction, AsyncIdQueueCloseOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClassNextFn, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value }; |
{ | ||
"name": "@orpc/shared", | ||
"type": "module", | ||
"version": "0.0.0-next.84e58e0", | ||
"version": "0.0.0-next.84ea648", | ||
"license": "MIT", | ||
@@ -27,5 +27,10 @@ "homepage": "https://orpc.unnoq.com", | ||
"dependencies": { | ||
"radash": "^12.1.0", | ||
"type-fest": "^4.26.1" | ||
"radash": "^12.1.1", | ||
"type-fest": "^4.39.1" | ||
}, | ||
"devDependencies": { | ||
"arktype": "2.1.20", | ||
"valibot": "^1.1.0", | ||
"zod": "^4.0.5" | ||
}, | ||
"scripts": { | ||
@@ -32,0 +37,0 @@ "build": "unbuild", |
@@ -0,3 +1,8 @@ | ||
> [!WARNING] | ||
> | ||
> `@orpc/shared` is an internal dependency of oRPC packages. It does not follow semver and may change at any time without notice. | ||
> Please do not use it in your project. | ||
<div align="center"> | ||
<image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 /> | ||
<image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" /> | ||
</div> | ||
@@ -24,3 +29,3 @@ | ||
**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. | ||
**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 | ||
@@ -31,18 +36,14 @@ --- | ||
- **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly. | ||
- **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation. | ||
- **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence. | ||
- **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation. | ||
- **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more. | ||
- **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue), Pinia Colada, and more. | ||
- **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more. | ||
- **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box. | ||
- **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency. | ||
- **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup. | ||
- **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature. | ||
- **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses. | ||
- **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly. | ||
- **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors. | ||
- **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind. | ||
- **Simplicity 💡**: Enjoy straightforward, clean code with no hidden magic. | ||
- **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server. | ||
- **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard. | ||
- **📝 Contract-First Development**: Optionally define your API contract before implementation. | ||
- **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), Pinia Colada, and more. | ||
- **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms. | ||
- **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators. | ||
- **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more. | ||
- **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature. | ||
- **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming. | ||
- **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond. | ||
- **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors. | ||
- **🛡️ Reliability**: Well-tested, TypeScript-based, production-ready, and MIT licensed. | ||
@@ -58,7 +59,11 @@ ## Documentation | ||
- [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety. | ||
- [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview). | ||
- [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview). | ||
- [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests. | ||
- [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/). | ||
- [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions. | ||
- [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration. | ||
- [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/). | ||
- [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests. | ||
- [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration. | ||
- [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet. | ||
- [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/). | ||
- [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/). | ||
@@ -69,4 +74,12 @@ ## `@orpc/shared` | ||
## Sponsors | ||
<p align="center"> | ||
<a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg"> | ||
<img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/> | ||
</a> | ||
</p> | ||
## License | ||
Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information. |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
39928
103.9%679
193.94%82
18.84%3
Infinity%Updated
Updated