/** * @license * SPDX-License-Identifier: Apache-2.0 */ import { createHtml, unwrapHtml } from '../internals/html_impl'; import { unwrapResourceUrl } from '../internals/resource_url_impl'; import { unwrapScript } from '../internals/script_impl'; /** * Returns HTML-escaped text as a `SafeHtml` object. * * Available options: * - `preserveSpaces` turns every second consecutive space character into its * HTML entity representation (` `). * - `preserveNewlines` turns newline characters into breaks (`
`). * - `preserveTabs` wraps tab characters in a span with style=white-space:pre. */ export function htmlEscape(text, options = {}) { let htmlEscapedString = htmlEscapeToString(text); if (options.preserveSpaces) { // Do this first to ensure we preserve spaces after newlines and tabs. htmlEscapedString = htmlEscapedString.replace(/(^|[\r\n\t ]) /g, '$1 '); } if (options.preserveNewlines) { htmlEscapedString = htmlEscapedString.replace(/(\r\n|\n|\r)/g, '
'); } if (options.preserveTabs) { htmlEscapedString = htmlEscapedString.replace(/(\t+)/g, '$1'); } return createHtml(htmlEscapedString); } /** * Creates a `SafeHtml` representing a script tag with inline script content. */ export function createScript(script, options = {}) { const unwrappedScript = unwrapScript(script).toString(); let stringTag = `${unwrappedScript}\x3c/script>`; return createHtml(stringTag); } /** * Creates a `SafeHtml` representing a script tag with the src attribute. * This also supports CSP nonces and async loading. */ export function createScriptSrc(src, async, nonce) { const unwrappedSrc = unwrapResourceUrl(src).toString(); let stringTag = `