1010
1111// Requires the following JavaScript features: MessageChannel, MessagePort, and dynamic imports.
1212
13+ /**
14+ * @typedef Implementation
15+ * @property {MessagePort } hostPort The port the host uses to communicate with the implementation.
16+ * @property {Function } disconnectFn A function to call when the port has been disconnected.
17+ */
18+
1319/**
1420 * Connects a host to a compress/decompress implementation via MessagePorts. The implementation must
1521 * have an exported connect() function that accepts a MessagePort. If the runtime support Workers
1622 * (e.g. web browsers, deno), imports the implementation inside a Web Worker. Otherwise, it
1723 * dynamically imports the implementation inside the current JS context (node, bun).
1824 * @param {string } implFilename The compressor/decompressor implementation filename relative to this
1925 * path (e.g. './unzip.js').
20- * @returns {Promise<MessagePort> } The Promise resolves to the MessagePort connected to the
21- * implementation that the host should use.
26+ * @param {Function } disconnectFn A function to run when the port is disconnected.
27+ * @returns {Promise<Implementation> } The Promise resolves to the Implementation, which includes the
28+ * MessagePort connected to the implementation that the host should use.
2229 */
2330export async function getConnectedPort ( implFilename ) {
2431 const messageChannel = new MessageChannel ( ) ;
@@ -28,13 +35,19 @@ export async function getConnectedPort(implFilename) {
2835 if ( typeof Worker === 'undefined' ) {
2936 const implModule = await import ( `${ implFilename } ` ) ;
3037 await implModule . connect ( implPort ) ;
31- return hostPort ;
38+ return {
39+ hostPort,
40+ disconnectFn : ( ) => implModule . disconnect ( ) ,
41+ } ;
3242 }
3343
3444 return new Promise ( ( resolve , reject ) => {
3545 const workerScriptPath = new URL ( `./webworker-wrapper.js` , import . meta. url ) . href ;
3646 const worker = new Worker ( workerScriptPath , { type : 'module' } ) ;
3747 worker . postMessage ( { implSrc : implFilename } , [ implPort ] ) ;
38- resolve ( hostPort ) ;
48+ resolve ( {
49+ hostPort,
50+ disconnectFn : ( ) => worker . postMessage ( { disconnect : true } ) ,
51+ } ) ;
3952 } ) ;
4053}
0 commit comments