This repository was archived by the owner on Sep 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
340 lines (301 loc) · 9.74 KB
/
index.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
const { flags } = require("@oclif/command");
const execa = require("execa");
const http = require("http");
const httpProxy = require("http-proxy");
const waitPort = require("wait-port");
const getPort = require("get-port");
const chokidar = require("chokidar");
const { serveFunctions } = require("../../utils/serve-functions");
const { serverSettings } = require("../../detect-server");
const { detectFunctionsBuilder } = require("../../detect-functions-builder");
const Command = require("@netlify/cli-utils");
const { track } = require("@netlify/cli-utils/src/utils/telemetry");
const chalk = require("chalk");
const {
NETLIFYDEV,
NETLIFYDEVLOG,
NETLIFYDEVWARN
// NETLIFYDEVERR
} = require("netlify-cli-logo");
const boxen = require("boxen");
const { createTunnel, connectTunnel } = require("../../live-tunnel");
function isFunction(settings, req) {
return settings.functionsPort && req.url.match(/^\/.netlify\/functions\/.+/);
}
function addonUrl(addonUrls, req) {
const m = req.url.match(/^\/.netlify\/([^\/]+)(\/.*)/); // eslint-disable-line no-useless-escape
const addonUrl = m && addonUrls[m[1]];
return addonUrl ? `${addonUrl}${m[2]}` : null;
}
// Used as an optimization to avoid dual lookups for missing assets
const assetExtensionRegExp = /\.(html?|png|jpg|js|css|svg|gif|ico|woff|woff2)$/;
function alternativePathsFor(url) {
const paths = [];
if (url[url.length - 1] === "/") {
const end = url.length - 1;
if (url !== "/") {
paths.push(url.slice(0, end) + ".html");
paths.push(url.slice(0, end) + ".htm");
}
paths.push(url + "index.html");
paths.push(url + "index.htm");
} else if (!url.match(assetExtensionRegExp)) {
paths.push(url + ".html");
paths.push(url + ".htm");
paths.push(url + "/index.html");
paths.push(url + "/index.htm");
}
return paths;
}
function initializeProxy(port) {
const proxy = httpProxy.createProxyServer({
selfHandleResponse: true,
target: {
host: "localhost",
port: port
}
});
proxy.on("proxyRes", (proxyRes, req, res) => {
if (
proxyRes.statusCode === 404 &&
req.alternativePaths &&
req.alternativePaths.length > 0
) {
req.url = req.alternativePaths.shift();
return proxy.web(req, res, req.proxyOptions);
}
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.on("data", function(data) {
res.write(data);
});
proxyRes.on("end", function() {
res.end();
});
});
return {
web: (req, res, options) => {
req.proxyOptions = options;
req.alternativePaths = alternativePathsFor(req.url);
return proxy.web(req, res, options);
},
ws: (req, socket, head) => proxy.ws(req, socket, head)
};
}
async function startProxy(settings, addonUrls) {
const rulesProxy = require("@netlify/rules-proxy");
await waitPort({ port: settings.proxyPort });
if (settings.functionsPort) {
await waitPort({ port: settings.functionsPort });
}
const port = await getPort({ port: settings.port || 8888 });
const functionsServer = settings.functionsPort
? `http://localhost:${settings.functionsPort}`
: null;
const proxy = initializeProxy(settings.proxyPort);
const rewriter = rulesProxy({ publicFolder: settings.dist });
const server = http.createServer(function(req, res) {
if (isFunction(settings, req)) {
return proxy.web(req, res, { target: functionsServer });
}
let url = addonUrl(addonUrls, req);
if (url) {
return proxy.web(req, res, { target: url });
}
rewriter(req, res, () => {
if (isFunction(settings, req)) {
return proxy.web(req, res, { target: functionsServer });
}
url = addonUrl(addonUrls, req);
if (url) {
return proxy.web(req, res, { target: url });
}
proxy.web(req, res, { target: `http://localhost:${settings.proxyPort}` });
});
});
server.on("upgrade", function(req, socket, head) {
proxy.ws(req, socket, head);
});
server.listen(port);
return { url: `http://localhost:${port}`, port };
}
function startDevServer(settings, log) {
if (settings.noCmd) {
const StaticServer = require("static-server");
const server = new StaticServer({
rootPath: settings.dist,
name: "netlify-dev",
port: settings.proxyPort,
templates: {
notFound: "404.html"
}
});
server.start(function() {
log(`\n${NETLIFYDEVLOG} Server listening to`, settings.proxyPort);
});
return;
}
log(`${NETLIFYDEVLOG} Starting Netlify Dev with ${settings.type}`);
const args =
settings.command === "npm" ? ["run", ...settings.args] : settings.args;
const ps = execa(settings.command, args, {
env: settings.env,
stdio: "inherit"
});
ps.on("close", code => process.exit(code));
ps.on("SIGINT", process.exit);
ps.on("SIGTERM", process.exit);
}
class DevCommand extends Command {
async run() {
this.log(`${NETLIFYDEV}`);
let { flags } = this.parse(DevCommand);
const { api, site, config } = this.netlify;
const functionsDir =
flags.functions ||
(config.dev && config.dev.functions) ||
(config.build && config.build.functions);
let addonUrls = {};
let accessToken = api.accessToken;
if (site.id && !flags.offline) {
const { addEnvVariables } = require("../../utils/dev");
addonUrls = await addEnvVariables(api, site, accessToken);
}
process.env.NETLIFY_DEV = "true";
let settings = await serverSettings(Object.assign({}, config.dev, flags));
if (!(settings && settings.command)) {
this.log(
`${NETLIFYDEVWARN} No dev server detected, using simple static server`
);
let dist =
(config.dev && config.dev.publish) ||
(config.build && config.build.publish);
if (!dist) {
this.log(`${NETLIFYDEVLOG} Using current working directory`);
this.log(
`${NETLIFYDEVWARN} Unable to determine public folder to serve files from.`
);
this.log(
`${NETLIFYDEVWARN} Setup a netlify.toml file with a [dev] section to specify your dev server settings.`
);
this.log(
`${NETLIFYDEVWARN} See docs at: https://github.com/netlify/netlify-dev-plugin#project-detection`
);
this.log(
`${NETLIFYDEVWARN} Using current working directory for now...`
);
dist = process.cwd();
}
settings = {
noCmd: true,
port: 8888,
proxyPort: await getPort({ port: 3999 }),
dist
};
}
// Reset port if not manually specified, to make it dynamic
if (!(config.dev && config.dev.port) && !flags.port) {
settings = {
port: await getPort({ port: settings.port }),
...settings
};
}
startDevServer(settings, this.log);
// serve functions from zip-it-and-ship-it
// env variables relies on `url`, careful moving this code
if (functionsDir) {
const functionBuilder = await detectFunctionsBuilder(settings);
if (functionBuilder) {
this.log(
`${NETLIFYDEVLOG} Function builder ${chalk.yellow(
functionBuilder.builderName
)} detected: Running npm script ${chalk.yellow(
functionBuilder.npmScript
)}`
);
this.warn(
`${NETLIFYDEVWARN} This is a beta feature, please give us feedback on how to improve at https://github.com/netlify/netlify-dev-plugin/`
);
await functionBuilder.build();
const functionWatcher = chokidar.watch(functionBuilder.src);
functionWatcher.on("add", functionBuilder.build);
functionWatcher.on("change", functionBuilder.build);
functionWatcher.on("unlink", functionBuilder.build);
}
const functionsPort = await getPort({ port: 34567 });
// returns a value but we dont use it
await serveFunctions({
...settings,
port: functionsPort,
functionsDir
});
settings.functionsPort = functionsPort;
}
let { url, port } = await startProxy(settings, addonUrls);
if (!url) {
url = proxyUrl;
}
if (flags.live) {
await waitPort({ port });
const liveSession = await createTunnel(site.id, accessToken, this.log);
url = liveSession.session_url;
process.env.BASE_URL = url;
await connectTunnel(liveSession, accessToken, port, this.log);
}
// Todo hoist this telemetry `command` to CLI hook
track("command", {
command: "dev",
projectType: settings.type || "custom",
live: flags.live || false
});
// boxen doesnt support text wrapping yet https://github.com/sindresorhus/boxen/issues/16
const banner = require("wrap-ansi")(
chalk.bold(`${NETLIFYDEVLOG} Server now ready on ${url}`),
70
);
process.env.URL = url;
process.env.DEPLOY_URL = process.env.URL;
this.log(
boxen(banner, {
padding: 1,
margin: 1,
align: "center",
borderColor: "#00c7b7"
})
);
}
}
DevCommand.description = `Local dev server
The dev command will run a local dev server with Netlify's proxy and redirect rules
`;
DevCommand.examples = [
"$ netlify dev",
'$ netlify dev -c "yarn start"',
"$ netlify dev -c hugo"
];
DevCommand.strict = false;
DevCommand.flags = {
command: flags.string({
char: "c",
description: "command to run"
}),
port: flags.integer({
char: "p",
description: "port of netlify dev" }),
dir: flags.string({
char: "d",
description: "dir with static files"
}),
functions: flags.string({
char: "f",
description: "Specify a functions folder to serve"
}),
offline: flags.boolean({
char: "o",
description: "disables any features that require network access"
}),
live: flags.boolean({
char: "l",
description: "Start a public live session"
})
};
module.exports = DevCommand;