@orpc/shared 0.0.0-next.e9dc36e → 0.0.0-next.eae6003

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 ADDED
@@ -0,0 +1,83 @@
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
+
6
+ <div align="center">
7
+ <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
8
+ </div>
9
+
10
+ <h1></h1>
11
+
12
+ <div align="center">
13
+ <a href="https://codecov.io/gh/unnoq/orpc">
14
+ <img alt="codecov" src="https://codecov.io/gh/unnoq/orpc/branch/main/graph/badge.svg">
15
+ </a>
16
+ <a href="https://www.npmjs.com/package/@orpc/shared">
17
+ <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fshared?logo=npm" />
18
+ </a>
19
+ <a href="https://github.com/unnoq/orpc/blob/main/LICENSE">
20
+ <img alt="MIT License" src="https://img.shields.io/github/license/unnoq/orpc?logo=open-source-initiative" />
21
+ </a>
22
+ <a href="https://discord.gg/TXEbwRBvQn">
23
+ <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
24
+ </a>
25
+ </div>
26
+
27
+ <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
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
30
+
31
+ ---
32
+
33
+ ## Highlights
34
+
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), 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.
47
+
48
+ ## Documentation
49
+
50
+ You can find the full documentation [here](https://orpc.unnoq.com).
51
+
52
+ ## Packages
53
+
54
+ - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
55
+ - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
56
+ - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
57
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with NestJS.
58
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
59
+ - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
60
+ - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
61
+ - [@orpc/solid-query](https://www.npmjs.com/package/@orpc/solid-query): Integration with [Solid Query](https://tanstack.com/query/latest/docs/framework/solid/overview).
62
+ - [@orpc/svelte-query](https://www.npmjs.com/package/@orpc/svelte-query): Integration with [Svelte Query](https://tanstack.com/query/latest/docs/framework/svelte/overview).
63
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
64
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
65
+ - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
66
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
67
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
68
+
69
+ ## `@orpc/shared`
70
+
71
+ Provides shared utilities for oRPC packages.
72
+
73
+ ## Sponsors
74
+
75
+ <p align="center">
76
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
77
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
78
+ </a>
79
+ </p>
80
+
81
+ ## License
82
+
83
+ Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,120 @@
1
+ import { Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, 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
+ type AnyFunction = (...args: any[]) => any;
12
+ declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
13
+ declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
14
+
15
+ type OmitChainMethodDeep<T extends object, K extends keyof any> = {
16
+ [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
17
+ };
18
+
19
+ declare class SequentialIdGenerator {
20
+ private nextId;
21
+ generate(): number;
22
+ }
23
+
24
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
25
+ type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
26
+ type PromiseWithError<T, TError> = Promise<T> & {
27
+ __error?: {
28
+ type: TError;
29
+ };
30
+ };
31
+ /**
32
+ * The place where you can config the orpc types.
33
+ *
34
+ * - `throwableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict.
35
+ */
36
+ interface Registry {
37
+ }
38
+ type ThrowableError = Registry extends {
39
+ throwableError: infer T;
40
+ } ? T : Error;
41
+
42
+ type InterceptableOptions = Record<string, any>;
43
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult, TError> = Omit<TOptions, 'next'> & {
44
+ next(options?: TOptions): PromiseWithError<TResult, TError>;
45
+ };
46
+ type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult, TError>) => Promisable<TResult>;
47
+ /**
48
+ * Can used for interceptors or middlewares
49
+ */
50
+ declare function onStart<T, TOptions extends {
51
+ next(): any;
52
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
53
+ /**
54
+ * Can used for interceptors or middlewares
55
+ */
56
+ declare function onSuccess<T, TOptions extends {
57
+ next(): any;
58
+ }, 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']>>>;
59
+ /**
60
+ * Can used for interceptors or middlewares
61
+ */
62
+ declare function onError<T, TOptions extends {
63
+ next(): any;
64
+ }, 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']>>>;
65
+ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
66
+ /**
67
+ * Can used for interceptors or middlewares
68
+ */
69
+ declare function onFinish<T, TOptions extends {
70
+ next(): any;
71
+ }, 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']>>>;
72
+ declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
73
+
74
+ declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
75
+ interface CreateAsyncIteratorObjectCleanupFn {
76
+ (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
77
+ }
78
+ declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>;
79
+
80
+ declare function parseEmptyableJSON(text: string | null | undefined): unknown;
81
+ declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
82
+
83
+ type Segment = string | number;
84
+ declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
85
+ maps: Segment[][];
86
+ values: unknown[];
87
+ };
88
+ /**
89
+ * Check if the value is an object even it created by `Object.create(null)` or more tricky way.
90
+ */
91
+ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>;
92
+ /**
93
+ * Check if the value satisfy a `object` type in typescript
94
+ */
95
+ declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
96
+ declare function clone<T>(value: T): T;
97
+ declare function get(object: object, path: readonly string[]): unknown;
98
+
99
+ interface AsyncIdQueueCloseOptions {
100
+ id?: number;
101
+ reason?: Error;
102
+ }
103
+ declare class AsyncIdQueue<T> {
104
+ private readonly openIds;
105
+ private readonly items;
106
+ private readonly pendingPulls;
107
+ get length(): number;
108
+ open(id: number): void;
109
+ isOpen(id: number): boolean;
110
+ push(id: number, item: T): void;
111
+ pull(id: number): Promise<T>;
112
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
113
+ assertOpen(id: number): void;
114
+ }
115
+
116
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
117
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
118
+
119
+ export { AsyncIdQueue, SequentialIdGenerator, clone, createAsyncIteratorObject, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
120
+ export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
@@ -0,0 +1,120 @@
1
+ import { Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, 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
+ type AnyFunction = (...args: any[]) => any;
12
+ declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
13
+ declare function sequential<A extends any[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
14
+
15
+ type OmitChainMethodDeep<T extends object, K extends keyof any> = {
16
+ [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
17
+ };
18
+
19
+ declare class SequentialIdGenerator {
20
+ private nextId;
21
+ generate(): number;
22
+ }
23
+
24
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
25
+ type IntersectPick<T, U> = Pick<T, keyof T & keyof U>;
26
+ type PromiseWithError<T, TError> = Promise<T> & {
27
+ __error?: {
28
+ type: TError;
29
+ };
30
+ };
31
+ /**
32
+ * The place where you can config the orpc types.
33
+ *
34
+ * - `throwableError` the error type that represent throwable errors should be `Error` or `null | undefined | {}` if you want more strict.
35
+ */
36
+ interface Registry {
37
+ }
38
+ type ThrowableError = Registry extends {
39
+ throwableError: infer T;
40
+ } ? T : Error;
41
+
42
+ type InterceptableOptions = Record<string, any>;
43
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult, TError> = Omit<TOptions, 'next'> & {
44
+ next(options?: TOptions): PromiseWithError<TResult, TError>;
45
+ };
46
+ type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult, TError>) => Promisable<TResult>;
47
+ /**
48
+ * Can used for interceptors or middlewares
49
+ */
50
+ declare function onStart<T, TOptions extends {
51
+ next(): any;
52
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions['next']>>>;
53
+ /**
54
+ * Can used for interceptors or middlewares
55
+ */
56
+ declare function onSuccess<T, TOptions extends {
57
+ next(): any;
58
+ }, 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']>>>;
59
+ /**
60
+ * Can used for interceptors or middlewares
61
+ */
62
+ declare function onError<T, TOptions extends {
63
+ next(): any;
64
+ }, 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']>>>;
65
+ type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
66
+ /**
67
+ * Can used for interceptors or middlewares
68
+ */
69
+ declare function onFinish<T, TOptions extends {
70
+ next(): any;
71
+ }, 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']>>>;
72
+ declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
73
+
74
+ declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
75
+ interface CreateAsyncIteratorObjectCleanupFn {
76
+ (reason: 'return' | 'throw' | 'next' | 'dispose'): Promise<void>;
77
+ }
78
+ declare function createAsyncIteratorObject<T, TReturn, TNext>(next: () => Promise<IteratorResult<T, TReturn>>, cleanup: CreateAsyncIteratorObjectCleanupFn): AsyncIteratorObject<T, TReturn, TNext> & AsyncGenerator<T, TReturn, TNext>;
79
+
80
+ declare function parseEmptyableJSON(text: string | null | undefined): unknown;
81
+ declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
82
+
83
+ type Segment = string | number;
84
+ declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
85
+ maps: Segment[][];
86
+ values: unknown[];
87
+ };
88
+ /**
89
+ * Check if the value is an object even it created by `Object.create(null)` or more tricky way.
90
+ */
91
+ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>;
92
+ /**
93
+ * Check if the value satisfy a `object` type in typescript
94
+ */
95
+ declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
96
+ declare function clone<T>(value: T): T;
97
+ declare function get(object: object, path: readonly string[]): unknown;
98
+
99
+ interface AsyncIdQueueCloseOptions {
100
+ id?: number;
101
+ reason?: Error;
102
+ }
103
+ declare class AsyncIdQueue<T> {
104
+ private readonly openIds;
105
+ private readonly items;
106
+ private readonly pendingPulls;
107
+ get length(): number;
108
+ open(id: number): void;
109
+ isOpen(id: number): boolean;
110
+ push(id: number, item: T): void;
111
+ pull(id: number): Promise<T>;
112
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
113
+ assertOpen(id: number): void;
114
+ }
115
+
116
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
117
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
118
+
119
+ export { AsyncIdQueue, SequentialIdGenerator, clone, createAsyncIteratorObject, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };
120
+ export type { AnyFunction, AsyncIdQueueCloseOptions, CreateAsyncIteratorObjectCleanupFn, InterceptableOptions, Interceptor, InterceptorOptions, IntersectPick, MaybeOptionalOptions, OmitChainMethodDeep, OnFinishState, PromiseWithError, Registry, Segment, SetOptional, ThrowableError, Value };
package/dist/index.mjs ADDED
@@ -0,0 +1,304 @@
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 once(fn) {
16
+ let cached;
17
+ return () => {
18
+ if (cached) {
19
+ return cached.result;
20
+ }
21
+ const result = fn();
22
+ cached = { result };
23
+ return result;
24
+ };
25
+ }
26
+ function sequential(fn) {
27
+ let lastOperationPromise = Promise.resolve();
28
+ return (...args) => {
29
+ return lastOperationPromise = lastOperationPromise.catch(() => {
30
+ }).then(() => {
31
+ return fn(...args);
32
+ });
33
+ };
34
+ }
35
+
36
+ class SequentialIdGenerator {
37
+ nextId = 0;
38
+ generate() {
39
+ if (this.nextId === Number.MAX_SAFE_INTEGER) {
40
+ this.nextId = 0;
41
+ return Number.MAX_SAFE_INTEGER;
42
+ }
43
+ return this.nextId++;
44
+ }
45
+ }
46
+
47
+ function onStart(callback) {
48
+ return async (options, ...rest) => {
49
+ await callback(options, ...rest);
50
+ return await options.next();
51
+ };
52
+ }
53
+ function onSuccess(callback) {
54
+ return async (options, ...rest) => {
55
+ const result = await options.next();
56
+ await callback(result, options, ...rest);
57
+ return result;
58
+ };
59
+ }
60
+ function onError(callback) {
61
+ return async (options, ...rest) => {
62
+ try {
63
+ return await options.next();
64
+ } catch (error) {
65
+ await callback(error, options, ...rest);
66
+ throw error;
67
+ }
68
+ };
69
+ }
70
+ function onFinish(callback) {
71
+ let state;
72
+ return async (options, ...rest) => {
73
+ try {
74
+ const result = await options.next();
75
+ state = [null, result, true];
76
+ return result;
77
+ } catch (error) {
78
+ state = [error, void 0, false];
79
+ throw error;
80
+ } finally {
81
+ await callback(state, options, ...rest);
82
+ }
83
+ };
84
+ }
85
+ async function intercept(interceptors, options, main) {
86
+ const next = async (options2, index) => {
87
+ const interceptor = interceptors[index];
88
+ if (!interceptor) {
89
+ return await main(options2);
90
+ }
91
+ return await interceptor({
92
+ ...options2,
93
+ next: (newOptions = options2) => next(newOptions, index + 1)
94
+ });
95
+ };
96
+ return next(options, 0);
97
+ }
98
+
99
+ function isAsyncIteratorObject(maybe) {
100
+ if (!maybe || typeof maybe !== "object") {
101
+ return false;
102
+ }
103
+ return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
104
+ }
105
+ function createAsyncIteratorObject(next, cleanup) {
106
+ let isExecuteComplete = false;
107
+ let isDone = false;
108
+ const iterator = {
109
+ next: sequential(async () => {
110
+ if (isDone) {
111
+ return { done: true, value: void 0 };
112
+ }
113
+ try {
114
+ const result = await next();
115
+ if (result.done) {
116
+ isDone = true;
117
+ }
118
+ return result;
119
+ } catch (err) {
120
+ isDone = true;
121
+ throw err;
122
+ } finally {
123
+ if (isDone && !isExecuteComplete) {
124
+ isExecuteComplete = true;
125
+ await cleanup("next");
126
+ }
127
+ }
128
+ }),
129
+ async return(value) {
130
+ isDone = true;
131
+ if (!isExecuteComplete) {
132
+ isExecuteComplete = true;
133
+ await cleanup("return");
134
+ }
135
+ return { done: true, value };
136
+ },
137
+ async throw(err) {
138
+ isDone = true;
139
+ if (!isExecuteComplete) {
140
+ isExecuteComplete = true;
141
+ await cleanup("throw");
142
+ }
143
+ throw err;
144
+ },
145
+ /**
146
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
147
+ */
148
+ async [Symbol.asyncDispose ?? Symbol.for("asyncDispose")]() {
149
+ isDone = true;
150
+ if (!isExecuteComplete) {
151
+ isExecuteComplete = true;
152
+ await cleanup("dispose");
153
+ }
154
+ },
155
+ [Symbol.asyncIterator]() {
156
+ return iterator;
157
+ }
158
+ };
159
+ return iterator;
160
+ }
161
+
162
+ function parseEmptyableJSON(text) {
163
+ if (!text) {
164
+ return void 0;
165
+ }
166
+ return JSON.parse(text);
167
+ }
168
+ function stringifyJSON(value) {
169
+ return JSON.stringify(value);
170
+ }
171
+
172
+ function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
173
+ if (check(payload)) {
174
+ maps.push(segments);
175
+ values.push(payload);
176
+ } else if (Array.isArray(payload)) {
177
+ payload.forEach((v, i) => {
178
+ findDeepMatches(check, v, [...segments, i], maps, values);
179
+ });
180
+ } else if (isObject(payload)) {
181
+ for (const key in payload) {
182
+ findDeepMatches(check, payload[key], [...segments, key], maps, values);
183
+ }
184
+ }
185
+ return { maps, values };
186
+ }
187
+ function isObject(value) {
188
+ if (!value || typeof value !== "object") {
189
+ return false;
190
+ }
191
+ const proto = Object.getPrototypeOf(value);
192
+ return proto === Object.prototype || !proto || !proto.constructor;
193
+ }
194
+ function isTypescriptObject(value) {
195
+ return !!value && (typeof value === "object" || typeof value === "function");
196
+ }
197
+ function clone(value) {
198
+ if (Array.isArray(value)) {
199
+ return value.map(clone);
200
+ }
201
+ if (isObject(value)) {
202
+ const result = {};
203
+ for (const key in value) {
204
+ result[key] = clone(value[key]);
205
+ }
206
+ return result;
207
+ }
208
+ return value;
209
+ }
210
+ function get(object, path) {
211
+ let current = object;
212
+ for (const key of path) {
213
+ if (!isTypescriptObject(current)) {
214
+ return void 0;
215
+ }
216
+ current = current[key];
217
+ }
218
+ return current;
219
+ }
220
+
221
+ class AsyncIdQueue {
222
+ openIds = /* @__PURE__ */ new Set();
223
+ items = /* @__PURE__ */ new Map();
224
+ pendingPulls = /* @__PURE__ */ new Map();
225
+ get length() {
226
+ return this.openIds.size;
227
+ }
228
+ open(id) {
229
+ this.openIds.add(id);
230
+ }
231
+ isOpen(id) {
232
+ return this.openIds.has(id);
233
+ }
234
+ push(id, item) {
235
+ this.assertOpen(id);
236
+ const pending = this.pendingPulls.get(id);
237
+ if (pending?.length) {
238
+ pending.shift()[0](item);
239
+ if (pending.length === 0) {
240
+ this.pendingPulls.delete(id);
241
+ }
242
+ } else {
243
+ const items = this.items.get(id);
244
+ if (items) {
245
+ items.push(item);
246
+ } else {
247
+ this.items.set(id, [item]);
248
+ }
249
+ }
250
+ }
251
+ async pull(id) {
252
+ this.assertOpen(id);
253
+ const items = this.items.get(id);
254
+ if (items?.length) {
255
+ const item = items.shift();
256
+ if (items.length === 0) {
257
+ this.items.delete(id);
258
+ }
259
+ return item;
260
+ }
261
+ return new Promise((resolve, reject) => {
262
+ const waitingPulls = this.pendingPulls.get(id);
263
+ const pending = [resolve, reject];
264
+ if (waitingPulls) {
265
+ waitingPulls.push(pending);
266
+ } else {
267
+ this.pendingPulls.set(id, [pending]);
268
+ }
269
+ });
270
+ }
271
+ close({ id, reason } = {}) {
272
+ if (id === void 0) {
273
+ this.pendingPulls.forEach((pendingPulls, id2) => {
274
+ pendingPulls.forEach(([, reject]) => {
275
+ reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id2}] was closed or aborted while waiting for pulling.`));
276
+ });
277
+ });
278
+ this.pendingPulls.clear();
279
+ this.openIds.clear();
280
+ this.items.clear();
281
+ return;
282
+ }
283
+ this.pendingPulls.get(id)?.forEach(([, reject]) => {
284
+ reject(reason ?? new Error(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`));
285
+ });
286
+ this.pendingPulls.delete(id);
287
+ this.openIds.delete(id);
288
+ this.items.delete(id);
289
+ }
290
+ assertOpen(id) {
291
+ if (!this.isOpen(id)) {
292
+ throw new Error(`[AsyncIdQueue] Cannot access queue[${id}] because it is not open or aborted.`);
293
+ }
294
+ }
295
+ }
296
+
297
+ function value(value2, ...args) {
298
+ if (typeof value2 === "function") {
299
+ return value2(...args);
300
+ }
301
+ return value2;
302
+ }
303
+
304
+ export { AsyncIdQueue, SequentialIdGenerator, clone, createAsyncIteratorObject, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, resolveMaybeOptionalOptions, sequential, splitInHalf, stringifyJSON, toArray, value };