-
Notifications
You must be signed in to change notification settings - Fork 187
/
normalize.ts
73 lines (61 loc) · 2.06 KB
/
normalize.ts
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
72
73
import type { Dict, SimpleDocumentFragment, SimpleNode } from '@glimmer/interfaces';
import type { TrustedTypesWindow } from 'trusted-types/lib';
export interface SafeString {
toHTML(): string;
}
export type Insertion = CautiousInsertion | TrustingInsertion;
export type CautiousInsertion = string | SafeString | SimpleNode;
export type TrustingInsertion = string | SimpleNode;
export function normalizeStringValue(value: unknown): string {
if (isEmpty(value)) {
return '';
}
return String(value);
}
export function normalizeTrustedValue(value: unknown): TrustingInsertion {
if (isEmpty(value)) {
return '';
}
if (isString(value)) {
return value;
}
if (isSafeString(value)) {
return value.toHTML();
}
if (isNode(value)) {
return value;
}
return String(value);
}
export function shouldCoerce(
value: unknown
): value is string | number | boolean | null | undefined {
return (
isString(value) || isEmpty(value) || typeof value === 'boolean' || typeof value === 'number'
);
}
export function isEmpty(value: unknown): boolean {
return value === null || value === undefined || typeof (value as Dict).toString !== 'function';
}
let isHTML: ((value: unknown) => boolean) | undefined;
if (typeof window !== 'undefined') {
let trustedTypes = (window as unknown as TrustedTypesWindow).trustedTypes;
if (trustedTypes?.isHTML) {
isHTML = trustedTypes?.isHTML.bind(trustedTypes);
}
}
export function isTrustedHTML(value: unknown): boolean {
return isHTML ? isHTML(value) : false;
}
export function isSafeString(value: unknown): value is SafeString {
return typeof value === 'object' && value !== null && typeof (value as any).toHTML === 'function';
}
export function isNode(value: unknown): value is SimpleNode {
return typeof value === 'object' && value !== null && typeof (value as any).nodeType === 'number';
}
export function isFragment(value: unknown): value is SimpleDocumentFragment {
return isNode(value) && value.nodeType === 11;
}
export function isString(value: unknown): value is string {
return typeof value === 'string';
}