@orpc/shared 0.0.0-next.f17a1a0 → 0.0.0-next.f356b86

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
@@ -1,5 +1,10 @@
1
+ > [!WARNING]
2
+ >
3
+ > `@orpc/shared` is an internal dependency of oRPC packages. It does not follow semver and may change at any time without notice.
4
+ > Please do not use it in your project.
5
+
1
6
  <div align="center">
2
- <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 />
7
+ <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
3
8
  </div>
4
9
 
5
10
  <h1></h1>
@@ -21,28 +26,24 @@
21
26
 
22
27
  <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
28
 
24
- **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
25
30
 
26
31
  ---
27
32
 
28
33
  ## Highlights
29
34
 
30
- - **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly.
31
- - **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation.
32
- - **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence.
33
- - **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation.
34
- - **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more.
35
- - **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue), Pinia Colada, and more.
36
- - **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more.
37
- - **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box.
38
- - **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency.
39
- - **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup.
40
- - **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature.
41
- - **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses.
42
- - **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly.
43
- - **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors.
44
- - **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind.
45
- - **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.
46
47
 
47
48
  ## Documentation
48
49
 
@@ -53,16 +54,28 @@ You can find the full documentation [here](https://orpc.unnoq.com).
53
54
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
55
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
56
  - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
56
- - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
57
- - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
58
- - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
59
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/).
59
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
60
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
61
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
62
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
60
63
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
64
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
65
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
61
66
 
62
67
  ## `@orpc/shared`
63
68
 
64
69
  Provides shared utilities for oRPC packages.
65
70
 
71
+ ## Sponsors
72
+
73
+ <p align="center">
74
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
75
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
76
+ </a>
77
+ </p>
78
+
66
79
  ## License
67
80
 
68
81
  Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,215 @@
1
+ import { Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
3
+ export { group, guard, mapEntries, mapValues, omit } from 'radash';
4
+
5
+ type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
6
+ declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
7
+
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>;
17
+
18
+ type AnyFunction = (...args: any[]) => any;
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;
25
+
26
+ type OmitChainMethodDeep<T extends object, K extends keyof any> = {
27
+ [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
28
+ };
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
+
94
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
95
+ type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
96
+ type PromiseWithError<T, TError> = Promise<T> & {
97
+ __error?: {
98
+ type: TError;
99
+ };
100
+ };
101
+ /**
102
+ * The place where you can config the orpc types.
103
+ *
104
+ * - `throwableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict.
105
+ */
106
+ interface Registry {
107
+ }
108
+ type ThrowableError = Registry extends {
109
+ throwableError: infer T;
110
+ } ? T : Error;
111
+
112
+ type InterceptableOptions = Record<string, any>;
113
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
114
+ next(options?: TOptions): TResult;
115
+ };
116
+ type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
117
+ /**
118
+ * Can used for interceptors or middlewares
119
+ */
120
+ declare function onStart<T, TOptions extends {
121
+ next(): any;
122
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
123
+ /**
124
+ * Can used for interceptors or middlewares
125
+ */
126
+ declare function onSuccess<T, TOptions extends {
127
+ next(): any;
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']>>>;
129
+ /**
130
+ * Can used for interceptors or middlewares
131
+ */
132
+ declare function onError<T, TOptions extends {
133
+ next(): any;
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];
136
+ /**
137
+ * Can used for interceptors or middlewares
138
+ */
139
+ declare function onFinish<T, TOptions extends {
140
+ next(): any;
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;
143
+
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>)[];
168
+
169
+ declare function parseEmptyableJSON(text: string | null | undefined): unknown;
170
+ declare function stringifyJSON<T>(value: T | {
171
+ toJSON(): T;
172
+ }): undefined extends T ? undefined | string : string;
173
+
174
+ type Segment = string | number;
175
+ declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
176
+ maps: Segment[][];
177
+ values: unknown[];
178
+ };
179
+ /**
180
+ * Check if the value is an object even it created by `Object.create(null)` or more tricky way.
181
+ */
182
+ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>;
183
+ /**
184
+ * Check if the value satisfy a `object` type in typescript
185
+ */
186
+ declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
187
+ declare function clone<T>(value: T): T;
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
+ }
210
+
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;
213
+
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 };
@@ -0,0 +1,215 @@
1
+ import { Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, JsonValue, PartialDeep, Promisable } from 'type-fest';
3
+ export { group, guard, mapEntries, mapValues, omit } from 'radash';
4
+
5
+ type MaybeOptionalOptions<TOptions> = Record<never, never> extends TOptions ? [options?: TOptions] : [options: TOptions];
6
+ declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
7
+
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>;
17
+
18
+ type AnyFunction = (...args: any[]) => any;
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;
25
+
26
+ type OmitChainMethodDeep<T extends object, K extends keyof any> = {
27
+ [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
28
+ };
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
+
94
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
95
+ type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
96
+ type PromiseWithError<T, TError> = Promise<T> & {
97
+ __error?: {
98
+ type: TError;
99
+ };
100
+ };
101
+ /**
102
+ * The place where you can config the orpc types.
103
+ *
104
+ * - `throwableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict.
105
+ */
106
+ interface Registry {
107
+ }
108
+ type ThrowableError = Registry extends {
109
+ throwableError: infer T;
110
+ } ? T : Error;
111
+
112
+ type InterceptableOptions = Record<string, any>;
113
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
114
+ next(options?: TOptions): TResult;
115
+ };
116
+ type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
117
+ /**
118
+ * Can used for interceptors or middlewares
119
+ */
120
+ declare function onStart<T, TOptions extends {
121
+ next(): any;
122
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
123
+ /**
124
+ * Can used for interceptors or middlewares
125
+ */
126
+ declare function onSuccess<T, TOptions extends {
127
+ next(): any;
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']>>>;
129
+ /**
130
+ * Can used for interceptors or middlewares
131
+ */
132
+ declare function onError<T, TOptions extends {
133
+ next(): any;
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];
136
+ /**
137
+ * Can used for interceptors or middlewares
138
+ */
139
+ declare function onFinish<T, TOptions extends {
140
+ next(): any;
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;
143
+
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>)[];
168
+
169
+ declare function parseEmptyableJSON(text: string | null | undefined): unknown;
170
+ declare function stringifyJSON<T>(value: T | {
171
+ toJSON(): T;
172
+ }): undefined extends T ? undefined | string : string;
173
+
174
+ type Segment = string | number;
175
+ declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
176
+ maps: Segment[][];
177
+ values: unknown[];
178
+ };
179
+ /**
180
+ * Check if the value is an object even it created by `Object.create(null)` or more tricky way.
181
+ */
182
+ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>;
183
+ /**
184
+ * Check if the value satisfy a `object` type in typescript
185
+ */
186
+ declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
187
+ declare function clone<T>(value: T): T;
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
+ }
210
+
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;
213
+
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 ADDED
@@ -0,0 +1,459 @@
1
+ export { group, guard, mapEntries, mapValues, omit } from 'radash';
2
+
3
+ function resolveMaybeOptionalOptions(rest) {
4
+ return rest[0] ?? {};
5
+ }
6
+
7
+ function toArray(value) {
8
+ return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
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
+ }
21
+
22
+ function once(fn) {
23
+ let cached;
24
+ return () => {
25
+ if (cached) {
26
+ return cached.result;
27
+ }
28
+ const result = fn();
29
+ cached = { result };
30
+ return result;
31
+ };
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
+ }
329
+
330
+ function onStart(callback) {
331
+ return async (options, ...rest) => {
332
+ await callback(options, ...rest);
333
+ return await options.next();
334
+ };
335
+ }
336
+ function onSuccess(callback) {
337
+ return async (options, ...rest) => {
338
+ const result = await options.next();
339
+ await callback(result, options, ...rest);
340
+ return result;
341
+ };
342
+ }
343
+ function onError(callback) {
344
+ return async (options, ...rest) => {
345
+ try {
346
+ return await options.next();
347
+ } catch (error) {
348
+ await callback(error, options, ...rest);
349
+ throw error;
350
+ }
351
+ };
352
+ }
353
+ function onFinish(callback) {
354
+ let state;
355
+ return async (options, ...rest) => {
356
+ try {
357
+ const result = await options.next();
358
+ state = [null, result, true];
359
+ return result;
360
+ } catch (error) {
361
+ state = [error, void 0, false];
362
+ throw error;
363
+ } finally {
364
+ await callback(state, options, ...rest);
365
+ }
366
+ };
367
+ }
368
+ function intercept(interceptors, options, main) {
369
+ const next = (options2, index) => {
370
+ const interceptor = interceptors[index];
371
+ if (!interceptor) {
372
+ return main(options2);
373
+ }
374
+ return interceptor({
375
+ ...options2,
376
+ next: (newOptions = options2) => next(newOptions, index + 1)
377
+ });
378
+ };
379
+ return next(options, 0);
380
+ }
381
+
382
+ function parseEmptyableJSON(text) {
383
+ if (!text) {
384
+ return void 0;
385
+ }
386
+ return JSON.parse(text);
387
+ }
388
+ function stringifyJSON(value) {
389
+ return JSON.stringify(value);
390
+ }
391
+
392
+ function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
393
+ if (check(payload)) {
394
+ maps.push(segments);
395
+ values.push(payload);
396
+ } else if (Array.isArray(payload)) {
397
+ payload.forEach((v, i) => {
398
+ findDeepMatches(check, v, [...segments, i], maps, values);
399
+ });
400
+ } else if (isObject(payload)) {
401
+ for (const key in payload) {
402
+ findDeepMatches(check, payload[key], [...segments, key], maps, values);
403
+ }
404
+ }
405
+ return { maps, values };
406
+ }
407
+ function isObject(value) {
408
+ if (!value || typeof value !== "object") {
409
+ return false;
410
+ }
411
+ const proto = Object.getPrototypeOf(value);
412
+ return proto === Object.prototype || !proto || !proto.constructor;
413
+ }
414
+ function isTypescriptObject(value) {
415
+ return !!value && (typeof value === "object" || typeof value === "function");
416
+ }
417
+ function clone(value) {
418
+ if (Array.isArray(value)) {
419
+ return value.map(clone);
420
+ }
421
+ if (isObject(value)) {
422
+ const result = {};
423
+ for (const key in value) {
424
+ result[key] = clone(value[key]);
425
+ }
426
+ return result;
427
+ }
428
+ return value;
429
+ }
430
+ function get(object, path) {
431
+ let current = object;
432
+ for (const key of path) {
433
+ if (!isTypescriptObject(current)) {
434
+ return void 0;
435
+ }
436
+ current = current[key];
437
+ }
438
+ return current;
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
+ })();
451
+
452
+ function value(value2, ...args) {
453
+ if (typeof value2 === "function") {
454
+ return value2(...args);
455
+ }
456
+ return value2;
457
+ }
458
+
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.f17a1a0",
4
+ "version": "0.0.0-next.f356b86",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,25 +15,25 @@
15
15
  ],
16
16
  "exports": {
17
17
  ".": {
18
- "types": "./dist/src/index.d.ts",
19
- "import": "./dist/index.js",
20
- "default": "./dist/index.js"
21
- },
22
- "./🔒/*": {
23
- "types": "./dist/src/*.d.ts"
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
24
21
  }
25
22
  },
26
23
  "files": [
27
- "!**/*.map",
28
- "!**/*.tsbuildinfo",
29
24
  "dist"
30
25
  ],
31
26
  "dependencies": {
32
- "radash": "^12.1.0",
33
- "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"
34
34
  },
35
35
  "scripts": {
36
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
36
+ "build": "unbuild",
37
37
  "build:watch": "pnpm run build --watch",
38
38
  "type:check": "tsc -b"
39
39
  }
package/dist/index.js DELETED
@@ -1,155 +0,0 @@
1
- // src/object.ts
2
- function set(root, segments, value2) {
3
- const ref = { root };
4
- let currentRef = ref;
5
- let preSegment = "root";
6
- for (const segment of segments) {
7
- currentRef = currentRef[preSegment];
8
- preSegment = segment;
9
- }
10
- currentRef[preSegment] = value2;
11
- return ref.root;
12
- }
13
- function get(root, segments) {
14
- const ref = { root };
15
- let currentRef = ref;
16
- let preSegment = "root";
17
- for (const segment of segments) {
18
- if (typeof currentRef !== "object" && typeof currentRef !== "function" || currentRef === null) {
19
- return void 0;
20
- }
21
- currentRef = currentRef[preSegment];
22
- preSegment = segment;
23
- }
24
- if (typeof currentRef !== "object" && typeof currentRef !== "function" || currentRef === null) {
25
- return void 0;
26
- }
27
- return currentRef[preSegment];
28
- }
29
- function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
30
- if (check(payload)) {
31
- maps.push(segments);
32
- values.push(payload);
33
- } else if (Array.isArray(payload)) {
34
- payload.forEach((v, i) => {
35
- findDeepMatches(check, v, [...segments, i], maps, values);
36
- });
37
- } else if (isObject(payload)) {
38
- for (const key in payload) {
39
- findDeepMatches(check, payload[key], [...segments, key], maps, values);
40
- }
41
- }
42
- return { maps, values };
43
- }
44
- function isObject(value2) {
45
- if (!value2 || typeof value2 !== "object") {
46
- return false;
47
- }
48
- const proto = Object.getPrototypeOf(value2);
49
- return proto === Object.prototype || !proto || !proto.constructor;
50
- }
51
-
52
- // src/error.ts
53
- function toError(error) {
54
- if (error instanceof Error) {
55
- return error;
56
- }
57
- if (typeof error === "string") {
58
- return new Error(error, { cause: error });
59
- }
60
- if (isObject(error)) {
61
- if ("message" in error && typeof error.message === "string") {
62
- return new Error(error.message, { cause: error });
63
- }
64
- if ("name" in error && typeof error.name === "string") {
65
- return new Error(error.name, { cause: error });
66
- }
67
- }
68
- return new Error("Unknown error", { cause: error });
69
- }
70
-
71
- // src/interceptor.ts
72
- function onStart(callback) {
73
- return async (options, ...rest) => {
74
- await callback(options, ...rest);
75
- return await options.next();
76
- };
77
- }
78
- function onSuccess(callback) {
79
- return async (options, ...rest) => {
80
- const result = await options.next();
81
- await callback(result, options, ...rest);
82
- return result;
83
- };
84
- }
85
- function onError(callback) {
86
- return async (options, ...rest) => {
87
- try {
88
- return await options.next();
89
- } catch (error) {
90
- await callback(error, options, ...rest);
91
- throw error;
92
- }
93
- };
94
- }
95
- function onFinish(callback) {
96
- let state;
97
- return async (options, ...rest) => {
98
- try {
99
- const result = await options.next();
100
- state = [result, void 0, "success"];
101
- return result;
102
- } catch (error) {
103
- state = [void 0, error, "error"];
104
- throw error;
105
- } finally {
106
- await callback(state, options, ...rest);
107
- }
108
- };
109
- }
110
- async function intercept(interceptors, options, main) {
111
- let index = 0;
112
- const next = async (options2) => {
113
- const interceptor = interceptors[index++];
114
- if (!interceptor) {
115
- return await main(options2);
116
- }
117
- return await interceptor({
118
- ...options2,
119
- next: (newOptions = options2) => next(newOptions)
120
- });
121
- };
122
- return await next(options);
123
- }
124
-
125
- // src/value.ts
126
- function value(value2, ...args) {
127
- if (typeof value2 === "function") {
128
- return value2(...args);
129
- }
130
- return value2;
131
- }
132
-
133
- // src/index.ts
134
- import { group, guard, mapEntries, mapValues, omit, retry, trim } from "radash";
135
- export {
136
- findDeepMatches,
137
- get,
138
- group,
139
- guard,
140
- intercept,
141
- isObject,
142
- mapEntries,
143
- mapValues,
144
- omit,
145
- onError,
146
- onFinish,
147
- onStart,
148
- onSuccess,
149
- retry,
150
- set,
151
- toError,
152
- trim,
153
- value
154
- };
155
- //# sourceMappingURL=index.js.map
@@ -1,5 +0,0 @@
1
- import type { AnyFunction } from './function';
2
- export type OmitChainMethodDeep<T extends object, K extends keyof any> = {
3
- [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
4
- };
5
- //# sourceMappingURL=chain.d.ts.map
@@ -1,2 +0,0 @@
1
- export declare function toError(error: unknown): Error;
2
- //# sourceMappingURL=error.d.ts.map
@@ -1,2 +0,0 @@
1
- export type AnyFunction = (...args: any[]) => any;
2
- //# sourceMappingURL=function.d.ts.map
@@ -1,10 +0,0 @@
1
- export * from './chain';
2
- export * from './error';
3
- export * from './function';
4
- export * from './interceptor';
5
- export * from './object';
6
- export * from './types';
7
- export * from './value';
8
- export { group, guard, mapEntries, mapValues, omit, retry, trim } from 'radash';
9
- export type { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
10
- //# sourceMappingURL=index.d.ts.map
@@ -1,45 +0,0 @@
1
- import type { Promisable } from 'type-fest';
2
- export type InterceptableOptions = Record<string, any>;
3
- export type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
4
- next(options?: TOptions): Promise<TResult>;
5
- };
6
- export type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult>) => Promise<TResult> & {
7
- __error?: {
8
- type: TError;
9
- };
10
- };
11
- /**
12
- * Can used for interceptors or middlewares
13
- */
14
- export declare function onStart<TOptions extends {
15
- next(): any;
16
- }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
17
- /**
18
- * Can used for interceptors or middlewares
19
- */
20
- export declare function onSuccess<TOptions extends {
21
- next(): any;
22
- }, 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']>>>;
23
- /**
24
- * Can used for interceptors or middlewares
25
- */
26
- export declare function onError<TError, TOptions extends {
27
- next(): any;
28
- }, TRest extends any[]>(callback: NoInfer<(error: TError, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>> & {
29
- __error?: {
30
- type: TError;
31
- };
32
- };
33
- export type OnFinishState<TResult, TError> = [TResult, undefined, 'success'] | [undefined, TError, 'error'];
34
- /**
35
- * Can used for interceptors or middlewares
36
- */
37
- export declare function onFinish<TError, TOptions extends {
38
- next(): any;
39
- }, 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']>>> & {
40
- __error?: {
41
- type: TError;
42
- };
43
- };
44
- export declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
45
- //# sourceMappingURL=interceptor.d.ts.map
@@ -1,12 +0,0 @@
1
- export type Segment = string | number;
2
- export declare function set(root: unknown, segments: Readonly<Segment[]>, value: unknown): unknown;
3
- export declare function get(root: Readonly<Record<string, unknown> | unknown[]>, segments: Readonly<Segment[]>): unknown;
4
- export declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
5
- maps: Segment[][];
6
- values: unknown[];
7
- };
8
- /**
9
- * Check if the value is an object even it created by `Object.create(null)` or more tricky way.
10
- */
11
- export declare function isObject(value: unknown): value is Record<PropertyKey, unknown>;
12
- //# sourceMappingURL=object.d.ts.map
@@ -1,3 +0,0 @@
1
- export type MaybeOptionalOptions<TOptions> = [options: TOptions] | (Record<never, never> extends TOptions ? [] : never);
2
- export type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
3
- //# sourceMappingURL=types.d.ts.map
@@ -1,4 +0,0 @@
1
- import type { Promisable } from 'type-fest';
2
- export type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
3
- export declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
4
- //# sourceMappingURL=value.d.ts.map