feat: init
This commit is contained in:
21
node_modules/birpc/LICENSE
generated
vendored
Normal file
21
node_modules/birpc/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 Anthony Fu <https://github.com/antfu>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
163
node_modules/birpc/README.md
generated
vendored
Normal file
163
node_modules/birpc/README.md
generated
vendored
Normal file
@@ -0,0 +1,163 @@
|
||||
# birpc
|
||||
|
||||
[](https://www.npmjs.com/package/birpc)
|
||||
|
||||
Message-based two-way remote procedure call. Useful for WebSockets and Workers communication.
|
||||
|
||||
## Features
|
||||
|
||||
- Intuitive - call remote functions just like locals, with Promise to get the response
|
||||
- TypeScript - safe function calls for arguments and returns
|
||||
- Protocol agonostic - WebSocket, MessageChannel, any protocols with messages communication would work!
|
||||
- Zero deps, ~0.5KB
|
||||
|
||||
## Examples
|
||||
|
||||
### Using WebSocket
|
||||
|
||||
When using WebSocket, you need to pass your custom serializer and deserializer.
|
||||
|
||||
#### Client
|
||||
|
||||
```ts
|
||||
import type { ServerFunctions } from './types'
|
||||
|
||||
const ws = new WebSocket('ws://url')
|
||||
|
||||
const clientFunctions: ClientFunctions = {
|
||||
hey(name: string) {
|
||||
return `Hey ${name} from client`
|
||||
}
|
||||
}
|
||||
|
||||
const rpc = createBirpc<ServerFunctions>(
|
||||
clientFunctions,
|
||||
{
|
||||
post: data => ws.send(data),
|
||||
on: fn => ws.on('message', fn),
|
||||
// these are required when using WebSocket
|
||||
serialize: v => JSON.stringify(v),
|
||||
deserialize: v => JSON.parse(v),
|
||||
},
|
||||
)
|
||||
|
||||
await rpc.hi('Client') // Hi Client from server
|
||||
```
|
||||
|
||||
#### Server
|
||||
|
||||
```ts
|
||||
import type { ClientFunctions } from './types'
|
||||
import { WebSocketServer } from 'ws'
|
||||
|
||||
const serverFunctions: ServerFunctions = {
|
||||
hi(name: string) {
|
||||
return `Hi ${name} from server`
|
||||
}
|
||||
}
|
||||
|
||||
const wss = new WebSocketServer()
|
||||
|
||||
wss.on('connection', (ws) => {
|
||||
const rpc = createBirpc<ClientFunctions>(
|
||||
serverFunctions,
|
||||
{
|
||||
post: data => ws.send(data),
|
||||
on: fn => ws.on('message', fn),
|
||||
serialize: v => JSON.stringify(v),
|
||||
deserialize: v => JSON.parse(v),
|
||||
},
|
||||
)
|
||||
|
||||
await rpc.hey('Server') // Hey Server from client
|
||||
})
|
||||
```
|
||||
|
||||
### Circular References
|
||||
|
||||
As `JSON.stringify` does not supporting circular references, we recommend using [`structured-clone-es`](https://github.com/antfu/structured-clone-es) as the serializer when you expect to have circular references.
|
||||
|
||||
```ts
|
||||
import { parse, stringify } from 'structured-clone-es'
|
||||
|
||||
const rpc = createBirpc<ServerFunctions>(
|
||||
functions,
|
||||
{
|
||||
post: data => ws.send(data),
|
||||
on: fn => ws.on('message', fn),
|
||||
// use structured-clone-es as serializer
|
||||
serialize: v => stringify(v),
|
||||
deserialize: v => parse(v),
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
### Using MessageChannel
|
||||
|
||||
[MessageChannel](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel) will automatically serialize the message and support circular references out-of-box.
|
||||
|
||||
```ts
|
||||
export const channel = new MessageChannel()
|
||||
```
|
||||
|
||||
#### Bob
|
||||
|
||||
``` ts
|
||||
import type { AliceFunctions } from './types'
|
||||
import { channel } from './channel'
|
||||
|
||||
const Bob: BobFunctions = {
|
||||
hey(name: string) {
|
||||
return `Hey ${name}, I am Bob`
|
||||
}
|
||||
}
|
||||
|
||||
const rpc = createBirpc<AliceFunctions>(
|
||||
Bob,
|
||||
{
|
||||
post: data => channel.port1.postMessage(data),
|
||||
on: fn => channel.port1.on('message', fn),
|
||||
},
|
||||
)
|
||||
|
||||
await rpc.hi('Bob') // Hi Bob, I am Alice
|
||||
```
|
||||
|
||||
#### Alice
|
||||
|
||||
``` ts
|
||||
import type { BobFunctions } from './types'
|
||||
import { channel } from './channel'
|
||||
|
||||
const Alice: AliceFunctions = {
|
||||
hi(name: string) {
|
||||
return `Hi ${name}, I am Alice`
|
||||
}
|
||||
}
|
||||
|
||||
const rpc = createBirpc<BobFunctions>(
|
||||
Alice,
|
||||
{
|
||||
post: data => channel.port2.postMessage(data),
|
||||
on: fn => channel.port2.on('message', fn),
|
||||
},
|
||||
)
|
||||
|
||||
await rpc.hey('Alice') // Hey Alice, I am Bob
|
||||
```
|
||||
|
||||
### One-to-multiple Communication
|
||||
|
||||
Refer to [./test/group.test.ts](./test/group.test.ts) as an example.
|
||||
|
||||
## Sponsors
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
|
||||
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
## License
|
||||
|
||||
[MIT](./LICENSE) License © 2021 [Anthony Fu](https://github.com/antfu)
|
||||
235
node_modules/birpc/dist/index.d.mts
generated
vendored
Normal file
235
node_modules/birpc/dist/index.d.mts
generated
vendored
Normal file
@@ -0,0 +1,235 @@
|
||||
//#region src/messages.d.ts
|
||||
declare const TYPE_REQUEST: "q";
|
||||
interface RpcRequest {
|
||||
/**
|
||||
* Type
|
||||
*/
|
||||
t: typeof TYPE_REQUEST;
|
||||
/**
|
||||
* ID
|
||||
*/
|
||||
i?: string;
|
||||
/**
|
||||
* Method
|
||||
*/
|
||||
m: string;
|
||||
/**
|
||||
* Arguments
|
||||
*/
|
||||
a: any[];
|
||||
/**
|
||||
* Optional
|
||||
*/
|
||||
o?: boolean;
|
||||
}
|
||||
//#endregion
|
||||
//#region src/utils.d.ts
|
||||
type ArgumentsType<T> = T extends ((...args: infer A) => any) ? A : never;
|
||||
type ReturnType<T> = T extends ((...args: any) => infer R) ? R : never;
|
||||
type Thenable<T> = T | PromiseLike<T>;
|
||||
//#endregion
|
||||
//#region src/main.d.ts
|
||||
type PromisifyFn<T> = ReturnType<T> extends Promise<any> ? T : (...args: ArgumentsType<T>) => Promise<Awaited<ReturnType<T>>>;
|
||||
type BirpcResolver<This> = (this: This, name: string, resolved: (...args: unknown[]) => unknown) => Thenable<((...args: any[]) => any) | undefined>;
|
||||
interface ChannelOptions {
|
||||
/**
|
||||
* Function to post raw message
|
||||
*/
|
||||
post: (data: any, ...extras: any[]) => Thenable<any>;
|
||||
/**
|
||||
* Listener to receive raw message
|
||||
*/
|
||||
on: (fn: (data: any, ...extras: any[]) => void) => Thenable<any>;
|
||||
/**
|
||||
* Clear the listener when `$close` is called
|
||||
*/
|
||||
off?: (fn: (data: any, ...extras: any[]) => void) => Thenable<any>;
|
||||
/**
|
||||
* Custom function to serialize data
|
||||
*
|
||||
* by default it passes the data as-is
|
||||
*/
|
||||
serialize?: (data: any) => any;
|
||||
/**
|
||||
* Custom function to deserialize data
|
||||
*
|
||||
* by default it passes the data as-is
|
||||
*/
|
||||
deserialize?: (data: any) => any;
|
||||
/**
|
||||
* Call the methods with the RPC context or the original functions object
|
||||
*/
|
||||
bind?: 'rpc' | 'functions';
|
||||
/**
|
||||
* Custom meta data to attached to the RPC instance's `$meta` property
|
||||
*/
|
||||
meta?: any;
|
||||
}
|
||||
interface EventOptions<RemoteFunctions extends object = Record<string, unknown>, LocalFunctions extends object = Record<string, unknown>, Proxify extends boolean = true> {
|
||||
/**
|
||||
* Names of remote functions that do not need response.
|
||||
*/
|
||||
eventNames?: (keyof RemoteFunctions)[];
|
||||
/**
|
||||
* Maximum timeout for waiting for response, in milliseconds.
|
||||
*
|
||||
* @default 60_000
|
||||
*/
|
||||
timeout?: number;
|
||||
/**
|
||||
* Whether to proxy the remote functions.
|
||||
*
|
||||
* When `proxify` is false, calling the remote function
|
||||
* with `rpc.$call('method', ...args)` instead of `rpc.method(...args)`
|
||||
* explicitly is required.
|
||||
*
|
||||
* @default true
|
||||
*/
|
||||
proxify?: Proxify;
|
||||
/**
|
||||
* Custom resolver to resolve function to be called
|
||||
*
|
||||
* For advanced use cases only
|
||||
*/
|
||||
resolver?: BirpcResolver<BirpcReturn<RemoteFunctions, LocalFunctions, Proxify>>;
|
||||
/**
|
||||
* Hook triggered before an event is sent to the remote
|
||||
*
|
||||
* @param req - Request parameters
|
||||
* @param next - Function to continue the request
|
||||
* @param resolve - Function to resolve the response directly
|
||||
*/
|
||||
onRequest?: (this: BirpcReturn<RemoteFunctions, LocalFunctions, Proxify>, req: RpcRequest, next: (req?: RpcRequest) => Promise<any>, resolve: (res: any) => void) => void | Promise<void>;
|
||||
/**
|
||||
* Custom error handler for errors occurred in local functions being called
|
||||
*
|
||||
* @returns `true` to prevent the error from being thrown
|
||||
*/
|
||||
onFunctionError?: (this: BirpcReturn<RemoteFunctions, LocalFunctions, Proxify>, error: Error, functionName: string, args: any[]) => boolean | void;
|
||||
/**
|
||||
* Custom error handler for errors occurred during serialization or messsaging
|
||||
*
|
||||
* @returns `true` to prevent the error from being thrown
|
||||
*/
|
||||
onGeneralError?: (this: BirpcReturn<RemoteFunctions, LocalFunctions, Proxify>, error: Error, functionName?: string, args?: any[]) => boolean | void;
|
||||
/**
|
||||
* Custom error handler for timeouts
|
||||
*
|
||||
* @returns `true` to prevent the error from being thrown
|
||||
*/
|
||||
onTimeoutError?: (this: BirpcReturn<RemoteFunctions, LocalFunctions, Proxify>, functionName: string, args: any[]) => boolean | void;
|
||||
}
|
||||
type BirpcOptions<RemoteFunctions extends object = Record<string, unknown>, LocalFunctions extends object = Record<string, unknown>, Proxify extends boolean = true> = EventOptions<RemoteFunctions, LocalFunctions, Proxify> & ChannelOptions;
|
||||
type BirpcFn<T> = PromisifyFn<T> & {
|
||||
/**
|
||||
* Send event without asking for response
|
||||
*/
|
||||
asEvent: (...args: ArgumentsType<T>) => Promise<void>;
|
||||
};
|
||||
interface BirpcReturnBuiltin<RemoteFunctions, LocalFunctions = Record<string, unknown>> {
|
||||
/**
|
||||
* Raw functions object
|
||||
*/
|
||||
$functions: LocalFunctions;
|
||||
/**
|
||||
* Whether the RPC is closed
|
||||
*/
|
||||
readonly $closed: boolean;
|
||||
/**
|
||||
* Custom meta data attached to the RPC instance
|
||||
*/
|
||||
readonly $meta: any;
|
||||
/**
|
||||
* Close the RPC connection
|
||||
*/
|
||||
$close: (error?: Error) => void;
|
||||
/**
|
||||
* Reject pending calls
|
||||
*/
|
||||
$rejectPendingCalls: (handler?: PendingCallHandler) => Promise<void>[];
|
||||
/**
|
||||
* Call the remote function and wait for the result.
|
||||
* An alternative to directly calling the function
|
||||
*/
|
||||
$call: <K$1 extends keyof RemoteFunctions>(method: K$1, ...args: ArgumentsType<RemoteFunctions[K$1]>) => Promise<Awaited<ReturnType<RemoteFunctions[K$1]>>>;
|
||||
/**
|
||||
* Same as `$call`, but returns `undefined` if the function is not defined on the remote side.
|
||||
*/
|
||||
$callOptional: <K$1 extends keyof RemoteFunctions>(method: K$1, ...args: ArgumentsType<RemoteFunctions[K$1]>) => Promise<Awaited<ReturnType<RemoteFunctions[K$1]> | undefined>>;
|
||||
/**
|
||||
* Send event without asking for response
|
||||
*/
|
||||
$callEvent: <K$1 extends keyof RemoteFunctions>(method: K$1, ...args: ArgumentsType<RemoteFunctions[K$1]>) => Promise<void>;
|
||||
/**
|
||||
* Call the remote function with the raw options.
|
||||
*/
|
||||
$callRaw: (options: {
|
||||
method: string;
|
||||
args: unknown[];
|
||||
event?: boolean;
|
||||
optional?: boolean;
|
||||
}) => Promise<Awaited<ReturnType<any>>[]>;
|
||||
}
|
||||
type ProxifiedRemoteFunctions<RemoteFunctions extends object = Record<string, unknown>> = { [K in keyof RemoteFunctions]: BirpcFn<RemoteFunctions[K]> };
|
||||
type BirpcReturn<RemoteFunctions extends object = Record<string, unknown>, LocalFunctions extends object = Record<string, unknown>, Proxify extends boolean = true> = Proxify extends true ? ProxifiedRemoteFunctions<RemoteFunctions> & BirpcReturnBuiltin<RemoteFunctions, LocalFunctions> : BirpcReturnBuiltin<RemoteFunctions, LocalFunctions>;
|
||||
interface CallRawOptions {
|
||||
method: string;
|
||||
args: unknown[];
|
||||
event?: boolean;
|
||||
optional?: boolean;
|
||||
}
|
||||
type PendingCallHandler = (options: Pick<PromiseEntry, 'method' | 'reject'>) => void | Promise<void>;
|
||||
interface PromiseEntry {
|
||||
resolve: (arg: any) => void;
|
||||
reject: (error: any) => void;
|
||||
method: string;
|
||||
timeoutId?: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
declare const setTimeout: typeof globalThis.setTimeout;
|
||||
declare function createBirpc<RemoteFunctions extends object = Record<string, unknown>, LocalFunctions extends object = Record<string, unknown>, Proxify extends boolean = true>($functions: LocalFunctions, options: BirpcOptions<RemoteFunctions, LocalFunctions, Proxify>): BirpcReturn<RemoteFunctions, LocalFunctions, Proxify>;
|
||||
//#endregion
|
||||
//#region src/group.d.ts
|
||||
interface BirpcGroupReturnBuiltin<RemoteFunctions> {
|
||||
/**
|
||||
* Call the remote function and wait for the result.
|
||||
* An alternative to directly calling the function
|
||||
*/
|
||||
$call: <K$1 extends keyof RemoteFunctions>(method: K$1, ...args: ArgumentsType<RemoteFunctions[K$1]>) => Promise<Awaited<ReturnType<RemoteFunctions[K$1]>>[]>;
|
||||
/**
|
||||
* Same as `$call`, but returns `undefined` if the function is not defined on the remote side.
|
||||
*/
|
||||
$callOptional: <K$1 extends keyof RemoteFunctions>(method: K$1, ...args: ArgumentsType<RemoteFunctions[K$1]>) => Promise<Awaited<ReturnType<RemoteFunctions[K$1]> | undefined>>;
|
||||
/**
|
||||
* Send event without asking for response
|
||||
*/
|
||||
$callEvent: <K$1 extends keyof RemoteFunctions>(method: K$1, ...args: ArgumentsType<RemoteFunctions[K$1]>) => Promise<void>;
|
||||
/**
|
||||
* Call the remote function with the raw options.
|
||||
*/
|
||||
$callRaw: (options: {
|
||||
method: string;
|
||||
args: unknown[];
|
||||
event?: boolean;
|
||||
optional?: boolean;
|
||||
}) => Promise<Awaited<ReturnType<any>>[]>;
|
||||
}
|
||||
interface BirpcGroupFn<T> {
|
||||
/**
|
||||
* Call the remote function and wait for the result.
|
||||
*/
|
||||
(...args: ArgumentsType<T>): Promise<Awaited<ReturnType<T>>[]>;
|
||||
/**
|
||||
* Send event without asking for response
|
||||
*/
|
||||
asEvent: (...args: ArgumentsType<T>) => Promise<void>;
|
||||
}
|
||||
type BirpcGroupReturn<RemoteFunctions extends object = Record<string, unknown>, Proxify extends boolean = true> = Proxify extends true ? ProxifiedRemoteFunctions<RemoteFunctions> & BirpcGroupReturnBuiltin<RemoteFunctions> : BirpcGroupReturnBuiltin<RemoteFunctions>;
|
||||
interface BirpcGroup<RemoteFunctions extends object = Record<string, unknown>, LocalFunctions extends object = Record<string, unknown>, Proxify extends boolean = true> {
|
||||
readonly clients: BirpcReturn<RemoteFunctions, LocalFunctions, Proxify>[];
|
||||
readonly functions: LocalFunctions;
|
||||
readonly broadcast: BirpcGroupReturn<RemoteFunctions, Proxify>;
|
||||
updateChannels: (fn?: ((channels: ChannelOptions[]) => void)) => BirpcReturn<RemoteFunctions, LocalFunctions, Proxify>[];
|
||||
}
|
||||
declare function createBirpcGroup<RemoteFunctions extends object = Record<string, unknown>, LocalFunctions extends object = Record<string, unknown>, Proxify extends boolean = true>(functions: LocalFunctions, channels: ChannelOptions[] | (() => ChannelOptions[]), options?: EventOptions<RemoteFunctions, LocalFunctions, Proxify>): BirpcGroup<RemoteFunctions, LocalFunctions, Proxify>;
|
||||
//#endregion
|
||||
export { BirpcFn, BirpcGroup, BirpcGroupFn, BirpcGroupReturn, BirpcGroupReturnBuiltin, BirpcOptions, BirpcResolver, BirpcReturn, BirpcReturnBuiltin, CallRawOptions, ChannelOptions, EventOptions, PendingCallHandler, PromisifyFn, ProxifiedRemoteFunctions, createBirpc, createBirpcGroup };
|
||||
277
node_modules/birpc/dist/index.mjs
generated
vendored
Normal file
277
node_modules/birpc/dist/index.mjs
generated
vendored
Normal file
@@ -0,0 +1,277 @@
|
||||
//#region src/messages.ts
|
||||
const TYPE_REQUEST = "q";
|
||||
const TYPE_RESPONSE = "s";
|
||||
|
||||
//#endregion
|
||||
//#region src/utils.ts
|
||||
function createPromiseWithResolvers() {
|
||||
let resolve;
|
||||
let reject;
|
||||
return {
|
||||
promise: new Promise((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
}),
|
||||
resolve,
|
||||
reject
|
||||
};
|
||||
}
|
||||
const _cacheMap = /* @__PURE__ */ new WeakMap();
|
||||
function cachedMap(items, fn) {
|
||||
return items.map((i) => {
|
||||
let r = _cacheMap.get(i);
|
||||
if (!r) {
|
||||
r = fn(i);
|
||||
_cacheMap.set(i, r);
|
||||
}
|
||||
return r;
|
||||
});
|
||||
}
|
||||
const random = Math.random.bind(Math);
|
||||
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
|
||||
function nanoid(size = 21) {
|
||||
let id = "";
|
||||
let i = size;
|
||||
while (i--) id += urlAlphabet[random() * 64 | 0];
|
||||
return id;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/main.ts
|
||||
const DEFAULT_TIMEOUT = 6e4;
|
||||
const defaultSerialize = (i) => i;
|
||||
const defaultDeserialize = defaultSerialize;
|
||||
const { clearTimeout, setTimeout } = globalThis;
|
||||
function createBirpc($functions, options) {
|
||||
const { post, on, off = () => {}, eventNames = [], serialize = defaultSerialize, deserialize = defaultDeserialize, resolver, bind = "rpc", timeout = DEFAULT_TIMEOUT, proxify = true } = options;
|
||||
let $closed = false;
|
||||
const _rpcPromiseMap = /* @__PURE__ */ new Map();
|
||||
let _promiseInit;
|
||||
let rpc;
|
||||
async function _call(method, args, event, optional) {
|
||||
if ($closed) throw new Error(`[birpc] rpc is closed, cannot call "${method}"`);
|
||||
const req = {
|
||||
m: method,
|
||||
a: args,
|
||||
t: TYPE_REQUEST
|
||||
};
|
||||
if (optional) req.o = true;
|
||||
const send = async (_req) => post(serialize(_req));
|
||||
if (event) {
|
||||
await send(req);
|
||||
return;
|
||||
}
|
||||
if (_promiseInit) try {
|
||||
await _promiseInit;
|
||||
} finally {
|
||||
_promiseInit = void 0;
|
||||
}
|
||||
let { promise, resolve, reject } = createPromiseWithResolvers();
|
||||
const id = nanoid();
|
||||
req.i = id;
|
||||
let timeoutId;
|
||||
async function handler(newReq = req) {
|
||||
if (timeout >= 0) {
|
||||
timeoutId = setTimeout(() => {
|
||||
try {
|
||||
if (options.onTimeoutError?.call(rpc, method, args) !== true) throw new Error(`[birpc] timeout on calling "${method}"`);
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
_rpcPromiseMap.delete(id);
|
||||
}, timeout);
|
||||
if (typeof timeoutId === "object") timeoutId = timeoutId.unref?.();
|
||||
}
|
||||
_rpcPromiseMap.set(id, {
|
||||
resolve,
|
||||
reject,
|
||||
timeoutId,
|
||||
method
|
||||
});
|
||||
await send(newReq);
|
||||
return promise;
|
||||
}
|
||||
try {
|
||||
if (options.onRequest) await options.onRequest.call(rpc, req, handler, resolve);
|
||||
else await handler();
|
||||
} catch (e) {
|
||||
if (options.onGeneralError?.call(rpc, e) !== true) throw e;
|
||||
return;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
_rpcPromiseMap.delete(id);
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
const builtinMethods = {
|
||||
$call: (method, ...args) => _call(method, args, false),
|
||||
$callOptional: (method, ...args) => _call(method, args, false, true),
|
||||
$callEvent: (method, ...args) => _call(method, args, true),
|
||||
$callRaw: (options$1) => _call(options$1.method, options$1.args, options$1.event, options$1.optional),
|
||||
$rejectPendingCalls,
|
||||
get $closed() {
|
||||
return $closed;
|
||||
},
|
||||
get $meta() {
|
||||
return options.meta;
|
||||
},
|
||||
$close,
|
||||
$functions
|
||||
};
|
||||
if (proxify) rpc = new Proxy({}, { get(_, method) {
|
||||
if (Object.prototype.hasOwnProperty.call(builtinMethods, method)) return builtinMethods[method];
|
||||
if (method === "then" && !eventNames.includes("then") && !("then" in $functions)) return void 0;
|
||||
const sendEvent = (...args) => _call(method, args, true);
|
||||
if (eventNames.includes(method)) {
|
||||
sendEvent.asEvent = sendEvent;
|
||||
return sendEvent;
|
||||
}
|
||||
const sendCall = (...args) => _call(method, args, false);
|
||||
sendCall.asEvent = sendEvent;
|
||||
return sendCall;
|
||||
} });
|
||||
else rpc = builtinMethods;
|
||||
function $close(customError) {
|
||||
$closed = true;
|
||||
_rpcPromiseMap.forEach(({ reject, method }) => {
|
||||
const error = /* @__PURE__ */ new Error(`[birpc] rpc is closed, cannot call "${method}"`);
|
||||
if (customError) {
|
||||
customError.cause ??= error;
|
||||
return reject(customError);
|
||||
}
|
||||
reject(error);
|
||||
});
|
||||
_rpcPromiseMap.clear();
|
||||
off(onMessage);
|
||||
}
|
||||
function $rejectPendingCalls(handler) {
|
||||
const handlerResults = Array.from(_rpcPromiseMap.values()).map(({ method, reject }) => {
|
||||
if (!handler) return reject(/* @__PURE__ */ new Error(`[birpc]: rejected pending call "${method}".`));
|
||||
return handler({
|
||||
method,
|
||||
reject
|
||||
});
|
||||
});
|
||||
_rpcPromiseMap.clear();
|
||||
return handlerResults;
|
||||
}
|
||||
async function onMessage(data, ...extra) {
|
||||
let msg;
|
||||
try {
|
||||
msg = deserialize(data);
|
||||
} catch (e) {
|
||||
if (options.onGeneralError?.call(rpc, e) !== true) throw e;
|
||||
return;
|
||||
}
|
||||
if (msg.t === TYPE_REQUEST) {
|
||||
const { m: method, a: args, o: optional } = msg;
|
||||
let result, error;
|
||||
let fn = await (resolver ? resolver.call(rpc, method, $functions[method]) : $functions[method]);
|
||||
if (optional) fn ||= () => void 0;
|
||||
if (!fn) error = /* @__PURE__ */ new Error(`[birpc] function "${method}" not found`);
|
||||
else try {
|
||||
result = await fn.apply(bind === "rpc" ? rpc : $functions, args);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
if (msg.i) {
|
||||
if (error && options.onFunctionError) {
|
||||
if (options.onFunctionError.call(rpc, error, method, args) === true) return;
|
||||
}
|
||||
if (!error) try {
|
||||
await post(serialize({
|
||||
t: TYPE_RESPONSE,
|
||||
i: msg.i,
|
||||
r: result
|
||||
}), ...extra);
|
||||
return;
|
||||
} catch (e) {
|
||||
error = e;
|
||||
if (options.onGeneralError?.call(rpc, e, method, args) !== true) throw e;
|
||||
}
|
||||
try {
|
||||
await post(serialize({
|
||||
t: TYPE_RESPONSE,
|
||||
i: msg.i,
|
||||
e: error
|
||||
}), ...extra);
|
||||
} catch (e) {
|
||||
if (options.onGeneralError?.call(rpc, e, method, args) !== true) throw e;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const { i: ack, r: result, e: error } = msg;
|
||||
const promise = _rpcPromiseMap.get(ack);
|
||||
if (promise) {
|
||||
clearTimeout(promise.timeoutId);
|
||||
if (error) promise.reject(error);
|
||||
else promise.resolve(result);
|
||||
}
|
||||
_rpcPromiseMap.delete(ack);
|
||||
}
|
||||
}
|
||||
_promiseInit = on(onMessage);
|
||||
return rpc;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/group.ts
|
||||
function createBirpcGroup(functions, channels, options = {}) {
|
||||
const { proxify = true } = options;
|
||||
const getChannels = () => typeof channels === "function" ? channels() : channels;
|
||||
const getClients = (channels$1 = getChannels()) => cachedMap(channels$1, (s) => createBirpc(functions, {
|
||||
...options,
|
||||
...s
|
||||
}));
|
||||
function _boardcast(options$1) {
|
||||
const clients = getClients();
|
||||
return Promise.all(clients.map((c) => c.$callRaw(options$1)));
|
||||
}
|
||||
const broadcastBuiltin = {
|
||||
$call: (method, ...args) => _boardcast({
|
||||
method,
|
||||
args,
|
||||
event: false
|
||||
}),
|
||||
$callOptional: (method, ...args) => _boardcast({
|
||||
method,
|
||||
args,
|
||||
event: false,
|
||||
optional: true
|
||||
}),
|
||||
$callEvent: (method, ...args) => _boardcast({
|
||||
method,
|
||||
args,
|
||||
event: true
|
||||
}),
|
||||
$callRaw: (options$1) => _boardcast(options$1)
|
||||
};
|
||||
const broadcastProxy = proxify ? new Proxy({}, { get(_, method) {
|
||||
if (Object.prototype.hasOwnProperty.call(broadcastBuiltin, method)) return broadcastBuiltin[method];
|
||||
const callbacks = getClients().map((c) => c[method]);
|
||||
const sendCall = (...args) => {
|
||||
return Promise.all(callbacks.map((i) => i(...args)));
|
||||
};
|
||||
sendCall.asEvent = async (...args) => {
|
||||
await Promise.all(callbacks.map((i) => i.asEvent(...args)));
|
||||
};
|
||||
return sendCall;
|
||||
} }) : broadcastBuiltin;
|
||||
function updateChannels(fn) {
|
||||
const channels$1 = getChannels();
|
||||
fn?.(channels$1);
|
||||
return getClients(channels$1);
|
||||
}
|
||||
getClients();
|
||||
return {
|
||||
get clients() {
|
||||
return getClients();
|
||||
},
|
||||
functions,
|
||||
updateChannels,
|
||||
broadcast: broadcastProxy
|
||||
};
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { createBirpc, createBirpcGroup };
|
||||
57
node_modules/birpc/package.json
generated
vendored
Normal file
57
node_modules/birpc/package.json
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"name": "birpc",
|
||||
"type": "module",
|
||||
"version": "4.0.0",
|
||||
"description": "Message based Two-way remote procedure call",
|
||||
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
|
||||
"license": "MIT",
|
||||
"funding": "https://github.com/sponsors/antfu",
|
||||
"homepage": "https://github.com/antfu-collective/birpc#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/antfu-collective/birpc.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/antfu-collective/birpc/issues"
|
||||
},
|
||||
"keywords": [
|
||||
"rpc",
|
||||
"messages"
|
||||
],
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": "./dist/index.mjs",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"main": "./dist/index.mjs",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.mts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^6.3.0",
|
||||
"@antfu/ni": "^28.0.0",
|
||||
"@types/node": "^24.10.1",
|
||||
"@vitest/coverage-v8": "^4.0.15",
|
||||
"bumpp": "^10.3.2",
|
||||
"eslint": "^9.39.1",
|
||||
"tinyexec": "^1.0.2",
|
||||
"tsdown": "0.17.0-beta.5",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.2.6",
|
||||
"vitest": "^4.0.15",
|
||||
"vitest-package-exports": "^0.1.1",
|
||||
"yaml": "^2.8.2"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsdown",
|
||||
"watch": "tsdown --watch",
|
||||
"lint": "eslint .",
|
||||
"release": "bumpp",
|
||||
"start": "tsx src/index.ts",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user