Skip to content

Instantly share code, notes, and snippets.

@rofe
Last active August 25, 2023 14:36
Show Gist options
  • Save rofe/50e157e5a329a0d9b6deb0e8a8d23364 to your computer and use it in GitHub Desktop.
Save rofe/50e157e5a329a0d9b6deb0e8a8d23364 to your computer and use it in GitHub Desktop.
/*
* Copyright 2023 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/* eslint-disable no-console */
/**
* Returns the browser's runtime API.
* @private
* @returns {Object} The runtime
*/
function getRuntime() {
const c = window.chrome || window.browser;
if (!c || !c.runtime) {
throw new Error('no browser runtime found');
}
return c.runtime;
}
/**
* Sends a message to the sidekick extension
* @private
* @param {string} action The action name
* @param {Object} options The message options
* @param {function} callback The callback function
* @return {Promise<*>} The API response
*/
async function msg(action, options = {}, callback = () => {}) {
getRuntime().sendMessage(
window.SIDEKICK_ID || 'ccfggkjabjahcjoljmgmklhpaccedipo',
{
...options,
action,
},
callback,
);
}
/**
* The Sidekick SDK
*/
export default class SidekickSDK {
#cfg;
/**
* Returns a new instance of {@code SidekickSDK}
* @param {Object} cfg The configuration
* @param {string} cfg.owner The GitHub owner
* @param {string} cfg.repo The GitHub repository
*/
constructor(cfg) {
this.#cfg = cfg;
}
/**
* Returns the sidekick's current status.
* @returns {Promise<Object>} The status
*/
async getStatus() {
try {
return new Promise((resolve) => {
msg('getStatus', this.#cfg, (res) => resolve(res));
});
} catch (e) {
console.error(e);
}
return null;
}
/**
* Tells the sidekick to load in the current tab.
*/
async loadSidekick() {
try {
await msg('loadSidekick', this.#cfg);
} catch (e) {
console.error(e);
}
}
/**
* Tells the sidekick to close a palette
* with the given plugin ID.
* @param {string} id The plugin ID
*/
async closePalette(id) {
try {
await msg('closePalette', { id });
} catch (e) {
console.error(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment