asarfuckery/electronasar/ptb/renderer/callbacks-registry.js

52 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-10-01 13:49:56 +00:00
'use strict';
const v8Util = process.electronBinding('v8_util');
2019-01-17 18:22:05 +00:00
class CallbacksRegistry {
2019-10-01 13:49:56 +00:00
constructor() {
this.nextId = 0;
this.callbacks = {};
2019-01-17 18:22:05 +00:00
}
2019-10-01 13:49:56 +00:00
add(callback) {
// The callback is already added.
let id = v8Util.getHiddenValue(callback, 'callbackId');
if (id != null)
return id;
id = this.nextId += 1;
// Capture the location of the function and put it in the ID string,
// so that release errors can be tracked down easily.
const regexp = /at (.*)/gi;
const stackString = (new Error()).stack;
let filenameAndLine;
let match;
while ((match = regexp.exec(stackString)) !== null) {
const location = match[1];
if (location.includes('(native)'))
continue;
if (location.includes('(<anonymous>)'))
continue;
if (location.includes('electron.asar'))
continue;
const ref = /([^/^)]*)\)?$/gi.exec(location);
filenameAndLine = ref[1];
break;
}
this.callbacks[id] = callback;
v8Util.setHiddenValue(callback, 'callbackId', id);
v8Util.setHiddenValue(callback, 'location', filenameAndLine);
return id;
}
get(id) {
return this.callbacks[id] || function () { };
}
apply(id, ...args) {
return this.get(id).apply(global, ...args);
}
remove(id) {
const callback = this.callbacks[id];
if (callback) {
v8Util.deleteHiddenValue(callback, 'callbackId');
delete this.callbacks[id];
}
2019-01-17 18:22:05 +00:00
}
}
2019-10-01 13:49:56 +00:00
module.exports = CallbacksRegistry;