forked from WorldBrain/Memex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webextensionRPC.ts
410 lines (376 loc) · 13.7 KB
/
webextensionRPC.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// A Remote Procedure Call abstraction around the message passing available to
// WebExtension scripts. Usable to call a function in the background script from
// a tab's content script, or vice versa.
//
// The calling side always gets a Promise of the return value. The executing
// (remote) function can be an async function (= it returns a Promise), whose
// completion then will then be waited for.
// Example use:
//
// === background.js ===
// function myFunc(arg) {
// return arg*2
// }
// makeRemotelyCallable({myFunc})
//
// === content_script.js ===
// const myRemoteFunc = remoteFunction('myFunc')
// myRemoteFunc(21).then(result => { ... result is 42! ... })
import mapValues from 'lodash/fp/mapValues'
import browser from 'webextension-polyfill'
import { EventEmitter } from 'events'
import { PortBasedRPCManager, RpcSideName, RpcRole } from 'src/util/rpc/rpc'
import type { RemoteFunctionImplementations } from 'src/util/remote-functions-background'
import type { Arguments, default as TypedEventEmitter } from 'typed-emitter'
import type { AuthRemoteEvents } from 'src/authentication/background/types'
import type { ContentSharingEvents } from 'src/content-sharing/background/types'
import type { PersonalCloudBackgroundEvents } from '../personal-cloud/background/types'
export class RpcError extends Error {
constructor(message: string) {
super(message)
this.name = this.constructor.name
}
}
export type RemoteFunctionRole = 'provider' | 'caller'
export type RemoteFunction<
Role extends RemoteFunctionRole,
Params,
Returns = void
> = Role extends 'provider'
? (info: { tab: { id: number } }, params: Params) => Promise<Returns>
: (params: Params) => Promise<Returns>
export type RemotePositionalFunction<
Role extends RemoteFunctionRole,
Params extends Array<any>,
Returns = void
> = Role extends 'provider'
? (info: { tab: { id: number } }, ...params: Params) => Promise<Returns>
: (...params: Params) => Promise<Returns>
export type RemoteFunctionWithExtraArgs<
Role extends RemoteFunctionRole,
Params,
Returns = void
> = Role extends 'provider'
? {
withExtraArgs: true
function: RemoteFunction<Role, Params, Returns>
}
: RemoteFunction<Role, Params, Returns>
export type RemoteFunctionWithoutExtraArgs<
Role extends RemoteFunctionRole,
Params,
Returns = void
> = Role extends 'provider'
? {
withExtraArgs: false
function: (params: Params) => Promise<Returns>
}
: (params: Params) => Promise<Returns>
export function remoteFunctionWithExtraArgs<Params, Returns = void>(
f: RemoteFunction<'provider', Params, Returns>,
): RemoteFunctionWithExtraArgs<'provider', Params, Returns> {
return { withExtraArgs: true, function: f }
}
export function remoteFunctionWithoutExtraArgs<Params, Returns = void>(
f: (params: Params) => Promise<Returns>,
): RemoteFunctionWithoutExtraArgs<'provider', Params, Returns> {
return { withExtraArgs: false, function: f }
}
export function registerRemoteFunctions<Functions>(
functions: {
[Name in keyof Functions]:
| RemoteFunctionWithExtraArgs<'provider', any, any>
| RemoteFunctionWithoutExtraArgs<'provider', any, any>
},
) {
for (const [name, metadata] of Object.entries(functions)) {
const typedMetadata = metadata as
| RemoteFunctionWithExtraArgs<'provider', any, any>
| RemoteFunctionWithoutExtraArgs<'provider', any, any>
makeRemotelyCallable(
{ [name]: typedMetadata.function },
{ insertExtraArg: typedMetadata.withExtraArgs },
)
}
}
// === Initiating side ===
// The extra options available when calling a remote function
interface RPCOpts {
tabId?: number
}
// runInBackground and runInTab create a Proxy object that look like the real interface but actually call remote functions
//
// When the Proxy is asked for a property (such as a method)
// return a function that executes the requested method over the RPC interface
//
// Example Usage:
// interface AnalyticsInterface { trackEvent({}) => any }
// const analytics = runInBackground<AnalyticsInterface>()
// analytics.trackEvent(...)
// Runs a remoteFunction in the background script
export function runInBackground<T extends object>(): T {
return new Proxy<T>({} as T, {
get(target, property): (...args: any[]) => Promise<any> {
return async (...args) => {
if (!rpcConnection) {
throw new Error(
`runInBackground: RPC connection has not been setup.\nfn name: ${property.toString()}\nargs: ${args}\n\nIf you are calling direct from content-script code, instead pass it down from the global content-script.\n`,
)
}
return rpcConnection.postMessageRequestToExtension(
property.toString(),
args,
)
}
},
})
}
// Runs a remoteFunction in the content script on a certain tab
export function runInTab<T extends object>(
tabId: number,
opts?: { quietConsole?: boolean },
): T {
return new Proxy<T>({} as T, {
get(target, property): any {
return (...args) =>
rpcConnection.postMessageRequestToTab(
tabId,
property.toString(),
args,
opts?.quietConsole,
)
},
})
}
// Runs a remoteFunction in the content script on a certain tab by asking the background script to do so
export function runInTabViaBg<T extends object>(tabId): T {
return new Proxy<T>({} as T, {
get(target, property): any {
return (...args) =>
rpcConnection.postMessageRequestToTabViaExtension(
tabId,
property.toString(),
args,
)
},
})
}
// @depreciated - Don't call this function directly. Instead use the above typesafe version runInBackground
export function remoteFunction(
funcName: string,
{ tabId }: { tabId?: number } = {},
): any {
// console.log(`depreciated: remoteFunction call for: ${funcName}`)
if (tabId) {
return (...args) =>
rpcConnection.postMessageRequestToTab(tabId, funcName, args)
} else {
return (...args) =>
rpcConnection.postMessageRequestToExtension(funcName, args)
}
}
// === Executing side ===
const remotelyCallableFunctions =
typeof globalThis !== 'undefined' ? globalThis['remoteFunctions'] || {} : {}
if (typeof globalThis !== 'undefined') {
globalThis['remoteFunctions'] = remotelyCallableFunctions
}
export function setupRemoteFunctionsImplementations<T>(
implementations: RemoteFunctionImplementations<'provider'>,
): void {
for (const [group, functions] of Object.entries(implementations)) {
makeRemotelyCallableType<typeof functions>(functions)
}
}
// Register a function to allow remote scripts to call it.
// Arguments:
// - functions (required):
// An object with a {functionName: function} mapping.
// Each function will be callable with the given name.
// - options (optional): {
// insertExtraArg:
// If truthy, each executed function also receives, as its first
// argument before the arguments it was invoked with, an object with
// the details of the tab that sent the message.
// }
export function makeRemotelyCallableType<T = never>(
functions: { [P in keyof T]: T[P] },
{ insertExtraArg = false } = {},
) {
return makeRemotelyCallable(functions, { insertExtraArg })
}
// @Depreciated to call this directly. Should use the above typesafe version
export function makeRemotelyCallable<T>(
functions: { [P in keyof T]: T[P] },
{ insertExtraArg = false } = {},
) {
// Every function is passed an extra argument with sender information,
// so remove this from the call if this was not desired.
if (!insertExtraArg) {
// Replace each func with...
// @ts-ignore
const wrapFunctions = mapValues((func) =>
// ...a function that calls func, but hides the inserted argument.
// @ts-ignore
(extraArg, ...args) => func(...args),
)
// @ts-ignore
functions = wrapFunctions(functions)
}
for (const functionName of Object.keys(functions)) {
if (remotelyCallableFunctions.hasOwnProperty(functionName)) {
const error = `RPC function with name ${functionName} has already been registered `
console.warn(error)
}
}
// Add the functions to our global repetoir.
Object.assign(remotelyCallableFunctions, functions)
// console.log('assigned to remotelyCallableFunctions this new functions', {
// functions,
// })
}
export function clearRemotelyCallableFunctions() {
for (const key of Object.keys(remotelyCallableFunctions)) {
delete remotelyCallableFunctions[key]
}
}
export class RemoteFunctionRegistry {
registerRemotelyCallable(functions, { insertExtraArg = false } = {}) {
makeRemotelyCallable(functions, { insertExtraArg })
}
}
export function fakeRemoteFunctions(functions: {
[name: string]: (...args) => any
}) {
return (name) => {
if (!functions[name]) {
throw new Error(
`Tried to call fake remote function '${name}' for which no implementation was provided`,
)
}
return (...args) => {
return Promise.resolve(functions[name](...args))
}
}
}
export interface RemoteEventEmitter<T extends keyof RemoteEvents> {
emit<EventName extends keyof RemoteEvents[T]>(
eventName: EventName,
...args: Arguments<RemoteEvents[T][EventName]>
): Promise<void>
}
const __REMOTE_EVENT__ = '__REMOTE_EVENT__'
const __REMOTE_EVENT_TYPE__ = '__REMOTE_EVENT_TYPE__'
const __REMOTE_EVENT_NAME__ = '__REMOTE_EVENT_NAME__'
// Sending Side, (e.g. background script)
export function remoteEventEmitter<ModuleName extends keyof RemoteEvents>(
moduleName: ModuleName,
{ broadcastToTabs = false } = {},
): RemoteEventEmitter<ModuleName> {
const message = {
__REMOTE_EVENT__,
__REMOTE_EVENT_TYPE__: moduleName,
}
if (broadcastToTabs) {
return {
emit: async (eventName, ...args: any[]) => {
const tabs = (await browser.tabs.query({})) ?? []
for (const { id: tabId } of tabs) {
try {
await browser.tabs.sendMessage(tabId, {
...message,
__REMOTE_EVENT_NAME__: eventName,
data: args[0],
})
} catch (err) {
console.error(
`Remote event emitter "${moduleName}" failed to emit event "${String(
eventName,
)}" to tab ${tabId}:\n\tError message: "${
err.message
}"`,
)
}
}
},
}
}
return {
emit: async (eventName, ...args: any[]) => {
try {
await browser.runtime.sendMessage({
...message,
__REMOTE_EVENT_NAME__: eventName,
data: args[0],
})
} catch (err) {
console.error(
`Remote event emitter "${moduleName}" failed to emit event "${String(
eventName,
)}":\n\tError message: "${err.message}"`,
)
}
},
}
}
// Receiving Side (e.g. content script, options page, etc)
const remoteEventEmitters: RemoteEventEmitters = {} as RemoteEventEmitters
type RemoteEventEmitters = {
[K in keyof RemoteEvents]?: TypedRemoteEventEmitter<K>
}
export type TypedRemoteEventEmitter<
T extends keyof RemoteEvents
> = TypedEventEmitter<RemoteEvents[T]>
// Statically defined types for now, move this to a registry
export interface RemoteEvents {
auth: AuthRemoteEvents
contentSharing: ContentSharingEvents
personalCloud: PersonalCloudBackgroundEvents
}
function registerRemoteEventForwarder() {
if (browser.runtime.onMessage.hasListener(remoteEventForwarder)) {
return
}
browser.runtime.onMessage.addListener(remoteEventForwarder)
}
const remoteEventForwarder = (message, _) => {
if (message == null || message[__REMOTE_EVENT__] !== __REMOTE_EVENT__) {
return
}
const emitterType = message[__REMOTE_EVENT_TYPE__]
const emitter = remoteEventEmitters[emitterType]
if (emitter == null) {
return
}
emitter.emit(message[__REMOTE_EVENT_NAME__], message.data)
}
export function getRemoteEventEmitter<EventType extends keyof RemoteEvents>(
eventType: EventType,
): RemoteEventEmitters[EventType] {
const existingEmitter = remoteEventEmitters[eventType]
if (existingEmitter) {
return existingEmitter
}
const newEmitter = new EventEmitter() as any
remoteEventEmitters[eventType] = newEmitter
registerRemoteEventForwarder()
return newEmitter
}
// Containing the evil globals here
let rpcConnection: PortBasedRPCManager
export const setupRpcConnection = (options: {
sideName: RpcSideName
role: RpcRole
paused?: boolean
}) => {
rpcConnection = new PortBasedRPCManager({
sideName: options.sideName,
role: options.role,
getRegisteredRemoteFunction: (name) => remotelyCallableFunctions[name],
connect: browser.runtime.connect,
onConnect: browser.runtime.onConnect,
paused: options.paused,
})
rpcConnection.setup()
return rpcConnection
}