-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathserver.js
115 lines (104 loc) · 2.83 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
const browserSync = require('browser-sync').create();
const path = require('path');
const hasStartArg = process.argv.includes('--start');
const serverConfig = {
hostname: '127.0.0.1',
port: hasStartArg ? 3002 : 3001,
};
function startServer(options = {}, cb = Function.prototype) {
const defaults = {
...serverConfig,
middleware: [
{
route: '/_blank.html',
handle: function (req, res, next) {
res.setHeader('Content-Type', 'text/html');
res.end('');
next();
},
},
],
notify: false,
open: false,
rewriteRules: [
// Replace docsify-related CDN URLs with local paths
{
match:
/(https?:)?\/\/cdn\.jsdelivr\.net\/npm\/docsify(@\d?\.?\d?\.?\d)?\/lib\//g,
replace: '/lib/',
},
],
server: {
baseDir: path.resolve(__dirname, '../'),
routes: {
'/docs': path.resolve(__dirname, '../../docs'),
'/docs/changelog.md': './CHANGELOG.md',
'/lib': path.resolve(__dirname, '../../lib'),
'/node_modules': path.resolve(__dirname, '../../node_modules'),
},
},
snippetOptions: {
rule: {
match: /<\/body>/i,
fn: function (snippet, match) {
// Override changelog alias to load local changelog (see routes)
const injectJS = `
<script>
// Fix /docs site configuration during tests
(function() {
const aliasConfig = (window && window.$docsify && window.$docsify.alias) || {};
aliasConfig['.*?/changelog'] = '/changelog.md';
})();
</script>
`;
return injectJS + snippet + match;
},
},
},
ui: false,
};
console.log('\n');
// Set TEST_HOST environment variable
process.env.TEST_HOST = `http://${serverConfig.hostname}:${serverConfig.port}`;
// Start server
browserSync.init(
// Config
{
...defaults,
...options,
},
// Callback
cb
);
}
async function startServerAsync() {
await new Promise((resolve, reject) => {
startServer({}, () => {
console.log('\n');
resolve();
});
});
}
function stopServer() {
browserSync.exit();
}
// Allow starting the test server from the CLI. Useful for viewing test content
// like fixtures (/index.html)) and local docs site (/docs) used for testing.
if (hasStartArg) {
startServer({
open: true,
port: serverConfig.port,
directory: true,
startPath: '/docs',
});
}
// Display friendly message about manually starting a server instance
else if (require.main === module) {
console.info('Use --start argument to manually start server instance');
}
module.exports = {
start: startServer,
startAsync: startServerAsync,
stop: stopServer,
TEST_HOST: `http://${serverConfig.hostname}:${serverConfig.port}`,
};