mirror of
https://github.com/stack-auth/stack.git
synced 2026-06-13 21:01:21 +08:00
61 lines
1.9 KiB
TypeScript
61 lines
1.9 KiB
TypeScript
import { templateIdentity } from "./strings";
|
|
|
|
export function escapeHtml(unsafe: string): string {
|
|
return `${unsafe}`
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/"/g, """)
|
|
.replace(/'/g, "'");
|
|
}
|
|
import.meta.vitest?.test("escapeHtml", ({ expect }) => {
|
|
// Test with empty string
|
|
expect(escapeHtml("")).toBe("");
|
|
|
|
// Test with string without special characters
|
|
expect(escapeHtml("hello world")).toBe("hello world");
|
|
|
|
// Test with special characters
|
|
expect(escapeHtml("<div>")).toBe("<div>");
|
|
expect(escapeHtml("a & b")).toBe("a & b");
|
|
expect(escapeHtml('a "quoted" string')).toBe("a "quoted" string");
|
|
expect(escapeHtml("it's a test")).toBe("it's a test");
|
|
|
|
// Test with multiple special characters
|
|
expect(escapeHtml("<a href=\"test\">It's a link</a>")).toBe(
|
|
"<a href="test">It's a link</a>"
|
|
);
|
|
});
|
|
|
|
export function html(strings: TemplateStringsArray, ...values: any[]): string {
|
|
return templateIdentity(strings, ...values.map(v => escapeHtml(`${v}`)));
|
|
}
|
|
import.meta.vitest?.test("html", ({ expect }) => {
|
|
// Test with no interpolation
|
|
expect(html`simple string`).toBe("simple string");
|
|
|
|
// Test with string interpolation
|
|
expect(html`Hello, ${"world"}!`).toBe("Hello, world!");
|
|
|
|
// Test with number interpolation
|
|
expect(html`Count: ${42}`).toBe("Count: 42");
|
|
|
|
// Test with HTML special characters in interpolated values
|
|
expect(html`<div>${"<script>"}</div>`).toBe("<div><script></div>");
|
|
|
|
// Test with multiple interpolations
|
|
expect(html`${1} + ${2} = ${"<3"}`).toBe("1 + 2 = <3");
|
|
|
|
// Test with object interpolation
|
|
const obj = { toString: () => "<object>" };
|
|
expect(html`Object: ${obj}`).toBe("Object: <object>");
|
|
});
|
|
|
|
export function htmlToText(untrustedHtml: string): string {
|
|
|
|
const doc = new DOMParser().parseFromString(untrustedHtml, 'text/html');
|
|
|
|
return doc.body.textContent;
|
|
|
|
}
|