/
BundleParser.java
299 lines (267 loc) · 11.1 KB
/
BundleParser.java
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/*
* Copyright 2000-2020 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.component.polymertemplate;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.flow.internal.StringUtil;
import elemental.json.Json;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
import elemental.json.JsonType;
import static com.vaadin.flow.server.frontend.FrontendUtils.DEAULT_FLOW_RESOURCES_FOLDER;
import static com.vaadin.flow.server.frontend.FrontendUtils.FLOW_NPM_PACKAGE_NAME;
import static elemental.json.JsonType.ARRAY;
import static elemental.json.JsonType.OBJECT;
import static elemental.json.JsonType.STRING;
/**
* Parse statistics data provided by webpack.
*
* @author Vaadin Ltd
* @since 2.0
*
* @see NpmTemplateParser
* @deprecated Use {@code BundleLitParser} to parse Lit template since polymer
* template is deprecated, we recommend you to use
* {@code LitTemplate} instead. Read more details from <a href=
* "https://vaadin.com/blog/future-of-html-templates-in-vaadin">the
* Vaadin blog.</a>
*/
@Deprecated
public final class BundleParser {
private static final Logger LOGGER = LoggerFactory
.getLogger(BundleParser.class);
private static final String SOURCE = "source";
private static final String NAME = "name";
private static final String CHUNKS = "chunks";
private static final String MODULES = "modules";
/**
* Polymer template pattern matches the template getter
*
* <pre>
* static get template() {
* return html`
* <style>
* .response { margin-top: 10px`; }
* </style>
* <paper-checkbox checked="{{liked}}">I like web components.</paper-checkbox>
*
* <div id="test" hidden$="[[!liked]]" class="response">Web components like you, too.</div>
* `;
* }
* </pre>
*
* <p>
* <code>get[\s]*template\(\)[\s]*\{</code> finds the template getter method
* <p>
* <code>[\s]*return[\s]*html([\`|\'|\"])</code> finds the return statement
* and captures the used string character
* <p>
* </p>
* <code>([\s\S]*)\1;[\s]*\}</code> captures all text until we encounter the
* end character with <code>;}</code> e.g. <code>';}</code>
*/
private static final Pattern POLYMER_TEMPLATE_PATTERN = Pattern.compile(
"get[\\s]*template\\(\\)[\\s]*\\{[\\s]*return[\\s]*html[\\s]*([\\`\\'\\\"])([\\s\\S]*)\\1;[\\s]*\\}");
private static final Pattern NO_TEMPLATE_PATTERN = Pattern.compile(
"innerHTML[\\s]*=[\\s]*([\\`\\'\\\"])([\\s]*<dom-module\\s+[\\s\\S]*)\\1;");
private static final Pattern HASH_PATTERN = Pattern
.compile("\"hash\"\\s*:\\s*\"([^\"]+)\"\\s*,");
private static final String TEMPLATE_TAG_NAME = "template";
private BundleParser() {
}
/**
* Gets the hash from the string content of a webpack stats file. It uses
* regex to avoid parsing the entire string into a json object.
*
* @param fileContents
* the content of the stats file
* @return the hash
*/
public static String getHashFromStatistics(String fileContents) {
Matcher matcher = HASH_PATTERN.matcher(fileContents);
return matcher.find() ? matcher.group(1) : "" + fileContents.length();
}
/**
* Parses the content of the stats file to return a json object.
*
* @param fileContents
* the content of the stats file
* @return a JsonObject with the stats
*/
public static JsonObject parseJsonStatistics(String fileContents) {
return Json.parse(fileContents);
}
/**
* Get a module source from the statistics Json file generated by webpack.
*
* @param fileName
* name of the file to get from the json
* @param statistics
* statistics json as a JsonObject
* @return JsonObject for the file statistic
*/
public static String getSourceFromStatistics(String fileName,
JsonObject statistics) {
return getSourceFromObject(statistics, fileName);
}
/**
* Get the template element for given statistics file object.
*
* @param name
* the file name of the template
* @param statisticsJson
* webpack profile json object
* @return template element for the sources of the given file sources
*/
public static Element parseTemplateElement(String name,
JsonObject statisticsJson) {
return parseTemplateElement(name, statisticsJson.getString(SOURCE));
}
/**
* Get the Polymer template element for the given polymer template source.
*
* @param fileName
* name of the handled file
* @param source
* source js to get template element from
* @return template element or {code null} if not found
*/
public static Element parseTemplateElement(String fileName, String source) {
Document templateDocument = null;
String content = StringUtil.removeComments(source);
Matcher templateMatcher = POLYMER_TEMPLATE_PATTERN.matcher(content);
Matcher noTemplateMatcher = NO_TEMPLATE_PATTERN.matcher(content);
// GroupCount should be 2 as the first group contains `|'|" depending
// on what was in template return html' and the second is the
// template contents.
if (templateMatcher.find() && templateMatcher.groupCount() == 2) {
String group = templateMatcher.group(2);
LOGGER.trace("Found regular Polymer 3 template content was {}",
group);
templateDocument = Jsoup.parse(group);
LOGGER.trace("The parsed template document was {}",
templateDocument);
} else {
Element template = tryParsePolymer2(templateDocument,
noTemplateMatcher);
if (template != null) {
return template;
}
}
if (templateDocument == null) {
LOGGER.warn("No polymer template data found in {} sources.",
fileName);
templateDocument = new Document("");
templateDocument
.appendChild(templateDocument.createElement("body"));
}
Element template = templateDocument.createElement(TEMPLATE_TAG_NAME);
Element body = templateDocument.body();
templateDocument.body().children().stream()
.filter(node -> !node.equals(body))
.forEach(template::appendChild);
return template;
}
private static Element tryParsePolymer2(Document templateDocument,
Matcher noTemplateMatcher) {
while (noTemplateMatcher.find()
&& noTemplateMatcher.groupCount() == 2) {
String group = noTemplateMatcher.group(2);
LOGGER.trace(
"Found Polymer 2 style insertion as a Polymer 3 template content {}",
group);
templateDocument = Jsoup.parse(group);
LOGGER.trace("The parsed template document was {}",
templateDocument);
Optional<Element> domModule = JsoupUtils
.getDomModule(templateDocument, null);
if (!domModule.isPresent()) {
continue;
}
JsoupUtils.removeCommentsRecursively(domModule.get());
Elements templates = domModule.get()
.getElementsByTag(TEMPLATE_TAG_NAME);
if (templates.isEmpty()) {
continue;
}
return templates.get(0);
}
return null;
}
// From the statistics json recursively go through all chunks and modules to
// find the first module whose name matches the file name
private static String getSourceFromObject(JsonObject module,
String fileName) {
String source = null;
if (validKey(module, MODULES, ARRAY)) {
source = getSourceFromArray(module.getArray(MODULES), fileName);
}
if (source == null && validKey(module, CHUNKS, ARRAY)) {
source = getSourceFromArray(module.getArray(CHUNKS), fileName);
}
if (source == null && validKey(module, NAME, STRING)
&& validKey(module, SOURCE, STRING)) {
String name = module.getString(NAME);
String alternativeFileName = fileName
// Replace frontend part since webpack entry-point is
// already in the frontend folder
.replaceFirst("^(\\./)frontend/", "$1")
// Replace the flow frontend protocol
.replaceFirst("^frontend://", ".");
// For polymer templates inside add-ons we will not find the sources
// using ./ as the actual path contains
// "node_modules/@vaadin/flow-frontend/" instead of "./"
// "target/flow-frontend/" instead of "./"
if (name.contains(FLOW_NPM_PACKAGE_NAME)
|| name.contains(DEAULT_FLOW_RESOURCES_FOLDER)) {
alternativeFileName = alternativeFileName.replaceFirst("\\./",
"");
}
// Remove query-string used by webpack modules like babel (e.g
// ?babel-target=es6)
name = name.replaceFirst("\\?.+$", "");
// Do check on the original fileName and the alternative one
if (name.endsWith(fileName) || name.endsWith(alternativeFileName)) {
source = module.getString(SOURCE);
}
}
return source;
}
// Visits all elements of a JsonArray and returns the first element with a
// valid source module
private static String getSourceFromArray(JsonArray objects,
String fileName) {
String source = null;
for (int i = 0; source == null && i < objects.length(); i++) {
if (objects.get(i).getType().equals(OBJECT)) {
source = getSourceFromObject(objects.get(i), fileName);
}
}
return source;
}
private static boolean validKey(JsonObject o, String k, JsonType t) {
boolean validKey = o != null && o.hasKey(k)
&& o.get(k).getType().equals(t);
return validKey && (!t.equals(STRING) || !o.getString(k).isEmpty());
}
}