-
Notifications
You must be signed in to change notification settings - Fork 102
/
initialize.ts
182 lines (169 loc) · 4.8 KB
/
initialize.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
import prompts from 'prompts';
import { consola } from 'consola';
import { downloadTemplate } from 'giget';
import fs from 'fs-extra';
import path from 'node:path';
import pc from 'picocolors';
import { Formatter } from 'picocolors/types';
export async function initialize(options: {
directory: string;
template: string;
packageManager: string;
}) {
consola.info('Initalizing new project');
const templates = await listTemplates();
const defaultTemplate = templates.find(
(template) => template.name === options.template?.toLowerCase().trim(),
);
const input = await prompts(
[
{
name: 'directory',
type: () => (options.directory == null ? 'text' : undefined),
message: 'Project Directory',
initial: options.directory,
},
{
name: 'template',
type: () => (defaultTemplate == null ? 'select' : undefined),
message: 'Choose a template',
choices: templates.map((template) => ({
title:
TEMPLATE_COLORS[template.name]?.(template.name) ?? template.name,
value: template,
})),
},
{
name: 'packageManager',
type: () => (options.packageManager == null ? 'select' : undefined),
message: 'Package Manager',
choices: [
{ title: pc.red('npm'), value: 'npm' },
{ title: pc.yellow('pnpm'), value: 'pnpm' },
{ title: pc.cyan('yarn'), value: 'yarn' },
{
title: `${pc.magenta('bun')}${pc.gray(' (experimental)')}`,
value: 'bun',
},
],
},
],
{
onCancel: () => process.exit(1),
},
);
input.directory ??= options.directory;
input.template ??= defaultTemplate;
input.packageManager ??= options.packageManager;
const isExists = await fs.pathExists(input.directory);
if (isExists) {
const isEmpty = (await fs.readdir(input.directory)).length === 0;
if (!isEmpty) {
consola.error(
`The directory ${path.resolve(input.directory)} is not empty. Aborted.`,
);
process.exit(1);
}
}
await cloneProject(input);
const cdPath = path.relative(process.cwd(), path.resolve(input.directory));
console.log();
consola.log(
`✨ WXT project created with the ${
TEMPLATE_COLORS[input.template.name]?.(input.template.name) ??
input.template.name
} template.`,
);
console.log();
consola.log('Next steps:');
let step = 0;
if (cdPath !== '') consola.log(` ${++step}.`, pc.cyan(`cd ${cdPath}`));
consola.log(` ${++step}.`, pc.cyan(`${input.packageManager} install`));
console.log();
}
interface Template {
/**
* Template's name.
*/
name: string;
/**
* Path to template directory in github repo.
*/
path: string;
}
async function listTemplates(): Promise<Template[]> {
try {
const res = await fetch('https://ungh.cc/repos/wxt-dev/wxt/files/main');
if (res.status >= 300)
throw Error(`Request failed with status ${res.status} ${res.statusText}`);
const data = (await res.json()) as {
meta: {
sha: string;
};
files: Array<{
path: string;
mode: string;
sha: string;
size: number;
}>;
};
return data.files
.map((item) => item.path.match(/templates\/(.+)\/package\.json/)?.[1])
.filter((name) => name != null)
.map((name) => ({ name: name!, path: `templates/${name}` }))
.sort((l, r) => {
const lWeight = TEMPLATE_SORT_WEIGHT[l.name] ?? Number.MAX_SAFE_INTEGER;
const rWeight = TEMPLATE_SORT_WEIGHT[r.name] ?? Number.MAX_SAFE_INTEGER;
const diff = lWeight - rWeight;
if (diff !== 0) return diff;
return l.name.localeCompare(r.name);
});
} catch (err) {
consola.error(err);
throw Error(`Failed to load templates`);
}
}
async function cloneProject({
directory,
template,
packageManager,
}: {
directory: string;
template: Template;
packageManager: string;
}) {
const { default: ora } = await import('ora');
const spinner = ora('Downloading template').start();
try {
// 1. Clone repo
await downloadTemplate(`gh:wxt-dev/wxt/${template.path}`, {
dir: directory,
force: true,
});
// 2. Move _gitignore -> .gitignore
await fs
.move(
path.join(directory, '_gitignore'),
path.join(directory, '.gitignore'),
)
.catch((err) =>
consola.warn('Failed to move _gitignore to .gitignore:', err),
);
spinner.succeed();
} catch (err) {
spinner.fail();
throw Error(`Failed to setup new project: ${JSON.stringify(err, null, 2)}`);
}
}
const TEMPLATE_COLORS: Record<string, Formatter> = {
vanilla: pc.blue,
vue: pc.green,
react: pc.cyan,
svelte: pc.red,
solid: pc.blue,
};
const TEMPLATE_SORT_WEIGHT: Record<string, number> = {
vanilla: 0,
vue: 1,
react: 2,
};