async'ify msg, don't throw for flow control

This commit is contained in:
tophf 2020-10-23 12:19:32 +03:00
parent 595b037ab1
commit 7849149fd0
3 changed files with 139 additions and 231 deletions

View File

@ -258,7 +258,7 @@ if (FIREFOX && browser.commands && browser.commands.update) {
}); });
} }
msg.broadcastTab({method: 'backgroundReady'}); msg.broadcast({method: 'backgroundReady'});
function webNavIframeHelperFF({tabId, frameId}) { function webNavIframeHelperFF({tabId, frameId}) {
if (!frameId) return; if (!frameId) return;

View File

@ -150,13 +150,10 @@ self.INJECTED !== 1 && (() => {
break; break;
case 'backgroundReady': case 'backgroundReady':
initializing initializing.catch(err =>
.catch(err => { msg.isIgnorableError(err)
if (msg.RX_NO_RECEIVER.test(err.message)) { ? init()
return init(); : console.error(err));
}
})
.catch(console.error);
break; break;
case 'updateCount': case 'updateCount':

357
js/msg.js
View File

@ -1,258 +1,169 @@
/* global promisifyChrome deepCopy */ /* global promisifyChrome deepCopy getOwnTab URLS msg */
// deepCopy is only used if the script is executed in extension pages.
'use strict'; 'use strict';
self.msg = self.INJECTED === 1 ? self.msg : (() => { // eslint-disable-next-line no-unused-expressions
window.INJECTED !== 1 && (() => {
promisifyChrome({ promisifyChrome({
runtime: ['sendMessage'], runtime: ['sendMessage'],
tabs: ['sendMessage', 'query'], tabs: ['sendMessage', 'query'],
}); });
const isBg = chrome.extension.getBackgroundPage && chrome.extension.getBackgroundPage() === window; const TARGETS = Object.assign(Object.create(null), {
if (isBg) { all: ['both', 'tab', 'extension'],
window._msg = { extension: ['both', 'extension'],
handler: null, tab: ['both', 'tab'],
clone: deepCopy });
}; const NEEDS_TAB_IN_SENDER = [
} 'getTabUrlPrefix',
const bgReady = getBg(); 'updateIconBadge',
const EXTENSION_URL = chrome.runtime.getURL(''); 'styleViaAPI',
let handler; ];
const RX_NO_RECEIVER = /Receiving end does not exist/; const isBg = getExtBg() === window;
// typo in Chrome 49 const handler = {
const RX_PORT_CLOSED = /The message port closed before a res?ponse was received/; both: new Set(),
return { tab: new Set(),
send, extension: new Set(),
sendTab,
sendBg,
broadcast,
broadcastTab,
broadcastExtension,
ignoreError,
on,
onTab,
onExtension,
off,
RX_NO_RECEIVER,
RX_PORT_CLOSED,
isBg,
}; };
function getBg() { chrome.runtime.onMessage.addListener(handleMessage);
if (isBg) {
return Promise.resolve(window);
}
// try using extension.getBackgroundPage because runtime.getBackgroundPage is too slow
// https://github.com/openstyles/stylus/issues/771
if (chrome.extension.getBackgroundPage) {
const bg = chrome.extension.getBackgroundPage();
if (bg && bg.document && bg.document.readyState !== 'loading') {
return Promise.resolve(bg);
}
}
if (chrome.runtime.getBackgroundPage) {
promisifyChrome({
runtime: ['getBackgroundPage'],
});
return browser.runtime.getBackgroundPage().catch(() => null);
}
return Promise.resolve(null);
}
function send(data, target = 'extension') { window.API = new Proxy({}, {
const message = {data, target}; get(target, name) {
return browser.runtime.sendMessage(message).then(unwrapData); return async (...args) => {
} const bg = isBg && window || chrome.tabs && (getExtBgIfReady() || await getRuntimeBg());
const message = {method: 'invokeAPI', name, args};
function sendTab(tabId, data, options, target = 'tab') { // frames and probably private tabs
return browser.tabs.sendMessage(tabId, {data, target}, options) if (!bg || window !== parent) return msg.send(message);
.then(unwrapData);
}
function sendBg(data) {
return bgReady.then(bg => {
if (bg) {
if (!bg._msg.handler) {
throw new Error('there is no bg handler');
}
const handlers = bg._msg.handler.extension.concat(bg._msg.handler.both);
// in FF, the object would become a dead object when the window // in FF, the object would become a dead object when the window
// is closed, so we have to clone the object into background. // is closed, so we have to clone the object into background.
return Promise.resolve(executeCallbacks(handlers, bg._msg.clone(data), {url: location.href})) const res = bg.msg._execute(TARGETS.extension, bg.deepCopy(message), {
.then(deepCopy); frameId: 0,
tab: NEEDS_TAB_IN_SENDER.includes(name) && await getOwnTab(),
url: location.href,
});
// avoiding an unnecessary `await` microtask сycle
return deepCopy(res instanceof bg.Promise ? await res : res);
};
},
});
window.msg = {
isBg,
async broadcast(data) {
const requests = [msg.send(data, 'both').catch(msg.ignoreError)];
for (const tab of await browser.tabs.query({})) {
const url = tab.pendingUrl || tab.url;
if (!tab.discarded &&
!url.startsWith(URLS.ownOrigin) &&
URLS.supported(url)) {
requests[tab.active ? 'unshift' : 'push'](
msg.sendTab(tab.id, data, null, 'both').catch(msg.ignoreError));
}
} }
return send(data); return Promise.all(requests);
}); },
}
function ignoreError(err) { isIgnorableError(err) {
if (err.message && ( return /Receiving end does not exist|The message port closed before/.test(err.message);
RX_NO_RECEIVER.test(err.message) || },
RX_PORT_CLOSED.test(err.message)
)) {
return;
}
console.warn(err);
}
function broadcast(data, filter) { ignoreError(err) {
return Promise.all([ if (!msg.isIgnorableError(err)) {
send(data, 'both').catch(ignoreError), console.warn(err);
broadcastTab(data, filter, null, true, 'both') }
]); },
}
function broadcastTab(data, filter, options, ignoreExtension = false, target = 'tab') { on(fn) {
return browser.tabs.query({}) handler.both.add(fn);
// TODO: send to activated tabs first? },
.then(tabs => {
const requests = []; onTab(fn) {
for (const tab of tabs) { handler.tab.add(fn);
const tabUrl = tab.pendingUrl || tab.url; },
const isExtension = tabUrl.startsWith(EXTENSION_URL);
if ( onExtension(fn) {
tab.discarded || handler.extension.add(fn);
// FIXME: use `URLS.supported`? },
!/^(http|ftp|file)/.test(tabUrl) &&
!tabUrl.startsWith('chrome://newtab/') && off(fn) {
!isExtension || for (const type of TARGETS.all) {
isExtension && ignoreExtension || handler[type].delete(fn);
filter && !filter(tab) }
) { },
continue;
send(data, target = 'extension') {
return browser.runtime.sendMessage({data, target})
.then(unwrapData);
},
sendTab(tabId, data, options, target = 'tab') {
return browser.tabs.sendMessage(tabId, {data, target}, options)
.then(unwrapData);
},
_execute(types, ...args) {
let result;
for (const type of types) {
for (const fn of handler[type]) {
let res;
try {
res = fn(...args);
} catch (err) {
res = Promise.reject(err);
} }
const dataObj = typeof data === 'function' ? data(tab) : data; if (res !== undefined && result === undefined) {
if (!dataObj) { result = res;
continue;
}
const message = {data: dataObj, target};
if (tab && tab.id) {
requests.push(
browser.tabs.sendMessage(tab.id, message, options)
.then(unwrapData)
.catch(ignoreError)
);
} }
} }
return Promise.all(requests);
});
}
function broadcastExtension(...args) {
return send(...args).catch(ignoreError);
}
function on(fn) {
initHandler();
handler.both.push(fn);
}
function onTab(fn) {
initHandler();
handler.tab.push(fn);
}
function onExtension(fn) {
initHandler();
handler.extension.push(fn);
}
function off(fn) {
for (const type of ['both', 'tab', 'extension']) {
const index = handler[type].indexOf(fn);
if (index >= 0) {
handler[type].splice(index, 1);
} }
} return result;
},
};
function getExtBg() {
const fn = chrome.extension.getBackgroundPage;
return fn && fn();
} }
function initHandler() { function getExtBgIfReady() {
if (handler) { const bg = getExtBg();
return; return bg && bg.document && bg.document.readyState !== 'loading' && bg;
}
handler = {
both: [],
tab: [],
extension: []
};
if (isBg) {
window._msg.handler = handler;
}
chrome.runtime.onMessage.addListener(handleMessage);
} }
function executeCallbacks(callbacks, ...args) { function getRuntimeBg() {
let result; return new Promise(resolve =>
for (const fn of callbacks) { chrome.runtime.getBackgroundPage(bg =>
const data = withPromiseError(fn, ...args); resolve(!chrome.runtime.lastError && bg)));
if (data !== undefined && result === undefined) {
result = data;
}
}
return result;
} }
function handleMessage(message, sender, sendResponse) { function handleMessage({data, target}, sender, sendResponse) {
const handlers = message.target === 'tab' ? const res = msg._execute(TARGETS[target] || TARGETS.all, data, sender);
handler.tab.concat(handler.both) : message.target === 'extension' ? if (res instanceof Promise) {
handler.extension.concat(handler.both) : handleResponseAsync(res, sendResponse);
handler.both.concat(handler.extension, handler.tab); return true;
if (!handlers.length) {
return;
} }
const result = executeCallbacks(handlers, message.data, sender); if (res !== undefined) sendResponse({data: res});
if (result === undefined) {
return;
}
Promise.resolve(result)
.then(
data => ({
error: false,
data
}),
err => ({
error: true,
data: Object.assign({
message: err.message || String(err),
// FIXME: do we want to pass the entire stack?
stack: err.stack
}, err) // this allows us to pass custom properties e.g. `err.index`
})
)
.then(sendResponse);
return true;
} }
function withPromiseError(fn, ...args) { async function handleResponseAsync(promise, sendResponse) {
try { try {
return fn(...args); sendResponse({
data: await promise,
});
} catch (err) { } catch (err) {
return Promise.reject(err); sendResponse({
error: true,
data: Object.assign({
message: err.message || String(err),
stack: err.stack,
}, err), // passing custom properties e.g. `err.index` to unwrapData
});
} }
} }
// {type, error, data, id} function unwrapData({data, error} = {}) {
function unwrapData(result) { return error
if (result === undefined) { ? Promise.reject(Object.assign(new Error(data.message), data))
throw new Error('Receiving end does not exist'); : data;
}
if (result.error) {
throw Object.assign(new Error(result.data.message), result.data);
}
return result.data;
} }
})(); })();
self.API = self.INJECTED === 1 ? self.API : new Proxy({
// Handlers for these methods need sender.tab.id which is set by `send` as it uses messaging,
// unlike `sendBg` which invokes the background page directly in our own extension tabs
getTabUrlPrefix: true,
updateIconBadge: true,
styleViaAPI: true,
}, {
get: (target, name) =>
(...args) => Promise.resolve(self.msg[target[name] ? 'send' : 'sendBg']({
method: 'invokeAPI',
name,
args
}))
});