From: 
Subject: Debian changes

The Debian packaging of node-babel-plugin-template-html-minifier is maintained in git, using a workflow
similar to the one described in dgit-maint-merge(7).
The Debian delta is represented by this one combined patch; there isn't a
patch queue that can be represented as a quilt series.

A detailed breakdown of the changes is available from their canonical
representation -- git commits in the packaging repository.
For example, to see the changes made by the Debian maintainer in the first
upload of upstream version 1.2.3, you could use:

    % git clone https://git.dgit.debian.org/node-babel-plugin-template-html-minifier
    % cd node-babel-plugin-template-html-minifier
    % git log --oneline 1.2.3..debian/1.2.3-1 -- . ':!debian'

(If you have dgit, use `dgit clone node-babel-plugin-template-html-minifier`, rather than plain `git clone`.)

We don't use debian/source/options single-debian-patch because it has bugs.
Therefore, NMUs etc. may nevertheless have made additional patches.

---

diff --git a/fixtures/transform-template-literals-after.js b/fixtures/transform-template-literals-after.js
deleted file mode 100644
index a15945f..0000000
--- a/fixtures/transform-template-literals-after.js
+++ /dev/null
@@ -1,28 +0,0 @@
-function _templateObject2() {
-	const data = _taggedTemplateLiteral(["<span class=\"", "\" disabled=\"", "\" >test</span>"]);
-	_templateObject2 = function() {
-		return data;
-	};
-	return data;
-}
-
-function _templateObject(){
-	const data = _taggedTemplateLiteral(["<span class=", " disabled=", ">test</span>"]);
-	_templateObject = function(){
-		return data;
-	};
-	return data;
-}
-
-function _taggedTemplateLiteral(strings, raw) {
-	if (!raw) {
-		raw = strings.slice(0);
-	}
-	return Object.freeze(Object.defineProperties(strings, {raw: {value: Object.freeze(raw)}}));
-}
-
-import {html, render} from 'lit-html';
-
-const myclass = 'test';
-const disabled = false;
-html(_templateObject(),myclass,disabled);render(_templateObject2(),myclass,disabled);
diff --git a/lib/config.js b/lib/config.js
index 6911f70..156a75e 100644
--- a/lib/config.js
+++ b/lib/config.js
@@ -1,4 +1,6 @@
 'use strict';
+const {readFileSync} = require('fs');
+const {join} = require('path');
 const isBuiltinModule = require('is-builtin-module');
 const createMinifyCSS = require('./minify-css');
 
@@ -9,7 +11,30 @@ function ownerName(importSource) {
 }
 
 function getPkgMain(importOwner) {
-	const pkgInfo = require(importOwner + '/package.json');
+	let pkgInfo;
+	try {
+		pkgInfo = require(importOwner + '/package.json');
+	} catch (error) {
+		if (error.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') {
+			throw error;
+		}
+
+		// Read package metadata even if the exports map hides package.json.
+		for (const directory of require.resolve.paths(importOwner)) {
+			try {
+				pkgInfo = JSON.parse(readFileSync(join(directory, importOwner, 'package.json'), 'utf8'));
+				break;
+			} catch (readError) {
+				if (readError.code !== 'ENOENT') {
+					throw readError;
+				}
+			}
+		}
+
+		if (!pkgInfo) {
+			throw error;
+		}
+	}
 	/* istanbul ignore next */
 	return pkgInfo.module || pkgInfo['jsnext:main'] || pkgInfo.main;
 }
diff --git a/lib/cook-raw-quasi.js b/lib/cook-raw-quasi.js
index 3ea8fa7..d1ad048 100644
--- a/lib/cook-raw-quasi.js
+++ b/lib/cook-raw-quasi.js
@@ -1,10 +1,10 @@
 'use strict';
 
-function cookRawQuasi({transform}, raw) {
+function cookRawQuasi({transformSync}, raw) {
 	// This nasty hack is needed until https://github.com/babel/babel/issues/9242 is resolved.
 	const args = {raw};
 
-	transform('cooked`' + args.raw + '`', {
+	transformSync('cooked`' + args.raw + '`', {
 		babelrc: false,
 		configFile: false,
 		plugins: [
diff --git a/lib/index.js b/lib/index.js
index 608a33f..1b09ff7 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -1,5 +1,5 @@
 'use strict';
-const htmlMinifier = require('html-minifier-terser');
+const minifyHTML = require('./minify-html');
 
 const cookRawQuasi = require('./cook-raw-quasi');
 const {normalizeModulesConfig, normalizeMinifierConfig, getModuleConfig} = require('./config.js');
@@ -69,7 +69,7 @@ function minify(path, state, bindingOptions) {
 	let parts;
 
 	try {
-		const minified = htmlMinifier.minify(tags.opening + quasis.join(placeholder) + tags.closing, state.minifierConfig);
+		const minified = minifyHTML(tags.opening + quasis.join(placeholder) + tags.closing, state.minifierConfig);
 		if (!minified.startsWith(tags.opening) || !minified.endsWith(tags.closing)) {
 			throw new Error(majorDeleteError);
 		}
diff --git a/lib/minify-html-worker.js b/lib/minify-html-worker.js
new file mode 100644
index 0000000..688d4bb
--- /dev/null
+++ b/lib/minify-html-worker.js
@@ -0,0 +1,42 @@
+'use strict';
+
+const {parentPort} = require('worker_threads');
+const {receive, send, outcome, unwrap} = require('./minify-html');
+
+function invoke(port, signal, callback, args) {
+	// Whitespace hooks receive the minifier's default predicate as a function.
+	const argumentIndex = args.findIndex(arg => typeof arg === 'function');
+	const defaultPredicate = argumentIndex < 0 ? undefined : args[argumentIndex];
+	if (defaultPredicate) {
+		args[argumentIndex] = undefined;
+	}
+
+	send(port, signal, {callback, args, defaultArgument: defaultPredicate ? argumentIndex : undefined});
+	let reply = receive(port, signal);
+	while ('defaultArgs' in reply) {
+		const {defaultArgs} = reply;
+		send(port, signal, outcome(() => defaultPredicate(...defaultArgs)));
+		reply = receive(port, signal);
+	}
+
+	return unwrap(reply);
+}
+
+async function run({html, options, callbacks, port, signal}) {
+	try {
+		const {minify} = require('html-minifier-terser');
+		for (const name of callbacks) {
+			options[name] = name === 'minifyCSS'
+				? async (...args) => invoke(port, signal, name, args)
+				: (...args) => invoke(port, signal, name, args);
+		}
+
+		send(port, signal, {value: await minify(html, options)});
+	} catch (error) {
+		send(port, signal, {error: String(error.message || error)});
+	} finally {
+		port.close();
+	}
+}
+
+parentPort.on('message', run);
diff --git a/lib/minify-html.js b/lib/minify-html.js
new file mode 100644
index 0000000..486d025
--- /dev/null
+++ b/lib/minify-html.js
@@ -0,0 +1,128 @@
+'use strict';
+
+const {MessageChannel, Worker, receiveMessageOnPort} = require('worker_threads');
+const {join} = require('path');
+let sharedWorker;
+let sharedWorkerBusy = false;
+
+function startWorker() {
+	const worker = new Worker(join(__dirname, 'minify-html-worker.js'));
+	const forgetWorker = () => {
+		if (sharedWorker === worker) {
+			sharedWorker = undefined;
+		}
+	};
+	worker.on('error', forgetWorker);
+	worker.on('exit', forgetWorker);
+	worker.unref();
+	return worker;
+}
+
+function receive(port, signal) {
+	const deadline = Date.now() + 30000;
+	while (true) {
+		const sequence = Atomics.load(signal, 0);
+		const packet = receiveMessageOnPort(port);
+		if (packet) {
+			return packet.message;
+		}
+
+		const remaining = deadline - Date.now();
+		if (remaining <= 0) {
+			throw new Error('Timed out waiting for html-minifier-terser');
+		}
+
+		Atomics.wait(signal, 0, sequence, remaining);
+	}
+}
+
+function send(port, signal, message) {
+	port.postMessage(message);
+	Atomics.add(signal, 0, 1);
+	Atomics.notify(signal, 0);
+}
+
+function outcome(callback) {
+	try {
+		return {value: callback()};
+	} catch (error) {
+		return {error: String(error.message || error)};
+	}
+}
+
+function unwrap(result) {
+	if ('error' in result) {
+		throw new Error(result.error);
+	}
+
+	return result.value;
+}
+
+function minifyHTML(html, options) {
+	const callbacks = new Map();
+	const workerOptions = {};
+	for (const [name, value] of Object.entries(options || {})) {
+		if (typeof value === 'function') {
+			callbacks.set(name, value);
+		} else {
+			workerOptions[name] = value;
+		}
+	}
+
+	// Babel visitors are synchronous. Let the worker await the minifier while
+	// this thread services synchronous option callbacks and waits for the result.
+	const {port1, port2} = new MessageChannel();
+	const signal = new Int32Array(new SharedArrayBuffer(4));
+	const callbackOptions = {...options};
+	const nested = sharedWorkerBusy;
+	let worker;
+	try {
+		if (nested) {
+			worker = startWorker();
+		} else {
+			sharedWorkerBusy = true;
+			sharedWorker = sharedWorker || startWorker();
+			worker = sharedWorker;
+		}
+
+		worker.postMessage({html, options: workerOptions, callbacks: [...callbacks.keys()], port: port2, signal}, [port2]);
+		while (true) {
+			const message = receive(port1, signal);
+			if (!message.callback) {
+				return unwrap(message);
+			}
+
+			const {callback, args, defaultArgument} = message;
+			if (defaultArgument !== undefined) {
+				args[defaultArgument] = (...defaultArgs) => {
+					send(port1, signal, {defaultArgs});
+					return unwrap(receive(port1, signal));
+				};
+			}
+
+			send(port1, signal, outcome(() => callbacks.get(callback).apply(callbackOptions, args)));
+		}
+	} catch (error) {
+		// Drop a worker if the message exchange was interrupted.
+		if (worker && sharedWorker === worker) {
+			sharedWorker = undefined;
+			worker.terminate();
+		}
+
+		throw error;
+	} finally {
+		port1.close();
+		port2.close();
+		if (nested && worker) {
+			worker.terminate();
+		} else if (!nested) {
+			sharedWorkerBusy = false;
+		}
+	}
+}
+
+module.exports = minifyHTML;
+module.exports.receive = receive;
+module.exports.send = send;
+module.exports.outcome = outcome;
+module.exports.unwrap = unwrap;
diff --git a/package.json b/package.json
index 9e72a1b..948de6d 100644
--- a/package.json
+++ b/package.json
@@ -27,11 +27,11 @@
 	},
 	"homepage": "https://github.com/cfware/babel-plugin-template-html-minifier#readme",
 	"engines": {
-		"node": ">=10.13.0"
+		"node": "^14.13.1 || >=16.0.0"
 	},
 	"dependencies": {
 		"clean-css": "^4.2.1",
-		"html-minifier-terser": "^5.0.0",
+		"html-minifier-terser": "^7.2.0",
 		"is-builtin-module": "^3.0.0"
 	},
 	"devDependencies": {
@@ -47,8 +47,7 @@
 	},
 	"xo": {
 		"ignores": [
-			"fixtures/ignore-invalid-require-source.js",
-			"fixtures/transform-template-literals-after.js"
+			"fixtures/ignore-invalid-require-source.js"
 		],
 		"rules": {
 			"unicorn/string-content": 0
diff --git a/test/test.js b/test/test.js
index 63f2d63..7e14c5c 100644
--- a/test/test.js
+++ b/test/test.js
@@ -3,7 +3,7 @@
 const path = require('path');
 const t = require('tap');
 
-const {transform, transformFileAsync} = require('@babel/core');
+const {transformSync, transformFileAsync} = require('@babel/core');
 
 const plugin = require('..');
 
@@ -124,20 +124,22 @@ async function fileTest(t, sourceID, resultID, pluginOptions, ...plugins) {
 	const sourceFile = path.join(fixturePath, (sourceID || titleID) + '-source.js');
 	const resultFile = path.join(fixturePath, [resultID ? resultID : titleID, '.js'].join(''));
 
-	plugins.unshift([plugin, pluginOptions || defaultLitConfig]);
 	const babelrc = {
 		babelrc: false,
 		configFile: false,
 		compact: true
 	};
-	const {code} = await transformFileAsync(sourceFile, {...babelrc, plugins});
-	const {code: result} = await transformFileAsync(resultFile, babelrc);
+	const {code} = await transformFileAsync(sourceFile, {
+		...babelrc,
+		plugins: [[plugin, pluginOptions || defaultLitConfig], ...plugins]
+	});
+	const {code: result} = await transformFileAsync(resultFile, {...babelrc, plugins});
 	t.equal(code, result);
 }
 
 t.test('errors', {buffered: false}, async t => {
 	const filename = path.resolve('error-file.js');
-	const testOptions = (source, options) => transform(source, {
+	const testOptions = (source, options) => transformSync(source, {
 		babelrc: false,
 		configFile: false,
 		filename,
@@ -313,6 +315,30 @@ t.test('errors', {buffered: false}, async t => {
 	console.error = originalLog;
 });
 
+t.test('synchronous transforms support custom minifier callbacks', t => {
+	const replacement = 'color:blue';
+	const source = 'import {html} from "lit-html"; html`<span style="color: red">  text  </span>`;';
+	const {code} = transformSync(source, {
+		babelrc: false,
+		configFile: false,
+		plugins: [[plugin, {
+			...defaultLitConfig,
+			htmlMinifier: {
+				collapseWhitespace: true,
+				canCollapseWhitespace(tag, attrs, defaultPredicate) {
+					return defaultPredicate(tag, attrs);
+				},
+				minifyCSS(css, type) {
+					t.equal(type, 'inline');
+					return css.replace('color: red', replacement);
+				}
+			}
+		}]]
+	});
+	t.match(code, /style="color:blue">text<\/span>/);
+	t.end();
+});
+
 test('do nothing', fileTest, 'lit-html', true, {});
 test('default import', fileTest, 'choo', null, defaultChooConfig);
 test('named import', fileTest, 'lit-html', null, complexLitConfig);
@@ -370,7 +396,7 @@ test('import member class of star export from non-matching module', fileTest, 'i
 
 test('ignore this outside class', fileTest, null, true);
 test('css unicode with double-backslash', fileTest);
-test('transform-template-literals after', fileTest, 'lit-html', null, null, '@babel/plugin-transform-template-literals');
+test('transform-template-literals after', fileTest, 'lit-html', 'named-import', null, '@babel/plugin-transform-template-literals');
 test('tagged template non-factory', fileTest);
 test('tagged template factory', fileTest, null, null, factoryHyperConfig);
 
