diff --git a/src/service-worker/sw.js b/src/service-worker/sw.js index 49c035027..3a69f3cfd 100644 --- a/src/service-worker/sw.js +++ b/src/service-worker/sw.js @@ -2,48 +2,12 @@ // Backup the native ReadableStream because OpenPGP.js might modify it on Firefox const NativeReadableStream = ReadableStream; -importScripts('openpgp/openpgp.min.js'); import {createReadableStreamWrapper} from '@mattiasbuelens/web-streams-adapter'; +importScripts('openpgp/openpgp.min.js'); - -/** - * Convert a native ReadableStream to polyfill ReadableStream if ReadableStream class is polyfill. - * - * @param readableStream Native ReadableStream - * @returns {*} - */ -function toPolyfillReadableIfNeed(readableStream) { - // If not polyfilled - if (NativeReadableStream === ReadableStream) { - return readableStream; - // If ReadableStream is polyfill - } else { - // (base: https://github.com/MattiasBuelens/web-streams-adapter/tree/d76e3789d67b1ab3c91699ecc0c42bde897d2298) - // NOTE: ReadableStream is polyfill ReadableStream in this condition - const toPolyfillReadable = createReadableStreamWrapper(ReadableStream); - // Convert a native ReadableStream to polyfill ReadableStream - return toPolyfillReadable(readableStream); - } -} - -/** - * Convert a polyfill ReadableStream to native ReadableStream if ReadableStream class is polyfill. - * - * @param readableStream Native ReadableStream or polyfill ReadableStream - * @returns {*} - */ -function toNativeReadableIfNeed(readableStream) { - // If not polyfilled - if (NativeReadableStream === ReadableStream) { - return readableStream; - // If ReadableStream is polyfill - } else { - // (base: https://github.com/MattiasBuelens/web-streams-adapter/tree/d76e3789d67b1ab3c91699ecc0c42bde897d2298) - const toNativeReadable = createReadableStreamWrapper(NativeReadableStream); - // Convert a polyfill ReadableStream to native ReadableStream - return toNativeReadable(readableStream); - } -} +// Create convert functions +const toPolyfillReadable = createReadableStreamWrapper(ReadableStream); +const toNativeReadable = createReadableStreamWrapper(NativeReadableStream); // Generate random string with specific length function generateRandomString(len){ @@ -189,7 +153,7 @@ self.addEventListener('fetch', (event) => { openpgp.config.allow_unauthenticated_stream = true; // Decrypt the response body const decrypted = await openpgp.decrypt({ - message: await openpgp.message.read(toPolyfillReadableIfNeed(res.body)), + message: await openpgp.message.read(toPolyfillReadable(res.body)), passwords: [password], format: 'binary' }); @@ -203,7 +167,7 @@ self.addEventListener('fetch', (event) => { } } - const downloadableRes = new Response(toNativeReadableIfNeed(plainStream), { + const downloadableRes = new Response(toNativeReadable(plainStream), { headers }); return downloadableRes;