-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathindex.ts
328 lines (288 loc) · 8.51 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
export type ArgumentsType<T> = T extends (...args: infer A) => any ? A : never
export type ReturnType<T> = T extends (...args: any) => infer R ? R : never
export type PromisifyFn<T> = ReturnType<T> extends Promise<any>
? T
: (...args: ArgumentsType<T>) => Promise<Awaited<ReturnType<T>>>
export type BirpcResolver = (name: string, resolved: (...args: unknown[]) => unknown) => ((...args: unknown[]) => unknown) | undefined
export interface ChannelOptions {
/**
* Function to post raw message
*/
post: (data: any, ...extras: any[]) => any | Promise<any>
/**
* Listener to receive raw message
*/
on: (fn: (data: any, ...extras: any[]) => void) => any | Promise<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
}
export interface EventOptions<Remote> {
/**
* Names of remote functions that do not need response.
*/
eventNames?: (keyof Remote)[]
/**
* Maximum timeout for waiting for response, in milliseconds.
*
* @default 60_000
*/
timeout?: number
/**
* Custom resolver to resolve function to be called
*
* For advanced use cases only
*/
resolver?: BirpcResolver
/**
* Custom error handler
*/
onError?: (error: Error, functionName: string, args: any[]) => boolean | void
/**
* Custom error handler for timeouts
*/
onTimeoutError?: (functionName: string, args: any[]) => boolean | void
}
export type BirpcOptions<Remote> = EventOptions<Remote> & ChannelOptions
export type BirpcFn<T> = PromisifyFn<T> & {
/**
* Send event without asking for response
*/
asEvent: (...args: ArgumentsType<T>) => void
}
export 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>) => void
}
export type BirpcReturn<RemoteFunctions, LocalFunctions = Record<string, never>> = {
[K in keyof RemoteFunctions]: BirpcFn<RemoteFunctions[K]>
} & { $functions: LocalFunctions }
export type BirpcGroupReturn<RemoteFunctions> = {
[K in keyof RemoteFunctions]: BirpcGroupFn<RemoteFunctions[K]>
}
export interface BirpcGroup<RemoteFunctions, LocalFunctions = Record<string, never>> {
readonly clients: BirpcReturn<RemoteFunctions, LocalFunctions>[]
readonly functions: LocalFunctions
readonly broadcast: BirpcGroupReturn<RemoteFunctions>
updateChannels: (fn?: ((channels: ChannelOptions[]) => void)) => BirpcReturn<RemoteFunctions, LocalFunctions>[]
}
interface Request {
/**
* Type
*/
t: 'q'
/**
* ID
*/
i?: string
/**
* Method
*/
m: string
/**
* Arguments
*/
a: any[]
}
interface Response {
/**
* Type
*/
t: 's'
/**
* Id
*/
i: string
/**
* Result
*/
r?: any
/**
* Error
*/
e?: any
}
type RPCMessage = Request | Response
export const DEFAULT_TIMEOUT = 60_000 // 1 minute
function defaultSerialize(i: any) {
return i
}
const defaultDeserialize = defaultSerialize
// Store public APIs locally in case they are overridden later
const { clearTimeout, setTimeout } = globalThis
const random = Math.random.bind(Math)
export function createBirpc<RemoteFunctions = Record<string, never>, LocalFunctions extends object = Record<string, never>>(
functions: LocalFunctions,
options: BirpcOptions<RemoteFunctions>,
): BirpcReturn<RemoteFunctions, LocalFunctions> {
const {
post,
on,
eventNames = [],
serialize = defaultSerialize,
deserialize = defaultDeserialize,
resolver,
timeout = DEFAULT_TIMEOUT,
} = options
const rpcPromiseMap = new Map<string, { resolve: (arg: any) => void, reject: (error: any) => void, timeoutId?: ReturnType<typeof setTimeout> }>()
let _promise: Promise<any> | any
const rpc = new Proxy({}, {
get(_, method: string) {
if (method === '$functions')
return functions
// catch if "createBirpc" is returned from async function
if (method === 'then' && !eventNames.includes('then' as any) && !('then' in functions))
return undefined
const sendEvent = (...args: any[]) => {
post(serialize(<Request>{ m: method, a: args, t: 'q' }))
}
if (eventNames.includes(method as any)) {
sendEvent.asEvent = sendEvent
return sendEvent
}
const sendCall = async (...args: any[]) => {
// Wait if `on` is promise
await _promise
return new Promise((resolve, reject) => {
const id = nanoid()
let timeoutId: ReturnType<typeof setTimeout> | undefined
if (timeout >= 0) {
timeoutId = setTimeout(() => {
try {
// Custom onTimeoutError handler can throw its own error too
options.onTimeoutError?.(method, args)
throw new Error(`[birpc] timeout on calling "${method}"`)
}
catch (e) {
reject(e)
}
rpcPromiseMap.delete(id)
}, timeout)
// For node.js, `unref` is not available in browser-like environments
if (typeof timeoutId === 'object')
timeoutId = timeoutId.unref?.()
}
rpcPromiseMap.set(id, { resolve, reject, timeoutId })
post(serialize(<Request>{ m: method, a: args, i: id, t: 'q' }))
})
}
sendCall.asEvent = sendEvent
return sendCall
},
}) as BirpcReturn<RemoteFunctions, LocalFunctions>
_promise = on(async (data, ...extra) => {
const msg = deserialize(data) as RPCMessage
if (msg.t === 'q') {
const { m: method, a: args } = msg
let result, error: any
const fn = resolver
? resolver(method, (functions as any)[method])
: (functions as any)[method]
if (!fn) {
error = new Error(`[birpc] function "${method}" not found`)
}
else {
try {
result = await fn.apply(rpc, args)
}
catch (e) {
error = e
}
}
if (msg.i) {
if (error && options.onError)
options.onError(error, method, args)
post(serialize(<Response>{ t: 's', i: msg.i, r: result, e: error }), ...extra)
}
}
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)
}
})
return rpc
}
const cacheMap = new WeakMap<any, any>()
export function cachedMap<T, R>(items: T[], fn: ((i: T) => R)): R[] {
return items.map((i) => {
let r = cacheMap.get(i)
if (!r) {
r = fn(i)
cacheMap.set(i, r)
}
return r
})
}
export function createBirpcGroup<RemoteFunctions = Record<string, never>, LocalFunctions extends object = Record<string, never>>(
functions: LocalFunctions,
channels: ChannelOptions[] | (() => ChannelOptions[]),
options: EventOptions<RemoteFunctions> = {},
): BirpcGroup<RemoteFunctions, LocalFunctions> {
const getChannels = () => typeof channels === 'function' ? channels() : channels
const getClients = (channels = getChannels()) => cachedMap(channels, s => createBirpc(functions, { ...options, ...s }))
const broadcastProxy = new Proxy({}, {
get(_, method) {
const client = getClients()
const callbacks = client.map(c => (c as any)[method])
const sendCall = (...args: any[]) => {
return Promise.all(callbacks.map(i => i(...args)))
}
sendCall.asEvent = (...args: any[]) => {
callbacks.map(i => i.asEvent(...args))
}
return sendCall
},
}) as BirpcGroupReturn<RemoteFunctions>
function updateChannels(fn?: ((channels: ChannelOptions[]) => void)) {
const channels = getChannels()
fn?.(channels)
return getClients(channels)
}
getClients()
return {
get clients() {
return getClients()
},
functions,
updateChannels,
broadcast: broadcastProxy,
/**
* @deprecated use `broadcast`
*/
// @ts-expect-error deprecated
boardcast: broadcastProxy,
}
}
// port from nanoid
// https://github.com/ai/nanoid
const urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
function nanoid(size = 21) {
let id = ''
let i = size
while (i--)
id += urlAlphabet[(random() * 64) | 0]
return id
}