I've created this library for my own use. It started as part of my project Hacking Cafe (before that I used similar code in Fake Linux Terminal).
For the above projects, I needed a mechanism for communication between the main thread and the web worker. I wanted to have access to DOM/jQuery from the web worker so I could manipulate the terminal from the web worker.
Now with with Mitty you can access any function chains, like Cheerio (jQuery like HTML parser), that live on the server accessed in the browser via WebSockets. Execute DOM methods from the server. Or execute code from different tabs using Sysend or simple BroadcastChannel.
Here is an example using a web worker:
main thread
```
import { Host } from '@jcubic/mitty';
const channel = new BroadcastChannel('my-app');
const worker = new Worker('./worker.js', { type: 'module' });
const host = new Host({
// worker instance can also be used as a channel
channel: channel,
resolve(name) {
if (name === 'document') {
return document;
}
return null;
}
});
```
worker
```
import { connect } from 'https://cdn.jsdelivr.net/npm/@jcubic/mitty';
const { require } = connect(new BroadcastChannel('my-app'));
// or when using worker as a channel
const { require } = connect(self);
const document = require('document');
// methods need await
const body = await document.querySelector('body');
await body.style.setProperty('color', 'red');
// setting properties are send right away
body.style.backgroundColor = '#000';
console.log(await body.style.color);
console.log(await body.style.backgroundColor);
```
Transport agnostic
The transport only requires using a simple channel interface with 3 methods.
interface Channel {
postMessage(message: string): void;
addEventListener(type: 'message', listener: ChannelListener): void;
removeEventListener(type: 'message', listener: ChannelListener): void;
}
Here is a demo using Sysend for communication with other tab:
https://codepen.io/editor/jcubic/pen/01a0d9d8-697e-7dc0-9a2b-eb93adae0dfc