-
Notifications
You must be signed in to change notification settings - Fork 406
/
Copy pathserver.js
118 lines (108 loc) · 3.17 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
'use strict';
const path = require('path');
const liveServer = require('@pattern-lab/live-server');
const events = require('./events');
const logger = require('./log');
const server = (patternlab) => {
const _module = {
serve: () => {
let serverReady = false;
// our default liveserver config
const defaults = {
open: true,
file: 'index.html',
logLevel: 0, // errors only
wait: 1000,
port: 3000,
};
const servers = Object.keys(patternlab.uikits).map((kit) => {
const uikit = patternlab.uikits[kit];
defaults.root = path.resolve(
path.join(
process.cwd(),
uikit.outputDir,
patternlab.config.paths.public.root
)
);
defaults.ignore = path.resolve(
path.join(
process.cwd(),
uikit.outputDir,
patternlab.config.paths.public.root
)
);
// allow for overrides should they exist inside patternlab-config.json
const liveServerConfig = Object.assign(
{},
defaults,
patternlab.config.serverOptions
);
const setupEventWatchers = () => {
//watch for builds to complete
patternlab.events.on(events.PATTERNLAB_BUILD_END, () => {
if (serverReady) {
_module.reload({
file: '',
action: 'reload',
});
}
});
};
//start!
//There is a new server instance for each uikit
const serveKit = new Promise((resolve, reject) => {
let resolveMsg = '';
setTimeout(() => {
try {
liveServer.start(liveServerConfig);
resolveMsg = `Pattern Lab is being served from ${
liveServerConfig.https ? 'https' : 'http'
}://127.0.0.1:${liveServerConfig.port}`;
logger.info(resolveMsg);
} catch (e) {
const err = `Pattern Lab serve failed to start: ${e}`;
logger.error(`Pattern Lab serve failed to start: ${e}`);
reject(err);
}
setupEventWatchers();
serverReady = true;
resolve(resolveMsg);
}, liveServerConfig.wait);
});
return serveKit;
});
return Promise.all(servers);
},
reload: (data) => {
const _data = data || {
file: '',
action: '',
};
return new Promise((resolve, reject) => {
let action;
try {
if (!patternlab.isBusy) {
if (_data.file.indexOf('css') > -1 || _data.action === 'refresh') {
action = 'refreshed CSS';
liveServer.refreshCSS();
} else {
action = 'reloaded';
liveServer.reload();
}
resolve(`Server ${action} successfully`);
}
} catch (e) {
reject(`Server reload or refresh failed: ${e}`);
}
});
},
refreshCSS: () => {
return _module.reload({
file: '',
action: 'refresh',
});
},
};
return _module;
};
module.exports = server;