/
utils.ts
114 lines (93 loc) · 2.47 KB
/
utils.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// TODO: allow '-' to trim up until newline. Use [^\S\n\r] instead of \s
// TODO: only include trimLeft polyfill if not in ES6
import { trimLeft, trimRight } from './polyfills'
/* TYPES */
import { EtaConfig } from './config'
interface EscapeMap {
'&': '&'
'<': '<'
'>': '>'
'"': '"'
"'": '''
[index: string]: string
}
/* END TYPES */
export function hasOwnProp (obj: object, prop: string) {
return Object.prototype.hasOwnProperty.call(obj, prop)
}
// TODO: what did notConfig do?
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function copyProps<T> (toObj: T, fromObj: T /* notConfig?: boolean */) {
for (var key in fromObj) {
if (hasOwnProp((fromObj as unknown) as object, key)) {
toObj[key] = fromObj[key]
}
}
return toObj
}
function trimWS (
str: string,
env: EtaConfig,
wsLeft: string | false,
wsRight?: string | false
): string {
var leftTrim
var rightTrim
if (Array.isArray(env.autoTrim)) {
// kinda confusing
// but _}} will trim the left side of the following string
leftTrim = env.autoTrim[1]
rightTrim = env.autoTrim[0]
} else {
leftTrim = rightTrim = env.autoTrim
}
if (wsLeft || wsLeft === false) {
leftTrim = wsLeft
}
if (wsRight || wsRight === false) {
rightTrim = wsRight
}
if (!rightTrim && !leftTrim) {
return str
}
if (leftTrim === 'slurp' && rightTrim === 'slurp') {
return str.trim()
}
if (leftTrim === '_' || leftTrim === 'slurp') {
// console.log('trimming left' + leftTrim)
// full slurp
str = trimLeft(str)
} else if (leftTrim === '-' || leftTrim === 'nl') {
// nl trim
str = str.replace(/^(?:\r\n|\n|\r)/, '')
}
if (rightTrim === '_' || rightTrim === 'slurp') {
// full slurp
str = trimRight(str)
} else if (rightTrim === '-' || rightTrim === 'nl') {
// nl trim
str = str.replace(/(?:\r\n|\n|\r)$/, '') // TODO: make sure this gets \r\n
}
return str
}
var escMap: EscapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}
function replaceChar (s: string): string {
return escMap[s]
}
function XMLEscape (str: any) {
// eslint-disable-line @typescript-eslint/no-explicit-any
// To deal with XSS. Based on Escape implementations of Mustache.JS and Marko, then customized.
var newStr = String(str)
if (/[&<>"']/.test(newStr)) {
return newStr.replace(/[&<>"']/g, replaceChar)
} else {
return newStr
}
}
export { trimWS, XMLEscape }