1 | const fs = require('fs-extra');
|
2 | const path = require('path');
|
3 |
|
4 | const getCwd = require('../utils/get-cwd');
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | const validateTemplate = optionTemplate => {
|
14 | if (typeof optionTemplate !== 'string')
|
15 | throw new Error('validate-template: `template` need to be String');
|
16 |
|
17 | let template;
|
18 | if (fs.existsSync(optionTemplate)) {
|
19 | template = fs.readFileSync(optionTemplate, 'utf-8');
|
20 | } else if (optionTemplate.substr(0, 2) === './') {
|
21 | template = fs.readFileSync(
|
22 | path.resolve(getCwd(), optionTemplate),
|
23 | 'utf-8'
|
24 | );
|
25 | } else if (path.isAbsolute(optionTemplate)) {
|
26 | template = fs.readFileSync(path.resolve(optionTemplate), 'utf-8');
|
27 | }
|
28 |
|
29 | {
|
30 |
|
31 | const important = {
|
32 | head: {
|
33 | append: ['metas', 'styles']
|
34 | },
|
35 | body: {
|
36 | prepend: ['react'],
|
37 | append: ['scripts']
|
38 | }
|
39 | };
|
40 |
|
41 | Object.keys(important).forEach(tagName => {
|
42 | Object.keys(important[tagName]).forEach(type => {
|
43 | important[tagName][type].forEach(inject => {
|
44 | const regex = new RegExp(`<%\\W*inject\\.${inject}\\W*%>`);
|
45 |
|
46 |
|
47 | if (regex.test(template)) return;
|
48 |
|
49 | const str = (() => {
|
50 | if (inject === 'react')
|
51 | return `<div id="root"><%- inject.${inject} %></div>`;
|
52 | return `<%- inject.${inject} %>`;
|
53 | })();
|
54 | template = template.replace(
|
55 | new RegExp(
|
56 | `<${type == 'append' ? '/' : ''}${tagName}.*?>`
|
57 | ),
|
58 | match => {
|
59 | if (type === 'prepend') return `${match}\n${str}`;
|
60 | return `${str}\n${match}`;
|
61 | }
|
62 | );
|
63 | });
|
64 | });
|
65 | });
|
66 | }
|
67 |
|
68 |
|
69 |
|
70 | return (
|
71 | template +
|
72 | `\n<!-- rendered by using koot.js ${process.env.KOOT_VERSION} -->`
|
73 | );
|
74 | };
|
75 |
|
76 | module.exports = validateTemplate;
|