-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathindex.js
2465 lines (2194 loc) · 70.3 KB
/
index.js
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { Command } from "commander";
import inquirer from "inquirer";
import { execSync } from "node:child_process";
import simpleGit from "simple-git";
import fs from "fs-extra";
import chalk from "chalk";
import { createSpinner } from "nanospinner";
import os from "node:os";
import path from "node:path";
import Table from "cli-table3";
import net from "node:net";
import { v4 as uuidv4 } from "uuid";
import { formatDistanceToNow } from "date-fns";
import latestVersion from "latest-version";
import semver from "semver";
import { fileURLToPath } from "node:url";
import axios from "axios";
import bcrypt from "bcrypt";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const program = new Command();
const packagePath = path.resolve(__dirname, "package.json");
const packageJson = JSON.parse(fs.readFileSync(packagePath, "utf-8"));
function updateCLI() {
try {
execSync("sudo npm install -g quicky", { stdio: "inherit" });
console.log(chalk.green("Quicky has been upgraded to the latest version."));
} catch (error) {
console.error(chalk.red(`Failed to upgrade Quicky: ${error.message}`));
}
}
async function checkForUpdates() {
try {
const latest = await latestVersion("quicky");
if (semver.gt(latest, packageJson.version)) {
console.log(
`\n🚀 A new version of Quicky (v${chalk.bold.blue(
latest,
)}) is available!`,
);
const { shouldUpgrade } = await inquirer.prompt([
{
type: "confirm",
name: "shouldUpgrade",
message:
" Would you like to update quicky to the latest version? Your configurations will be preserved.",
default: true,
},
]);
if (shouldUpgrade) {
updateCLI();
} else {
console.log(
chalk.yellow("You can upgrade later by running 'quicky upgrade'."),
);
}
}
} catch (error) {
console.error("Error checking for updates:", error);
}
}
// Check for updates after the command execution
program.hook("postAction", async () => {
const excludedCommands = ["upgrade", "uninstall"];
const command = process.argv[2];
if (!excludedCommands.includes(command)) {
await checkForUpdates();
}
});
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const log = console.log;
const homeDir = os.homedir();
const defaultFolder = path.join(homeDir, ".quicky");
const projectsDir = `${defaultFolder}/projects`;
const tempDir = `${defaultFolder}/temp`;
const configPath = `${defaultFolder}/config.json`;
// Ensure directories exist
if (!fs.existsSync(projectsDir)) {
fs.mkdirSync(projectsDir, { recursive: true });
}
if (!fs.existsSync(configPath)) {
fs.writeFileSync(configPath, JSON.stringify({ projects: [] }, null, 2));
}
// Read configuration file once
const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
// Function to save the configuration file
const saveConfig = (config) => {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
};
// Function to update the projects configuration file
const updateProjectsConfig = ({
pid = uuidv4().slice(0, 5),
owner,
repo,
port,
webhookId,
type = "next.js",
}) => {
const project = {
pid,
owner,
repo,
port,
webhookId,
type,
last_updated: new Date().toISOString(),
};
const existing = config.projects.find((p) => p.repo === repo);
if (existing) {
existing.port = port;
existing.owner = owner;
existing.type = type;
existing.last_updated = new Date().toISOString();
} else {
config.projects.push(project);
}
saveConfig(config);
};
// Function to remove a domain or subdomain and delete Nginx and Certbot configuration files
async function removeDomain(domain) {
// Remove Nginx configuration
const nginxConfigPath = `/etc/nginx/sites-available/${domain}`;
if (fs.existsSync(nginxConfigPath)) {
const command = `sudo rm -f ${nginxConfigPath} /etc/nginx/sites-enabled/${domain}`;
execSync(command, { stdio: "inherit" });
execSync("sudo service nginx restart", { stdio: "inherit" });
log(chalk.green(`Nginx configuration removed for ${domain}.`));
}
// Remove SSL certificate using Certbot
const certbotCommand = `sudo certbot delete --cert-name ${domain}`;
execSync(certbotCommand, { stdio: "inherit" });
log(chalk.green(`SSL certificate removed for ${domain}.`));
// Update the config file and remove the domain from the config
config.domains = config.domains.filter((d) => d.domain !== domain);
saveConfig(config);
log(
chalk.green(
`Domain ${domain} removed successfully.`,
),
);
}
async function setupDomain(domain, port) {
// Install Nginx if not already installed
try {
execSync("nginx -v", { stdio: "ignore" });
} catch (error) {
execSync("sudo apt install nginx -y", { stdio: "inherit" });
}
// Install Certbot if not already installed
try {
execSync("certbot --version && certbot plugins | grep nginx", {
stdio: "ignore",
});
} catch (error) {
// If not installed, install certbot and the nginx plugin
execSync("sudo apt install certbot python3-certbot-nginx -y", {
stdio: "inherit",
});
}
// Check if domain exists in config.json
const domainExists = (config.domains || []).some((d) => d.domain === domain);
if (domainExists) {
const { overwrite } = await inquirer.prompt([{
type: "confirm",
name: "overwrite",
message: `Domain ${domain} already exists. Do you want to overwrite and reconfigure it?`,
default: false
}]);
if (!overwrite) {
throw new Error('Domain configuration cancelled by user');
}
await removeDomain(domain);
log(chalk.green(`Existing configuration for ${domain} has been removed. Proceeding with new setup...`));
} else {
// Check if nginx config exists for this domain and remove it
const nginxConfigPath = `/etc/nginx/sites-available/${domain}`;
const nginxSymlinkPath = `/etc/nginx/sites-enabled/${domain}`;
if (fs.existsSync(nginxConfigPath) || fs.existsSync(nginxSymlinkPath)) {
log(chalk.yellow(`Found existing Nginx configuration for ${domain}, removing...`));
try {
fs.unlinkSync(nginxSymlinkPath);
fs.unlinkSync(nginxConfigPath);
} catch (error) {
log(chalk.yellow(`Error removing existing files: ${error.message}`));
}
}
// Check and remove any existing SSL certificates
try {
execSync(`certbot delete --cert-name ${domain} --non-interactive`, {
stdio: "ignore",
});
log(chalk.yellow(`Removed existing SSL certificate for ${domain}`));
} catch (error) {
// Certificate doesn't exist, continue with setup
}
}
// Inform user to ensure domain points to server
log(chalk.yellow(`Please ensure that ${domain} is pointing to this server's IPv4 address before proceeding.`));
log(chalk.yellow('You can do this by updating your domain\'s DNS A record.'));
const nginxConfigPath = `/etc/nginx/sites-available/${domain}`;
const nginxSymlinkPath = `/etc/nginx/sites-enabled/${domain}`;
// Remove existing Nginx configuration if it exists
if (fs.existsSync(nginxConfigPath) || fs.existsSync(nginxSymlinkPath)) {
log(chalk.yellow(`Found existing Nginx configuration for ${domain}, removing...`));
try {
fs.unlinkSync(nginxSymlinkPath);
fs.unlinkSync(nginxConfigPath);
} catch (error) {
log(chalk.yellow(`Error removing existing files: ${error.message}`));
log(chalk.yellow('Continuing with setup...'));
}
}
const zoneName = `zone_${uuidv4().slice(0, 5)}`;
const nginxConfig = `
# Rate limiting zone definition
limit_req_zone $binary_remote_addr zone=${zoneName}:10m rate=30r/s;
server {
listen 80;
server_name ${domain};
# Main location block for proxying to the application
location / {
# Rate limiting with burst and delay
limit_req zone=${zoneName} burst=10 delay=10;
# Proxy settings
proxy_pass http://localhost:${port};
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-NginX-Proxy true;
# Buffering and memory optimization
proxy_buffering on;
proxy_buffer_size 256k;
proxy_buffers 8 256k;
proxy_busy_buffers_size 512k;
proxy_temp_file_write_size 512k;
proxy_max_temp_file_size 1024m;
# Next.js specific configuration
proxy_cache_bypass $http_upgrade;
proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
proxy_cache_valid 200 60m;
proxy_cache_valid 404 1m;
}
# Next.js static files location
location /_next/static {
proxy_pass http://localhost:${port};
proxy_cache_bypass $http_upgrade;
expires 365d;
access_log off;
add_header Cache-Control "public, no-transform, must-revalidate";
}
# Static files location
location /static {
proxy_pass http://localhost:${port};
proxy_cache_bypass $http_upgrade;
expires 365d;
access_log off;
add_header Cache-Control "public, no-transform, must-revalidate";
}
# Static asset caching with ETag and Last-Modified headers
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
proxy_pass http://localhost:${port};
proxy_cache_bypass $http_upgrade;
expires 7d;
add_header Cache-Control "public, no-transform, must-revalidate";
etag on;
if_modified_since exact;
access_log off;
log_not_found off;
}
# Compression settings
gzip on;
gzip_types
text/plain
text/css
application/json
application/javascript
text/xml
application/xml
application/xml+rss
text/javascript;
gzip_comp_level 6;
gzip_min_length 1000;
# Connection timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
keepalive_timeout 65s;
keepalive_requests 100;
# Request size limit
client_max_body_size 50M;
# Logging configuration
access_log /var/log/nginx/${domain}-access.log combined buffer=512k flush=1m;
error_log /var/log/nginx/${domain}-error.log warn;
# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
add_header Content-Security-Policy "default-src 'self' *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *; img-src 'self' data: https: *; font-src 'self' data: *; connect-src 'self' https: *; frame-ancestors 'none';" always;
}
`;
// Write Nginx config to the sites-available and sites-enabled directories
const tempFilePath = `/tmp/${domain}.conf`;
fs.writeFileSync(tempFilePath, nginxConfig, { mode: 0o644 });
execSync(`sudo mv ${tempFilePath} ${nginxConfigPath}`, {
stdio: "inherit",
});
// Check if the symlink already exists
if (!fs.existsSync(nginxSymlinkPath)) {
// Create a symlink to the sites-enabled directory
execSync(`sudo ln -s ${nginxConfigPath} ${nginxSymlinkPath}`, {
stdio: "inherit",
});
} else {
log(chalk.yellow(`Symlink already exists for ${domain}.`));
}
// Restart Nginx to apply the changes
execSync("sudo service nginx restart", { stdio: "inherit" });
log(chalk.green(`Nginx configuration created for ${domain}.`));
if (!config.email) {
const { email } = await inquirer.prompt([
{
type: "input",
name: "email",
message: "Enter your email address for SSL certificate:",
validate: (input) => {
const emailRegex = /\S+@\S+\.\S+/;
return emailRegex.test(input) ? true : "Please enter a valid email.";
},
},
]);
config.email = email;
saveConfig(config);
}
// Obtain SSL certificate using Certbot
try {
execSync("which certbot", { stdio: "ignore" });
execSync("which python3-certbot-nginx", { stdio: "ignore" });
} catch (error) {
execSync("sudo apt install certbot python3-certbot-nginx -y", {
stdio: "inherit",
});
} finally {
try {
execSync(
`sudo certbot --nginx -d ${domain} --non-interactive --agree-tos --email ${config.email}`,
{ stdio: "inherit" },
);
} catch (error) {
console.error(
chalk.red(`Failed to obtain SSL certificate: ${error.message}`),
);
process.exit(1);
}
}
log(chalk.green(`SSL certificate obtained and configured for ${domain}.`));
}
async function setupWebhookServer() {
const { webhookUrl } = await inquirer.prompt([
{
type: "input",
name: "webhookUrl",
message:
"Enter the URL where the webhook will be received (e.g., quicky.example.com):",
validate: (input) => {
if (input.trim() === "") {
return "URL is required.";
}
if (config.domains?.some((d) => d.domain === input.trim())) {
return "This domain is already in use. Please enter a different URL.";
}
return true;
},
},
]);
const isPortInUse = (port) => {
return new Promise((resolve) => {
const server = net.createServer();
server.once("error", (err) => {
if (err.code === "EADDRINUSE") {
resolve(true);
} else {
resolve(false);
}
});
server.once("listening", () => {
server.close();
resolve(false);
});
server.listen(port);
});
};
const getRandomPort = () => {
return Math.floor(Math.random() * (65535 - 1024 + 1)) + 1024;
};
const getAvailablePort = async () => {
let port;
do {
port = getRandomPort();
} while (await isPortInUse(port));
return port;
};
const availablePort = await getAvailablePort();
// Set up the webhook server
const git = simpleGit();
const webhookPath = `${defaultFolder}/webhook`; // .quicky/webhook
// Check if the webhook directory already exists and is not empty
if (fs.existsSync(webhookPath) && fs.readdirSync(webhookPath).length > 0) {
log(
chalk.yellow(
`Directory ${webhookPath} already exists and is not empty. Deleting...`,
),
);
// Stop and delete the PM2 instance if it exists
try {
execSync(
"pm2 stop quicky-webhook-server && pm2 del quicky-webhook-server",
{
stdio: "inherit",
},
);
} catch (error) {
log(chalk.red(`Failed to stop/delete PM2 instance: ${error.message}`));
}
fs.removeSync(webhookPath);
}
// Clone the webhook repository
await git.clone("https://github.com/alohe/quicky-webhook.git", webhookPath);
// Install dependencies
execSync(`cd ${webhookPath} && npm install`, { stdio: "inherit" });
// Set up the domain using the setupDomain function
await setupDomain(webhookUrl, availablePort);
// Generate a random secret for securing the webhook
const webhookSecret = uuidv4();
// Add a .env file to the webhook server
const envFilePath = `${webhookPath}/.env`;
fs.writeFileSync(
envFilePath,
`WEBHOOK_URL=${webhookUrl}\nWEBHOOK_PORT=${availablePort}\nWEBHOOK_SECRET=${webhookSecret}`,
{ flag: "wx" },
);
// Update the webhook URL and secret for all the projects managed by Quicky
if (config.projects && config.projects.length > 0) {
for (const project of config.projects) {
if (project.webhookId) {
const webhookConfig = {
config: {
url: `https://${webhookUrl}/webhook`,
content_type: "json",
secret: webhookSecret,
},
};
try {
await axios.patch(
`https://api.github.com/repos/${project.owner}/${project.repo}/hooks/${project.webhookId}`,
webhookConfig,
{
headers: {
Authorization: `Bearer ${config.github.access_token}`,
},
},
);
console.log(`Webhook updated for project: ${project.repo}`);
} catch (error) {
console.error(
`Error updating webhook for project ${project.repo}: ${error.message}`,
);
}
}
}
}
try {
// Start the webhook server with PM2
execSync(
`pm2 start ${path.join(
webhookPath,
"index.js",
)} --name "quicky-webhook-server"`,
{
stdio: "inherit",
},
);
} catch (error) {
if (error.message.includes("Script already launched")) {
// If the script is already running, attempt to restart it
try {
execSync(`pm2 restart "quicky-webhook-server"`, {
stdio: "inherit",
});
} catch (restartError) {
console.error(
"Failed to restart the webhook server:",
restartError.message,
);
throw restartError; // Re-throw the error after logging
}
} else {
console.error("Failed to start the webhook server:", error.message);
throw error; // Re-throw the error after logging
}
}
// Update the global config.json with the webhook server details
config.webhook = {
webhookUrl: `https://${webhookUrl}/webhook`,
webhookPort: availablePort,
secret: webhookSecret,
pm2Name: "quicky-webhook-server",
};
saveConfig(config);
log(
chalk.green(
`Webhook server set up and running at https://${webhookUrl}/webhook`,
),
);
}
// Function to set up a webhook on a repository to be used during deployment
async function setupWebhook(repo) {
// check if the webhook config is already set up in the config file
if (
!config.webhook ||
!config.webhook.webhookUrl ||
!config.webhook.webhookPort ||
!config.webhook.secret
) {
log(
chalk.yellow(
"Webhook server is not fully configured. Please set up the webhook server first.",
),
);
const { confirmWebhookSetup } = await inquirer.prompt([
{
type: "confirm",
name: "setupWebhookServer",
message: "Do you want to set up the webhook server now?",
default: true,
},
]);
if (confirmWebhookSetup) {
await setupWebhookServer();
} else {
log(chalk.yellow("Operation cancelled."));
return;
}
}
const webhookConfig = {
name: "web",
active: true,
events: ["push"], // Listen for push events
config: {
url: config.webhook.webhookUrl, // User's local service URL
content_type: "json",
secret: config.webhook.secret, // Add the secret for securing the webhook
},
};
// Create the webhook on the user's repository
try {
const response = await axios.post(
`https://api.github.com/repos/${repo}/hooks`,
webhookConfig,
{
headers: {
Authorization: `Bearer ${config.github.access_token}`,
},
},
);
console.log(`Webhook created: ${response.data.id}`);
return response.data.id; // Return the webhook ID
} catch (error) {
console.error(`Error creating webhook: ${error.message}`);
return null; // Return null if there was an error
}
}
// Function to remove a webhook from a repo to be used during project deletion
async function removeWebhook(repo, webhookId) {
try {
await axios.delete(
`https://api.github.com/repos/${repo}/hooks/${webhookId}`,
{
headers: {
Authorization: `Bearer ${config.github.access_token}`,
},
},
);
console.log(`Webhook ${webhookId} removed.`);
return true;
} catch (error) {
console.error(`Error removing webhook: ${error.message}`);
return false;
}
}
// Function to update a project with the latest changes from the repository
async function updateProject(project, promptEnv = false) {
try {
// Validate project configuration upfront
if (!project.owner || !project.repo) {
throw new Error("Invalid project configuration: Missing owner or repo");
}
// Validate project type and required configurations
if (project.type === "next.js" && !project.port) {
throw new Error("A port is required for a Next.js project");
}
const git = simpleGit();
const repoPath = `${projectsDir}/${project.repo}`;
const tempPath = `${tempDir}/${project.repo}`;
const spinner = createSpinner(`Updating ${project.repo}...`).start();
await sleep(1000);
try {
// Clone into temporary directory
spinner.update({ text: "Cloning the repository..." });
// Clean up any existing temp directory first
if (fs.existsSync(tempPath)) {
spinner.update({ text: "Cleaning up existing temp directory..." });
try {
await fs.remove(tempPath);
} catch (err) {
console.error(`Error removing temp dir: ${err.message}`);
}
}
// Ensure the tempPath directory exists and is empty
await fs.ensureDir(tempPath);
await git.clone(
`https://${config.github.access_token}@github.com/${project.owner}/${project.repo}.git`,
tempPath,
);
// Stop the spinner before prompting
spinner.stop();
if (promptEnv) {
if (fs.existsSync(`${repoPath}/.env`)) {
const { updateEnv } = await inquirer.prompt([
{
type: "confirm",
name: "updateEnv",
message: "Would you like to update the .env file?",
default: false,
},
]);
if (updateEnv) {
// Copy existing .env to temp location and open in nano
fs.copyFileSync(`${repoPath}/.env`, `${tempPath}/.env`);
execSync(`nano ${tempPath}/.env`, { stdio: "inherit" });
} else {
// Preserve existing .env file by copying to temp directory
fs.copyFileSync(`${repoPath}/.env`, `${tempPath}/.env`);
}
} else {
// Prompt user if they want to create a .env file
const { createEnv } = await inquirer.prompt([
{
type: "confirm",
name: "createEnv",
message: "Would you like to create a .env file?",
default: false
},
]);
if (createEnv) {
execSync(`nano ${tempPath}/.env`, { stdio: "inherit" });
}
}
} else if (fs.existsSync(`${repoPath}/.env`)) {
fs.copyFileSync(`${repoPath}/.env`, `${tempPath}/.env`);
}
// Restart the spinner after prompts
spinner.start();
// Install dependencies and build the project in the temporary directory
const packageManager = config.packageManager || "npm";
const installCommand = `${packageManager} install`;
const buildCommand = `${packageManager} run build`;
try {
spinner.update({ text: "Installing dependencies..." });
execSync(`cd ${tempPath} && ${installCommand}`, {
stdio: "inherit",
});
} catch (error) {
spinner.error({ text: `Install failed: ${error.message}` });
throw new Error(`Failed to install dependencies: ${error.message}`);
}
// Check for build script and validate build process
let buildSuccessful = false;
try {
const packageJson = JSON.parse(
fs.readFileSync(`${tempPath}/package.json`, "utf8"),
);
const hasBuildScript = packageJson.scripts?.build;
if (hasBuildScript) {
spinner.update({ text: "Building the project in temp directory..." });
try {
// Execute build command for both Next.js and Node.js projects
execSync(`cd ${tempPath} && ${buildCommand}`, {
stdio: "inherit",
});
// Validate build success based on project type
if (project.type === "next.js") {
buildSuccessful = fs.existsSync(`${tempPath}/.next`);
if (!buildSuccessful) {
throw new Error(
"Next.js build did not generate .next directory",
);
}
} else if (project.type === "node.js") {
buildSuccessful = true;
} else {
throw new Error("Invalid project type");
}
} catch (buildError) {
buildSuccessful = false;
throw buildError;
}
} else {
// If no build script, consider it successful
buildSuccessful = true;
}
} catch (error) {
spinner.error({ text: `Build failed: ${error.message}` });
throw new Error(`Failed to build project: ${error.message}`);
}
// Stop the PM2 process if it exists
spinner.update({ text: "Stopping PM2 process..." });
try {
execSync(`pm2 stop ${project.repo}`, { stdio: "ignore" });
} catch (error) {
// Ignore error if process doesn't exist
}
const backupPath = `${repoPath}_backup`;
try {
// Create backup by renaming if project directory exists
if (fs.existsSync(repoPath)) {
if (fs.existsSync(backupPath)) {
fs.removeSync(backupPath); // Remove existing backup if any
}
// Use fs-extra's moveSync instead of renameSync for better cross-platform support
fs.moveSync(repoPath, backupPath, { overwrite: true });
spinner.success({ text: "Backup created." });
}
} catch (err) {
spinner.error({ text: `Error during backup: ${err.message}` });
throw err; // Propagate error since this is a critical operation
} finally {
spinner.stop();
}
// Move temp directory to project directory using moveSync
fs.moveSync(tempPath, repoPath, { overwrite: true });
// Check if the main entry file exists before starting
const packageJsonPath = `${repoPath}/package.json`;
let mainFile = 'index.js';
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
mainFile = packageJson.main || 'index.js';
}
log("Starting the project...");
// Determine start command based on project type
let startCommand;
if (project.type === "next.js") {
startCommand = `pm2 start npm --name "${project.repo}" -- start -- --port ${project.port}`;
} else {
const entryFile = `${repoPath}/${mainFile}`;
if (!fs.existsSync(entryFile)) {
throw new Error(`Entry file ${entryFile} not found. Please check that the "main" field in your package.json points to the correct entry file, or ensure index.js exists in the root directory.`);
}
startCommand = project.port
? `pm2 start ${mainFile} --name "${project.repo}" -- --port ${project.port}`
: `pm2 start ${mainFile} --name "${project.repo}"`;
}
// Start the project
try {
log("Stopping existing PM2 process if any...");
try {
execSync(`pm2 delete "${project.repo}"`, { stdio: "ignore" });
} catch (deleteError) {
// Ignore error if process doesn't exist
}
log("Starting the project...");
execSync(`cd ${repoPath} && ${startCommand}`, {
stdio: "inherit",
});
} catch (startError) {
// Rollback if start fails
log(chalk.red(`Failed to start project: ${startError.message}`));
try {
// Remove failed directory if it exists
if (fs.existsSync(`${repoPath}_failed`)) {
fs.removeSync(`${repoPath}_failed`);
}
// Move current repo to failed state
fs.moveSync(repoPath, `${repoPath}_failed`, { overwrite: true });
// Restore backup
fs.moveSync(backupPath, repoPath, { overwrite: true });
log(
chalk.yellow(
`Project ${project.repo} has been rolled back due to startup failure.`,
),
);
} catch (rollbackError) {
log(chalk.red(`Failed to rollback: ${rollbackError.message}`));
}
throw new Error(`Failed to start project: ${startError.message}`);
}
// Update the last_updated timestamp
project.last_updated = new Date().toISOString();
saveConfig(config);
log(`✔ Project ${chalk.green.bold(project.repo)} updated successfully.`);
} catch (error) {
spinner.error({
text: `Failed to update project: ${error.message}`,
});
throw error;
}
} catch (error) {
console.error(chalk.red(`Error: ${error.message}`));
process.exit(1);
}
}
function help() {
const rabbit = `
(\\(\\
( -.-)
o_(")(")
`;
log(chalk.blue(rabbit)); // Change color to whatever fits your style
log(
`${chalk.hex("#fd6d4c").bold("Quicky")}${chalk.hex("#f39549")(
" - A CLI tool to deploy Next.js and Node.js projects",
)}`,
);
log("");
log("Usage:");
// use the chalk package to colorize the output
log(
`${chalk.blue(" quicky")} ${chalk.hex("#FFA500")(
"<command>",
)} ${chalk.green("[options]")}`,
);
log("");
log("Commands:");
log(
` ${chalk
.hex("#cea9fe")
.bold(
"init",
)} Save your GitHub account details and install dependencies\n`,
);
log(
` ${chalk.blue.bold(
"deploy",
)} Deploy a Next.js or Node.js project from GitHub`,
);
log(
` ${chalk.blue.bold(
"list",
)} List the current configuration and associated PM2 instances`,
);
log(
` ${chalk.blue.bold(
"manage",
)} Start, stop, restart, update, or delete a project \n`,
);
log(
` ${chalk.blue.bold(
"update",
)} Update a project by its PID, primarily used by the webhook server\n`,
);
log(
` ${chalk.cyanBright.bold(
"domains",
)} Manage domains and subdomains for the projects`,
);
log(
` ${chalk.cyanBright.bold(
"webhooks",
)} Manage the webhook server for your projects`,
);
log("");
log(` ${chalk.hex("#fe64fa").bold("install")} Install quicky globally`);
log(
` ${chalk
.hex("#fe64fa")
.bold("upgrade")} Upgrade quicky to the latest version`,