src/vs/base/browser/markdownRenderer.ts/_uriMassage
export function renderMarkdown(markdown: IMarkdownString, options: MarkdownRenderOptions = {}, markedOptions: MarkedOptions = {}): { element: HTMLElement; dispose: () => void } {
	const disposables = new DisposableStore();
	let isDisposed = false;

	const cts = disposables.add(new CancellationTokenSource());

	const element = createElement(options);

	const _uriMassage = function (part: string): string {
		let data: any;
		try {
			data = parse(decodeURIComponent(part));
		} catch (e) {
			// ignore
		}
		if (!data) {
			return part;
		}
		data = cloneAndChange(data, value => {
			if (markdown.uris && markdown.uris[value]) {
				return URI.revive(markdown.uris[value]);
			} else {
				return undefined;
			}
		});
		return encodeURIComponent(JSON.stringify(data));
	};

	const _href = function (href: string, isDomUri: boolean): string {
		const data = markdown.uris && markdown.uris[href];
		let uri = URI.revive(data);
		if (isDomUri) {
			if (href.startsWith(Schemas.data + ':')) {
				return href;
			}
			if (!uri) {
				uri = URI.parse(href);
			}
			// this URI will end up as "src"-attribute of a dom node
			// and because of that special rewriting needs to be done
			// so that the URI uses a protocol that's understood by
			// browsers (like http or https)
			return FileAccess.asBrowserUri(uri).toString(true);
		}
		if (!uri) {
			return href;
		}
		if (URI.parse(href).toString() === uri.toString()) {
			return href; // no transformation performed
		}
		if (uri.query) {
			uri = uri.with({ query: _uriMassage(uri.query) });
		}
		return uri.toString();
	};

	// signal to code-block render that the
	// element has been created
	let signalInnerHTML: () => void;
	const withInnerHTML = new Promise<void>(c => signalInnerHTML = c);

	const renderer = new marked.Renderer();

	renderer.image = (href: string, title: string, text: string) => {
		let dimensions: string[] = [];
		let attributes: string[] = [];
		if (href) {
			({ href, dimensions } = parseHrefAndDimensions(href));
			attributes.push(`src="${escapeDoubleQuotes(href)}"`);
		}
		if (text) {
			attributes.push(`alt="${escapeDoubleQuotes(text)}"`);
		}
		if (title) {
			attributes.push(`title="${escapeDoubleQuotes(title)}"`);
		}
		if (dimensions.length) {
			attributes = attributes.concat(dimensions);
		}
		return '<img ' + attributes.join(' ') + '>';
	};
	renderer.link = (href, title, text): string => {
		if (typeof href !== 'string') {
			return '';
		}

		// Remove markdown escapes. Workaround for https://github.com/chjj/marked/issues/829
		if (href === text) { // raw link case
			text = removeMarkdownEscapes(text);
		}

		title = typeof title === 'string' ? escapeDoubleQuotes(removeMarkdownEscapes(title)) : '';
		href = removeMarkdownEscapes(href);

		// HTML Encode href
		href = href.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#39;');
		return `<a href="${href}" title="${title || href}">${text}</a>`;
	};
	renderer.paragraph = (text): string => {
		return `<p>${text}</p>`;
	};

	if (options.codeBlockRenderer) {
		renderer.code = (code, lang) => {
			const value = options.codeBlockRenderer!(lang ?? '', code);
			// when code-block rendering is async we return sync
			// but update the node with the real result later.
			const id = defaultGenerator.nextId();
			raceCancellation(Promise.all([value, withInnerHTML]), cts.token).then(values => {
				if (!isDisposed && values) {
					const span = element.querySelector<HTMLDivElement>(`div[data-code="${id}"]`);
					if (span) {
						DOM.reset(span, values[0]);
					}
					options.asyncRenderCallback?.();
				}
			}).catch(() => {
				// ignore
			});

			return `<div class="code" data-code="${id}">${escape(code)}</div>`;
		};
	}

	if (options.actionHandler) {
		const onClick = options.actionHandler.disposables.add(new DomEmitter(element, 'click'));
		const onAuxClick = options.actionHandler.disposables.add(new DomEmitter(element, 'auxclick'));
		options.actionHandler.disposables.add(Event.any(onClick.event, onAuxClick.event)(e => {
			const mouseEvent = new StandardMouseEvent(e);
			if (!mouseEvent.leftButton && !mouseEvent.middleButton) {
				return;
			}

			let target: HTMLElement | null = mouseEvent.target;
			if (target.tagName !== 'A') {
				target = target.parentElement;
				if (!target || target.tagName !== 'A') {
					return;
				}
			}
			try {
				let href = target.dataset['href'];
				if (href) {
					if (markdown.baseUri) {
						href = resolveWithBaseUri(URI.from(markdown.baseUri), href);
					}
					options.actionHandler!.callback(href, mouseEvent);
				}
			} catch (err) {
				onUnexpectedError(err);
			} finally {
				mouseEvent.preventDefault();
			}
		}));
	}

	if (!markdown.supportHtml) {
		// TODO: Can we deprecated this in favor of 'supportHtml'?

		// Use our own sanitizer so that we can let through only spans.
		// Otherwise, we'd be letting all html be rendered.
		// If we want to allow markdown permitted tags, then we can delete sanitizer and sanitize.
		// We always pass the output through dompurify after this so that we don't rely on
		// marked for sanitization.
		markedOptions.sanitizer = (html: string): string => {
			const match = markdown.isTrusted ? html.match(/^(<span[^>]+>)|(<\/\s*span>)$/) : undefined;
			return match ? html : '';
		};
		markedOptions.sanitize = true;
		markedOptions.silent = true;
	}

	markedOptions.renderer = renderer;

	// values that are too long will freeze the UI
	let value = markdown.value ?? '';
	if (value.length > 100_000) {
		value = `${value.substr(0, 100_000)}…`;
	}
	// escape theme icons
	if (markdown.supportThemeIcons) {
		value = markdownEscapeEscapedIcons(value);
	}

	let renderedMarkdown = marked.parse(value, markedOptions);

	// Rewrite theme icons
	if (markdown.supportThemeIcons) {
		const elements = renderLabelWithIcons(renderedMarkdown);
		renderedMarkdown = elements.map(e => typeof e === 'string' ? e : e.outerHTML).join('');
	}

	const htmlParser = new DOMParser();
	const markdownHtmlDoc = htmlParser.parseFromString(sanitizeRenderedMarkdown(markdown, renderedMarkdown) as unknown as string, 'text/html');

	markdownHtmlDoc.body.querySelectorAll('img')
		.forEach(img => {
			const src = img.getAttribute('src'); // Get the raw 'src' attribute value as text, not the resolved 'src'
			if (src) {
				let href = src;
				try {
					if (markdown.baseUri) { // absolute or relative local path, or file: uri
						href = resolveWithBaseUri(URI.from(markdown.baseUri), href);
					}
				} catch (err) { }

				img.src = _href(href, true);
			}
		});

	markdownHtmlDoc.body.querySelectorAll('a')
		.forEach(a => {
			const href = a.getAttribute('href'); // Get the raw 'href' attribute value as text, not the resolved 'href'
			a.setAttribute('href', ''); // Clear out href. We use the `data-href` for handling clicks instead
			if (
				!href
				|| /^data:|javascript:/i.test(href)
				|| (/^command:/i.test(href) && !markdown.isTrusted)
				|| /^command:(\/\/\/)?_workbench\.downloadResource/i.test(href)
			) {
				// drop the link
				a.replaceWith(...a.childNodes);
			} else {
				let resolvedHref = _href(href, false);
				if (markdown.baseUri) {
					resolvedHref = resolveWithBaseUri(URI.from(markdown.baseUri), href);
				}
				a.dataset.href = resolvedHref;
			}
		});

	element.innerHTML = sanitizeRenderedMarkdown(markdown, markdownHtmlDoc.body.innerHTML) as unknown as string;

	// signal that async code blocks can be now be inserted
	signalInnerHTML!();

	// signal size changes for image tags
	if (options.asyncRenderCallback) {
		for (const img of element.getElementsByTagName('img')) {
			const listener = disposables.add(DOM.addDisposableListener(img, 'load', () => {
				listener.dispose();
				options.asyncRenderCallback!();
			}));
		}
	}

	return {
		element,
		dispose: () => {
			isDisposed = true;
			cts.cancel();
			disposables.dispose();
		}
	};
}