create-cookbook 1.0.0-alpha.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.mjs +222 -0
  2. package/package.json +17 -0
  3. package/tsconfig.json +27 -0
package/index.mjs ADDED
@@ -0,0 +1,222 @@
1
+ #!/usr/bin/env node
2
+
3
+ import os from "node:os";
4
+ import { join } from "node:path";
5
+ import { exit } from "node:process";
6
+ import { Readable } from "node:stream";
7
+ import { finished } from "node:stream/promises";
8
+ import { execFileSync } from "node:child_process";
9
+ import { mkdirSync, existsSync, createWriteStream, rmSync } from "node:fs";
10
+ import { remove } from "fs-extra";
11
+ import consola from "consola";
12
+ import gradient from "gradient-string";
13
+ import compressing from "compressing";
14
+
15
+ const colorLong = gradient(["cyan", "green"]);
16
+ const color = gradient(["cyan", "#2d9b87"]);
17
+
18
+ (async () => {
19
+ const args = process.argv.slice(2);
20
+ let version = "latest";
21
+ // biome-ignore lint/complexity/useOptionalChain: <explanation>
22
+ if (args[0] && args[0].startsWith("--version=")) {
23
+ version = args[0].slice(10);
24
+ }
25
+ const workspace = process.platform === "win32" ? join(process.env.USERPROFILE, ".cookbook") : join(process.env.HOME, ".cookbook");
26
+ const tempspace = process.platform === "win32" ? join(process.env.USERPROFILE, ".cookbook", ".temp") : join(process.env.HOME, ".cookbook", ".temp");
27
+ if (!existsSync(workspace)) mkdirSync(workspace);
28
+ if (!existsSync(tempspace)) mkdirSync(tempspace);
29
+
30
+ const uiName = "@milkio/cookbook-ui";
31
+ const cookbookName = `@milkio/cookbook-${process.platform}-${os.arch()}`;
32
+ let uiPackageInfo;
33
+ let cookbookPackageInfo;
34
+ console.log("");
35
+ for (const mirror of ["https://registry.npmjs.org/", "https://registry.npmmirror.com/", "https://mirrors.cloud.tencent.com/npm/", "https://cdn.jsdelivr.net/npm/"]) {
36
+ try {
37
+ consola.start(color(`[1/2] Checking (${mirror}${uiName})..`));
38
+ const controller = new AbortController();
39
+ const timeout = setTimeout(() => controller.abort(), 8000);
40
+ const response = await fetch(`${mirror}${uiName}`, {
41
+ signal: controller.signal
42
+ });
43
+ clearTimeout(timeout);
44
+ if (response.status !== 200) continue;
45
+ const json = await response.json();
46
+ if (json.name !== uiName) continue;
47
+ uiPackageInfo = {
48
+ mirror,
49
+ json,
50
+ };
51
+ break;
52
+ } catch (error) {
53
+ // biome-ignore lint/correctness/noUnnecessaryContinue: <explanation>
54
+ continue;
55
+ }
56
+ }
57
+ if (!uiPackageInfo) {
58
+ consola.error(color("Network connection failed!"));
59
+ exit(1);
60
+ }
61
+ for (const mirror of ["https://registry.npmjs.org/", "https://registry.npmmirror.com/", "https://mirrors.cloud.tencent.com/npm/", "https://cdn.jsdelivr.net/npm/"]) {
62
+ try {
63
+ consola.start(color(`[2/2] Checking (${mirror}${cookbookName})..`));
64
+ const controller = new AbortController();
65
+ const timeout = setTimeout(() => controller.abort(), 8000);
66
+ const response = await fetch(`${mirror}${cookbookName}`, {
67
+ signal: controller.signal
68
+ });
69
+ clearTimeout(timeout);
70
+ if (response.status !== 200) continue;
71
+ const json = await response.json();
72
+ if (json.name !== cookbookName) continue;
73
+ cookbookPackageInfo = {
74
+ mirror,
75
+ json,
76
+ };
77
+ break;
78
+ } catch (error) {
79
+ // biome-ignore lint/correctness/noUnnecessaryContinue: <explanation>
80
+ continue;
81
+ }
82
+ }
83
+ if (!cookbookPackageInfo) {
84
+ consola.error(color("Network connection failed!"));
85
+ exit(1);
86
+ }
87
+
88
+ const uiUrl = `${cookbookPackageInfo.mirror}${uiName}/-/cookbook-ui-${version === 'latest' ? uiPackageInfo.json["dist-tags"].latest : version}.tgz`;
89
+ consola.start(uiUrl);
90
+ consola.start(color(`[1/2] Downloading Cookbook UI (${uiUrl})..`));
91
+ await utils.downloadFile(uiUrl, tempspace, "ui.tgz");
92
+ consola.success(color("[1/2] Downloaded!"));
93
+ const uiExtractPromise = ((async () => {
94
+ if (!existsSync(join(tempspace, "ui"))) mkdirSync(join(tempspace, "ui"))
95
+ await compressing.tgz.uncompress(join(tempspace, "ui.tgz"), join(tempspace, "ui"));
96
+ }))();
97
+
98
+ const cookbookUrl = `${cookbookPackageInfo.mirror}${cookbookName}/-/cookbook-${process.platform}-${os.arch()}-${version === 'latest' ? cookbookPackageInfo.json["dist-tags"].latest : version}.tgz`;
99
+ consola.start(cookbookUrl);
100
+ consola.start(color(`[2/2] Downloading Cookbook Core (${cookbookUrl})..`));
101
+ await utils.downloadFile(cookbookUrl, tempspace, "cookbook.tgz");
102
+ consola.success(color("[2/2] Downloaded!"));
103
+ const cookbookExtractPromise = ((async () => {
104
+ await compressing.tgz.uncompress(join(tempspace, "cookbook.tgz"), tempspace);
105
+ }))();
106
+
107
+ consola.start(color("[1/2] Extracting.."));
108
+ await Promise.all([uiExtractPromise, cookbookExtractPromise]);
109
+ consola.success(color("[1/2] Extracted!"));
110
+
111
+ consola.success(color("[2/2] Installing.."));
112
+ await utils.mvToPathAndInstall(join(tempspace, "package"), process.platform === "win32" ? "co.exe" : "co", tempspace);
113
+ await utils.mvUIDir(join(tempspace, "ui", "package"));
114
+ await utils.tempspaceClean(tempspace);
115
+ consola.success(color("[2/2] Installed!"));
116
+
117
+ console.log("");
118
+ consola.info(color("Try run: co version"));
119
+ consola.info(colorLong("* If you find that the co command does not exist, try restarting your Terminal or System"));
120
+ })();
121
+
122
+ const utils = {
123
+ downloadFile: async (url, workspace, filename) => {
124
+ const res = await fetch(url);
125
+ if (existsSync(join(workspace, filename))) await remove(join(workspace, filename));
126
+ const destination = join(workspace, filename);
127
+ const fileStream = createWriteStream(destination, { flags: "wx" });
128
+ await finished(Readable.fromWeb(res.body).pipe(fileStream));
129
+ },
130
+ mvUIDir: async (tempspace) => {
131
+ if (!existsSync(process.env.HOME || process.env.USERPROFILE, ".cookbook")) mkdirSync(join(process.env.HOME || process.env.USERPROFILE, ".cookbook"));
132
+ if (process.platform === "win32") {
133
+ if (existsSync(join(process.env.USERPROFILE, ".cookbook", 'ui'))) await utils.executePowershell(`Remove-Item -Recurse -Force "${join(process.env.USERPROFILE, ".cookbook", 'ui')}";`);
134
+ await utils.executePowershell(`Move-Item -Path "${join(tempspace)}" -Destination "${join(process.env.USERPROFILE, ".cookbook", 'ui')}" -Force;`);
135
+ return;
136
+ }
137
+ if (process.platform === "linux") {
138
+ if (existsSync(join(process.env.HOME, ".cookbook", 'ui'))) await utils.executeBash(`rm -rf "${join(process.env.HOME, ".cookbook", 'ui')}";`);
139
+ await utils.executeBash(`mv "${join(tempspace)}" "${join(process.env.HOME, ".cookbook", 'ui')}"`);
140
+ }
141
+ if (process.platform === "darwin") {
142
+ if (existsSync(join(process.env.HOME, ".cookbook", 'ui'))) await utils.executeBash(`rm -rf "${join(process.env.HOME, ".cookbook", 'ui')}";`);
143
+ await utils.executeBash(`mv "${join(tempspace)}" "${join(process.env.HOME, ".cookbook", 'ui')}"`);
144
+ }
145
+ },
146
+ tempspaceClean: async (tempspace) => {
147
+ if (process.platform === "win32") {
148
+ if (existsSync(join(tempspace))) await utils.executePowershell(`Remove-Item -Recurse -Force "${join(tempspace)}";`);
149
+ return;
150
+ }
151
+ if (process.platform === "linux") {
152
+ if (existsSync(join(tempspace))) await utils.executeBash(`rm -rf "${join(tempspace)}"`);
153
+ }
154
+ if (process.platform === "darwin") {
155
+ if (existsSync(join(tempspace))) await utils.executeBash(`rm -rf "${join(tempspace)}"`);
156
+ }
157
+ },
158
+ mvToPathAndInstall: async (workspace, filename, tempspace) => {
159
+ if (process.platform === "win32") {
160
+ await new Promise((resolve) => setTimeout(resolve, 500));
161
+ if (!(process.env.PATH.includes(`${join(process.env.USERPROFILE, ".cookbook")};`) || process.env.PATH.includes(`;${join(process.env.USERPROFILE, ".cookbook")}`) || process.env.PATH === `${join(process.env.USERPROFILE, ".cookbook")}`)) {
162
+ await utils.executePowershell(`[System.Environment]::SetEnvironmentVariable("PATH", [System.Environment]::GetEnvironmentVariable("PATH", "User") + ";${join(process.env.USERPROFILE, ".cookbook")}", "User");`);
163
+ }
164
+ if (!existsSync(process.env.USERPROFILE, ".cookbook")) mkdirSync(process.env.USERPROFILE, ".cookbook");
165
+ if (existsSync(join(process.env.USERPROFILE, ".cookbook", filename))) rmSync(join(process.env.USERPROFILE, ".cookbook", filename));
166
+ await utils.executePowershell(`Move-Item -Path "${join(workspace, filename)}" -Destination "${join(process.env.USERPROFILE, ".cookbook")}";`);
167
+ return;
168
+ }
169
+ if (process.platform === "linux") {
170
+ const paths = [join(process.env.HOME, ".bin"), "/usr/bin/", "/usr/sbin"];
171
+ let pathChecked = "";
172
+ for (const path of paths) {
173
+ if (process.env.PATH.includes(`${path}:`) || process.env.PATH.includes(`:${path}`) || process.env.PATH === `${path}`) {
174
+ pathChecked = path;
175
+ break;
176
+ }
177
+ }
178
+ if (!pathChecked) {
179
+ consola.error(color("No path found!"));
180
+ exit(0);
181
+ }
182
+ if (!existsSync(pathChecked)) mkdirSync(pathChecked);
183
+ if (existsSync(join(pathChecked, filename))) {
184
+ if (pathChecked.startsWith("/home")) await utils.executeBash(`rm -f ${join(pathChecked, filename)}`);
185
+ else await utils.executeBash(`sudo rm -f ${join(pathChecked, filename)}`);
186
+ }
187
+ if (pathChecked.startsWith("/home")) await utils.executeBash(`mv ${join(workspace, filename)} ${pathChecked} && chmod +x ${join(pathChecked, filename)}`);
188
+ else await utils.executeBash(`sudo mv ${join(workspace, filename)} ${pathChecked} && sudo chmod +x ${join(pathChecked, filename)}`);
189
+ }
190
+ if (process.platform === "darwin") {
191
+ const paths = [join(process.env.HOME, "bin"), join(process.env.HOME, ".bin"), join(process.env.HOME, ".local", "bin"), "/usr/local/bin"];
192
+ let pathChecked = "";
193
+ for (const path of paths) {
194
+ if (process.env.PATH.includes(`${path}:`) || process.env.PATH.includes(`:${path}`) || process.env.PATH === `${path}`) {
195
+ pathChecked = path;
196
+ break;
197
+ }
198
+ }
199
+ if (!pathChecked) {
200
+ consola.error(color("No path found!"));
201
+ exit(0);
202
+ }
203
+ if (!existsSync(pathChecked)) mkdirSync(pathChecked);
204
+ if (existsSync(join(pathChecked, filename))) {
205
+ if (pathChecked.startsWith("/Users")) await utils.executeBash(`rm -f ${join(pathChecked, filename)}`);
206
+ else await utils.executeBash(`sudo rm -f ${join(pathChecked, filename)}`);
207
+ }
208
+ if (pathChecked.startsWith("/Users")) await utils.executeBash(`mv ${join(workspace, filename)} ${pathChecked} && chmod +x ${join(pathChecked, filename)}`);
209
+ else await utils.executeBash(`sudo mv ${join(workspace, filename)} ${pathChecked} && sudo chmod +x ${join(pathChecked, filename)}`);
210
+ }
211
+ },
212
+ executePowershell: async (script) => {
213
+ return execFileSync("powershell.exe", ["-c", script], {
214
+ stdio: "inherit",
215
+ });
216
+ },
217
+ executeBash: (script) => {
218
+ return execFileSync("bash", ["-c", script], {
219
+ stdio: "inherit",
220
+ });
221
+ },
222
+ };
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "create-cookbook",
3
+ "version": "1.0.0-alpha.100",
4
+ "main": "index.mjs",
5
+ "bin": {
6
+ "create-cookbook": "./index.mjs"
7
+ },
8
+ "scripts": {
9
+ "create-cookbook": "./index.mjs"
10
+ },
11
+ "dependencies": {
12
+ "compressing": "^1.10.1",
13
+ "consola": "^3.4.0",
14
+ "fs-extra": "^11.2.0",
15
+ "gradient-string": "^3.0.0"
16
+ }
17
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Enable latest features
4
+ "lib": ["ESNext", "DOM"],
5
+ "target": "ESNext",
6
+ "module": "ESNext",
7
+ "moduleDetection": "force",
8
+ "jsx": "react-jsx",
9
+ "allowJs": true,
10
+
11
+ // Bundler mode
12
+ "moduleResolution": "bundler",
13
+ "allowImportingTsExtensions": true,
14
+ "verbatimModuleSyntax": true,
15
+ "noEmit": true,
16
+
17
+ // Best practices
18
+ "strict": true,
19
+ "skipLibCheck": true,
20
+ "noFallthroughCasesInSwitch": true,
21
+
22
+ // Some stricter flags (disabled by default)
23
+ "noUnusedLocals": false,
24
+ "noUnusedParameters": false,
25
+ "noPropertyAccessFromIndexSignature": false
26
+ }
27
+ }