-
Notifications
You must be signed in to change notification settings - Fork 243
/
DomTransformer.js
179 lines (169 loc) · 5.65 KB
/
DomTransformer.js
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
/**
* Copyright 2017 The AMP HTML Authors. All Rights Reserved.
*
* 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.
*/
'use strict';
const treeParser = require('./TreeParser');
const log = require('./log');
let fetch = require('cross-fetch');
const RuntimeVersion = require('@ampproject/toolbox-runtime-version/lib/RuntimeVersion');
const fetchRuntimeParameters = require('./fetchRuntimeParameters');
/**
* AMP Optimizer Configuration only applying AMP validity perserving transformations.
*/
const TRANSFORMATIONS_AMP_FIRST = [
// Adds missing AMP tags
'AddMandatoryTags',
// Optional Markdown compatibility
// needs to run before ServerSideRendering
'Markdown',
// Adds missing AMP extensions
'AutoExtensionImporter',
// Applies server-side-rendering optimizations
'ServerSideRendering',
// Removes the boilerplate
// needs to run after ServerSideRendering
'AmpBoilerplateTransformer',
// Optimizes script import order
// needs to run after ServerSideRendering
'ReorderHeadTransformer',
// needs to run after ReorderHeadTransformer
'RewriteAmpUrls',
'GoogleFontsPreconnect',
// Detect hero image and preload link rel=preload
'PreloadHeroImage',
'PruneDuplicateResourceHints',
// Move keyframes into a separate style tag
'SeparateKeyframes',
'AddTransformedFlag',
// Removes unsupported nonce attribute from scripts
'RemoveCspNonce',
// Minifies HTML, JSON, inline amp-script
'MinifyHtml',
// Inject CSP script has required for inline amp-script
// needs to run after MinifyHtml which changes the inline script
'AmpScriptCsp',
];
/**
* AMP Optimizer Configuration for transformations resulting in invalid AMP pages setting up paired AMP mode.
*
* @deprecated
*/
const TRANSFORMATIONS_PAIRED_AMP = [
// Adds missing AMP extensions
'AutoExtensionImporter',
// Adds a link to the valid AMP version
'AddAmpLink',
// Applies server-side-rendering optimizations
'ServerSideRendering',
// Removes ⚡ or 'amp' from the html tag
'RemoveAmpAttribute',
// Removes the boilerplate
// needs to run after ServerSideRendering
'AmpBoilerplateTransformer',
// Optimizes script import order
// needs to run after ServerSideRendering
'ReorderHeadTransformer',
// needs to run after ReorderHeadTransformer
'RewriteAmpUrls',
'GoogleFontsPreconnect',
// Detect hero image and preload link rel=preload
'PreloadHeroImage',
'PruneDuplicateResourceHints',
'AddBlurryImagePlaceholders',
'SeparateKeyframes',
'AddTransformedFlag',
// Minifies HTML, JSON, inline amp-script
'MinifyHtml',
// Inject CSP script has required for inline amp-script
// needs to run after MinifyHtml which changes the inline script
'AmpScriptCsp',
];
const DEFAULT_CONFIG = {
fetch,
log,
transformations: TRANSFORMATIONS_AMP_FIRST,
verbose: false,
};
/**
* Applies a set of transformations to a DOM tree.
*/
class DomTransformer {
/**
* Create a DomTransformer.
* @param {Object} config - The config.
* @param {Array.<Transformer>} config.transformers - a list of transformers to be applied.
*/
constructor(config = DEFAULT_CONFIG) {
this.setConfig(config);
}
/**
* Transforms an html string.
* @param {string} html - a string containing valid HTML.
* @param {Object} params - a dictionary containing transformer specific parameters.
* @return {string} - the transformed html string
*/
async transformHtml(html, params) {
const tree = await treeParser.parse(html);
await this.transformTree(tree, params);
return treeParser.serialize(tree);
}
/**
* Transforms a DOM tree.
* @param {Tree} tree - a DOM tree.
* @param {Object} customParams - a dictionary containing transformer specific parameters.
*/
async transformTree(tree, customParams = {}) {
log.verbose(customParams.verbose || false);
const runtimeParameters = await fetchRuntimeParameters(this.config, customParams);
const sequence = async (promise, transformer) => {
await promise;
return transformer.transform(tree, runtimeParameters);
};
return this.transformers_.reduce(sequence, Promise.resolve());
}
/**
* Set the config.
* @param {Object} config - The config.
* @param {boolean} config.verbose - true if verbose mode should be enabled [default: false].
* @param {Object} config.fetch - the fetch implementation to use.
* @param {Array.<Transformer>} config.transformations - a list of transformers to be applied.
*/
setConfig(config) {
this.config = Object.assign({}, DEFAULT_CONFIG, config);
if (!this.config.runtimeVersion) {
// Re-use custom fetch implementation for runtime version provider
this.config.runtimeVersion = new RuntimeVersion(this.config.fetch);
}
log.verbose(this.config.verbose);
this.initTransformers_(this.config);
}
/**
* @private
*/
initTransformers_(config) {
this.transformers_ = config.transformations.map((Transformer) => {
if (typeof Transformer === 'string') {
Transformer = require(`./transformers/${Transformer}.js`);
}
return new Transformer(config);
});
}
}
module.exports = {
DomTransformer,
DEFAULT_CONFIG,
TRANSFORMATIONS_AMP_FIRST,
TRANSFORMATIONS_PAIRED_AMP,
};