All files / html / unstable_html.ts

100.00% Branches 2/2
100.00% Functions 1/1
100.00% Lines 7/7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x7
x7
x7
 
x209
x209
x209
 
x209





































































// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * A template literal tag function for creating HTML strings with interpolated
 * values.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * This function processes template literals and concatenates them with
 * interpolated values. Values are inserted as-is without any HTML escaping or
 * sanitization. Undefined values are treated as empty strings.
 *
 * > [!WARNING]
 * > **Security Warning**: This function does NOT escape HTML. When
 * > interpolating user-provided data, you must manually escape it to prevent
 * > XSS (Cross-Site Scripting) attacks. Only use this function with trusted
 * > data or data that has been properly sanitized. Use
 * > {@linkcode https://jsr.io/@std/html/doc/~/escape | escape()} for escaping.
 *
 * @param strings The template string array containing the static parts of the template
 * @param values The values to be interpolated into the template
 * @returns The resulting HTML string with interpolated values
 *
 * @example Usage with trusted content
 * ```ts
 * import { html } from "@std/html/unstable-html";
 * import { assertEquals } from "@std/assert/equals";
 *
 * const name = "Alice";
 * const color = "blue";
 * const htmlContent = html`
 *   <div>
 *     <h1>Hello, ${name}!</h1>
 *     <p style="color: ${color};">Welcome to our site.</p>
 *   </div>
 * `;
 *
 * assertEquals(htmlContent, `
 *   <div>
 *     <h1>Hello, Alice!</h1>
 *     <p style="color: blue;">Welcome to our site.</p>
 *   </div>
 * `);
 * ```
 *
 * @example Usage with untrusted content that needs to be escaped
 * ```ts
 * import { html } from "@std/html/unstable-html";
 * import { assertEquals } from "@std/assert/equals";
 * import { escape } from "@std/html/entities";
 *
 * // WARNING: This is vulnerable to XSS attacks!
 * const userInput = '<script>alert("XSS")</script>';
 * const unsafeHtml = html`<div>${userInput}</div>`;
 *
 * const safeHtml = html`<div>${escape(userInput)}</div>`;
 *
 * assertEquals(unsafeHtml, '<div><script>alert("XSS")</script></div>');
 * assertEquals(safeHtml, "<div>&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;</div>");
 * ```
 */
export function html(
  strings: TemplateStringsArray,
  ...values: unknown[]
): string {
  return strings.reduce(
    (result, str, i) => result + str + (values[i] ?? ""),
    "",
  );
}