/** * @license * SPDX-License-Identifier: Apache-2.0 */ import '../environment/dev'; import { createScript, unwrapScript } from '../internals/script_impl'; import { assertIsTemplateObject } from '../internals/string_literal'; /** * Creates a SafeScript object from a template literal (without any embedded * expressions). * * This function is a template literal tag function. It should be called with * a template literal that does not contain any expressions. For example, * safeScript`foo`; * * @param templateObj This contains the literal part of the template literal. */ export function safeScript(templateObj) { if (process.env.NODE_ENV !== 'production') { assertIsTemplateObject(templateObj, false, 'safeScript is a template literal tag function ' + 'that only accepts template literals without expressions. ' + 'For example, safeScript`foo`;'); } return createScript(templateObj[0]); } /** Creates a `SafeScript` value by concatenating multiple `SafeScript`s. */ export function concatScripts(scripts) { return createScript(scripts.map(unwrapScript).join('')); } /** * Converts a serializable value into JSON that is safe to interpolate into a * script context. In particular it escapes < characters so that a value of * "" doesn't break out of the context. * @param value The value to serialize. */ export function scriptFromJson(value) { return createScript(JSON.stringify(value).replace(/ a !== '')) { throw new Error('safeScriptWithArgs only allows empty string expressions ' + 'to enable inline comments.'); } assertIsTemplateObject(templateObj, true, 'safeScriptWithArgs is a template literal tag function ' + 'that only accepts template literals. ' + 'For example, safeScriptWithArgs`foo`;'); } return (...argValues) => { const values = argValues.map((v) => scriptFromJson(v).toString()); return createScript(`(${templateObj.join('')})(${values.join(',')})`); }; }