@orpc/shared 0.0.0-next.ccd4e42 → 0.0.0-next.d0e429d

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,68 @@
1
+ <div align="center">
2
+ <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 />
3
+ </div>
4
+
5
+ <h1></h1>
6
+
7
+ <div align="center">
8
+ <a href="https://codecov.io/gh/unnoq/orpc">
9
+ <img alt="codecov" src="https://codecov.io/gh/unnoq/orpc/branch/main/graph/badge.svg">
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@orpc/shared">
12
+ <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fshared?logo=npm" />
13
+ </a>
14
+ <a href="https://github.com/unnoq/orpc/blob/main/LICENSE">
15
+ <img alt="MIT License" src="https://img.shields.io/github/license/unnoq/orpc?logo=open-source-initiative" />
16
+ </a>
17
+ <a href="https://discord.gg/TXEbwRBvQn">
18
+ <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
19
+ </a>
20
+ </div>
21
+
22
+ <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
+
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.
25
+
26
+ ---
27
+
28
+ ## Highlights
29
+
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.
46
+
47
+ ## Documentation
48
+
49
+ You can find the full documentation [here](https://orpc.unnoq.com).
50
+
51
+ ## Packages
52
+
53
+ - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
+ - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
+ - [@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
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
60
+ - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
61
+
62
+ ## `@orpc/shared`
63
+
64
+ Provides shared utilities for oRPC packages.
65
+
66
+ ## License
67
+
68
+ Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
package/dist/index.js CHANGED
@@ -1,9 +1,58 @@
1
- // src/constants.ts
2
- var ORPC_HANDLER_HEADER = "x-orpc-handler";
3
- var ORPC_HANDLER_VALUE = "orpc";
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
+ function isTypescriptObject(value2) {
52
+ return !!value2 && (typeof value2 === "object" || typeof value2 === "function");
53
+ }
4
54
 
5
55
  // src/error.ts
6
- import { isPlainObject } from "is-what";
7
56
  function toError(error) {
8
57
  if (error instanceof Error) {
9
58
  return error;
@@ -11,7 +60,7 @@ function toError(error) {
11
60
  if (typeof error === "string") {
12
61
  return new Error(error, { cause: error });
13
62
  }
14
- if (isPlainObject(error)) {
63
+ if (isObject(error)) {
15
64
  if ("message" in error && typeof error.message === "string") {
16
65
  return new Error(error.message, { cause: error });
17
66
  }
@@ -35,64 +84,6 @@ function once(fn) {
35
84
  };
36
85
  }
37
86
 
38
- // src/hook.ts
39
- async function executeWithHooks(options) {
40
- const interceptors = convertToArray(options.hooks?.interceptor);
41
- const onStarts = convertToArray(options.hooks?.onStart);
42
- const onSuccesses = convertToArray(options.hooks?.onSuccess);
43
- const onErrors = convertToArray(options.hooks?.onError);
44
- const onFinishes = convertToArray(options.hooks?.onFinish);
45
- let currentExecuteIndex = 0;
46
- const next = async () => {
47
- const execute = interceptors[currentExecuteIndex];
48
- if (execute) {
49
- currentExecuteIndex++;
50
- return await execute(options.input, options.context, {
51
- ...options.meta,
52
- next
53
- });
54
- }
55
- let state = { status: "pending", input: options.input, output: void 0, error: void 0 };
56
- try {
57
- for (const onStart2 of onStarts) {
58
- await onStart2(state, options.context, options.meta);
59
- }
60
- const output = await options.execute();
61
- state = { status: "success", input: options.input, output, error: void 0 };
62
- for (let i = onSuccesses.length - 1; i >= 0; i--) {
63
- await onSuccesses[i](state, options.context, options.meta);
64
- }
65
- } catch (e) {
66
- state = { status: "error", input: options.input, error: toError(e), output: void 0 };
67
- for (let i = onErrors.length - 1; i >= 0; i--) {
68
- try {
69
- await onErrors[i](state, options.context, options.meta);
70
- } catch (e2) {
71
- state = { status: "error", input: options.input, error: toError(e2), output: void 0 };
72
- }
73
- }
74
- }
75
- for (let i = onFinishes.length - 1; i >= 0; i--) {
76
- try {
77
- await onFinishes[i](state, options.context, options.meta);
78
- } catch (e) {
79
- state = { status: "error", input: options.input, error: toError(e), output: void 0 };
80
- }
81
- }
82
- if (state.status === "error") {
83
- throw state.error;
84
- }
85
- return state.output;
86
- };
87
- return await next();
88
- }
89
- function convertToArray(value2) {
90
- if (value2 === void 0) {
91
- return [];
92
- }
93
- return Array.isArray(value2) ? value2 : [value2];
94
- }
95
-
96
87
  // src/interceptor.ts
97
88
  function onStart(callback) {
98
89
  return async (options, ...rest) => {
@@ -132,104 +123,38 @@ function onFinish(callback) {
132
123
  }
133
124
  };
134
125
  }
135
- async function intercept(interceptable, options, main) {
136
- const interceptors = interceptable.interceptors ?? [];
126
+ async function intercept(interceptors, options, main) {
137
127
  let index = 0;
138
- const next = async (nextOptions = options) => {
128
+ const next = async (options2) => {
139
129
  const interceptor = interceptors[index++];
140
130
  if (!interceptor) {
141
- return await main(nextOptions);
131
+ return await main(options2);
142
132
  }
143
133
  return await interceptor({
144
- ...nextOptions,
145
- next
134
+ ...options2,
135
+ next: (newOptions = options2) => next(newOptions)
146
136
  });
147
137
  };
148
- return await next();
138
+ return await next(options);
149
139
  }
150
140
 
151
- // src/json.ts
152
- function parseJSONSafely(text) {
153
- if (text === "")
154
- return void 0;
155
- try {
156
- return JSON.parse(text);
157
- } catch {
158
- return text;
141
+ // src/iterator.ts
142
+ function isAsyncIteratorObject(maybe) {
143
+ if (!maybe || typeof maybe !== "object") {
144
+ return false;
159
145
  }
146
+ return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
160
147
  }
161
148
 
162
- // src/object.ts
163
- import { isPlainObject as isPlainObject2 } from "is-what";
164
- function set(root, segments, value2) {
165
- const ref = { root };
166
- let currentRef = ref;
167
- let preSegment = "root";
168
- for (const segment of segments) {
169
- currentRef = currentRef[preSegment];
170
- preSegment = segment;
171
- }
172
- currentRef[preSegment] = value2;
173
- return ref.root;
174
- }
175
- function get(root, segments) {
176
- const ref = { root };
177
- let currentRef = ref;
178
- let preSegment = "root";
179
- for (const segment of segments) {
180
- if (typeof currentRef !== "object" && typeof currentRef !== "function" || currentRef === null) {
181
- return void 0;
182
- }
183
- currentRef = currentRef[preSegment];
184
- preSegment = segment;
185
- }
186
- if (typeof currentRef !== "object" && typeof currentRef !== "function" || currentRef === null) {
149
+ // src/json.ts
150
+ function parseEmptyableJSON(text) {
151
+ if (!text) {
187
152
  return void 0;
188
153
  }
189
- return currentRef[preSegment];
190
- }
191
- function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
192
- if (check(payload)) {
193
- maps.push(segments);
194
- values.push(payload);
195
- } else if (Array.isArray(payload)) {
196
- payload.forEach((v, i) => {
197
- findDeepMatches(check, v, [...segments, i], maps, values);
198
- });
199
- } else if (isPlainObject2(payload)) {
200
- for (const key in payload) {
201
- findDeepMatches(check, payload[key], [...segments, key], maps, values);
202
- }
203
- }
204
- return { maps, values };
154
+ return JSON.parse(text);
205
155
  }
206
-
207
- // src/proxy.ts
208
- function createCallableObject(obj, handler) {
209
- const proxy = new Proxy(handler, {
210
- has(target, key) {
211
- return Reflect.has(obj, key) || Reflect.has(target, key);
212
- },
213
- ownKeys(target) {
214
- return Array.from(new Set(Reflect.ownKeys(obj).concat(...Reflect.ownKeys(target))));
215
- },
216
- get(target, key) {
217
- if (!Reflect.has(target, key) || Reflect.has(obj, key)) {
218
- return Reflect.get(obj, key);
219
- }
220
- return Reflect.get(target, key);
221
- },
222
- defineProperty(_, key, descriptor) {
223
- return Reflect.defineProperty(obj, key, descriptor);
224
- },
225
- set(_, key, value2) {
226
- return Reflect.set(obj, key, value2);
227
- },
228
- deleteProperty(target, key) {
229
- return Reflect.deleteProperty(target, key) && Reflect.deleteProperty(obj, key);
230
- }
231
- });
232
- return proxy;
156
+ function stringifyJSON(value2) {
157
+ return JSON.stringify(value2);
233
158
  }
234
159
 
235
160
  // src/value.ts
@@ -241,20 +166,16 @@ function value(value2, ...args) {
241
166
  }
242
167
 
243
168
  // src/index.ts
244
- import { isPlainObject as isPlainObject3 } from "is-what";
245
- import { group, guard, mapEntries, mapValues, omit, trim } from "radash";
169
+ import { group, guard, mapEntries, mapValues, omit, retry, trim } from "radash";
246
170
  export {
247
- ORPC_HANDLER_HEADER,
248
- ORPC_HANDLER_VALUE,
249
- convertToArray,
250
- createCallableObject,
251
- executeWithHooks,
252
171
  findDeepMatches,
253
172
  get,
254
173
  group,
255
174
  guard,
256
175
  intercept,
257
- isPlainObject3 as isPlainObject,
176
+ isAsyncIteratorObject,
177
+ isObject,
178
+ isTypescriptObject,
258
179
  mapEntries,
259
180
  mapValues,
260
181
  omit,
@@ -263,8 +184,10 @@ export {
263
184
  onStart,
264
185
  onSuccess,
265
186
  once,
266
- parseJSONSafely,
187
+ parseEmptyableJSON,
188
+ retry,
267
189
  set,
190
+ stringifyJSON,
268
191
  toError,
269
192
  trim,
270
193
  value
@@ -1,14 +1,12 @@
1
1
  export * from './chain';
2
- export * from './constants';
3
2
  export * from './error';
4
3
  export * from './function';
5
- export * from './hook';
6
4
  export * from './interceptor';
5
+ export * from './iterator';
7
6
  export * from './json';
8
7
  export * from './object';
9
- export * from './proxy';
8
+ export * from './types';
10
9
  export * from './value';
11
- export { isPlainObject } from 'is-what';
12
- export { group, guard, mapEntries, mapValues, omit, trim } from 'radash';
13
- export type * from 'type-fest';
10
+ export { group, guard, mapEntries, mapValues, omit, retry, trim } from 'radash';
11
+ export type { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
14
12
  //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,4 @@
1
1
  import type { Promisable } from 'type-fest';
2
- import type { AnyFunction } from './function';
3
2
  export type InterceptableOptions = Record<string, any>;
4
3
  export type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
5
4
  next(options?: TOptions): Promise<TResult>;
@@ -9,9 +8,6 @@ export type Interceptor<TOptions extends InterceptableOptions, TResult, TError>
9
8
  type: TError;
10
9
  };
11
10
  };
12
- export interface Interceptable<TOptions extends InterceptableOptions, TResult, TError> {
13
- interceptors?: Interceptor<TOptions, TResult, TError>[];
14
- }
15
11
  /**
16
12
  * Can used for interceptors or middlewares
17
13
  */
@@ -24,7 +20,6 @@ export declare function onStart<TOptions extends {
24
20
  export declare function onSuccess<TOptions extends {
25
21
  next(): any;
26
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']>>>;
27
- export type InferError<T extends AnyFunction> = T extends Interceptor<any, any, infer TError> ? TError : unknown;
28
23
  /**
29
24
  * Can used for interceptors or middlewares
30
25
  */
@@ -46,5 +41,5 @@ export declare function onFinish<TError, TOptions extends {
46
41
  type: TError;
47
42
  };
48
43
  };
49
- export declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptable: Interceptable<TOptions, TResult, TError>, options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
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>;
50
45
  //# sourceMappingURL=interceptor.d.ts.map
@@ -0,0 +1,2 @@
1
+ export declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
2
+ //# sourceMappingURL=iterator.d.ts.map
@@ -1,2 +1,3 @@
1
- export declare function parseJSONSafely(text: string): unknown;
1
+ export declare function parseEmptyableJSON(text: string | null | undefined): unknown;
2
+ export declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
2
3
  //# sourceMappingURL=json.d.ts.map
@@ -5,4 +5,12 @@ export declare function findDeepMatches(check: (value: unknown) => boolean, payl
5
5
  maps: Segment[][];
6
6
  values: unknown[];
7
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
+ /**
13
+ * Check if the value satisfy a `object` type in typescript
14
+ */
15
+ export declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
8
16
  //# sourceMappingURL=object.d.ts.map
@@ -0,0 +1,3 @@
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 +1,4 @@
1
1
  import type { Promisable } from 'type-fest';
2
2
  export type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
3
- export declare function value<T extends Value<any, TArgs>, TArgs extends any[] = []>(value: T, ...args: TArgs): Promise<T extends Value<infer U, any> ? U : never>;
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
4
  //# sourceMappingURL=value.d.ts.map
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.ccd4e42",
4
+ "version": "0.0.0-next.d0e429d",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -29,8 +29,6 @@
29
29
  "dist"
30
30
  ],
31
31
  "dependencies": {
32
- "@standard-schema/spec": "1.0.0-beta.4",
33
- "is-what": "^5.0.2",
34
32
  "radash": "^12.1.0",
35
33
  "type-fest": "^4.26.1"
36
34
  },
@@ -1,3 +0,0 @@
1
- export declare const ORPC_HANDLER_HEADER = "x-orpc-handler";
2
- export declare const ORPC_HANDLER_VALUE = "orpc";
3
- //# sourceMappingURL=constants.d.ts.map
@@ -1,42 +0,0 @@
1
- import type { Arrayable, Promisable } from 'type-fest';
2
- export type OnStartState<TInput> = {
3
- status: 'pending';
4
- input: TInput;
5
- output: undefined;
6
- error: undefined;
7
- };
8
- export type OnSuccessState<TInput, TOutput> = {
9
- status: 'success';
10
- input: TInput;
11
- output: TOutput;
12
- error: undefined;
13
- };
14
- export type OnErrorState<TInput> = {
15
- status: 'error';
16
- input: TInput;
17
- output: undefined;
18
- error: Error;
19
- };
20
- export interface BaseHookMeta<TOutput> {
21
- next(): Promise<TOutput>;
22
- }
23
- export interface Hooks<TInput, TOutput, TContext, TMeta extends (Record<string, any> & {
24
- next?: never;
25
- }) | undefined> {
26
- interceptor?: Arrayable<(input: TInput, context: TContext, meta: (TMeta extends undefined ? unknown : TMeta) & BaseHookMeta<TOutput>) => Promise<TOutput>>;
27
- onStart?: Arrayable<(state: OnStartState<TInput>, context: TContext, meta: TMeta) => Promisable<void>>;
28
- onSuccess?: Arrayable<(state: OnSuccessState<TInput, TOutput>, context: TContext, meta: TMeta) => Promisable<void>>;
29
- onError?: Arrayable<(state: OnErrorState<TInput>, context: TContext, meta: TMeta) => Promisable<void>>;
30
- onFinish?: Arrayable<(state: OnSuccessState<TInput, TOutput> | OnErrorState<TInput>, context: TContext, meta: TMeta) => Promisable<void>>;
31
- }
32
- export declare function executeWithHooks<TInput, TOutput, TContext, TMeta extends (Record<string, any> & {
33
- next?: never;
34
- }) | undefined>(options: {
35
- hooks?: Hooks<TInput, TOutput, TContext, TMeta>;
36
- input: TInput;
37
- context: TContext;
38
- meta: TMeta;
39
- execute: BaseHookMeta<TOutput>['next'];
40
- }): Promise<TOutput>;
41
- export declare function convertToArray<T>(value: undefined | T | readonly T[]): readonly T[];
42
- //# sourceMappingURL=hook.d.ts.map
@@ -1,3 +0,0 @@
1
- import type { AnyFunction } from './function';
2
- export declare function createCallableObject<TObject extends object, THandler extends AnyFunction>(obj: TObject, handler: THandler): TObject & THandler;
3
- //# sourceMappingURL=proxy.d.ts.map