forked from carbon-design-system/carbon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
229 lines (207 loc) · 7 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
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
'use strict';
/* eslint import/no-extraneous-dependencies: [2, {"devDependencies": true}] */
const path = require('path');
const Module = require('module');
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 origResolveFilename = Module._resolveFilename;
Module._resolveFilename = function resolveModule(request, parentModule, ...other) {
const newRequest = !/feature-flags$/i.test(request)
? request
: path.relative(path.dirname(parentModule.id), path.resolve(__dirname, 'demo/feature-flags.js'));
return origResolveFilename.call(this, newRequest, parentModule, ...other);
};
const reComponentPath = pathRegexp('/component/:component');
const reDemoComponentPath = pathRegexp('/demo/:component');
const reCodePath = pathRegexp('/code/:component');
const demoStaticRoute = serveStatic('demo');
/**
* @param {ComponentCollection|Component} metadata The component data.
* @returns {Promise<ComponentCollection|Component>}
* The normalized component data,
* esp. with README.md content assigned to `.notes` property for component with variants (`ComponentCollection`).
* Fractal automatically populate `.notes` for component without variants (`Component`).
*/
const normalizeMetadata = metadata => {
const items = metadata.isCollection ? metadata : !metadata.isCollated && metadata.variants && metadata.variants();
const visibleItems = items && items.filter(item => !item.isHidden);
const metadataJSON = typeof metadata.toJSON !== 'function' ? metadata : metadata.toJSON();
if (!metadata.isCollection && visibleItems && visibleItems.size === 1) {
const firstVariant = visibleItems.first();
return Object.assign(metadataJSON, {
context: firstVariant.context,
notes: firstVariant.notes,
preview: firstVariant.preview,
variants: undefined,
});
}
return Object.assign(metadataJSON, {
items: !items || items.size <= 1 ? undefined : items.map(normalizeMetadata).toJSON().items,
variants: undefined,
});
};
/**
* @returns {Promise<(ComponentCollection|Component)[]>} The promise resolved with the list of nav items.
*/
const getNavItems = () =>
templates.cache
.get()
.then(({ componentSource, docSource, contents }) =>
Promise.all([Promise.all(componentSource.items().map(normalizeMetadata)), docSource.items(), contents])
)
.then(([componentItems, docItems, contents]) => ({
componentItems,
docItems,
contents,
}));
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 {
getNavItems()
.then(({ componentItems, docItems, contents }) => {
res.setHeader('Content-Type', 'text/html');
res.end(
contents.get('demo-nav')({
body: contents.get('demo-nav-data')({
componentItems,
docItems,
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();
}
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 : {},
});