1 import { CryptoProxy } from '@proton/crypto';
2 import type { WorkerPoolInitOptions as CryptoWorkerOptions } from '@proton/crypto/lib/worker/workerPool';
3 import { CryptoWorkerPool } from '@proton/crypto/lib/worker/workerPool';
5 import { hasModulesSupport } from './browser';
7 let promise: undefined | Promise<void>;
10 * Initialize worker pool and set it as CryptoProxy endpoint.
11 * If workers are not supported by the current browser, the pmcrypto API is imported instead.
13 const init = async (options?: CryptoWorkerOptions) => {
14 const isWorker = typeof window === 'undefined' || typeof document === 'undefined';
15 const isCompat = isWorker || !hasModulesSupport();
17 // Compat browsers do not support the worker.
19 // dynamic import needed to avoid loading openpgp into the main thread, unless we get here
20 const { Api: CryptoApi } = await import(
21 /* webpackChunkName: "crypto-worker-api" */ '@proton/crypto/lib/worker/api'
24 CryptoProxy.setEndpoint(new CryptoApi(), (endpoint) => endpoint.clearKeyStore());
26 await CryptoWorkerPool.init(options);
27 CryptoProxy.setEndpoint(CryptoWorkerPool, (endpoint) => endpoint.destroy());
32 * Start crypto worker and set it as `CryptoProxy` endpoint.
33 * If the crypto worker was already loaded, this function is a no-op.
34 * If the browser does not support workers, the pmcrypto API (including OpenPGP.js) is loaded directly in the main thread.
35 * @returns init promise singleton
37 export const loadCryptoWorker = (options?: CryptoWorkerOptions) => {
39 promise = init(options);
45 * Release crypto worker as `CryptoProxy` endpoint, then clear the key store and terminate the worker.
47 export const destroyCryptoWorker = () => {
50 return CryptoProxy.releaseEndpoint();
53 export type { CryptoWorkerOptions };