-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
cli.ts
449 lines (421 loc) · 11.8 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import path from 'path'
import net from 'net'
import os from 'os'
import { exec } from 'child_process'
import * as readline from 'readline'
import fs from 'fs-extra'
import openBrowser from 'open'
import type { Argv } from 'yargs'
import yargs from 'yargs'
import prompts from 'prompts'
import { blue, bold, cyan, dim, gray, green, underline, yellow } from 'kolorist'
import type { LogLevel, ViteDevServer } from 'vite'
import type { SlidevConfig } from '@slidev/types'
import isInstalledGlobally from 'is-installed-globally'
import equal from 'fast-deep-equal'
import { version } from '../package.json'
import { createServer } from './server'
import type { ResolvedSlidevOptions } from './options'
import { getThemeRoots, isPath, resolveOptions } from './options'
import { resolveThemeName } from './themes'
import { parser } from './parser'
const CONFIG_RESTART_FIELDS: (keyof SlidevConfig)[] = [
'highlighter',
'monaco',
'routerMode',
'fonts',
]
const cli = yargs
.scriptName('slidev')
.usage('$0 [args]')
.version(version)
.strict()
.showHelpOnFail(false)
.alias('h', 'help')
.alias('v', 'version')
cli.command(
'* [entry]',
'Start a local server for Slidev',
args => commonOptions(args)
.option('port', {
alias: 'p',
type: 'number',
describe: 'port',
})
.option('open', {
alias: 'o',
default: false,
type: 'boolean',
describe: 'open in browser',
})
.option('remote', {
type: 'string',
describe: 'listen public host and enable remote control',
})
.option('log', {
default: 'warn',
type: 'string',
choices: ['error', 'warn', 'info', 'silent'],
describe: 'log level',
})
.option('force', {
alias: 'f',
default: false,
type: 'boolean',
describe: 'force the optimizer to ignore the cache and re-bundle ',
})
.strict()
.help(),
async ({ entry, theme, port: userPort, open, log, remote, force }) => {
if (!fs.existsSync(entry) && !entry.endsWith('.md'))
entry = `${entry}.md`
if (!fs.existsSync(entry)) {
const { create } = await prompts({
name: 'create',
type: 'confirm',
initial: 'Y',
message: `Entry file ${yellow(`"${entry}"`)} does not exist, do you want to create it?`,
})
if (create)
await fs.copyFile(path.resolve(__dirname, '../template.md'), entry)
else
process.exit(0)
}
let server: ViteDevServer | undefined
let port = 3030
async function initServer() {
if (server)
await server.close()
const options = await resolveOptions({ entry, remote, theme }, 'dev')
port = userPort || await findFreePort(3030)
server = (await createServer(
options,
{
server: {
port,
strictPort: true,
open,
host: remote !== undefined ? '0.0.0.0' : 'localhost',
force,
},
logLevel: log as LogLevel,
},
{
onDataReload(newData, data) {
if (!theme && resolveThemeName(newData.config.theme) !== resolveThemeName(data.config.theme)) {
console.log(yellow('\n restarting on theme change\n'))
initServer()
}
else if (CONFIG_RESTART_FIELDS.some(i => !equal(newData.config[i], data.config[i]))) {
console.log(yellow('\n restarting on config change\n'))
initServer()
}
},
},
))
await server.listen()
printInfo(options, port, remote)
}
const SHORTCUTS = [
{
name: 'r',
fullname: 'restart',
action() {
initServer()
},
},
{
name: 'o',
fullname: 'open',
action() {
openBrowser(`http://localhost:${port}`)
},
},
{
name: 'e',
fullname: 'edit',
action() {
exec(`code "${entry}"`)
},
},
]
function bindShortcut() {
process.stdin.resume()
process.stdin.setEncoding('utf8')
readline.emitKeypressEvents(process.stdin)
if (process.stdin.isTTY)
process.stdin.setRawMode(true)
process.stdin.on('keypress', (str, key) => {
if (key.ctrl && key.name === 'c') {
process.exit()
}
else {
const [sh] = SHORTCUTS.filter(item => item.name === str)
if (sh) {
try {
sh.action()
}
catch (err) {
console.error(`Failed to execute shortcut ${sh.fullname}`, err)
}
}
}
})
}
initServer()
bindShortcut()
},
)
cli.command(
'build [entry]',
'Build hostable SPA',
args => commonOptions(args)
.option('watch', {
alias: 'w',
default: false,
describe: 'build watch',
})
.option('out', {
alias: 'o',
type: 'string',
default: 'dist',
describe: 'output dir',
})
.option('base', {
type: 'string',
describe: 'output base',
})
.option('download', {
alias: 'd',
type: 'boolean',
describe: 'allow download as PDF',
})
.strict()
.help(),
async ({ entry, theme, watch, base, download, out }) => {
const { build } = await import('./build')
const options = await resolveOptions({ entry, theme }, 'build')
if (download && !options.data.config.download)
options.data.config.download = download
printInfo(options)
await build(options, {
base,
build: {
watch: watch ? {} : undefined,
outDir: out,
},
})
},
)
cli.command(
'format [entry]',
'Format the markdown file',
args => commonOptions(args)
.strict()
.help(),
async ({ entry }) => {
const data = await parser.load(entry)
parser.prettify(data)
await parser.save(data)
},
)
cli.command(
'theme [subcommand]',
'Theme related operations',
(command) => {
return command
.command(
'eject',
'Eject current theme into local file system',
args => commonOptions(args)
.option('dir', {
type: 'string',
default: 'theme',
}),
async ({ entry, dir, theme: themeInput }) => {
const data = await parser.load(entry)
const theme = resolveThemeName(themeInput || data.config.theme)
if (theme === 'none') {
console.error('Can not eject theme "none"')
process.exit(1)
}
if (isPath(theme)) {
console.error('Theme is already ejected')
process.exit(1)
}
const roots = getThemeRoots(theme, entry)
if (!roots.length) {
console.error(`Does not found theme "${theme}"`)
process.exit(1)
}
const root = roots[0]
await fs.copy(root, path.resolve(dir), {
filter: i => !/node_modules|.git/.test(path.relative(root, i)),
})
const dirPath = `./${dir}`
data.slides[0].frontmatter.theme = dirPath
// @ts-expect-error remove the value
data.slides[0].raw = null
await parser.save(data)
console.log(`Theme "${theme}" ejected successfully to "${dirPath}"`)
},
)
},
() => {
cli.showHelp()
process.exit(1)
},
)
cli.command(
'export [entry]',
'Export slides to PDF',
args => commonOptions(args)
.option('output', {
type: 'string',
describe: 'path to the output',
})
.option('format', {
default: 'pdf',
type: 'string',
choices: ['pdf', 'png', 'md'],
describe: 'output format',
})
.option('timeout', {
default: 30000,
type: 'number',
describe: 'timeout for rendering the print page',
})
.option('range', {
type: 'string',
describe: 'page ranges to export, for example "1,4-5,6"',
})
.option('dark', {
default: false,
type: 'boolean',
describe: 'export as dark theme',
})
.option('with-clicks', {
alias: 'c',
default: false,
type: 'boolean',
describe: 'export pages for every clicks',
})
.strict()
.help(),
async ({
entry,
theme,
output,
format,
timeout,
range,
dark,
'with-clicks': withClicks,
}) => {
process.env.NODE_ENV = 'production'
const { exportSlides } = await import('./export')
const port = await findFreePort(12445)
const options = await resolveOptions({ entry, theme }, 'build')
output = output || options.data.config.exportFilename || `${path.basename(entry, '.md')}-export`
const server = await createServer(
options,
{
server: { port },
clearScreen: false,
},
)
await server.listen(port)
printInfo(options)
parser.filterDisabled(options.data)
const width = options.data.config.canvasWidth
const height = Math.round(width / options.data.config.aspectRatio)
output = await exportSlides({
port,
slides: options.data.slides,
total: options.data.slides.length,
range,
format: format as any,
output,
timeout,
dark,
routerMode: options.data.config.routerMode,
width,
height,
withClicks,
})
console.log(`${green(' ✓ ')}${dim('exported to ')}./${output}\n`)
server.close()
process.exit(0)
},
)
cli
.help()
.parse()
function commonOptions(args: Argv<{}>) {
return args
.positional('entry', {
default: 'slides.md',
type: 'string',
describe: 'path to the slides markdown entry',
})
.option('theme', {
alias: 't',
type: 'string',
describe: 'override theme',
})
}
function printInfo(options: ResolvedSlidevOptions, port?: number, remote?: string) {
console.log()
console.log()
console.log(` ${cyan('●') + blue('■') + yellow('▲')}`)
console.log(`${bold(' Slidev')} ${blue(`v${version}`)} ${isInstalledGlobally ? yellow('(global)') : ''}`)
console.log()
console.log(dim(' theme ') + (options.theme ? green(options.theme) : gray('none')))
console.log(dim(' entry ') + dim(path.dirname(options.entry) + path.sep) + path.basename(options.entry))
if (port) {
const query = remote ? `?password=${remote}` : ''
const presenterPath = `${options.data.config.routerMode === 'hash' ? '/#/' : '/'}presenter/${query}`
console.log()
console.log(`${dim(' public slide show ')} > ${cyan(`http://localhost:${bold(port)}/`)}`)
if (query)
console.log(`${dim(' private slide show ')} > ${cyan(`http://localhost:${bold(port)}/${query}`)}`)
console.log(`${dim(' presenter mode ')} > ${blue(`http://localhost:${bold(port)}${presenterPath}`)}`)
if (remote !== undefined) {
Object.values(os.networkInterfaces())
.forEach(v => (v || [])
.filter(details => details.family === 'IPv4' && !details.address.includes('127.0.0.1'))
.forEach(({ address }) => {
console.log(`${dim(' remote control ')} > ${blue(`http://${address}:${port}${presenterPath}`)}`)
}),
)
}
else {
console.log(`${dim(' remote control ')} > ${dim('pass --remote to enable')}`)
}
console.log()
console.log(`${dim(' shortcuts ')} > ${underline('r')}${dim('estart | ')}${underline('o')}${dim('pen | ')}${underline('e')}${dim('dit')}`)
}
console.log()
console.log()
}
function isPortFree(port: number) {
return new Promise((resolve) => {
const server = net.createServer((socket) => {
socket.write('Echo server\r\n')
socket.pipe(socket)
})
server.listen(port, '127.0.0.1')
server.on('error', () => {
resolve(false)
})
server.on('listening', () => {
server.close()
resolve(true)
})
})
}
async function findFreePort(start: number): Promise<number> {
if (await isPortFree(start))
return start
return findFreePort(start + 1)
}