This repository has been archived by the owner on Jan 11, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 433
/
Copy pathcli.ts
executable file
·317 lines (276 loc) · 10 KB
/
cli.ts
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
import * as fs from 'fs';
import * as path from 'path';
import sade from 'sade';
import colors from 'kleur';
import * as pkg from '../package.json';
import { elapsed, repeat, left_pad, format_milliseconds } from './utils';
import { InvalidEvent, ErrorEvent, FatalEvent, BuildEvent, ReadyEvent } from './interfaces';
import { module } from './config/env';
const prog = sade('sapper').version(pkg.version);
if (process.argv[2] === 'start') {
// remove this in a future version
console.error(colors.bold().red('"sapper start" has been removed'));
console.error('Use "node [build_dir]" instead');
process.exit(1);
}
const start = Date.now();
prog.command('dev')
.describe('Start a development server')
.option('-p, --port', 'Specify a port')
.option('-o, --open', 'Open a browser window')
.option('--dev-port', 'Specify a port for development server')
.option('--hot', 'Use hot module replacement (requires webpack)', true)
.option('--live', 'Reload on changes if not using --hot', true)
.option('--bundler', 'Specify a bundler (rollup or webpack)')
.option('--cwd', 'Current working directory', '.')
.option('--src', 'Source directory', 'src')
.option('--routes', 'Routes directory', 'src/routes')
.option('--static', 'Static files directory', 'static')
.option('--output', 'Sapper intermediate file output directory', 'src/node_modules/@sapper')
.option('--build-dir', 'Development build directory', '__sapper__/dev')
.option('--ext', 'Custom Route Extension', '.svelte .html')
.action(async (opts: {
port: number;
open: boolean;
'dev-port': number;
live: boolean;
hot: boolean;
bundler?: 'rollup' | 'webpack';
cwd: string;
src: string;
routes: string;
static: string;
output: string;
'build-dir': string;
ext: string;
}) => {
const { dev } = await import('./api/dev');
try {
const watcher = dev({
cwd: opts.cwd,
src: opts.src,
routes: opts.routes,
static: opts.static,
output: opts.output,
dest: opts['build-dir'],
port: opts.port,
'dev-port': opts['dev-port'],
live: opts.live,
hot: opts.hot,
bundler: opts.bundler,
ext: opts.ext
});
let first = true;
watcher.on('stdout', data => {
process.stdout.write(data);
});
watcher.on('stderr', data => {
process.stderr.write(data);
});
watcher.on('ready', async (event: ReadyEvent) => {
if (first) {
console.log(colors.bold().cyan(`> Listening on http://localhost:${event.port}`));
if (opts.open) {
const { exec } = await import('child_process');
exec(`open http://localhost:${event.port}`);
}
first = false;
}
});
watcher.on('invalid', (event: InvalidEvent) => {
const changed = event.changed.map(filename => path.relative(process.cwd(), filename)).join(', ');
console.log(`\n${colors.bold().cyan(changed)} changed. Rebuilding...`);
});
watcher.on('error', (event: ErrorEvent) => {
const { type, error } = event;
console.log(colors.bold().red(`✗ ${type}`));
if (error.loc && error.loc.file) {
console.log(colors.bold(`${path.relative(process.cwd(), error.loc.file)} (${error.loc.line}:${error.loc.column})`));
}
console.log(colors.red(event.error.message));
if (error.frame) console.log(error.frame);
});
watcher.on('fatal', (event: FatalEvent) => {
console.log(colors.bold().red(`> ${event.message}`));
if (event.log) console.log(event.log);
});
watcher.on('build', (event: BuildEvent) => {
if (event.errors.length) {
console.log(colors.bold().red(`✗ ${event.type}`));
event.errors.filter(e => !e.duplicate).forEach(error => {
if (error.file) console.log(colors.bold(error.file));
console.log(error.message);
});
const hidden = event.errors.filter(e => e.duplicate).length;
if (hidden > 0) {
console.log(`${hidden} duplicate ${hidden === 1 ? 'error' : 'errors'} hidden\n`);
}
} else if (event.warnings.length) {
console.log(colors.bold().yellow(`• ${event.type}`));
event.warnings.filter(e => !e.duplicate).forEach(warning => {
if (warning.file) console.log(colors.bold(warning.file));
console.log(warning.message);
});
const hidden = event.warnings.filter(e => e.duplicate).length;
if (hidden > 0) {
console.log(`${hidden} duplicate ${hidden === 1 ? 'warning' : 'warnings'} hidden\n`);
}
} else {
console.log(`${colors.bold().green(`✔ ${event.type}`)} ${colors.gray(`(${format_milliseconds(event.duration)})`)}`);
}
});
} catch (err) {
console.log(colors.bold().red(`> ${err.message}`));
console.log(colors.gray(err.stack));
process.exit(1);
}
});
prog.command('build [dest]')
.describe('Create a production-ready version of your app')
.option('-p, --port', 'Default of process.env.PORT', '3000')
.option('--bundler', 'Specify a bundler (rollup or webpack, blank for auto)')
.option('--legacy', 'Create separate legacy build')
.option('--cwd', 'Current working directory', '.')
.option('--src', 'Source directory', 'src')
.option('--routes', 'Routes directory', 'src/routes')
.option('--output', 'Sapper intermediate file output directory', 'src/node_modules/@sapper')
.option('--ext', 'Custom page route extensions (space separated)', '.svelte .html')
.example('build custom-dir -p 4567')
.action(async (dest = '__sapper__/build', opts: {
port: string;
legacy: boolean;
bundler?: 'rollup' | 'webpack';
cwd: string;
src: string;
routes: string;
output: string;
ext: string;
}) => {
console.log('> Building...');
try {
await _build(opts.bundler, opts.legacy, opts.cwd, opts.src, opts.routes, opts.output, dest, opts.ext);
const launcher = path.resolve(dest, 'index.js');
const import_statement = module
? "import './server/server.js';"
: "require('./server/server.js');";
fs.writeFileSync(launcher, `
// generated by sapper build at ${new Date().toISOString()}
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
process.env.PORT = process.env.PORT || ${opts.port || 3000};
console.log('Starting server on port ' + process.env.PORT);
${import_statement}
`.replace(/^\t+/gm, '').trim());
console.error(`\n> Finished in ${elapsed(start)}. Type ${colors.bold().cyan(`node ${dest}`)} to run the app.`);
} catch (err) {
console.log(`${colors.bold().red(`> ${err.message}`)}`);
console.log(colors.gray(err.stack));
process.exit(1);
}
});
prog.command('export [dest]')
.describe('Export your app as static files (if possible)')
.option('--build', '(Re)build app before exporting', true)
.option('--basepath', 'Specify a base path')
.option('--host', 'Host header to use when crawling site')
.option('--concurrent', 'Concurrent requests', 8)
.option('--timeout', 'Milliseconds to wait for a page (--no-timeout to disable)', 5000)
.option('--legacy', 'Creates an additional build, served only to legacy browsers')
.option('--bundler', 'Specify a bundler (rollup or webpack, blank for auto)')
.option('--cwd', 'Current working directory', '.')
.option('--src', 'Source directory', 'src')
.option('--routes', 'Routes directory', 'src/routes')
.option('--static', 'Static files directory', 'static')
.option('--output', 'Sapper intermediate file output directory', 'src/node_modules/@sapper')
.option('--build-dir', 'Intermediate build directory', '__sapper__/build')
.option('--ext', 'Custom page route extensions (space separated)', '.svelte .html')
.option('--entry', 'Custom entry points (space separated)', '/')
.action(async (dest = '__sapper__/export', opts: {
build: boolean;
legacy: boolean;
bundler?: 'rollup' | 'webpack';
basepath?: string;
host?: string;
concurrent: number;
timeout: number | false;
cwd: string;
src: string;
routes: string;
static: string;
output: string;
'build-dir': string;
ext: string;
entry: string;
}) => {
try {
if (opts.build) {
console.log('> Building...');
await _build(opts.bundler, opts.legacy, opts.cwd, opts.src, opts.routes, opts.output, opts['build-dir'], opts.ext);
console.error(`\n> Built in ${elapsed(start)}`);
}
const { export: _export } = await import('./api/export');
const { default: pb } = await import('pretty-bytes');
await _export({
cwd: opts.cwd,
static: opts.static,
build_dir: opts['build-dir'],
export_dir: dest,
basepath: opts.basepath,
host_header: opts.host,
timeout: opts.timeout,
concurrent: opts.concurrent,
entry: opts.entry,
oninfo: event => {
console.log(colors.bold().cyan(`> ${event.message}`));
},
onfile: event => {
const size_color = event.size > 150000 ? colors.bold().red : event.size > 50000 ? colors.bold().yellow : colors.bold().gray;
const size_label = size_color(left_pad(pb(event.size), 10));
const file_label = event.status === 200
? event.file
: colors.bold()[event.status >= 400 ? 'red' : 'yellow'](`(${event.status}) ${event.file}`);
console.log(`${size_label} ${file_label}`);
}
});
console.error(`\n> Finished in ${elapsed(start)}. Type ${colors.bold().cyan(`npx serve ${dest}`)} to run the app.`);
} catch (err) {
console.error(colors.bold().red(`> ${err.message}`));
process.exit(1);
}
});
prog.parse(process.argv, { unknown: (arg: string) => `Unknown option: ${arg}` });
async function _build(
bundler: 'rollup' | 'webpack',
legacy: boolean,
cwd: string,
src: string,
routes: string,
output: string,
dest: string,
ext: string
) {
const { build } = await import('./api/build');
await build({
bundler,
legacy,
cwd,
src,
routes,
dest,
ext,
output,
oncompile: event => {
let banner = `built ${event.type}`;
let c = (txt: string) => colors.cyan(txt);
const { warnings } = event.result;
if (warnings.length > 0) {
banner += ` with ${warnings.length} ${warnings.length === 1 ? 'warning' : 'warnings'}`;
c = (txt: string) => colors.cyan(txt);
}
console.log();
console.log(c(`┌─${repeat('─', banner.length)}─┐`));
console.log(c(`│ ${colors.bold(banner) } │`));
console.log(c(`└─${repeat('─', banner.length)}─┘`));
console.log(event.result.print());
}
});
}