forked from openpgpjs/openpgpjs
/
application_worker.js
41 lines (35 loc) · 1.21 KB
/
application_worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* globals tryTests: true */
const chai = require('chai');
const { expect } = chai;
/* eslint-disable no-invalid-this */
module.exports = () => tryTests('Application Worker', tests, {
if: typeof window !== 'undefined' && window.Worker && window.MessageChannel
});
function tests() {
it('Should support loading OpenPGP.js from inside a Web Worker', async function() {
try {
globalThis.eval('(async function() {})');
} catch (e) {
console.error(e); // eslint-disable-line no-console
this.skip();
}
const worker = new Worker('./worker/worker_example.js');
async function delegate(action, message) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel();
channel.port1.onmessage = function({ data }) {
if (data.error !== undefined) {
reject(new Error(data.error));
} else {
resolve(data.result);
}
};
worker.postMessage({ action, message }, [channel.port2]);
});
}
const encrypted = await delegate('encrypt', 'Hello World!');
const decrypted = await delegate('decrypt', encrypted);
expect(decrypted).to.equal('Hello World!');
worker.terminate();
});
}