forked from carbon-design-system/carbon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
181 lines (162 loc) · 5.03 KB
/
server.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
'use strict';
/* eslint import/no-extraneous-dependencies: [2, {"devDependencies": true}] */
const path = require('path');
const pathRegexp = require('path-to-regexp');
const browserSync = require('browser-sync');
const serveStatic = require('serve-static');
const chokidar = require('chokidar');
const debounce = require('lodash.debounce');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const devMode = !process.env.NODE_ENV || process.env.NODE_ENV === 'development';
const templates = require('./tools/templates');
const config = devMode && require('./tools/webpack.dev.config'); // eslint-disable-line global-require
const compiler = devMode && webpack(config);
const hotMiddleware = devMode && webpackHotMiddleware(compiler);
let dummyHashSeq = 0;
let templateOrConfigChanged = false;
const watchCallback = debounce(() => {
const featureFlagCacheKey = Object.keys(require.cache).find(key => /feature-flags\.js$/i.test(key));
if (featureFlagCacheKey) {
require.cache[featureFlagCacheKey] = undefined;
}
templates.cache.clear();
if (templateOrConfigChanged) {
templateOrConfigChanged = false;
hotMiddleware.publish({ action: 'sync', hash: `DUMMY_HASH_${dummyHashSeq++}`, errors: [], warnings: [] });
}
}, 500);
const invokeWatchCallback = name => {
if (!/feature-flags\.js$/i.test(name)) {
templateOrConfigChanged = true;
}
watchCallback();
};
if (devMode) {
chokidar
.watch(['demo/feature-flags.js', 'demo/**/*.hbs', 'src/**/*.hbs', 'src/**/*.config.js'])
.on('add', invokeWatchCallback)
.on('change', invokeWatchCallback)
.on('unlink', invokeWatchCallback);
}
const reComponentPath = pathRegexp('/component/:component');
const reDemoComponentPath = pathRegexp('/demo/:component');
const reCodePath = pathRegexp('/code/:component');
const demoStaticRoute = serveStatic('demo');
function noopRoute(req, res, next) {
next();
}
function navRoute(req, res, next) {
const { url } = req;
const name = url === '/' ? url : (reDemoComponentPath.exec(url) || [])[1];
if (!name || /\.(js|css)/i.test(name)) {
next();
} else if (name !== '/' && path.relative('src/components', `src/components/${name}`).substr(0, 2) === '..') {
res.status(404).end();
} else {
templates.cache
.get()
.then(({ componentSource, docSource, contents }) => {
res.setHeader('Content-Type', 'text/html');
res.end(
contents.get('demo-nav')({
yield: contents.get('demo-nav-data')({
componentSource,
docSource,
portSassBuild: process.env.PORT_SASS_DEV_BUILD,
}),
})
);
})
.catch(err => {
console.error(err.stack); // eslint-disable-line no-console
res.writeHead(500);
res.end();
});
}
}
function componentRoute(req, res, next) {
const name = (reComponentPath.exec(req.url) || [])[1];
if (!name) {
next();
} else if (path.relative('src/components', `src/components/${name}`).substr(0, 2) === '..') {
res.writeHead(404);
res.end();
} else {
templates
.render({ layout: 'preview', concat: true }, name)
.then(rendered => {
// eslint-disable-next-line eqeqeq
if (rendered == null) {
res.writeHead(404);
res.end();
} else {
res.setHeader('Content-Type', 'text/html');
res.end(rendered);
}
})
.catch(error => {
console.error(error.stack); // eslint-disable-line no-console
res.writeHead(500);
res.end();
});
}
}
function codeRoute(req, res, next) {
const name = (reCodePath.exec(req.url) || [])[1];
if (!name) {
next();
} else if (path.relative('src/components', `src/components/${name}`).substr(0, 2) === '..') {
res.writeHead(404);
res.end();
} else {
templates
.render({ layout: false }, name)
.then(renderedItems => {
const o = {};
renderedItems.forEach((rendered, item) => {
o[item.handle] = rendered.trim();
});
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(o));
})
.catch(error => {
console.error(error.stack); // eslint-disable-line no-console
res.writeHead(500);
res.end();
});
}
}
function demoRoute(req, res, next) {
if (!/^\/demo\.(css|js)$/i.test(req.url)) {
next();
} else {
demoStaticRoute(req, res, next);
}
}
browserSync({
files: ['demo/demo.css'],
open: false,
port: process.env.PORT || 8080,
server: {
baseDir: 'demo',
middleware: [
!devMode
? noopRoute
: webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
stats: { colors: true },
}),
!devMode ? noopRoute : hotMiddleware,
navRoute,
componentRoute,
codeRoute,
demoRoute,
serveStatic('src'),
serveStatic('scripts'),
],
},
ui: !devMode ? false : {},
});