-
Notifications
You must be signed in to change notification settings - Fork 685
/
serve.js
executable file
·316 lines (243 loc) · 7.52 KB
/
serve.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#!/usr/bin/env node
// Native
const http = require('http');
const path = require('path');
const fs = require('fs');
const {promisify} = require('util');
const {URL} = require('url');
// Packages
const Ajv = require('ajv');
const checkForUpdate = require('update-check');
const chalk = require('chalk');
const arg = require('arg');
const handler = require('serve-handler');
const schema = require('@zeit/schemas/deployment/config-static');
// Utilities
const pkg = require('../package');
const readFile = promisify(fs.readFile);
const warning = message => chalk`{yellow WARNING:} ${message}`;
const info = message => chalk`{magenta INFO:} ${message}`;
const error = message => chalk`{red ERROR:} ${message}`;
const updateCheck = async isDebugging => {
let update = null;
try {
update = await checkForUpdate(pkg);
} catch (err) {
const suffix = isDebugging ? ':' : ' (use `--debug` to see full error)';
console.error(warning(`Checking for updates failed${suffix}`));
if (isDebugging) {
console.error(err);
}
}
if (!update) {
return;
}
console.log(`${chalk.bgRed('UPDATE AVAILABLE')} The latest version of \`serve\` is ${update.latest}`);
};
const getHelp = () => chalk`
{bold.cyan serve} - Static file serving and directory listing
{bold USAGE}
{bold $} {cyan serve} --help
{bold $} {cyan serve} --version
{bold $} {cyan serve} [-l {underline listen_uri} [-l ...]] [{underline directory}]
By default, {cyan serve} will listen on {bold 0.0.0.0:3000} and serve the
current working directory on that address.
Specifying a single {bold --listen} argument will overwrite the default, not supplement it.
{bold OPTIONS}
--help Shows this help message
-v, --version Displays the current version of serve
-l, --listen {underline listen_uri} Specify a URI endpoint on which to listen (see below) -
more than one may be specified to listen in multiple places
-d, --debug Show debugging information
-s, --single Rewrite all not-found requests to \`index.html\`
{bold ENDPOINTS}
Listen endpoints (specified by the {bold --listen} or {bold -l} options above) instruct {cyan serve}
to listen on one or more interfaces/ports, UNIX domain sockets, or Windows named pipes.
For TCP ports on hostname "localhost":
{bold $} {cyan serve} -l {underline 1234}
For TCP (traditional host/port) endpoints:
{bold $} {cyan serve} -l tcp://{underline hostname}:{underline 1234}
For UNIX domain socket endpoints:
{bold $} {cyan serve} -l unix:{underline /path/to/socket.sock}
For Windows named pipe endpoints:
{bold $} {cyan serve} -l pipe:\\\\.\\pipe\\{underline PipeName}
`;
const parseEndpoint = str => {
if (!isNaN(str)) {
return [str];
}
const url = new URL(str);
switch (url.protocol) {
case 'pipe:': {
// some special handling
const cutStr = str.replace(/^pipe:/, '');
if (cutStr.slice(0, 4) !== '\\\\.\\') {
throw new Error(`Invalid Windows named pipe endpoint: ${str}`);
}
return [cutStr];
}
case 'unix:':
if (!url.pathname) {
throw new Error(`Invalid UNIX domain socket endpoint: ${str}`);
}
return [url.pathname];
case 'tcp:':
url.port = url.port || '3000';
return [parseInt(url.port, 10), url.hostname];
default:
throw new Error(`Unknown --listen endpoint scheme (protocol): ${url.protocol}`);
}
};
const registerShutdown = fn => {
let run = false;
const wrapper = () => {
if (!run) {
run = true;
fn();
}
};
process.on('SIGINT', wrapper);
process.on('SIGTERM', wrapper);
process.on('exit', wrapper);
};
const startEndpoint = (endpoint, config) => {
const server = http.createServer((request, response) => handler(request, response, config));
server.on('error', err => {
console.error('serve:', err.stack);
process.exit(1);
});
server.listen(...endpoint, () => {
const details = server.address();
registerShutdown(() => server.close());
if (typeof details === 'string') {
console.log(info(`Accepting connections at ${details}`));
} else if (typeof details === 'object' && details.port) {
const address = details.address === '::' ? 'localhost' : details.address;
console.log(info(`Accepting connections at http://${address}:${details.port}`));
} else {
console.log(info('Accepting connections'));
}
});
};
const loadConfig = async (cwd, entry) => {
const files = [
'serve.json',
'now.json',
'package.json'
];
const config = {};
for (const file of files) {
const location = path.join(entry, file);
let content = null;
try {
content = await readFile(location, 'utf8');
} catch (err) {
if (err.code === 'ENOENT') {
continue;
}
console.error(error(`Not able to read ${location}: ${err.message}`));
process.exit(1);
}
try {
content = JSON.parse(content);
} catch (err) {
console.error(error(`Could not parse ${location} as JSON: ${err.message}`));
process.exit(1);
}
if (typeof content !== 'object') {
console.error(warning(`Didn't find a valid object in ${location}. Skipping...`));
continue;
}
try {
switch (file) {
case 'now.json':
content = content.static;
break;
case 'package.json':
content = content.now.static;
break;
}
} catch (err) {
continue;
}
Object.assign(config, content);
console.log(info(`Discovered configuration in \`${file}\``));
break;
}
if (entry) {
const {public} = config;
config.public = path.relative(cwd, (public ? path.join(entry, public) : entry));
}
if (Object.keys(config).length !== 0) {
const ajv = new Ajv();
const validateSchema = ajv.compile(schema);
if (!validateSchema(config)) {
const defaultMessage = error('The configuration you provided is wrong:');
const {message, params} = validateSchema.errors[0];
console.error(`${defaultMessage}\n${message}\n${JSON.stringify(params)}`);
process.exit(1);
}
}
return config;
};
(async () => {
let args = null;
try {
args = arg({
'--help': Boolean,
'--version': Boolean,
'--listen': [parseEndpoint],
'--single': Boolean,
'--debug': Boolean,
'-h': '--help',
'-v': '--version',
'-l': '--listen',
'-d': '--debug',
'-s': '--single',
// This is deprecated and only for backwards-compatibility.
'-p': '--listen'
});
} catch (err) {
console.error(error(err.message));
process.exit(1);
}
await updateCheck(args['--debug']);
if (args['--version']) {
console.log(pkg.version);
return;
}
if (args['--help']) {
console.log(getHelp());
return;
}
if (!args['--listen']) {
// Default endpoint
args['--listen'] = [[3000]];
}
if (args._.length > 1) {
console.error(error('Please provide one path argument at maximum'));
process.exit(1);
}
const cwd = process.cwd();
const entry = args._.length > 0 ? path.join(cwd, args._[0]) : cwd;
const config = await loadConfig(cwd, entry);
if (args['--single']) {
const {rewrites} = config;
const existingRewrites = Array.isArray(rewrites) ? rewrites : [];
// As the first rewrite rule, make `--single` work
config.rewrites = [{
source: '**',
destination: '/index.html'
}, ...existingRewrites];
}
for (const endpoint of args['--listen']) {
startEndpoint(endpoint, config);
}
registerShutdown(() => {
console.log(`\n${info('Gracefully shutting down. Please wait...')}`);
process.on('SIGINT', () => {
console.log(`\n${warning('Force-closing all open sockets...')}`);
process.exit(0);
});
});
})();