1 | import {join} from 'path';
|
2 |
|
3 | import {PathReference, fileFromString} from '../filesystem';
|
4 |
|
5 | import {RuntimeException} from '../exception';
|
6 |
|
7 | export const inlineStylesheets = (path: PathReference, document: Document): string => {
|
8 | try {
|
9 | const links = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));
|
10 |
|
11 | for (const link of links) {
|
12 | const resource = readResource(window.document, path, link as HTMLLinkElement);
|
13 | if (resource == null) {
|
14 | continue;
|
15 | }
|
16 |
|
17 | link.parentElement.replaceChild(resource, link);
|
18 | }
|
19 |
|
20 | return window.document.documentElement.outerHTML;
|
21 | }
|
22 | catch (exception) {
|
23 | throw new RuntimeException('Failed to inline stylesheet resources', exception);
|
24 | }
|
25 | };
|
26 |
|
27 | const readResource = (document: Document, path: PathReference, link: HTMLLinkElement): HTMLStyleElement => {
|
28 | if (link.href == null || link.href.length === 0) {
|
29 | return null;
|
30 | }
|
31 |
|
32 | const href = Array.from(link.attributes).find(a => a.localName.toLowerCase() === 'href');
|
33 | if (href == null) {
|
34 | return null;
|
35 | }
|
36 |
|
37 | const file = fileFromString(join(path.toString(), href.value));
|
38 | if (file.exists() === false) {
|
39 | return null;
|
40 | }
|
41 |
|
42 | const element = document.createElement('style');
|
43 | element.setAttribute('type', 'text/css');
|
44 | element.setAttribute('media', link.media);
|
45 | element.textContent = file.content();
|
46 | return element;
|
47 | };
|