@orpc/shared 2.0.0-beta.5 → 2.0.0-beta.51

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.
Files changed (51) hide show
  1. package/README.md +139 -102
  2. package/dist/args.d.ts +2 -0
  3. package/dist/args.js +5 -0
  4. package/dist/array.d.ts +5 -0
  5. package/dist/array.js +13 -0
  6. package/dist/bigint.d.ts +9 -0
  7. package/dist/bigint.js +15 -0
  8. package/dist/buffer.d.ts +18 -0
  9. package/dist/buffer.js +54 -0
  10. package/dist/compare.d.ts +1 -0
  11. package/dist/compare.js +26 -0
  12. package/dist/consts.d.ts +1 -0
  13. package/dist/consts.js +3 -0
  14. package/dist/error.d.ts +1 -0
  15. package/dist/error.js +5 -0
  16. package/dist/function.d.ts +12 -0
  17. package/dist/function.js +33 -0
  18. package/dist/http.d.ts +58 -0
  19. package/dist/http.js +147 -0
  20. package/dist/id.d.ts +8 -0
  21. package/dist/id.js +13 -0
  22. package/dist/index.d.ts +26 -306
  23. package/dist/index.js +23 -0
  24. package/dist/interceptor.d.ts +66 -0
  25. package/dist/interceptor.js +119 -0
  26. package/dist/iterator.d.ts +55 -0
  27. package/dist/iterator.js +141 -0
  28. package/dist/object.d.ts +62 -0
  29. package/dist/object.js +194 -0
  30. package/dist/plugin.d.ts +12 -0
  31. package/dist/plugin.js +45 -0
  32. package/dist/promise.d.ts +17 -0
  33. package/dist/promise.js +32 -0
  34. package/dist/proxy.d.ts +12 -0
  35. package/dist/proxy.js +25 -0
  36. package/dist/queue.d.ts +16 -0
  37. package/dist/queue.js +64 -0
  38. package/dist/regex.d.ts +9 -0
  39. package/dist/regex.js +11 -0
  40. package/dist/signal.d.ts +23 -0
  41. package/dist/signal.js +88 -0
  42. package/dist/stream.d.ts +47 -0
  43. package/dist/stream.js +129 -0
  44. package/dist/tracing.d.ts +73 -0
  45. package/dist/tracing.js +76 -0
  46. package/dist/types.d.ts +27 -0
  47. package/dist/value.d.ts +2 -0
  48. package/dist/value.js +6 -0
  49. package/package.json +22 -30
  50. package/dist/index.d.mts +0 -306
  51. package/dist/index.mjs +0 -892
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ export { resolveMaybeOptionalOptions } from "./args.js";
2
+ export { splitInHalf, takeLast } from "./array.js";
3
+ export { DEFAULT_MAX_BIGINT_DIGITS, parseBigIntString } from "./bigint.js";
4
+ export { encodeBase64, loadBytes, toStringOrBytes } from "./buffer.js";
5
+ export { isDeepEqual } from "./compare.js";
6
+ export { ORPC_NAME } from "./consts.js";
7
+ export { isAbortError } from "./error.js";
8
+ export { defer, isAsyncGeneratorFunction, once, tryOrUndefined } from "./function.js";
9
+ export { estimateCompressibleFormDataSize, estimateUtf8ByteLength, isAcceptableEncoding, isCompressibleContentType, isCompressionEncoding, isNoTransformCacheControl, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, parseAcceptEncodingQualities, parseContentEncodings, pathToHttpPath, stripHttpPathPrefix, varyByAcceptEncoding } from "./http.js";
10
+ export { compareSequentialIds } from "./id.js";
11
+ export { intercept, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess } from "./interceptor.js";
12
+ export { consumeAsyncIterator, replicateAsyncIterator, traceAsyncIterator, wrapAsyncIterator } from "./iterator.js";
13
+ export { NullProtoObj, bindMethods, clone, copyOnWrite, findDeepMatches, get, getConstructor, getConstructors, getOwn, isPlainObject as isObject, isPlainObject, isPlainObjectOrArray, isPropertyKey, mergeTwoLevels, omit, pick, set, setOwn } from "./object.js";
14
+ export { sortPlugins } from "./plugin.js";
15
+ export { captureAsyncContext, promiseWithResolvers } from "./promise.js";
16
+ export { override } from "./proxy.js";
17
+ export { AsyncIdQueue } from "./queue.js";
18
+ export { INTEGER_REGEX, NON_NEGATIVE_INTEGER_REGEX } from "./regex.js";
19
+ export { anyAbortSignal, disposableAllAbortSignal, listenAbort, runWithSignal } from "./signal.js";
20
+ export { asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, replicateReadableStream, streamToAsyncIteratorObject, traceReadableStream, wrapReadableStream } from "./stream.js";
21
+ export { getTracer, recordSpanError, runInSpanContext, runWithSpan, setSpanAttributeIfDefined, setTracer, startSpan, toSpanAttributeValue, toTracingException } from "./tracing.js";
22
+ export { value } from "./value.js";
23
+ export { AbortError, AsyncIteratorClass, SequentialIdGenerator, getOrBind, isAsyncIteratorObject, isNonPrimitive, isNonPrimitive as isTypescriptObject, parseEmptyableJSON, safeDecodeURIComponent, safeEncodeURIComponent, sequential, sleep, stringifyJSON, throwIfAborted, toArray } from "@standard-server/shared";
@@ -0,0 +1,66 @@
1
+ import { Promisable, PromiseWithError, ThrowableError } from "./types.js";
2
+ export type InterceptableOptions = Record<string, any>;
3
+ export type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, "next"> & {
4
+ next(options?: TOptions): TResult;
5
+ };
6
+ export type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
7
+ /**
8
+ * Infers the error type of `next()` from `PromiseWithError`, or `unknown` when
9
+ * `next()` doesn't carry a typed error (e.g. it returns a plain promise).
10
+ */
11
+ export type InferNextError<TOptions extends {
12
+ next: () => any;
13
+ }> = ReturnType<TOptions["next"]> extends PromiseWithError<any, infer E> ? E : unknown;
14
+ /**
15
+ * Can used for interceptors or middlewares
16
+ */
17
+ export declare function onStart<TOptions extends {
18
+ next: () => any;
19
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions["next"]>>>;
20
+ /**
21
+ * Can used for interceptors or middlewares
22
+ */
23
+ export declare function onSuccess<TOptions extends {
24
+ next: () => any;
25
+ }, 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"]>>>;
26
+ /**
27
+ * Creates an interceptor or middleware that invokes a callback whenever an error
28
+ * is thrown. The error is rethrown after the callback completes.
29
+ *
30
+ * @see {@link https://orpc.dev/docs/adapters/fetch-api | Fetch API Adapter}
31
+ */
32
+ export declare function onError<TOptions extends {
33
+ next: () => any;
34
+ }, TRest extends any[]>(callback: NoInfer<(error: InferNextError<TOptions>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions["next"]>>>;
35
+ export type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
36
+ /**
37
+ * Can used for interceptors or middlewares
38
+ */
39
+ export declare function onFinish<TOptions extends {
40
+ next: () => any;
41
+ }, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions["next"]>>, InferNextError<TOptions>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions["next"]>>>;
42
+ /**
43
+ * Creates a middleware or interceptor that invokes a callback when the returned async
44
+ * iterator object throws an error while being consumed.
45
+ *
46
+ * This does not replace the `onError`. `onError` only fires on the
47
+ * initial call (before the interceptor returns the iterator), whereas this
48
+ * callback only fires while consuming the iterator. Use both together to
49
+ * catch all possible errors.
50
+ */
51
+ export declare function onAsyncIteratorObjectError<TOptions extends {
52
+ next: () => any;
53
+ }, TRest extends any[]>(callback: NoInfer<(error: ThrowableError | InferNextError<TOptions>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions["next"]>>>;
54
+ /**
55
+ * Creates an interceptor that invokes a callback when the returned readable
56
+ * stream errors while being consumed.
57
+ *
58
+ * This does not replace the `onError`. `onError` only fires on the
59
+ * initial call (before the interceptor returns the stream), whereas this
60
+ * callback only fires while consuming the stream. Use both together to catch
61
+ * all possible errors.
62
+ */
63
+ export declare function onReadableStreamError<TOptions extends {
64
+ next: () => any;
65
+ }, TRest extends any[]>(callback: NoInfer<(error: ThrowableError | InferNextError<TOptions>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions["next"]>>>;
66
+ export declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: undefined | Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
@@ -0,0 +1,119 @@
1
+ import { wrapAsyncIterator } from "./iterator.js";
2
+ import { override } from "./proxy.js";
3
+ import { wrapReadableStream } from "./stream.js";
4
+ import { isAsyncIteratorObject } from "@standard-server/shared";
5
+ // src/interceptor.ts
6
+ /**
7
+ * Can used for interceptors or middlewares
8
+ */
9
+ function onStart(callback) {
10
+ return async (options, ...rest) => {
11
+ await callback(options, ...rest);
12
+ return await options.next();
13
+ };
14
+ }
15
+ /**
16
+ * Can used for interceptors or middlewares
17
+ */
18
+ function onSuccess(callback) {
19
+ return async (options, ...rest) => {
20
+ const result = await options.next();
21
+ await callback(result, options, ...rest);
22
+ return result;
23
+ };
24
+ }
25
+ /**
26
+ * Creates an interceptor or middleware that invokes a callback whenever an error
27
+ * is thrown. The error is rethrown after the callback completes.
28
+ *
29
+ * @see {@link https://orpc.dev/docs/adapters/fetch-api | Fetch API Adapter}
30
+ */
31
+ function onError(callback) {
32
+ return async (options, ...rest) => {
33
+ try {
34
+ return await options.next();
35
+ } catch (error) {
36
+ await callback(error, options, ...rest);
37
+ throw error;
38
+ }
39
+ };
40
+ }
41
+ /**
42
+ * Can used for interceptors or middlewares
43
+ */
44
+ function onFinish(callback) {
45
+ return async (options, ...rest) => {
46
+ let state;
47
+ try {
48
+ const result = await options.next();
49
+ state = [
50
+ null,
51
+ result,
52
+ true
53
+ ];
54
+ return result;
55
+ } catch (error) {
56
+ state = [
57
+ error,
58
+ void 0,
59
+ false
60
+ ];
61
+ throw error;
62
+ } finally {
63
+ await callback(state, options, ...rest);
64
+ }
65
+ };
66
+ }
67
+ /**
68
+ * Creates a middleware or interceptor that invokes a callback when the returned async
69
+ * iterator object throws an error while being consumed.
70
+ *
71
+ * This does not replace the `onError`. `onError` only fires on the
72
+ * initial call (before the interceptor returns the iterator), whereas this
73
+ * callback only fires while consuming the iterator. Use both together to
74
+ * catch all possible errors.
75
+ */
76
+ function onAsyncIteratorObjectError(callback) {
77
+ return async (options, ...rest) => {
78
+ const output = await options.next();
79
+ if (!isAsyncIteratorObject(output)) return output;
80
+ /**
81
+ * @warning
82
+ * Remember use `override` for AsyncIteratorObject to remain other special properties
83
+ */
84
+ return override(output, wrapAsyncIterator(output, { onError: (error) => callback(error, options, ...rest) }));
85
+ };
86
+ }
87
+ /**
88
+ * Creates an interceptor that invokes a callback when the returned readable
89
+ * stream errors while being consumed.
90
+ *
91
+ * This does not replace the `onError`. `onError` only fires on the
92
+ * initial call (before the interceptor returns the stream), whereas this
93
+ * callback only fires while consuming the stream. Use both together to catch
94
+ * all possible errors.
95
+ */
96
+ function onReadableStreamError(callback) {
97
+ return async (options, ...rest) => {
98
+ const output = await options.next();
99
+ if (!(output instanceof ReadableStream)) return output;
100
+ /**
101
+ * @warning
102
+ * Remember use `override` for ReadableStream to remain other special properties
103
+ */
104
+ return override(output, wrapReadableStream(output, { onError: (error) => callback(error, options, ...rest) }));
105
+ };
106
+ }
107
+ function intercept(interceptors, options, main) {
108
+ if (!interceptors?.length) return main(options);
109
+ const next = (options, index) => {
110
+ const interceptor = interceptors[index];
111
+ if (!interceptor) return main(options);
112
+ return interceptor({
113
+ ...options,
114
+ next: (newOptions = options) => next(newOptions, index + 1)
115
+ });
116
+ };
117
+ return next(options, 0);
118
+ }
119
+ export { intercept, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess };
@@ -0,0 +1,55 @@
1
+ import { StartSpanOptions } from "./tracing.js";
2
+ import { Promisable, PromiseWithError, ThrowableError } from "./types.js";
3
+ import { AsyncIteratorClass } from "@standard-server/shared";
4
+ export interface WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn> {
5
+ /**
6
+ * Any call to the original iterator will be executed inside this function.
7
+ * Useful when you want execution to happen within a specific context,
8
+ * such as AsyncLocalStorage.
9
+ */
10
+ runWith?: (<T>(run: () => Promise<T>) => Promisable<T>) | undefined;
11
+ mapResult?: ((result: IteratorResult<TYield, TReturn>) => Promisable<IteratorResult<TMappedYield, TMappedReturn>>) | undefined;
12
+ mapError?: ((error: ThrowableError) => Promisable<ThrowableError>) | undefined;
13
+ onError?: ((error: ThrowableError) => Promisable<void>) | undefined;
14
+ /**
15
+ * Execute after the stream finishes or is cancelled.
16
+ */
17
+ onFinish?: (() => Promisable<void>) | undefined;
18
+ }
19
+ export declare function wrapAsyncIterator<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { runWith, mapResult, mapError, onError, onFinish }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): NoInfer<AsyncIteratorClass<TMappedYield, TMappedReturn>>;
20
+ export declare function traceAsyncIterator<T, TReturn, TNext>(options: StartSpanOptions | string, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
21
+ export declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): AsyncIteratorClass<T, TReturn, TNext>[];
22
+ export interface ConsumeAsyncIteratorOptions<T, TReturn, TError> {
23
+ /**
24
+ * Called on each event
25
+ */
26
+ onEvent: (event: T) => void;
27
+ /**
28
+ * Called once error happens
29
+ */
30
+ onError?: ((error: TError) => void) | undefined;
31
+ /**
32
+ * Called once AsyncIteratorObject is done
33
+ *
34
+ * @remarks
35
+ * **Note**: If iterator is canceled, `undefined` can be passed on success
36
+ */
37
+ onSuccess?: ((value: TReturn | undefined) => void) | undefined;
38
+ /**
39
+ * Called once after onError or onSuccess
40
+ *
41
+ * @remarks
42
+ * **Note**: If iterator is canceled, `undefined` can be passed on success
43
+ */
44
+ onFinish?: ((state: [error: TError, data: undefined, isSuccess: false] | [error: null, data: TReturn | undefined, isSuccess: true]) => void) | undefined;
45
+ }
46
+ /**
47
+ * Consumes an AsyncIteratorObject with lifecycle callbacks.
48
+ *
49
+ * @remarks
50
+ * **Warning**: If no `onError` or `onFinish` is provided, errors are thrown into the unhandled rejection channel.
51
+ *
52
+ * @returns An unsubscribe callback that stops consuming and cleans up the iterator.
53
+ * @see {@link https://orpc.dev/docs/client/async-iterator-object#using-consumeasynciterator | AsyncIteratorObject in Client - Using consumeAsyncIterator}
54
+ */
55
+ export declare function consumeAsyncIterator<T, TReturn, TError = ThrowableError>(iterator: AsyncIterator<T, TReturn> | PromiseWithError<AsyncIterator<T, TReturn>, TError>, options: ConsumeAsyncIteratorOptions<T, TReturn, TError | ThrowableError>): () => Promise<void>;
@@ -0,0 +1,141 @@
1
+ import { once } from "./function.js";
2
+ import { AsyncIdQueue } from "./queue.js";
3
+ import { recordSpanError, runInSpanContext, startSpan } from "./tracing.js";
4
+ import { AsyncIteratorClass } from "@standard-server/shared";
5
+ // src/iterator.ts
6
+ function wrapAsyncIterator(iterator, { runWith, mapResult, mapError, onError, onFinish }) {
7
+ runWith ??= (run) => run();
8
+ let isDone;
9
+ return new AsyncIteratorClass(async () => {
10
+ try {
11
+ let result;
12
+ try {
13
+ result = await runWith(() => iterator.next());
14
+ isDone = result.done;
15
+ } catch (error) {
16
+ isDone = true;
17
+ throw error;
18
+ }
19
+ return mapResult ? await mapResult(result) : result;
20
+ } catch (error) {
21
+ await onError?.(error);
22
+ throw mapError ? await mapError(error) : error;
23
+ }
24
+ }, async (_state) => {
25
+ try {
26
+ if (!isDone) try {
27
+ await runWith(async () => iterator.return?.());
28
+ } catch (error) {
29
+ await onError?.(error);
30
+ throw error;
31
+ }
32
+ } finally {
33
+ await onFinish?.();
34
+ }
35
+ });
36
+ }
37
+ function traceAsyncIterator(options, iterator) {
38
+ const getSpan = once(() => startSpan(options));
39
+ return wrapAsyncIterator(iterator, {
40
+ runWith: (run) => runInSpanContext(getSpan(), run),
41
+ mapResult(result) {
42
+ getSpan()?.addEvent(result.done ? "completed" : "yielded");
43
+ return result;
44
+ },
45
+ onError(error) {
46
+ recordSpanError(getSpan(), error);
47
+ },
48
+ onFinish() {
49
+ getSpan()?.end();
50
+ }
51
+ });
52
+ }
53
+ function replicateAsyncIterator(source, count) {
54
+ const queue = new AsyncIdQueue();
55
+ const ids = Array.from({ length: count }, (_, i) => i.toString());
56
+ let isSourceFinished = false;
57
+ const start = once(async () => {
58
+ try {
59
+ while (true) {
60
+ const item = await source.next();
61
+ ids.forEach((id) => {
62
+ if (queue.isOpen(id)) queue.push(id, { next: item });
63
+ });
64
+ if (item.done) break;
65
+ }
66
+ } catch (error) {
67
+ ids.forEach((id) => {
68
+ if (queue.isOpen(id)) queue.push(id, { error });
69
+ });
70
+ } finally {
71
+ isSourceFinished = true;
72
+ }
73
+ });
74
+ return ids.map((id) => {
75
+ queue.open(id);
76
+ return new AsyncIteratorClass(async () => {
77
+ start();
78
+ const item = await queue.pull(id);
79
+ if (item.next) return item.next;
80
+ throw item.error;
81
+ }, async ({ kind, error }) => {
82
+ queue.close({
83
+ id,
84
+ reason: error
85
+ });
86
+ if (kind === "cancelled" && !queue.size && !isSourceFinished) {
87
+ isSourceFinished = true;
88
+ await source?.return?.();
89
+ }
90
+ });
91
+ });
92
+ }
93
+ /**
94
+ * Consumes an AsyncIteratorObject with lifecycle callbacks.
95
+ *
96
+ * @remarks
97
+ * **Warning**: If no `onError` or `onFinish` is provided, errors are thrown into the unhandled rejection channel.
98
+ *
99
+ * @returns An unsubscribe callback that stops consuming and cleans up the iterator.
100
+ * @see {@link https://orpc.dev/docs/client/async-iterator-object#using-consumeasynciterator | AsyncIteratorObject in Client - Using consumeAsyncIterator}
101
+ */
102
+ function consumeAsyncIterator(iterator, options) {
103
+ (async () => {
104
+ let onFinishState;
105
+ try {
106
+ const resolvedIterator = await iterator;
107
+ while (true) {
108
+ const { done, value } = await resolvedIterator.next();
109
+ if (done) {
110
+ const realValue = value;
111
+ onFinishState = [
112
+ null,
113
+ realValue,
114
+ true
115
+ ];
116
+ options.onSuccess?.(realValue);
117
+ break;
118
+ }
119
+ try {
120
+ options.onEvent(value);
121
+ } catch (error) {
122
+ await resolvedIterator.return?.();
123
+ throw error;
124
+ }
125
+ }
126
+ } catch (error) {
127
+ onFinishState = [
128
+ error,
129
+ void 0,
130
+ false
131
+ ];
132
+ options.onError?.(error);
133
+ } finally {
134
+ options.onFinish?.(onFinishState);
135
+ }
136
+ })();
137
+ return async () => {
138
+ await (await iterator)?.return?.();
139
+ };
140
+ }
141
+ export { consumeAsyncIterator, replicateAsyncIterator, traceAsyncIterator, wrapAsyncIterator };
@@ -0,0 +1,62 @@
1
+ import { AnyFunction } from "./function.js";
2
+ export type Segment = string | number;
3
+ export declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
4
+ maps: Segment[][];
5
+ values: unknown[];
6
+ };
7
+ /**
8
+ * Get constructor of the value
9
+ *
10
+ */
11
+ export declare function getConstructor(value: unknown): Function | null | undefined;
12
+ export declare function getConstructors(value: unknown): Generator<Function>;
13
+ /**
14
+ * Checks whether a value is a plain object, including objects created with
15
+ * `Object.create(null)`.
16
+ */
17
+ export declare function isPlainObject(value: unknown): value is Record<PropertyKey, unknown>;
18
+ /**
19
+ * Checks whether a value is an array or a plain object, i.e. something whose keys can be walked.
20
+ */
21
+ export declare function isPlainObjectOrArray(value: unknown): value is unknown[] | Record<PropertyKey, unknown>;
22
+ /**
23
+ * Returns `object[key]` only when it is an own property, so keys like
24
+ * `toString` do not resolve through the prototype chain.
25
+ */
26
+ export declare function getOwn<T extends object>(object: T, key: PropertyKey): T[keyof T] | undefined;
27
+ export declare function get(object: unknown, path: readonly PropertyKey[]): unknown;
28
+ /**
29
+ * Sets a value at the given path, creating plain objects for intermediate keys as needed.
30
+ */
31
+ export declare function set(root: object, path: [PropertyKey, ...PropertyKey[]] | [...PropertyKey[], PropertyKey], value: unknown): void;
32
+ /**
33
+ * Sets `object[key]`, defining `__proto__` as an own property instead of re-parenting the object.
34
+ */
35
+ export declare function setOwn(object: object, key: PropertyKey, value: unknown): void;
36
+ /**
37
+ * Merges two values by copying the second over the first, repeating the merge one level deeper for
38
+ * nested plain objects. Anything that is not a pair of plain objects is replaced by the second one.
39
+ */
40
+ export declare function mergeTwoLevels(first: unknown, second: unknown): unknown;
41
+ export declare function omit<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Omit<T, K>;
42
+ export declare function pick<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Pick<T, K>;
43
+ /**
44
+ * Deep clones arrays and plain objects, leaving every other value as is.
45
+ * Circular and shared references are preserved in the copy.
46
+ */
47
+ export declare function clone<T>(value: T): T;
48
+ export declare function copyOnWrite(parent: object, key: PropertyKey, original: unknown): unknown;
49
+ export declare function isPropertyKey(value: unknown): value is PropertyKey;
50
+ export declare const NullProtoObj: {
51
+ new <T extends Record<PropertyKey, unknown>>(): T;
52
+ };
53
+ /**
54
+ * Returns an object containing all methods of the given object, with each
55
+ * method bound to the original object instance.
56
+ *
57
+ * Methods are collected from both the object itself and its prototype chain
58
+ * (excluding `Object.prototype` and the `constructor` property).
59
+ */
60
+ export declare function bindMethods<T extends object>(obj: T, options?: {
61
+ unbound?: (keyof T)[];
62
+ }): Pick<T, { [K in keyof T]: T[K] extends AnyFunction ? K : never; }[keyof T]>;
package/dist/object.js ADDED
@@ -0,0 +1,194 @@
1
+ import { getOrBind, isNonPrimitive } from "@standard-server/shared";
2
+ // src/object.ts
3
+ function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
4
+ if (check(payload)) {
5
+ maps.push(segments);
6
+ values.push(payload);
7
+ } else if (Array.isArray(payload)) payload.forEach((v, i) => {
8
+ findDeepMatches(check, v, [...segments, i], maps, values);
9
+ });
10
+ else if (isPlainObject(payload)) for (const key of Object.keys(payload)) findDeepMatches(check, payload[key], [...segments, key], maps, values);
11
+ return {
12
+ maps,
13
+ values
14
+ };
15
+ }
16
+ /**
17
+ * Get constructor of the value
18
+ *
19
+ */
20
+ function getConstructor(value) {
21
+ if (!isNonPrimitive(value)) return null;
22
+ return Object.getPrototypeOf(value)?.constructor;
23
+ }
24
+ function* getConstructors(value) {
25
+ if (!isNonPrimitive(value)) return;
26
+ let proto = Object.getPrototypeOf(value);
27
+ while (proto !== null) {
28
+ if (proto.constructor) yield proto.constructor;
29
+ proto = Object.getPrototypeOf(proto);
30
+ }
31
+ }
32
+ /**
33
+ * Checks whether a value is a plain object, including objects created with
34
+ * `Object.create(null)`.
35
+ */
36
+ function isPlainObject(value) {
37
+ if (!value || typeof value !== "object") return false;
38
+ const proto = Object.getPrototypeOf(value);
39
+ return proto === Object.prototype || !proto || !proto.constructor;
40
+ }
41
+ /**
42
+ * Checks whether a value is an array or a plain object, i.e. something whose keys can be walked.
43
+ */
44
+ function isPlainObjectOrArray(value) {
45
+ return Array.isArray(value) || isPlainObject(value);
46
+ }
47
+ /**
48
+ * Returns `object[key]` only when it is an own property, so keys like
49
+ * `toString` do not resolve through the prototype chain.
50
+ */
51
+ function getOwn(object, key) {
52
+ return Object.hasOwn(object, key) ? object[key] : void 0;
53
+ }
54
+ function get(object, path) {
55
+ let current = object;
56
+ for (const key of path) {
57
+ if (!isNonPrimitive(current)) return;
58
+ current = getOwn(current, key);
59
+ }
60
+ return current;
61
+ }
62
+ /**
63
+ * Sets a value at the given path, creating plain objects for intermediate keys as needed.
64
+ */
65
+ function set(root, path, value) {
66
+ let current = root;
67
+ for (let i = 0; i < path.length - 1; i++) {
68
+ const key = path[i];
69
+ const next = getOwn(current, key);
70
+ if (!isNonPrimitive(next)) {
71
+ const child = {};
72
+ setOwn(current, key, child);
73
+ current = child;
74
+ } else current = next;
75
+ }
76
+ setOwn(current, path.at(-1), value);
77
+ }
78
+ /**
79
+ * Sets `object[key]`, defining `__proto__` as an own property instead of re-parenting the object.
80
+ */
81
+ function setOwn(object, key, value) {
82
+ if (key === "__proto__") Object.defineProperty(object, key, {
83
+ value,
84
+ writable: true,
85
+ enumerable: true,
86
+ configurable: true
87
+ });
88
+ else object[key] = value;
89
+ }
90
+ /**
91
+ * Merges two values by copying the second over the first, repeating the merge one level deeper for
92
+ * nested plain objects. Anything that is not a pair of plain objects is replaced by the second one.
93
+ */
94
+ function mergeTwoLevels(first, second) {
95
+ if (!isPlainObject(first) || !isPlainObject(second)) return second;
96
+ const result = {
97
+ ...first,
98
+ ...second
99
+ };
100
+ for (const key of Object.keys(second)) {
101
+ if (!Object.hasOwn(first, key)) continue;
102
+ const firstValue = first[key];
103
+ const secondValue = second[key];
104
+ if (isPlainObject(firstValue) && isPlainObject(secondValue)) result[key] = {
105
+ ...firstValue,
106
+ ...secondValue
107
+ };
108
+ }
109
+ return result;
110
+ }
111
+ function omit(obj, keys) {
112
+ const result = { ...obj };
113
+ for (const key of keys) delete result[key];
114
+ return result;
115
+ }
116
+ function pick(obj, keys) {
117
+ const result = {};
118
+ for (const key of keys) if (Object.hasOwn(obj, key)) result[key] = obj[key];
119
+ return result;
120
+ }
121
+ /**
122
+ * Deep clones arrays and plain objects, leaving every other value as is.
123
+ * Circular and shared references are preserved in the copy.
124
+ */
125
+ function clone(value) {
126
+ return cloneWithVisited(value, /* @__PURE__ */ new WeakMap());
127
+ }
128
+ function cloneWithVisited(value, visited) {
129
+ if (Array.isArray(value)) {
130
+ const existing = visited.get(value);
131
+ if (existing) return existing;
132
+ const result = [];
133
+ visited.set(value, result);
134
+ for (const item of value) result.push(cloneWithVisited(item, visited));
135
+ return result;
136
+ }
137
+ if (isPlainObject(value)) {
138
+ const existing = visited.get(value);
139
+ if (existing) return existing;
140
+ const result = {};
141
+ visited.set(value, result);
142
+ for (const key of Object.keys(value)) setOwn(result, key, cloneWithVisited(value[key], visited));
143
+ for (const sym of Object.getOwnPropertySymbols(value)) setOwn(result, sym, cloneWithVisited(value[sym], visited));
144
+ return result;
145
+ }
146
+ return value;
147
+ }
148
+ function copyOnWrite(parent, key, original) {
149
+ const value = parent[key];
150
+ if (value !== original) return value;
151
+ let copy;
152
+ if (Array.isArray(value)) copy = value.slice();
153
+ else if (isPlainObject(value)) copy = { ...value };
154
+ else return value;
155
+ setOwn(parent, key, copy);
156
+ return copy;
157
+ }
158
+ function isPropertyKey(value) {
159
+ const type = typeof value;
160
+ return type === "string" || type === "number" || type === "symbol";
161
+ }
162
+ const NullProtoObj = /* @__PURE__ */ (() => {
163
+ const e = function() {};
164
+ e.prototype = Object.create(null);
165
+ Object.freeze(e.prototype);
166
+ return e;
167
+ })();
168
+ /**
169
+ * Returns an object containing all methods of the given object, with each
170
+ * method bound to the original object instance.
171
+ *
172
+ * Methods are collected from both the object itself and its prototype chain
173
+ * (excluding `Object.prototype` and the `constructor` property).
174
+ */
175
+ function bindMethods(obj, options = {}) {
176
+ const unbound = new Set(options.unbound);
177
+ const methods = new NullProtoObj();
178
+ let current = obj;
179
+ while (current && current !== Object.prototype) {
180
+ for (const key of Object.getOwnPropertyNames(current)) {
181
+ if (key === "constructor" || key in methods) continue;
182
+ const val = getOrBind(obj, key, { bind: !unbound.has(key) });
183
+ if (typeof val === "function") methods[key] = val;
184
+ }
185
+ for (const sym of Object.getOwnPropertySymbols(current)) {
186
+ if (sym in methods) continue;
187
+ const val = getOrBind(obj, sym, { bind: !unbound.has(sym) });
188
+ if (typeof val === "function") methods[sym] = val;
189
+ }
190
+ current = Object.getPrototypeOf(current);
191
+ }
192
+ return methods;
193
+ }
194
+ export { NullProtoObj, bindMethods, clone, copyOnWrite, findDeepMatches, get, getConstructor, getConstructors, getOwn, isPlainObject, isPlainObjectOrArray, isPropertyKey, mergeTwoLevels, omit, pick, set, setOwn };
@@ -0,0 +1,12 @@
1
+ export interface OrderablePlugin {
2
+ /** Unique name of the plugin, used for ordering and identification. */
3
+ name: string;
4
+ /** Plugins this plugin should execute before. */
5
+ before?: string[] | undefined;
6
+ /** Plugins this plugin should execute after. */
7
+ after?: string[] | undefined;
8
+ }
9
+ /**
10
+ * Sorts plugins based on their `before` and `after` dependencies.
11
+ */
12
+ export declare function sortPlugins<T extends OrderablePlugin>(plugins: T[]): T[];