Repository navigation
Expand file tree
/
Copy pathrender.js
More file actions
executable file
·188 lines (140 loc) · 5.18 KB
/
Copy pathrender.js
File metadata and controls
executable file
·188 lines (140 loc) · 5.18 KB
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
'use strict';
const moment = require('momentWithLocale');
const util = require('util');
const path = require('path');
const config = require('config');
const fs = require('fs');
const log = require('log')();
const pug = require('lib/serverPug');
const assert = require('assert');
const t = require('i18n');
const pugResolve = require('pugResolve');
const url = require('url');
const validate = require('validate');
const BasicParser = require('markit').BasicParser;
// public.versions.json is regenerated and THEN node is restarted on redeploy
// so it loads a new version.
let publicVersions;
function getPublicVersion(publicPath) {
if (!publicVersions) {
// don't include at module top, let the generating task to finish
publicVersions = require(path.join(config.projectRoot, 'public.versions.json'));
}
let busterPath = publicPath.slice(1);
return publicVersions[busterPath];
}
function addStandardHelpers(locals, ctx) {
// same locals may be rendered many times, let's not add helpers twice
if (locals._hasStandardHelpers) return;
locals.moment = moment;
locals.lang = config.lang;
locals.url = url.parse(ctx.protocol + '://' + ctx.host + ctx.originalUrl);
locals.context = ctx;
locals.livereloadEnabled = true;
locals.js = function(name, options) {
options = options || {};
let src = locals.pack(name, 'js');
let attrs = options.defer ? ' defer' : '';
return `<script src="${src}"${attrs}></script>`;
};
locals.css = function(name) {
let src = locals.pack(name, 'css');
return `<link href="${src}" rel="stylesheet">`;
};
locals.env = process.env;
locals.urlBase = config.urlBase;
// replace lone surrogates in json, </script> -> <\/script>
locals.escapeJSON = function(s) {
let json = JSON.stringify(s);
return json.replace(/\//g, '\\/')
.replace(/[\u003c\u003e]/g,
function(c) {
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4).toUpperCase();
}
).replace(/[\u007f-\uffff]/g,
function(c) {
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
}
);
};
locals.markit = function(text, options) {
return new BasicParser(options).render(text);
};
locals.markitInline = function(text, options) {
return new BasicParser(options).renderInline(text);
};
locals.t = t;
//locals.bem = require('bemPug')();
locals.pack = function(name, ext) {
let versions = JSON.parse(
fs.readFileSync(path.join(config.cacheRoot, 'webpack.versions.json'), {encoding: 'utf-8'})
);
let versionName = versions[name];
// e.g style = [ style.js, style.js.map, style.css, style.css.map ]
if (!Array.isArray(versionName)) return versionName;
let extTestReg = new RegExp(`.${ext}\\b`);
// select right .js\b extension from files
for (let i = 0; i < versionName.length; i++) {
let versionNameItem = versionName[i]; // e.g. style.css.map
if (/\.map/.test(versionNameItem)) continue; // we never need a map
if (extTestReg.test(versionNameItem)) return versionNameItem;
}
throw new Error(`Not found pack name:${name} ext:${ext}`);
/*
if (process.env.NODE_ENV == 'development') {
// webpack-dev-server url
versionName = process.env.STATIC_HOST + ':' + config.webpack.devServer.port + versionName;
}*/
};
locals._hasStandardHelpers = true;
}
// (!) this.render does not assign this.body to the result
// that's because render can be used for different purposes, e.g to send emails
exports.init = function(app) {
app.use(async function(ctx, next) {
let renderFileCache = {};
ctx.locals = Object.assign({}, config.pug);
/**
* Render template
* Find the file:
* if locals.useAbsoluteTemplatePath => use templatePath
* else if templatePath starts with / => lookup in locals.basedir
* otherwise => lookup in ctx.templateDir (MW should set it)
* @param templatePath file to find (see the logic above)
* @param locals
* @returns {String}
*/
ctx.render = function(templatePath, locals) {
// add helpers at render time, not when middleware is used time
// probably we will have more stuff initialized here
addStandardHelpers(ctx.locals, ctx);
// warning!
// Object.assign does NOT copy defineProperty
// so I use ctx.locals as a root and merge all props in it, instead of cloning ctx.locals
let loc = Object.create(ctx.locals);
Object.assign(loc, locals);
if (!loc.schema) {
loc.schema = {};
}
if (!loc.canonicalPath) {
// strip query
loc.canonicalPath = ctx.request.originalUrl.replace(/\?.*/, '');
// /intro/ -> /intro
loc.canonicalPath = loc.canonicalPath.replace(/\/+$/, '');
}
loc.canonicalUrl = config.urlBase.main + loc.canonicalPath;
if (ctx.templateDir) {
loc.roots = [ctx.templateDir];
}
if (loc.sitetoolbar === undefined) {
loc.sitetoolbar = true;
}
loc.plugins = [{
resolve: pugResolve
}];
log.debug("render template", templatePath);
return pug.renderFile(pugResolve(templatePath, null, loc), loc);
};
await next();
});
};