Create mainWorldContentScriptBridge

These classes are the base of a communication bridge between the main
world and content scripts, which has been extracted from the main world
options watcher.

This will be used by the main world i18n component.

Bug: twpowertools:157
Change-Id: I08553b05648ad8453203ab08ecf01e824af15fea
diff --git a/src/common/mainWorldContentScriptBridge/Server.js b/src/common/mainWorldContentScriptBridge/Server.js
new file mode 100644
index 0000000..321a068
--- /dev/null
+++ b/src/common/mainWorldContentScriptBridge/Server.js
@@ -0,0 +1,37 @@
+export default class MainWorldContentScriptBridgeServer {
+  constructor(CSTarget, MWTarget) {
+    if (!CSTarget || !MWTarget) {
+      throw new Error(
+          `[MWOptionsWatcherServer] CSTarget and MWTarget are compulsory.`);
+    }
+
+    this.CSTarget = CSTarget;
+    this.MWTarget = MWTarget;
+    this.handler = () => {};
+  }
+
+  // Handler should be an action of the form (uuid, action, request) => {...}.
+  setUpHandler(handler) {
+    this.handler = handler;
+    window.addEventListener('message', e => this.#handleMessage(e));
+  }
+
+  #handleMessage(e) {
+    const uuid = e.data?.uuid;
+    if (e.source !== window || e.data?.target !== this.CSTarget || !uuid)
+      return;
+
+    const action = e.data?.action;
+    const request = e.data?.request;
+    return this.handler(uuid, action, request);
+  }
+
+  _respond(uuid, response) {
+    const data = {
+      target: this.MWTarget,
+      uuid,
+      response,
+    };
+    window.postMessage(data, window.origin);
+  }
+}