1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | import * as dom5 from 'dom5/lib/index-next';
|
16 | import * as htmlMinifier from 'html-minifier';
|
17 | import * as parse5 from 'parse5';
|
18 |
|
19 | import * as externalJs from './external-js';
|
20 | import {scriptWasSplitByHtmlSplitter} from './html-splitter';
|
21 | import {jsTransform, JsTransformOptions} from './js-transform';
|
22 |
|
23 | const p = dom5.predicates;
|
24 |
|
25 | const isJsScript = p.AND(
|
26 | p.hasTagName('script'),
|
27 | p.OR(
|
28 | p.NOT(p.hasAttr('type')),
|
29 | p.hasAttrValue('type', 'text/javascript'),
|
30 | p.hasAttrValue('type', 'application/javascript'),
|
31 | p.hasAttrValue('type', 'module')));
|
32 |
|
33 | const isJsScriptOrHtmlImport = p.OR(
|
34 | isJsScript,
|
35 | p.AND(p.hasTagName('link'), p.hasSpaceSeparatedAttrValue('rel', 'import')));
|
36 |
|
37 |
|
38 |
|
39 |
|
40 | export interface HtmlTransformOptions {
|
41 | |
42 |
|
43 |
|
44 | js?: JsTransformOptions;
|
45 |
|
46 | |
47 |
|
48 |
|
49 | minifyHtml?: boolean;
|
50 |
|
51 | |
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 | injectBabelHelpers?: 'none'|'full'|'amd';
|
61 |
|
62 | |
63 |
|
64 |
|
65 |
|
66 | injectRegeneratorRuntime?: boolean;
|
67 |
|
68 | |
69 |
|
70 |
|
71 |
|
72 |
|
73 | injectAmdLoader?: boolean;
|
74 | }
|
75 |
|
76 |
|
77 |
|
78 |
|
79 | export function htmlTransform(
|
80 | html: string, options: HtmlTransformOptions): string {
|
81 | if (options.js && options.js.moduleResolution === 'node' &&
|
82 | !options.js.filePath) {
|
83 | throw new Error('Cannot perform node module resolution without filePath.');
|
84 | }
|
85 |
|
86 | const document = parse5.parse(html, {
|
87 | locationInfo: true,
|
88 | });
|
89 | removeFakeNodes(document);
|
90 | const allScripts = [...dom5.queryAll(document, isJsScript)];
|
91 |
|
92 | const shouldTransformEsModuleToAmd = options.js &&
|
93 | options.js.transformModulesToAmd &&
|
94 |
|
95 |
|
96 |
|
97 |
|
98 | !allScripts.some((node) => dom5.hasAttribute(node, 'nomodule'));
|
99 |
|
100 | let wctScript, firstModuleScript;
|
101 |
|
102 | for (const script of allScripts) {
|
103 | const isModule = dom5.getAttribute(script, 'type') === 'module';
|
104 | if (isModule) {
|
105 | if (firstModuleScript === undefined) {
|
106 | firstModuleScript = script;
|
107 | }
|
108 | if (shouldTransformEsModuleToAmd) {
|
109 | transformEsModuleToAmd(script, options.js);
|
110 | continue;
|
111 | }
|
112 | }
|
113 |
|
114 | const isInline = !dom5.hasAttribute(script, 'src');
|
115 | if (isInline) {
|
116 |
|
117 |
|
118 | const newJs = jsTransform(
|
119 | dom5.getTextContent(script),
|
120 | {...options.js, transformModulesToAmd: false});
|
121 | dom5.setTextContent(script, newJs);
|
122 |
|
123 | } else if (wctScript === undefined) {
|
124 | const src = dom5.getAttribute(script, 'src') || '';
|
125 | if (src.includes('web-component-tester/browser.js') ||
|
126 | src.includes('wct-browser-legacy/browser.js') ||
|
127 | src.includes('wct-mocha/wct-mocha.js')) {
|
128 | wctScript = script;
|
129 | }
|
130 | }
|
131 | }
|
132 |
|
133 | if (options.injectAmdLoader && shouldTransformEsModuleToAmd &&
|
134 | firstModuleScript !== undefined) {
|
135 | const fragment = parse5.parseFragment('<script></script>\n');
|
136 | dom5.setTextContent(fragment.childNodes![0], externalJs.getAmdLoader());
|
137 | const amdLoaderScript = fragment.childNodes![0];
|
138 |
|
139 |
|
140 |
|
141 |
|
142 |
|
143 |
|
144 | dom5.insertBefore(
|
145 | firstModuleScript.parentNode!, firstModuleScript, fragment);
|
146 |
|
147 | if (wctScript !== undefined) {
|
148 | addWctTimingHack(wctScript, amdLoaderScript);
|
149 | }
|
150 | }
|
151 |
|
152 | const injectScript = (js: string) => {
|
153 | const fragment = parse5.parseFragment('<script></script>\n');
|
154 | dom5.setTextContent(fragment.childNodes![0], js);
|
155 |
|
156 | const firstJsScriptOrHtmlImport =
|
157 | dom5.query(document, isJsScriptOrHtmlImport);
|
158 | if (firstJsScriptOrHtmlImport) {
|
159 | dom5.insertBefore(
|
160 | firstJsScriptOrHtmlImport.parentNode!,
|
161 | firstJsScriptOrHtmlImport,
|
162 | fragment);
|
163 |
|
164 | } else {
|
165 | const headOrDocument =
|
166 | dom5.query(document, dom5.predicates.hasTagName('head')) || document;
|
167 | dom5.append(headOrDocument, fragment);
|
168 | }
|
169 | };
|
170 |
|
171 | let babelHelpers;
|
172 | switch (options.injectBabelHelpers) {
|
173 | case undefined:
|
174 | case 'none':
|
175 | break;
|
176 | case 'full':
|
177 | babelHelpers = externalJs.getBabelHelpersFull();
|
178 | break;
|
179 | case 'amd':
|
180 | babelHelpers = externalJs.getBabelHelpersAmd();
|
181 | break;
|
182 | default:
|
183 | const never: never = options.injectBabelHelpers;
|
184 | throw new Error(`Unknown injectBabelHelpers value: ${never}`);
|
185 | }
|
186 |
|
187 | if (babelHelpers !== undefined) {
|
188 | injectScript(babelHelpers);
|
189 | }
|
190 | if (options.injectRegeneratorRuntime === true) {
|
191 | injectScript(externalJs.getRegeneratorRuntime());
|
192 | }
|
193 |
|
194 | html = parse5.serialize(document);
|
195 |
|
196 | if (options.minifyHtml) {
|
197 | html = htmlMinifier.minify(html, {
|
198 | collapseWhitespace: true,
|
199 | removeComments: true,
|
200 | });
|
201 | }
|
202 |
|
203 | return html;
|
204 | }
|
205 |
|
206 | function transformEsModuleToAmd(
|
207 | script: dom5.Node, jsOptions: JsTransformOptions|undefined) {
|
208 |
|
209 | dom5.removeAttribute(script, 'type');
|
210 |
|
211 | if (scriptWasSplitByHtmlSplitter(script)) {
|
212 |
|
213 |
|
214 | return;
|
215 | }
|
216 |
|
217 | const isExternal = dom5.hasAttribute(script, 'src');
|
218 | if (isExternal) {
|
219 | const src = dom5.getAttribute(script, 'src');
|
220 | dom5.removeAttribute(script, 'src');
|
221 | dom5.setTextContent(script, `define(['${src}']);`);
|
222 |
|
223 | } else {
|
224 |
|
225 | const newJs = jsTransform(dom5.getTextContent(script), {
|
226 | ...jsOptions,
|
227 | transformModulesToAmd: true,
|
228 | });
|
229 | dom5.setTextContent(script, newJs);
|
230 | }
|
231 | }
|
232 |
|
233 | function addWctTimingHack(wctScript: dom5.Node, amdLoaderScript: dom5.Node) {
|
234 |
|
235 |
|
236 |
|
237 |
|
238 |
|
239 |
|
240 |
|
241 |
|
242 |
|
243 |
|
244 |
|
245 |
|
246 |
|
247 |
|
248 | dom5.insertBefore(wctScript.parentNode!, wctScript, parse5.parseFragment(`
|
249 | <script>
|
250 | // Injected by polymer-build to defer WCT until all AMD modules are loaded.
|
251 | (function() {
|
252 | window.WCT = window.WCT || {};
|
253 | var originalWaitFor = window.WCT.waitFor;
|
254 | window.WCT.waitFor = function(cb) {
|
255 | window._wctCallback = function() {
|
256 | if (originalWaitFor) {
|
257 | originalWaitFor(cb);
|
258 | } else {
|
259 | cb();
|
260 | }
|
261 | };
|
262 | };
|
263 | }());
|
264 | </script>
|
265 | `));
|
266 |
|
267 |
|
268 |
|
269 |
|
270 |
|
271 | dom5.insertAfter(
|
272 | amdLoaderScript.parentNode!, amdLoaderScript, parse5.parseFragment(`
|
273 | <script>
|
274 | // Injected by polymer-build to defer WCT until all AMD modules are loaded.
|
275 | (function() {
|
276 | var originalDefine = window.define;
|
277 | var moduleCount = 0;
|
278 | window.define = function(deps, factory) {
|
279 | moduleCount++;
|
280 | originalDefine(deps, function() {
|
281 | if (factory) {
|
282 | factory.apply(undefined, arguments);
|
283 | }
|
284 | moduleCount--;
|
285 | if (moduleCount === 0) {
|
286 | window._wctCallback();
|
287 | }
|
288 | });
|
289 | };
|
290 | })();
|
291 | </script>
|
292 | `));
|
293 | }
|
294 |
|
295 |
|
296 |
|
297 |
|
298 |
|
299 |
|
300 |
|
301 |
|
302 |
|
303 |
|
304 | function removeFakeNodes(document: dom5.Node) {
|
305 | const suspects = [];
|
306 | const html =
|
307 | (document.childNodes || []).find((child) => child.tagName === 'html');
|
308 | if (html !== undefined) {
|
309 | suspects.push(html);
|
310 | for (const child of html.childNodes || []) {
|
311 | if (child.tagName === 'head' || child.tagName === 'body') {
|
312 | suspects.push(child);
|
313 | }
|
314 | }
|
315 | }
|
316 | for (const suspect of suspects) {
|
317 |
|
318 | if (!suspect.__location) {
|
319 | dom5.removeNodeSaveChildren(suspect);
|
320 | }
|
321 | }
|
322 | }
|