forked from natahouse/react-snap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
923 lines (853 loc) · 28.8 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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
const crawl = require("./src/puppeteer_utils.js").crawl;
const http = require("http");
const express = require("express");
const serveStatic = require("serve-static");
const fallback = require("express-history-api-fallback");
const path = require("path");
const nativeFs = require("fs");
const mkdirp = require("mkdirp");
const minify = require("html-minifier").minify;
const url = require("url");
const minimalcss = require("minimalcss");
const CleanCSS = require("clean-css");
const glob = require("glob-to-regexp");
const isGlob = require("is-glob");
const twentyKb = 20 * 1024;
const defaultOptions = {
//# stable configurations
port: 45678,
source: "build",
destination: null,
concurrency: 4,
include: ["/"],
exclude: [],
userAgent: "ReactSnap",
// 4 params below will be refactored to one: `puppeteer: {}`
// https://github.com/stereobooster/react-snap/issues/120
headless: true,
puppeteer: {
cache: true
},
puppeteerArgs: [],
puppeteerExecutablePath: undefined,
puppeteerIgnoreHTTPSErrors: false,
publicPath: "/",
minifyCss: {},
minifyHtml: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
decodeEntities: true,
keepClosingSlash: true,
sortAttributes: true,
sortClassName: false
},
// mobile first approach
viewport: {
width: 480,
height: 850
},
sourceMaps: true,
//# workarounds
// using CRA1 for compatibility with previous version will be changed to false in v2
fixWebpackChunksIssue: "CRA1",
removeBlobs: true,
fixInsertRule: true,
skipThirdPartyRequests: false,
cacheAjaxRequests: false,
http2PushManifest: false,
// may use some glob solution in the future, if required
// works when http2PushManifest: true
ignoreForPreload: ["service-worker.js"],
//# unstable configurations
preconnectThirdParty: true,
// Experimental. This config stands for two strategies inline and critical.
// TODO: inline strategy can contain errors, like, confuse relative urls
inlineCss: false,
//# feature creeps to generate screenshots
saveAs: "html",
// if true latest path becomes file name: '{route}.html' instead of 'route/index.html'
// or 'path/to/{route}.html' instead of 'path/to/route/index.html'
useRouteAsFileName: false,
crawl: true,
waitFor: false,
externalServer: false,
//# even more workarounds
removeStyleTags: false,
preloadImages: false,
// add async true to script tags
asyncScriptTags: false,
//# another feature creep
// tribute to Netflix Server Side Only React https://twitter.com/NetflixUIE/status/923374215041912833
// but this will also remove code which registers service worker
removeScriptTags: false
};
/**
*
* @param {{source: ?string, destination: ?string, include: ?Array<string>, sourceMaps: ?boolean, skipThirdPartyRequests: ?boolean }} userOptions
* @return {*}
*/
const defaults = userOptions => {
const options = {
...defaultOptions,
...userOptions
};
options.destination = options.destination || options.source;
let exit = false;
if (!options.include || !options.include.length) {
console.log("🔥 include option should be an non-empty array");
exit = true;
} else {
const hasInvalidInclude = options.include.some((path) => isGlob(path));
if (hasInvalidInclude) {
console.log("🔥 you may not use glob patterns for include.");
exit = true;
}
if (options.exclude.length) {
const excludeGlobs = options.exclude.map(g => glob(g, { extended: true, globstar: true}));
const hasOverlappingInclude = excludeGlobs.some((excludeGlob) =>
options.include.some(pagePath => excludeGlob.test(pagePath))
);
if (hasOverlappingInclude) {
console.log("🔥 overlapping include and exclude configs were detected.");
exit = true;
}
}
}
if (options.preloadResources) {
console.log(
"🔥 preloadResources option deprecated. Use preloadImages or cacheAjaxRequests"
);
exit = true;
}
if (options.minifyOptions) {
console.log("🔥 minifyOptions option renamed to minifyHtml");
options.minifyHtml = options.minifyOptions;
}
if (options.asyncJs) {
console.log("🔥 asyncJs option renamed to asyncScriptTags");
options.asyncScriptTags = options.asyncJs;
}
if (options.fixWebpackChunksIssue === true) {
console.log(
"🔥 fixWebpackChunksIssue - behaviour changed, valid options are CRA1, CRA2, Parcel, false"
);
options.fixWebpackChunksIssue = "CRA1";
}
if (
options.saveAs !== "html" &&
options.saveAs !== "png" &&
options.saveAs !== "jpeg"
) {
console.log("🔥 saveAs supported values are html, png, and jpeg");
exit = true;
}
if (exit) throw new Error();
if (options.minifyHtml && !options.minifyHtml.minifyCSS) {
options.minifyHtml.minifyCSS = options.minifyCss;
}
if (!options.publicPath.startsWith("/")) {
options.publicPath = `/${options.publicPath}`;
}
options.publicPath = options.publicPath.replace(/\/$/, "");
options.include = options.include.map(
include => options.publicPath + include
);
return options;
};
const normalizePath = path => (path === "/" ? "/" : path.replace(/\/$/, ""));
/**
*
* @param {{page: Page, basePath: string}} opt
*/
const preloadResources = opt => {
const {
page,
basePath,
preloadImages,
cacheAjaxRequests,
preconnectThirdParty,
http2PushManifest,
ignoreForPreload
} = opt;
const ajaxCache = {};
const http2PushManifestItems = [];
const uniqueResources = new Set();
page.on("response", async response => {
const responseUrl = response.url();
if (/^data:|blob:/i.test(responseUrl)) return;
const ct = response.headers()["content-type"] || "";
const route = responseUrl.replace(basePath, "");
if (/^http:\/\/localhost/i.test(responseUrl)) {
if (uniqueResources.has(responseUrl)) return;
if (preloadImages && /\.(png|jpg|jpeg|webp|gif|svg)$/.test(responseUrl)) {
if (http2PushManifest) {
http2PushManifestItems.push({
link: route,
as: "image"
});
} else {
await page.evaluate(route => {
const linkTag = document.createElement("link");
linkTag.setAttribute("rel", "preload");
linkTag.setAttribute("as", "image");
linkTag.setAttribute("href", route);
document.body.appendChild(linkTag);
}, route);
}
} else if (cacheAjaxRequests && ct.includes("json")) {
const json = await response.json();
ajaxCache[route] = json;
} else if (http2PushManifest && /\.(js)$/.test(responseUrl)) {
const fileName = url
.parse(responseUrl)
.pathname.split("/")
.pop();
if (!ignoreForPreload.includes(fileName)) {
http2PushManifestItems.push({
link: route,
as: "script"
});
}
} else if (http2PushManifest && /\.(css)$/.test(responseUrl)) {
const fileName = url
.parse(responseUrl)
.pathname.split("/")
.pop();
if (!ignoreForPreload.includes(fileName)) {
http2PushManifestItems.push({
link: route,
as: "style"
});
}
}
uniqueResources.add(responseUrl);
} else if (preconnectThirdParty) {
const urlObj = url.parse(responseUrl);
const domain = `${urlObj.protocol}//${urlObj.host}`;
if (uniqueResources.has(domain)) return;
uniqueResources.add(domain);
await page.evaluate(route => {
const linkTag = document.createElement("link");
linkTag.setAttribute("rel", "preconnect");
linkTag.setAttribute("href", route);
document.head.appendChild(linkTag);
}, domain);
}
});
return { ajaxCache, http2PushManifestItems };
};
const removeStyleTags = ({ page }) =>
page.evaluate(() => {
Array.from(document.querySelectorAll("style")).forEach(ell => {
ell.parentElement && ell.parentElement.removeChild(ell);
});
});
const removeScriptTags = ({ page }) =>
page.evaluate(() => {
Array.from(document.querySelectorAll("script")).forEach(ell => {
ell.parentElement && ell.parentElement.removeChild(ell);
});
});
const preloadPolyfill = nativeFs.readFileSync(
`${__dirname}/vendor/preload_polyfill.min.js`,
"utf8"
);
/**
*
* @param {{page: Page}} opt
* @return Promise
*/
const removeBlobs = async opt => {
const { page } = opt;
return page.evaluate(() => {
const stylesheets = Array.from(
document.querySelectorAll("link[rel=stylesheet]")
);
stylesheets.forEach(link => {
if (link.href && link.href.startsWith("blob:")) {
link.parentNode && link.parentNode.removeChild(link);
}
});
});
};
/**
* @param {{page: Page, pageUrl: string, options: {skipThirdPartyRequests: boolean, userAgent: string}, basePath: string, browser: Browser}} opt
* @return {Promise}
*/
const inlineCss = async opt => {
const { page, pageUrl, options, basePath, browser } = opt;
const minimalcssResult = await minimalcss.minimize({
urls: [pageUrl],
skippable: request =>
options.skipThirdPartyRequests && !request.url().startsWith(basePath),
browser: browser,
userAgent: options.userAgent
});
const criticalCss = minimalcssResult.finalCss;
const criticalCssSize = Buffer.byteLength(criticalCss, "utf8");
const result = await page.evaluate(async () => {
const stylesheets = Array.from(
document.querySelectorAll("link[rel=stylesheet]")
);
const cssArray = await Promise.all(
stylesheets.map(async link => {
const response = await fetch(link.href);
return response.text();
})
);
return {
cssFiles: stylesheets.map(link => link.href),
allCss: cssArray.join("")
};
});
const allCss = new CleanCSS(options.minifyCss).minify(result.allCss).styles;
const allCssSize = Buffer.byteLength(allCss, "utf8");
let cssStrategy, cssSize;
if (criticalCssSize * 2 >= allCssSize) {
cssStrategy = "inline";
cssSize = allCssSize;
} else {
cssStrategy = "critical";
cssSize = criticalCssSize;
}
if (cssSize > twentyKb)
console.log(
`⚠️ warning: inlining CSS more than 20kb (${cssSize /
1024}kb, ${cssStrategy})`
);
if (cssStrategy === "critical") {
await page.evaluate(
(criticalCss, preloadPolyfill) => {
const head = document.head || document.getElementsByTagName("head")[0],
style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode(criticalCss));
head.appendChild(style);
const noscriptTag = document.createElement("noscript");
document.head.appendChild(noscriptTag);
const stylesheets = Array.from(
document.querySelectorAll("link[rel=stylesheet]")
);
stylesheets.forEach(link => {
noscriptTag.appendChild(link.cloneNode(false));
link.setAttribute("rel", "preload");
link.setAttribute("as", "style");
link.setAttribute("react-snap-onload", "this.rel='stylesheet'");
document.head.appendChild(link);
});
const scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.text = preloadPolyfill;
// scriptTag.id = "preloadPolyfill";
document.body.appendChild(scriptTag);
},
criticalCss,
preloadPolyfill
);
} else {
await page.evaluate(allCss => {
if (!allCss) return;
const head = document.head || document.getElementsByTagName("head")[0],
style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode(allCss));
if (!head) throw new Error("No <head> element found in document");
head.appendChild(style);
const stylesheets = Array.from(
document.querySelectorAll("link[rel=stylesheet]")
);
stylesheets.forEach(link => {
link.parentNode && link.parentNode.removeChild(link);
});
}, allCss);
}
return {
cssFiles: cssStrategy === "inline" ? result.cssFiles : []
};
};
const asyncScriptTags = ({ page }) => {
return page.evaluate(() => {
Array.from(document.querySelectorAll("script[src]")).forEach(x => {
x.setAttribute("async", "true");
});
});
};
const fixWebpackChunksIssue1 = ({
page,
basePath,
http2PushManifest,
inlineCss
}) => {
return page.evaluate(
(basePath, http2PushManifest, inlineCss) => {
const localScripts = Array.from(document.scripts).filter(
x => x.src && x.src.startsWith(basePath)
);
// CRA v1|v2.alpha
const mainRegexp = /main\.[\w]{8}.js|main\.[\w]{8}\.chunk\.js/;
const mainScript = localScripts.find(x => mainRegexp.test(x.src));
const firstStyle = document.querySelector("style");
if (!mainScript) return;
const chunkRegexp = /(\w+)\.[\w]{8}(\.chunk)?\.js/g;
const chunkScripts = localScripts.filter(x => {
const matched = chunkRegexp.exec(x.src);
// we need to reset state of RegExp https://stackoverflow.com/a/11477448
chunkRegexp.lastIndex = 0;
return matched && matched[1] !== "main" && matched[1] !== "vendors";
});
const mainScripts = localScripts.filter(x => {
const matched = chunkRegexp.exec(x.src);
// we need to reset state of RegExp https://stackoverflow.com/a/11477448
chunkRegexp.lastIndex = 0;
return matched && (matched[1] === "main" || matched[1] === "vendors");
});
const createLink = x => {
if (http2PushManifest) return;
const linkTag = document.createElement("link");
linkTag.setAttribute("rel", "preload");
linkTag.setAttribute("as", "script");
linkTag.setAttribute("href", x.src.replace(basePath, ""));
if (inlineCss) {
firstStyle.parentNode.insertBefore(linkTag, firstStyle);
} else {
document.head.appendChild(linkTag);
}
};
mainScripts.map(x => createLink(x));
for (let i = chunkScripts.length - 1; i >= 0; --i) {
const x = chunkScripts[i];
if (x.parentElement && mainScript.parentNode) {
x.parentElement.removeChild(x);
createLink(x);
}
}
},
basePath,
http2PushManifest,
inlineCss
);
};
const fixWebpackChunksIssue2 = ({
page,
basePath,
http2PushManifest,
inlineCss
}) => {
return page.evaluate(
(basePath, http2PushManifest, inlineCss) => {
const localScripts = Array.from(document.scripts).filter(
x => x.src && x.src.startsWith(basePath)
);
// CRA v2
const mainRegexp = /main\.[\w]{8}\.chunk\.js/;
const mainScript = localScripts.find(x => mainRegexp.test(x.src));
const firstStyle = document.querySelector("style");
if (!mainScript) return;
const chunkRegexp = /(\w+)\.[\w]{8}\.chunk\.js/g;
const headScripts = Array.from(document.querySelectorAll("head script"))
.filter(x => x.src && x.src.startsWith(basePath))
.filter(x => {
const matched = chunkRegexp.exec(x.src);
// we need to reset state of RegExp https://stackoverflow.com/a/11477448
chunkRegexp.lastIndex = 0;
return matched;
});
const chunkScripts = localScripts.filter(x => {
const matched = chunkRegexp.exec(x.src);
// we need to reset state of RegExp https://stackoverflow.com/a/11477448
chunkRegexp.lastIndex = 0;
return matched;
});
const createLink = x => {
if (http2PushManifest) return;
const linkTag = document.createElement("link");
linkTag.setAttribute("rel", "preload");
linkTag.setAttribute("as", "script");
linkTag.setAttribute("href", x.src.replace(basePath, ""));
if (inlineCss) {
firstStyle.parentNode.insertBefore(linkTag, firstStyle);
} else {
document.head.appendChild(linkTag);
}
};
for (let i = headScripts.length; i <= chunkScripts.length - 1; i++) {
const x = chunkScripts[i];
if (x.parentElement && mainScript.parentNode) {
createLink(x);
}
}
for (let i = headScripts.length - 1; i >= 0; --i) {
const x = headScripts[i];
if (x.parentElement && mainScript.parentNode) {
x.parentElement.removeChild(x);
createLink(x);
}
}
},
basePath,
http2PushManifest,
inlineCss
);
};
const fixParcelChunksIssue = ({
page,
basePath,
http2PushManifest,
inlineCss
}) => {
return page.evaluate(
(basePath, http2PushManifest, inlineCss) => {
const localScripts = Array.from(document.scripts)
.filter(x => x.src && x.src.startsWith(basePath))
const mainRegexp = /main\.[\w]{8}\.js/;
const mainScript = localScripts.find(x => mainRegexp.test(x.src));
const firstStyle = document.querySelector("style");
if (!mainScript) return;
const chunkRegexp = /(\w+)\.[\w]{8}\.js/g;
const chunkScripts = localScripts.filter(x => {
const matched = chunkRegexp.exec(x.src);
// we need to reset state of RegExp https://stackoverflow.com/a/11477448
chunkRegexp.lastIndex = 0;
return matched && matched[1] !== "main";
});
const createLink = x => {
if (http2PushManifest) return;
const linkTag = document.createElement("link");
linkTag.setAttribute("rel", "preload");
linkTag.setAttribute("as", "script");
linkTag.setAttribute("href", x.src.replace(`${basePath}/`, ""));
if (inlineCss) {
firstStyle.parentNode.insertBefore(linkTag, firstStyle);
} else {
document.head.appendChild(linkTag);
}
};
for (let i = 0; i <= chunkScripts.length - 1; i++) {
const x = chunkScripts[i];
if (x.parentElement && mainScript.parentNode) {
x.parentElement.removeChild(x);
createLink(x);
}
}
},
basePath,
http2PushManifest,
inlineCss
);
};
const fixInsertRule = ({ page }) => {
return page.evaluate(() => {
Array.from(document.querySelectorAll("style")).forEach(style => {
if (style.innerHTML === "") {
style.innerHTML = Array.from(style.sheet.rules)
.map(rule => rule.cssText)
.join("");
}
});
});
};
const fixFormFields = ({ page }) => {
return page.evaluate(() => {
Array.from(document.querySelectorAll("[type=radio]")).forEach(element => {
if (element.checked) {
element.setAttribute("checked", "checked");
} else {
element.removeAttribute("checked");
}
});
Array.from(document.querySelectorAll("[type=checkbox]")).forEach(
element => {
if (element.checked) {
element.setAttribute("checked", "checked");
} else {
element.removeAttribute("checked");
}
}
);
Array.from(document.querySelectorAll("option")).forEach(element => {
if (element.selected) {
element.setAttribute("selected", "selected");
} else {
element.removeAttribute("selected");
}
});
});
};
const saveAsHtml = async ({ page, filePath, options, route, fs }) => {
let content = await page.content();
content = content.replace(/react-snap-onload/g, "onload");
const title = await page.title();
const minifiedContent = options.minifyHtml
? minify(content, options.minifyHtml)
: content;
const isRootRoute = route == '/'
const hasTrailingSlash = route.endsWith('/')
filePath = filePath.replace(/\//g, path.sep);
// remove trailing / to prevent saving with filename '/route.html'
if (hasTrailingSlash && !isRootRoute) {
filePath = filePath.slice(0, -1)
route = route.slice(0, -1)
}
// saving as 200.html, 404.html
// if useRouteAsFileName: route1.html, route2.html...
if (route.endsWith(".html") || (options.useRouteAsFileName && !isRootRoute)) {
if (route.endsWith("/404.html") && !title.includes("404"))
console.log('⚠️ warning: 404 page title does not contain "404" string');
mkdirp.sync(path.dirname(filePath));
const outputPath = route.endsWith(".html") ? filePath : `${filePath}.html`
fs.writeFileSync(outputPath, minifiedContent);
} else {
// saving as route1/index.html, route2/index.html...
if (title.includes("404"))
console.log(`⚠️ warning: page not found ${route}`);
mkdirp.sync(filePath);
fs.writeFileSync(path.join(filePath, "index.html"), minifiedContent);
}
};
const saveAsPng = ({ page, filePath, options, route }) => {
mkdirp.sync(path.dirname(filePath));
let screenshotPath;
if (route.endsWith(".html")) {
screenshotPath = filePath.replace(/\.html$/, ".png");
} else if (route === "/") {
screenshotPath = `${filePath}index.png`;
} else {
screenshotPath = `${filePath.replace(/\/$/, "")}.png`;
}
return page.screenshot({ path: screenshotPath });
};
const saveAsJpeg = ({ page, filePath, options, route }) => {
mkdirp.sync(path.dirname(filePath));
let screenshotPath;
if (route.endsWith(".html")) {
screenshotPath = filePath.replace(/\.html$/, ".jpeg");
} else if (route === "/") {
screenshotPath = `${filePath}index.jpeg`;
} else {
screenshotPath = `${filePath.replace(/\/$/, "")}.jpeg`;
}
return page.screenshot({ path: screenshotPath });
};
const run = async (userOptions, { fs } = { fs: nativeFs }) => {
let options;
try {
options = defaults(userOptions);
} catch (e) {
return Promise.reject(e.message);
}
const sourceDir = path.normalize(`${process.cwd()}/${options.source}`);
const destinationDir = path.normalize(
`${process.cwd()}/${options.destination}`
);
const startServer = options => {
const app = express()
.use(options.publicPath, serveStatic(sourceDir))
.use(fallback("200.html", { root: sourceDir }));
const server = http.createServer(app);
server.listen(options.port);
return server;
};
if (
destinationDir === sourceDir &&
options.saveAs === "html" &&
fs.existsSync(path.join(sourceDir, "200.html"))
) {
console.log(
`🔥 200.html is present in the sourceDir (${sourceDir}). You can not run react-snap twice - this will break the build`
);
return Promise.reject("");
}
fs.createReadStream(path.join(sourceDir, "index.html")).pipe(
fs.createWriteStream(path.join(sourceDir, "200.html"))
);
if (destinationDir !== sourceDir && options.saveAs === "html") {
mkdirp.sync(destinationDir);
fs.createReadStream(path.join(sourceDir, "index.html")).pipe(
fs.createWriteStream(path.join(destinationDir, "200.html"))
);
}
const server = options.externalServer ? null : startServer(options);
const basePath = `http://localhost:${options.port}`;
const publicPath = options.publicPath;
const ajaxCache = {};
const { http2PushManifest } = options;
const http2PushManifestItems = {};
await crawl({
options,
basePath,
publicPath,
sourceDir,
beforeFetch: async ({ page, route }) => {
const {
preloadImages,
cacheAjaxRequests,
preconnectThirdParty
} = options;
if (
preloadImages ||
cacheAjaxRequests ||
preconnectThirdParty ||
http2PushManifest
) {
const { ajaxCache: ac, http2PushManifestItems: hpm } = preloadResources(
{
page,
basePath,
preloadImages,
cacheAjaxRequests,
preconnectThirdParty,
http2PushManifest,
ignoreForPreload: options.ignoreForPreload
}
);
ajaxCache[route] = ac;
http2PushManifestItems[route] = hpm;
}
},
afterFetch: async ({ page, route, browser, addToQueue }) => {
const pageUrl = `${basePath}${route}`;
if (options.removeStyleTags) await removeStyleTags({ page });
if (options.removeScriptTags) await removeScriptTags({ page });
if (options.removeBlobs) await removeBlobs({ page });
if (options.inlineCss) {
const { cssFiles } = await inlineCss({
page,
pageUrl,
options,
basePath,
browser
});
if (http2PushManifest) {
const filesToRemove = cssFiles
.filter(file => file.startsWith(basePath))
.map(file => file.replace(basePath, ""));
for (let i = http2PushManifestItems[route].length - 1; i >= 0; i--) {
const x = http2PushManifestItems[route][i];
filesToRemove.forEach(fileToRemove => {
if (x.link.startsWith(fileToRemove)) {
http2PushManifestItems[route].splice(i, 1);
}
});
}
}
}
if (options.fixWebpackChunksIssue === "Parcel") {
await fixParcelChunksIssue({
page,
basePath,
http2PushManifest,
inlineCss: options.inlineCss
});
} else if (options.fixWebpackChunksIssue === "CRA2") {
await fixWebpackChunksIssue2({
page,
basePath,
http2PushManifest,
inlineCss: options.inlineCss
});
} else if (options.fixWebpackChunksIssue === "CRA1") {
await fixWebpackChunksIssue1({
page,
basePath,
http2PushManifest,
inlineCss: options.inlineCss
});
}
if (options.asyncScriptTags) await asyncScriptTags({ page });
await page.evaluate(ajaxCache => {
const snapEscape = (() => {
const UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g;
// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their
// Unicode char counterparts which are safe to use in JavaScript strings.
const ESCAPED_CHARS = {
"<": "\\u003C",
">": "\\u003E",
"/": "\\u002F",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
const escapeUnsafeChars = unsafeChar => ESCAPED_CHARS[unsafeChar];
return str => str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
})();
// TODO: as of now it only prevents XSS attack,
// but can stringify only basic data types
// e.g. Date, Set, Map, NaN won't be handled right
const snapStringify = obj => snapEscape(JSON.stringify(obj));
let scriptTagText = "";
if (ajaxCache && Object.keys(ajaxCache).length > 0) {
scriptTagText += `window.snapStore=${snapEscape(
JSON.stringify(ajaxCache)
)};`;
}
let state;
if (
window.snapSaveState &&
(state = window.snapSaveState()) &&
Object.keys(state).length !== 0
) {
scriptTagText += Object.keys(state)
.map(key => `window["${key}"]=${snapStringify(state[key])};`)
.join("");
}
if (scriptTagText !== "") {
const scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.text = scriptTagText;
const firstScript = Array.from(document.scripts)[0];
firstScript.parentNode.insertBefore(scriptTag, firstScript);
}
}, ajaxCache[route]);
delete ajaxCache[route];
if (options.fixInsertRule) await fixInsertRule({ page });
await fixFormFields({ page });
let routePath = route.replace(publicPath, "");
let filePath = path.join(destinationDir, routePath);
if (options.saveAs === "html") {
await saveAsHtml({ page, filePath, options, route, fs });
let newRoute = await page.evaluate(() => location.toString());
newPath = normalizePath(
newRoute.replace(publicPath, "").replace(basePath, "")
);
routePath = normalizePath(routePath);
if (routePath !== newPath) {
console.log(newPath)
console.log(`💬 in browser redirect (${newPath})`);
addToQueue(newRoute);
}
} else if (options.saveAs === "png") {
await saveAsPng({ page, filePath, options, route, fs });
} else if (options.saveAs === "jpeg") {
await saveAsJpeg({ page, filePath, options, route, fs });
}
},
onEnd: () => {
if (server) server.close();
if (http2PushManifest) {
const manifest = Object.keys(http2PushManifestItems).reduce(
(accumulator, key) => {
if (http2PushManifestItems[key].length !== 0)
accumulator.push({
source: key,
headers: [
{
key: "Link",
value: http2PushManifestItems[key]
.map(x => `<${x.link}>;rel=preload;as=${x.as}`)
.join(",")
}
]
});
return accumulator;
},
[]
);
fs.writeFileSync(
`${destinationDir}/http2-push-manifest.json`,
JSON.stringify(manifest)
);
}
}
});
};
exports.defaultOptions = defaultOptions;
exports.run = run;