function clean_children(node, opts) {
	let previous = null;
	let has_element_children = false;
	let template =
		node.nodeName === 'TEMPLATE' ? /** @type {HTMLTemplateElement} */ (node) : undefined;

	if (template) {
		const div = document.createElement('div');
		div.append(template.content);
		node = div;
	}

	// sort attributes
	const attributes = Array.from(node.attributes).sort((a, b) => {
		return a.name < b.name ? -1 : 1;
	});

	attributes.forEach((attr) => {
		node.removeAttribute(attr.name);
	});

	attributes.forEach((attr) => {
		// Strip out the special onload/onerror hydration events from the test output
		if ((attr.name === 'onload' || attr.name === 'onerror') && attr.value === 'this.__e=event') {
			return;
		}

		node.setAttribute(attr.name, attr.value);
	});

	for (let child of [...node.childNodes]) {
		if (child.nodeType === 3) {
			let text = /** @type {Text} */ (child);

			if (
				node.namespaceURI === 'http://www.w3.org/2000/svg' &&
				node.tagName !== 'text' &&
				node.tagName !== 'tspan'
			) {
				node.removeChild(child);
				continue;
			}

			text.data = text.data.replace(/[^\S]+/g, ' ');

			if (previous && previous.nodeType === 3) {
				const prev = /** @type {Text} */ (previous);

				prev.data += text.data;
				node.removeChild(text);

				text = prev;
				text.data = text.data.replace(/[^\S]+/g, ' ');

				continue;
			}
		}

		if (child.nodeType === 8 && !opts.preserveComments) {
			// comment
			child.remove();
			continue;
		}

		// add newlines for better readability and potentially recurse into children
		if (child.nodeType === 1 || child.nodeType === 8) {
			if (previous?.nodeType === 3) {
				const prev = /** @type {Text} */ (previous);
				prev.data = prev.data.replace(/^[^\S]+$/, '\n');
			} else if (previous?.nodeType === 1 || previous?.nodeType === 8) {
				node.insertBefore(document.createTextNode('\n'), child);
			}

			if (child.nodeType === 1) {
				has_element_children = true;
				clean_children(/** @type {Element} */ (child), opts);
			}
		}

		previous = child;
	}

	// collapse whitespace
	if (node.firstChild && node.firstChild.nodeType === 3) {
		const text = /** @type {Text} */ (node.firstChild);
		text.data = text.data.trimStart();
	}

	if (node.lastChild && node.lastChild.nodeType === 3) {
		const text = /** @type {Text} */ (node.lastChild);
		text.data = text.data.trimEnd();
	}

	// indent code for better readability
	if (has_element_children && node.parentNode) {
		node.innerHTML = `\n\  ${node.innerHTML.replace(/\n/g, '\n  ')}\n`;
	}

	if (template) {
		template.innerHTML = node.innerHTML;
	}
}
@param {Element} node
@param {{ preserveComments: boolean }} opts