feat: init

This commit is contained in:
2026-02-13 22:02:30 +01:00
commit 8f9ff830fb
16711 changed files with 3307340 additions and 0 deletions

235
node_modules/birpc/dist/index.d.mts generated vendored Normal file
View 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
View 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 };