-
Notifications
You must be signed in to change notification settings - Fork 28
/
preview.ts
79 lines (59 loc) · 2.18 KB
/
preview.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
import { existsSync } from 'fs';
import { resolve } from 'path';
import chalk from 'chalk';
import type { Infer } from 'superstruct';
import { assert, boolean, number, object, optional, string, union } from 'superstruct';
import { type InlineConfig, createServer } from 'vite';
import type { CommandFn } from './types';
const PreviewOptionsStruct = object({
host: optional(boolean()),
open: optional(boolean()),
port: optional(union([number(), string()]))
});
type PreviewOptions = Infer<typeof PreviewOptionsStruct>;
const { error, info } = console;
export const help = chalk`
{blue email preview}
Starts the preview server for a directory of email templates
{underline Usage}
$ email preview <template dir path> [...options]
{underline Options}
--host Allow thew preview server to listen on all addresses (0.0.0.0)
--no-open Do not open a browser tab when the preview server starts
--port The local port number the preview server should run on. Default: 55420
{underline Examples}
$ email preview ./src/templates --port 55420
`;
export const command: CommandFn = async (argv: PreviewOptions, input) => {
if (input.length < 1) return false;
assert(argv, PreviewOptionsStruct);
const [target] = input;
const targetPath = resolve(target);
await start(targetPath, argv);
return true;
};
export const start = async (targetPath: string, argv: PreviewOptions) => {
if (!existsSync(targetPath)) {
error(chalk`\n{red D'oh} The directory provided ({dim ${targetPath}}) doesn't exist`);
return;
}
const { host = false, open = true, port = 55420 } = argv;
const { viteConfig } = await import('./vite');
const mergedConfig = {
configFile: false,
...viteConfig,
resolve: {
alias: {
'@': targetPath,
...viteConfig.resolve?.alias
}
},
server: { fs: { strict: false }, host, port: parseInt(port.toString(), 10) }
} satisfies InlineConfig;
const server = await createServer(mergedConfig);
info(chalk`\n 🚀 {yellow jsx-email} Preview\n`);
await server.listen();
// TODO: bind CLI shortcuts. this hasn't landed in Vite yet, will be released with 5.0
if (open) server.openBrowser();
server.printUrls();
};