This repository has been archived by the owner on Jul 24, 2021. It is now read-only.
forked from rkazakov/ampify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
232 lines (207 loc) · 7.33 KB
/
index.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
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
const fs = require('fs');
const url = require('url');
const axios = require('axios');
const cheerio = require('cheerio');
const sizeOf = require('image-size');
const CleanCss = require('clean-css');
module.exports = async (html, options) => {
const tags = {
amp: ['img', 'video'],
};
let youtube = false;
const cheerioOptions = options || {
cwd: options.cwd || '',
round: options.round || true,
normalizeWhitespace: options.normalizeWhitespace || false,
xmlMode: options.xmlMode || false,
decodeEntities: options.decodeEntities || false,
};
const $ = cheerio.load(html, cheerioOptions);
const round = cheerioOptions.round ? numb => Math.round(numb / 5) * 5 : numb => numb;
/* Fetch images and CSS */
const promises = [];
const responses = {};
$('img:not([width]):not([height])').each((index, element) => {
const src = $(element).attr('src');
// skip if already fetched
if (responses[src]) {
return;
}
if (src && src.indexOf('//') !== -1) {
// set a flag
responses[src] = true;
let imageUrl = src;
if (src.indexOf('//') === 0) {
imageUrl = `https:${src}`;
}
promises.push(axios.get(imageUrl, { responseType: 'arraybuffer' })
.then((response) => {
responses[src] = response;
}));
}
});
$('link[rel=stylesheet]').each((index, element) => {
const src = $(element).attr('href');
if (responses[src]) {
return;
}
try {
if (src && src.indexOf('//') !== -1) {
let cssSrc = src;
if (src.indexOf('//') === 0) {
cssSrc = `https:${src}`;
}
responses[src] = true;
promises.push(axios.get(cssSrc)
.then((response) => {
responses[src] = response;
}));
}
} catch (err) {
console.dir(err);
}
});
await Promise.all(promises);
/* html ⚡ */
$('html').each((index, element) => {
$(element).attr('amp', '');
});
/* head */
/* main amp library */
$('head script[src="https://cdn.ampproject.org/v0.js"]').remove();
$('head').prepend('<script async src="https://cdn.ampproject.org/v0.js"></script>');
/* meta charset */
$('head meta[charset="utf-8"]').remove();
$('head meta[charset="UTF-8"]').remove();
$('head').prepend('<meta charset="utf-8">');
/* google analytics */
$('script').each((index, element) => {
const src = $(element).attr('src');
if (src) {
const trackingId = src.match(/\bUA-\d{4,10}-\d{1,4}\b/);
if (trackingId) {
$(element).remove();
$('head').prepend('<script async custom-element="amp-analytics"src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>');
$('body').append(`<amp-analytics type="googleanalytics">
<script type="application/json">
{ "vars": {
"account": "${trackingId}"
},
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
}
}
}
</script>
</amp-analytics>`);
}
}
const scriptContent = $(element).html();
const htmlScriptContent = scriptContent.match(/function gtag\(\){dataLayer\.push\(arguments\);}/);
if (scriptContent && htmlScriptContent) {
$(element).remove();
}
});
/* meta viewport */
if ($('head meta[content="width=device-width,minimum-scale=1,initial-scale=1"]').length === 0) {
$('head').append('<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">');
}
/* style amp-boilerplate */
if ($('head style[amp-boilerplate]').length === 0) {
$('head').append('<style amp-boilerplate="">body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate="">body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>');
}
/* body */
/* img dimensions */
$('img:not([width]):not([height])').each((index, element) => {
const src = $(element).attr('src');
if (!src) {
return $(element).remove();
}
if (src.indexOf('//') === -1) {
const image = `${options.cwd}/${$(element).attr('src')}`;
if (fs.existsSync(image)) {
const size = sizeOf(image);
$(element).attr({
width: round(size.width),
height: round(size.height),
layout: 'intrinsic'
});
}
} else if (src.indexOf('//') !== -1) {
const response = responses[src];
if (response === true) {
throw new Error('No image for', src);
}
const size = sizeOf(Buffer.from(response.data, 'binary'));
$(element).attr({
width: round(size.width),
height: round(size.height),
layout: 'intrinsic'
});
}
});
$('img').each((index, element) => {
$(element).attr('loading', null); // remove `loading` attribute from all images, as it's not valid amp syntax
});
/* inline styles */
$('link[rel=stylesheet]').each((index, element) => {
const src = $(element).attr('href');
let path = src;
let file = '';
const setFile = (data) => {
const minified = new CleanCss().minify(data).styles;
return `<style amp-custom>${minified}</style>`;
};
try {
if (src.indexOf('//') === -1) {
path = `${options.cwd}/${src}`;
if (fs.existsSync(path)) {
file = setFile(String(fs.readFileSync(path)));
}
} else if (src.indexOf('//') !== -1) {
const response = responses[src];
if (response === true) {
throw new Error('No CSS for', src);
}
file = setFile(response.data);
}
} catch (err) {
console.dir(err);
}
$(element).replaceWith(file);
});
/* youtube */
$('iframe[src*="http://www.youtube.com"],iframe[src*="https://www.youtube.com"],iframe[src*="http://youtu.be/"],iframe[src*="https://youtu.be/"]').each((index, element) => {
youtube = true;
const src = $(element).attr('src');
let width = $(element).attr('width');
let height = $(element).attr('height');
if(width === "100%" && height === 'auto'){
// default to 720p
width = 480;
height = 270;
}
const path = url.parse(src).pathname.split('/');
const ampYoutube = `
<amp-youtube
data-videoid="${path[path.length - 1]}"
width="${width}"
height="${height}"
layout="responsive">
</amp-youtube>`;
$(element).replaceWith(ampYoutube);
});
if (youtube) {
$('head').prepend('<script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js">');
}
/* amp tags */
$(tags.amp.join(',')).each((index, element) => {
const ampElement = Object.assign(element, {
name: `amp-${element.name}`,
});
$(element).html($(ampElement).html());
});
return $.html();
};