/
static.ts
177 lines (162 loc) · 5.59 KB
/
static.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
// Any new exports need to be added to the export statement in
// `packages/lit/src/index.all.ts`.
import {html as coreHtml, svg as coreSvg, TemplateResult} from './lit-html.js';
export interface StaticValue {
/** The value to interpolate as-is into the template. */
_$litStatic$: string;
/**
* A value that can't be decoded from ordinary JSON, make it harder for
* a attacker-controlled data that goes through JSON.parse to produce a valid
* StaticValue.
*/
r: typeof brand;
}
/**
* Prevents JSON injection attacks.
*
* The goals of this brand:
* 1) fast to check
* 2) code is small on the wire
* 3) multiple versions of Lit in a single page will all produce mutually
* interoperable StaticValues
* 4) normal JSON.parse (without an unusual reviver) can not produce a
* StaticValue
*
* Symbols satisfy (1), (2), and (4). We use Symbol.for to satisfy (3), but
* we don't care about the key, so we break ties via (2) and use the empty
* string.
*/
const brand = Symbol.for('');
/** Safely extracts the string part of a StaticValue. */
const unwrapStaticValue = (value: unknown): string | undefined => {
if ((value as Partial<StaticValue>)?.r !== brand) {
return undefined;
}
return (value as Partial<StaticValue>)?.['_$litStatic$'];
};
/**
* Wraps a string so that it behaves like part of the static template
* strings instead of a dynamic value.
*
* Users must take care to ensure that adding the static string to the template
* results in well-formed HTML, or else templates may break unexpectedly.
*
* Note that this function is unsafe to use on untrusted content, as it will be
* directly parsed into HTML. Do not pass user input to this function
* without sanitizing it.
*
* Static values can be changed, but they will cause a complete re-render
* since they effectively create a new template.
*/
export const unsafeStatic = (value: string): StaticValue => ({
['_$litStatic$']: value,
r: brand,
});
const textFromStatic = (value: StaticValue) => {
if (value['_$litStatic$'] !== undefined) {
return value['_$litStatic$'];
} else {
throw new Error(
`Value passed to 'literal' function must be a 'literal' result: ${value}. Use 'unsafeStatic' to pass non-literal values, but
take care to ensure page security.`
);
}
};
/**
* Tags a string literal so that it behaves like part of the static template
* strings instead of a dynamic value.
*
* The only values that may be used in template expressions are other tagged
* `literal` results or `unsafeStatic` values (note that untrusted content
* should never be passed to `unsafeStatic`).
*
* Users must take care to ensure that adding the static string to the template
* results in well-formed HTML, or else templates may break unexpectedly.
*
* Static values can be changed, but they will cause a complete re-render since
* they effectively create a new template.
*/
export const literal = (
strings: TemplateStringsArray,
...values: unknown[]
): StaticValue => ({
['_$litStatic$']: values.reduce(
(acc, v, idx) => acc + textFromStatic(v as StaticValue) + strings[idx + 1],
strings[0]
) as string,
r: brand,
});
const stringsCache = new Map<string, TemplateStringsArray>();
/**
* Wraps a lit-html template tag (`html` or `svg`) to add static value support.
*/
export const withStatic =
(coreTag: typeof coreHtml | typeof coreSvg) =>
(strings: TemplateStringsArray, ...values: unknown[]): TemplateResult => {
const l = values.length;
let staticValue: string | undefined;
let dynamicValue: unknown;
const staticStrings: Array<string> = [];
const dynamicValues: Array<unknown> = [];
let i = 0;
let hasStatics = false;
let s: string;
while (i < l) {
s = strings[i];
// Collect any unsafeStatic values, and their following template strings
// so that we treat a run of template strings and unsafe static values as
// a single template string.
while (
i < l &&
((dynamicValue = values[i]),
(staticValue = unwrapStaticValue(dynamicValue))) !== undefined
) {
s += staticValue + strings[++i];
hasStatics = true;
}
dynamicValues.push(dynamicValue);
staticStrings.push(s);
i++;
}
// If the last value isn't static (which would have consumed the last
// string), then we need to add the last string.
if (i === l) {
staticStrings.push(strings[l]);
}
if (hasStatics) {
const key = staticStrings.join('$$lit$$');
strings = stringsCache.get(key)!;
if (strings === undefined) {
// Beware: in general this pattern is unsafe, and doing so may bypass
// lit's security checks and allow an attacker to execute arbitrary
// code and inject arbitrary content.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(staticStrings as any).raw = staticStrings;
stringsCache.set(
key,
(strings = staticStrings as unknown as TemplateStringsArray)
);
}
values = dynamicValues;
}
return coreTag(strings, ...values);
};
/**
* Interprets a template literal as an HTML template that can efficiently
* render to and update a container.
*
* Includes static value support from `lit-html/static.js`.
*/
export const html = withStatic(coreHtml);
/**
* Interprets a template literal as an SVG template that can efficiently
* render to and update a container.
*
* Includes static value support from `lit-html/static.js`.
*/
export const svg = withStatic(coreSvg);