electron/lib/renderer/remote/callbacks-registry.ts

60 lines
1.6 KiB
TypeScript
Raw Normal View History

export class CallbacksRegistry {
private nextId: number = 0
private callbacks = new Map<number, Function>()
private callbackIds = new WeakMap<Function, number>();
private locationInfo = new WeakMap<Function, string>();
2016-01-12 02:40:23 +00:00
add (callback: Function) {
2016-01-14 18:35:29 +00:00
// The callback is already added.
let id = this.callbackIds.get(callback);
2020-03-20 20:28:31 +00:00
if (id != null) return id;
2017-11-16 05:04:33 +00:00
2020-03-20 20:28:31 +00:00
id = this.nextId += 1;
2016-01-12 02:40:23 +00:00
2016-01-14 18:44:21 +00:00
// Capture the location of the function and put it in the ID string,
// so that release errors can be tracked down easily.
2020-03-20 20:28:31 +00:00
const regexp = /at (.*)/gi;
const stackString = (new Error()).stack;
if (!stackString) return;
2017-11-16 05:04:33 +00:00
let filenameAndLine: string;
2020-03-20 20:28:31 +00:00
let match;
2017-11-16 05:04:33 +00:00
2016-01-12 02:40:23 +00:00
while ((match = regexp.exec(stackString)) !== null) {
2020-03-20 20:28:31 +00:00
const location = match[1];
if (location.includes('(native)')) continue;
if (location.includes('(<anonymous>)')) continue;
if (location.includes('electron/js2c')) continue;
const ref = /([^/^)]*)\)?$/gi.exec(location);
if (ref) filenameAndLine = ref![1];
break;
2016-01-12 02:40:23 +00:00
}
2020-03-20 20:28:31 +00:00
this.callbacks.set(id, callback);
this.callbackIds.set(callback, id);
this.locationInfo.set(callback, filenameAndLine!);
2020-03-20 20:28:31 +00:00
return id;
2016-01-15 22:31:23 +00:00
}
2016-01-12 02:40:23 +00:00
get (id: number) {
2020-03-20 20:28:31 +00:00
return this.callbacks.get(id) || function () {};
2016-01-15 22:31:23 +00:00
}
2016-01-12 02:40:23 +00:00
getLocation (callback: Function) {
return this.locationInfo.get(callback);
}
apply (id: number, ...args: any[]) {
2020-03-20 20:28:31 +00:00
return this.get(id).apply(global, ...args);
2016-01-15 22:31:23 +00:00
}
2016-01-12 02:40:23 +00:00
remove (id: number) {
2020-03-20 20:28:31 +00:00
const callback = this.callbacks.get(id);
if (callback) {
this.callbackIds.delete(callback);
2020-03-20 20:28:31 +00:00
this.callbacks.delete(id);
}
2016-01-15 22:31:23 +00:00
}
}